天天看點

一小時學會使用SpringBoot整合阿裡雲SMS短信服務

一小時學會使用SpringBoot整合阿裡雲SMS短信服務

1. 登入阿裡雲進入控制台

進入阿裡雲控制台,

https://home.console.aliyun.com/

在個人頭像位置點選進入AccessKey管理:

一小時學會使用SpringBoot整合阿裡雲SMS短信服務
一小時學會使用SpringBoot整合阿裡雲SMS短信服務

2. 建立使用者和使用者組

建立使用者組
一小時學會使用SpringBoot整合阿裡雲SMS短信服務

添加完成後進入使用者組,并為其添權重限:

一小時學會使用SpringBoot整合阿裡雲SMS短信服務

建立使用者

一小時學會使用SpringBoot整合阿裡雲SMS短信服務
一小時學會使用SpringBoot整合阿裡雲SMS短信服務
一小時學會使用SpringBoot整合阿裡雲SMS短信服務

注意:使用者建立完成後,将其添加到使用者組中,點選進入該使用者,在認證管理下方會有該使用者對應的AccessKeyId和AccessKeySecret!要将其儲存下來,不然忘記後,還得删除使用者,重新建立,在之後使用代碼整合短信業務時候需要用到!

3. 開通阿裡雲短信服務

阿裡雲短信服務位址:

https://dysms.console.aliyun.com/dysms.htm
一小時學會使用SpringBoot整合阿裡雲SMS短信服務

在概覽中直接點選立即開通短信服務!接下來點選快速學習:

一小時學會使用SpringBoot整合阿裡雲SMS短信服務

點選添加簽名,添加模闆,去向阿裡雲申請自己定義的簽名和短信模闆!

一小時學會使用SpringBoot整合阿裡雲SMS短信服務
一小時學會使用SpringBoot整合阿裡雲SMS短信服務

模闆和簽名申請送出後等待申請結果通過即可!

注意:由于阿裡雲通信短信服務稽核管理規則更新,12月17日以後,個人身份申請稽核短信簽名更加嚴格了

這裡我稽核用的是自己的公衆号名稱作為SMS短信簽名,去申請的!

4. 代碼整合阿裡雲SMS短信服務

官方SDK文檔:

https://help.aliyun.com/document_detail/112148.html

官方APIDemo:

https://api.aliyun.com/new#/?product=Dysmsapi&version=2017-05-25&api=SendSms&tab=DEMO&lang=JAVA

4.1 pom.xml 中引入SDK依賴

Spring Boot版本我使用的是2.3.x:

<!-- aliyun sms SDK -->
<dependency>
    <groupId>com.aliyun</groupId>
    <artifactId>aliyun-java-sdk-core</artifactId>
    <version>4.5.3</version>
</dependency>
<!-- fastjson -->
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>1.2.68</version>
</dependency>
<!-- redis -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
      

4.2 測試官方提供的執行個體Demo

@SpringBootTest
class AliyunSmsDemoApplicationTests {

    @Test
    void contextLoads() {

        /**
         * 連接配接阿裡雲:
         *
         * 三個參數:
         * regionId 不要動,預設使用官方的
         * accessKeyId 自己的使用者accessKeyId
         * accessSecret 自己的使用者accessSecret
         */
        DefaultProfile profile = DefaultProfile.getProfile(
                "cn-hangzhou", "LTAI4GKDZbrcaESV1fBV8V9B", "1bc8phOIbAbfvMXSWFt2AlLctBMMCI");
        IAcsClient client = new DefaultAcsClient(profile);

        // 建構請求:
        CommonRequest request = new CommonRequest();
        request.setSysMethod(MethodType.POST);
        request.setSysDomain("dysmsapi.aliyuncs.com");
        request.setSysVersion("2017-05-25");
        request.setSysAction("SendSms");

        // 自定義參數:
        request.putQueryParameter("PhoneNumbers", "xxxxx0440");// 接收短信的手機号
        request.putQueryParameter("SignName", "CSP網上商城");// 短信簽名
        request.putQueryParameter("TemplateCode", "SMS_20xxxxx74");// 短信模版CODE

        // 建構短信驗證碼
        Map<String,Object> map = new HashMap<>();
        map.put("code",1234);// 這裡僅用于測試,是以驗證碼寫死
        request.putQueryParameter("TemplateParam", JSONObject.toJSONString(map));

        try {
            CommonResponse response = client.getCommonResponse(request);
            System.out.println(response.getData());
        } catch (ServerException e) {
            e.printStackTrace();
        } catch (ClientException e) {
            e.printStackTrace();
        }
    }
}
      

執行發送測試,結果如下圖:

4.3 建構短信發送微服務

4.3.1 service

/**
 * @Auther: csp1999
 * @Date: 2020/12/18/12:08
 * @Description: 阿裡雲SMS短信服務Service
 */
@Service
public class AliyunSendSmsService {

    @Value("${aliyun.sms.accessKeyId}")
    private String accessKeyId;

