博主
258
258
258
258
专辑

第二节 短信发送通知

亮子 2024-06-22 11:26:53 3710 0 0 0

1、定义service接口

package com.bwie.service;

/**
 * @author 军哥
 * @version 1.0
 * @description: TODO
 * @date 2024/6/20 14:33
 */

public interface IMobileSenderService {
    boolean send(String mobile, String message);
}

2、定义service实现类

package com.bwie.service.impl;

import cn.hutool.http.HttpRequest;
import com.bwie.service.IMobileSenderService;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * @author 军哥
 * @version 1.0
 * @description: TODO
 * @date 2024/6/20 14:34
 */

@Service
public class IMobileSenderServiceImpl implements IMobileSenderService {

    /***
     * @description 短信发送
     * @return boolean
     * @author 军哥
     * @date 2024/6/20 14:35
     */
    @Override
    public boolean send(String mobile, String message) {
//        String url = "https://gyytz.market.alicloudapi.com/sms/smsSend";
        String url = "http://gyytz.market.alicloudapi.com/sms/smsSend";
        String appcode = "99b192f09a2a432ea1987f29aacf53b4";

        Map<String, Object> querys = new HashMap<String, Object>();

        // message 只能是4-6位的数字
        querys.put("mobile", mobile);
        querys.put("param", "**code**:" + message + ",**minute**:5");
        querys.put("smsSignId", "2e65b1bb3d054466b82f0c9d125465e2");
        querys.put("templateId", "908e94ccf08b4476ba6c876d13f084ad");

        // 发送短信
        String body = HttpRequest.post(url)
                .header("Authorization", "APPCODE " + appcode)
                .form(querys)
                .execute()
                .body();

        // 判断是否成功
        if(body.contains("成功")) {
            System.out.println("短信发送成功了");
            return true;
        }

        System.out.println("短信发送失败了");
        return false;
    }
}

3、控制层调用

package com.bwie.controller;

import com.bwie.service.IMobileSenderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author 军哥
 * @version 1.0
 * @description: TODO
 * @date 2024/6/20 14:42
 */

@RestController
@Slf4j
@RequestMapping(value = "/m")
public class MobileController {

    @Autowired
    IMobileSenderService iMobileSenderService;

    @GetMapping(value = "/sendCode/{mobile}/{code}")
    public String sendCode(@PathVariable("mobile") String mobile, @PathVariable("code") String code) {
        boolean send = iMobileSenderService.send(mobile, code);
        if(send) {
            log.info("短信发送成功了");
            return "短信发送成功了";
        }
        else {
            log.info("短信发送失败了");
            return "短信发送失败了";
        }
    }

}