Use Tencent Cloud to send SMS API interface implementation (complete process)

1. Open Tencent Cloud SMS service

Find the SMS service on the official website of Tencent Cloud and activate it

 2. Create signature and template

create signature

Fill in the information and wait for review 

 

 create template

Fill in the information and wait for review 

 Get the secret key
official website link: api secret key

3. Use springboot to call

1. Import dependencies

<!--腾讯云短信依赖-->
<!-- https://mvnrepository.com/artifact/com.tencentcloudapi/tencentcloud-sdk-java -->
<dependency>
    <groupId>com.tencentcloudapi</groupId>
    <artifactId>tencentcloud-sdk-java</artifactId>
    <version>3.1.423</version>
</dependency>

2. Write application.yml configuration

tencent:
  sms:
    #腾讯云短信服务参数
    #腾讯云账户secretId,secretKey
    keyId: 
    keysecret: 
    #短信签名内容: 使用 UTF-8 编码,必须填写已审核通过的签名
    signName: 
    #短信应用ID: 短信SdkAppId在 [短信控制台] 添加应用后生成的实际SdkAppId
    smsSdkAppId: 
    #模板 ID: 必须填写已审核通过的模板 ID
    templateId: 

3. Create a tool class

import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class ConstantSmsUtils implements InitializingBean {

    @Value("${tencent.sms.keyId}")
    private String secretID ;
    @Value("${tencent.sms.keysecret}")
    private String secretKey ;
    @Value("${tencent.sms.smsSdkAppId}")
    private String smsSdkAppID ;
    @Value("${tencent.sms.signName}")
    private String signName ;
    @Value("${tencent.sms.templateId}")
    private String templateID ;

    public static String SECRET_ID;
    public static String SECRET_KEY;
    public static String SMSSDKAPP_ID;
    public static String SIGN_NAME;
    public static String TEMPLATE_ID;


    @Override
    public void afterPropertiesSet() throws Exception {
        SECRET_ID = secretID;
        SECRET_KEY = secretKey;
        SMSSDKAPP_ID = smsSdkAppID;
        SIGN_NAME = signName;
        TEMPLATE_ID = templateID;
    }
}

utils to generate random numbers

import java.text.DecimalFormat;
import java.util.Random;

public class RandomUtil {

    private static final Random random = new Random();

    private static final DecimalFormat fourdf = new DecimalFormat("0000");

    private static final DecimalFormat sixdf = new DecimalFormat("000000");

    //生成4位随机数
    public static String getFourBitRandom() {
        return fourdf.format(random.nextInt(10000));
    }
    //生成6位随机数
    public static String getSixBitRandom() {
        return sixdf.format(random.nextInt(1000000));
    }
}

Writing Send SMS API

controller

    /**
     * 发送验证码
     * @param phoneNumber
     * @return
     */
    @ApiOperation("发送验证码")
    @PostMapping("/sendCode")
    public R sendCode(String phoneNumber) {
        boolean isSend = userService.send(phoneNumber);
        if (isSend){
            return R.ok();
        }else {
            return R.fail("短信发送失败!");
        }
    }

serviceImpl

    /**
     * 发送验证码
     * @param phoneNumber
     * @return
     */
    @Override
    public boolean send(String phoneNumber) {
        //判断手机号是否为空
        if (StringUtils.isEmpty(phoneNumber)){
            return false;
        }
        try{
            // 实例化一个认证对象,入参需要传入腾讯云账户secretId,secretKey,此处还需注意密钥对的保密
            // 密钥可前往https://console.cloud.tencent.com/cam/capi网站进行获取
            Credential cred = new Credential(ConstantSmsUtils.SECRET_ID, ConstantSmsUtils.SECRET_KEY);
            // 实例化一个http选项,可选的,没有特殊需求可以跳过
            HttpProfile httpProfile = new HttpProfile();
            httpProfile.setEndpoint("sms.tencentcloudapi.com");
            // 实例化一个client选项,可选的,没有特殊需求可以跳过
            ClientProfile clientProfile = new ClientProfile();
            clientProfile.setHttpProfile(httpProfile);
            // 实例化要请求产品的client对象,clientProfile是可选的  第二个参数是地域信息
            SmsClient client = new SmsClient(cred, "ap-guangzhou", clientProfile);
            // 实例化一个请求对象,每个接口都会对应一个request对象
            SendSmsRequest req = new SendSmsRequest();
            //设置固定的参数
            req.setSmsSdkAppId(ConstantSmsUtils.SMSSDKAPP_ID);// 短信应用ID: 短信SdkAppId在 [短信控制台] 添加应用后生成的实际SdkAppId
            req.setSignName(ConstantSmsUtils.SIGN_NAME);//短信签名内容: 使用 UTF-8 编码,必须填写已审核通过的签名
            req.setTemplateId(ConstantSmsUtils.TEMPLATE_ID);//模板 ID: 必须填写已审核通过的模板 ID
            /* 用户的 session 内容: 可以携带用户侧 ID 等上下文信息,server 会原样返回 */
//            String sessionContext = "xxx";
//            req.setSessionContext(sessionContext);

            //设置发送相关的参数
            String[] phoneNumberSet1 = {"+86"+phoneNumber};
            req.setPhoneNumberSet(phoneNumberSet1);//发送的手机号
            //生成6位数随机验证码
            String verificationCode = RandomUtil.getSixBitRandom();
            String[] templateParamSet1 = {verificationCode};//模板的参数 第一个是验证码,第二个是过期时间
            req.setTemplateParamSet(templateParamSet1);//发送验证码
            //发送短信
            // 返回的resp是一个SendSmsResponse的实例,与请求对象对应
            SendSmsResponse resp = client.SendSms(req);
            System.out.println("resp"+resp);
            // 输出json格式的字符串回包
            System.out.println(SendSmsResponse.toJsonString(resp));
            //将验证码放入redis中
//            redisService.setCacheObject(VERIFICATION_CODE + phoneNumber, verificationCode, 60*5L, TimeUnit.SECONDS);
            return true;
        } catch (TencentCloudSDKException e) {
            e.printStackTrace();
            return false;
        }
    }
import com.tencentcloudapi.sms.v20210111.SmsClient;
import com.tencentcloudapi.sms.v20210111.models.SendSmsRequest;
import com.tencentcloudapi.sms.v20210111.models.SendSmsResponse;
#导包时这几个包一定要相对应

postman test

{
    "code": 200,
    "msg": null,
    "data": null
}
#输出json格式的字符串回包
{
	"SendStatusSet":[
						{
							"SerialNo":"2433:325730845216576992445817097",
							"PhoneNumber":"+8613888888888",
							"Fee":1,
							"SessionContext":"",
							"Code":"Ok",
							"Message":"send success",
							"IsoCode":"CN"
						}
					],
	"RequestId":"2ee712e7-481d-460c-b6b3-e2857ba12086"
}

Guess you like

Origin blog.csdn.net/poker_zero/article/details/125764137