    @Value("${aliyun.sms.accessKeySecret}")
    private String accessKeySecret;

    /**
     * 發送短信驗證碼
     *
     * @param phone        接收短信的手機号
     * @param templateCode 短信模闆CODE
     * @param codeMap      驗證碼map 集合
     * @return
     */
    public Boolean sendMessage(String phone, String templateCode, Map<String, Object> codeMap) {

        /**
         * 連接配接阿裡雲:
         *
         * 三個參數:
         * regionId 不要動,預設使用官方的
         * accessKeyId 自己的使用者accessKeyId
         * accessSecret 自己的使用者accessSecret
         */
        DefaultProfile profile = DefaultProfile.getProfile(
                "cn-hangzhou", accessKeyId, accessKeySecret);
        IAcsClient client = new DefaultAcsClient(profile);

        // 建構請求:
        CommonRequest request = new CommonRequest();
        request.setSysMethod(MethodType.POST);
        request.setSysDomain("dysmsapi.aliyuncs.com");
        request.setSysVersion("2017-05-25");
        request.setSysAction("SendSms");

        // 自定義參數:
        request.putQueryParameter("PhoneNumbers", phone);// 手機号
        request.putQueryParameter("SignName", "CSP網上商城");// 短信簽名
        request.putQueryParameter("TemplateCode", templateCode);// 短信模版CODE

        // 建構短信驗證碼
        request.putQueryParameter("TemplateParam", JSONObject.toJSONString(codeMap));

        try {
            CommonResponse response = client.getCommonResponse(request);
            System.out.println(response.getData());
            return response.getHttpResponse().isSuccess();
        } catch (ServerException e) {
            e.printStackTrace();
        } catch (ClientException e) {
            e.printStackTrace();
        }
        return false;
    }
}
      

4.3.2 controller

/**
 * @Auther: csp1999
 * @Date: 2020/12/18/12:21
 * @Description: 阿裡雲SMS短信發送API
 */
@RestController
public class AliyunSmsApiController {

    @Autowired
    private AliyunSendSmsService aliyunSendSmsService;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Value("${aliyun.sms.templateCode}")
    private String templateCode;

    /**
     * 短信發送
     *
     * @param phone
     * @return
     */
    @GetMapping("/send/{phone}")
    public String sendCode(@PathVariable("phone") String phone) {

        // 根據手機号從redis中拿驗證碼
        String code = redisTemplate.opsForValue().get(phone);
        if (!StringUtils.isEmpty(code)) {
            return phone + " : " + code + "已經存在,還沒有過期!";
        }

        // 如果redis 中根據手機号拿不到驗證碼,則生成4位随機驗證碼
        code = UUID.randomUUID().toString().substring(0, 4);

        // 驗證碼存入codeMap
        Map<String, Object> codeMap = new HashMap<>();
        codeMap.put("code", code);

        // 調用aliyunSendSmsService發送短信
        Boolean bool = aliyunSendSmsService.sendMessage(phone, templateCode, codeMap);

        if (bool) {
            // 如果發送成功,則将生成的4位随機驗證碼存入redis緩存,5分鐘後過期
            redisTemplate.opsForValue().set(phone, code, 5, TimeUnit.MINUTES);
            return phone + " : " + code + "發送成功!";
        } else {
            return phone + " : " + code + "發送失敗!";
        }
    }
}
      

4.3.3 application.yml

server:
  port: 8080

# spring相關配置
spring:
  redis:
    # Redis資料庫索引(預設為0)
    database: 0
    # Redis伺服器位址
    host: 8.xxx.xx.xx6
    # Redis伺服器連接配接端口
    port: 6379
    # Redis伺服器連接配接密碼(預設為空)
    password: cspxxxxxxx
    jedis:
      pool:
        # 連接配接池最大連接配接數(使用負值表示沒有限制)
        max-active: 8
        # 連接配接池最大阻塞等待時間(使用負值表示沒有限制)
        max-wait: -1
        # 連接配接池中的最大空閑連接配接
        max-idle: 8
        # 連接配接池中的最小空閑連接配接
        min-idle: 0
    # 連接配接逾時時間(毫秒)
    timeout: 8000
      

4.3.4 application.properties

# accessKeyId
aliyun.sms.accessKeyId=LTAI4xxxxxxxxxxV9B
# accessKeySecret
aliyun.sms.accessKeySecret=LTAI4xxxxxxxxxxV8V9B
# 短信模闆Code
aliyun.sms.templateCode=SMS_xxxxx74
      

4.4 啟動項目測試發送

一小時學會使用SpringBoot整合阿裡雲SMS短信服務

手機收到短信驗證碼!

5. Demo位址

Demo案例源碼參考:

https://gitee.com/caoshipeng/my-demo-code/tree/newbranch2/aliyun-sms-demo

如果對大家有幫助,請三連支援一下!

有問題歡迎評論區留言,及時幫大家解決!

一小時學會使用SpringBoot整合阿裡雲SMS短信服務