实现springboot对接腾讯云短信

1,导入pom依赖

1      <dependency>
2             <groupId>com.github.qcloudsms</groupId>
3             <artifactId>qcloudsms</artifactId>
4             <version>1.0.6</version>
5         </dependency>

2,编写工具类

 1 package com.chesupi.message.util;
 2 
 3 import com.github.qcloudsms.SmsSingleSender;
 4 import com.github.qcloudsms.SmsSingleSenderResult;
 5 import lombok.extern.slf4j.Slf4j;
 6 
 7 @Slf4j
 8 public class SmsUtil {
 9     private final static int appid = 1400XXXXXX;
10     private final static String appkey = "6def9c1d5314bce4070e4b4xxxxxxxxx";
11 
12     public static String sendMessage(int templateId, String smsSign, String phoneNumber,String[] replacedValues) {
13 
14         String status = "";
15         //给手机发送短信
16         //1.腾讯云自己项目的AppID
17         //2.腾讯云自己项目的Appkey
18         //3  短信的模板ID templateId
19         //4  签名的名字  smsSign
20         //5 .给谁发 phoneNumber
21         //String phoneNumber = "17671775xxx";
22         //6. 验证码:手动不随机验证码 最多六位数 只能是数字
23         // String[] params = {"876032"};
24         //7.发送短信对象
25         SmsSingleSender ssender = new SmsSingleSender(appid,appkey);
26 
27         //地区,电话,模板ID,验证码,签名
28         try {
29             SmsSingleSenderResult result = ssender.sendWithParam("86", phoneNumber, templateId, replacedValues, smsSign, "", "");
30             status=result.errMsg;
31             log.info("sms send status,template id [{}],phone is [{}],status is [{}] ",templateId,phoneNumber,status);
32         } catch (Exception e){
33             log.info("sms send status,template id [{}],phone is [{}],status is [{}] ",templateId,phoneNumber,status,e);
34         }
35         return status;  // 此处的status只有发送成功是"OK"
36     }

3,调用工具类发送短信

 1 package com.chesupi.message.service;
 2 
 3 import com.chesupi.message.util.SmsUtil;
 4 import lombok.extern.slf4j.Slf4j;
 5 import org.springframework.stereotype.Component;
 6 
 7 @Component
 8 @Slf4j
 9 public class DealerRegisterMessageReceiver {
10 
11     /**
12      * 接收消息方法
13      */
14     public void receiverMessage(String message) {
15         try {
16             log.info("用户注册收到一条新消息:[{}]", message);
17             String[] messageArray=message.split(",");
18             String phoneNumber = messageArray[0];
19             String[] replacedValues={messageArray[1]};
20             SmsUtil.sendMessage(888878,"短信签名名字", phoneNumber,replacedValues);  // 888878 是templateId “短信签名名字” 这个是腾讯天申请的短信签名  replacedValues 是短信内容需要的参数
21         }catch (Exception e){
22             log.error("send sms exception, message is [{}]",message);
23         }
24     }
25 
26 
27 }

完成! 

把templateId smsSign 放在方法参数是为了其他短信模版可以通用此方法!

猜你喜欢

转载自www.cnblogs.com/LKiss/p/11973543.html