自学内容网 自学内容网

腾讯云短信服务(Java)

腾讯云短信服务(Java)

1、开通短信服务

https://console.cloud.tencent.com/smsv2

在这里插入图片描述

2、购买套餐包

新人会有一个免费的,注意领取哦

https://buy.cloud.tencent.com/sms

在这里插入图片描述

3、配置请求

https://console.cloud.tencent.com/api/explorer?Product=sms&Version=2021-01-11&Action=SendSms

3.1、发送短信

  • Region:资源地域
  • PhoneNumberSet:下发手机号码(可以填写多个,字符串数组),格式为+[国家或地区码][手机号]
  • TemplateId:模板 ID
  • SmsSdkAppId:短信应用ID
  • SignName:短信签名内容
  • TemplateParamSet:模板参数(注意这里要填写的模板参数需要和模板对应,而不是和手机号数量对应)

在这里插入图片描述

确认在此页面可以请求成功并收到短信后就进行下一步

4、代码实现

这里的例子是发送验证码

4.1、导入依赖

<dependency>
    <groupId>com.tencentcloudapi</groupId>
    <artifactId>tencentcloud-sdk-java</artifactId>
    <version>4.0.11</version>
</dependency>

4.2、SMSUtil

package cn.darkiris.util;

import com.tencentcloudapi.common.Credential;
import com.tencentcloudapi.common.profile.ClientProfile;
import com.tencentcloudapi.common.profile.HttpProfile;
import com.tencentcloudapi.sms.v20190711.SmsClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class SMSUtil {

    private static final String SECRET_ID = "SECRET_ID";

    private static final String SECRET_KEY = "SECRET_KEY";

    @Bean
    public SmsClient smsClient() {
        // 实例化一个认证对象,入参需要传入腾讯云账户 SecretId,SecretKey。
        // 为了保护密钥安全,建议将密钥设置在环境变量中或者配置文件中,请参考凭证管理 https://github.com/TencentCloud/tencentcloud-sdk-java?tab=readme-ov-file#%E5%87%AD%E8%AF%81%E7%AE%A1%E7%90%86。
        // 硬编码密钥到代码中有可能随代码泄露而暴露,有安全隐患,并不推荐。
        // SecretId、SecretKey 查询: https://console.cloud.tencent.com/cam/capi
        // Credential cred = new Credential("SecretId", "SecretKey");
        Credential cred = new Credential(SECRET_ID, SECRET_KEY);
        // 实例化一个http选项,可选的,没有特殊需求可以跳过
        HttpProfile httpProfile = new HttpProfile();
        // 指定接入地域域名,默认就近地域接入域名为 sms.tencentcloudapi.com ,也支持指定地域域名访问,例如广州地域的域名为 sms.ap-guangzhou.tencentcloudapi.com
        httpProfile.setEndpoint("sms.tencentcloudapi.com");
        // 实例化一个客户端配置对象
        ClientProfile clientProfile = new ClientProfile();
        clientProfile.setHttpProfile(httpProfile);
        // 实例化要请求产品(sms)的client对象,第二个参数是地域信息,可以直接填写字符串ap-guangzhou,支持的地域列表参考 https://cloud.tencent.com/document/api/382/52071#.E5.9C.B0.E5.9F.9F.E5.88.97.E8.A1.A8
        return new SmsClient(cred, "ap-guangzhou", clientProfile);
    }
}

4.3、CaptchaUtil

package cn.darkiris.util;

import org.springframework.stereotype.Component;

import java.security.SecureRandom;

@Component
public class CaptchaUtil {

    private static final int CODE_LENGTH = 6;
    private static final SecureRandom random = new SecureRandom();

    public String[] generateCaptcha() {
        StringBuilder captcha = new StringBuilder(CODE_LENGTH);
        for (int i = 0; i < CODE_LENGTH; i++) {
            int digit = random.nextInt(10); // 生成0-9之间的随机数
            captcha.append(digit);
        }
        return new String[]{captcha.toString()};
    }
}

4.4、SMSService

package cn.darkiris.service;

import cn.darkiris.util.CaptchaUtil;
import cn.darkiris.util.RedisTemplateUtil;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import com.tencentcloudapi.sms.v20190711.SmsClient;
import com.tencentcloudapi.sms.v20190711.models.SendSmsRequest;
import com.tencentcloudapi.sms.v20190711.models.SendSmsResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Slf4j
@Service
public class SMSServiceImpl implements SMSService {

    private static final String SMS_SDK_APP_ID = "1400932857";

    // http://www.esjson.com/unicodeEncode.html
    private static final String SIGN_NAME = "\u6d77\u53e3\u9e22\u5c3e\u7f51\u7edc\u79d1\u6280";

    private static final String CAPTCHA_TEMPLATE_ID = "2260287";

    @Autowired
    private CaptchaUtil captchaUtil;

    @Autowired
    private RedisTemplateUtil redisTemplateUtil;

    @Autowired
    private SmsClient smsClient;

    @Override
    public String captcha(String phone) {
        // 实例化一个请求对象,根据调用的接口和实际情况,可以进一步设置请求参数
        SendSmsRequest req = new SendSmsRequest();
        // 下发手机号码,采用 E.164 标准,+[国家或地区码][手机号]
        req.setPhoneNumberSet(new String[]{"+86" + phone});
        // 短信应用ID: 短信SdkAppId在 [短信控制台] 添加应用后生成的实际SdkAppId,可前往 [短信控制台](https://console.cloud.tencent.com/smsv2/app-manage) 查看
        req.setSmsSdkAppid(SMS_SDK_APP_ID);
        // 模板 ID: 必须填写已审核通过的模板 ID,可前往 [国内短信](https://console.cloud.tencent.com/smsv2/csms-template) 或 [国际/港澳台短信](https://console.cloud.tencent.com/smsv2/isms-template) 的正文模板管理查看
        req.setTemplateID(CAPTCHA_TEMPLATE_ID);
        // 短信签名内容: 使用 UTF-8 编码,必须填写已审核通过的签名;签名信息可前往 [国内短信](https://console.cloud.tencent.com/smsv2/csms-sign) 或 [国际/港澳台短信](https://console.cloud.tencent.com/smsv2/isms-sign) 的签名管理查看
        req.setSign(SIGN_NAME);
        // 模板参数: 模板参数的个数需要与 TemplateId 对应模板的变量个数保持一致,若无模板参数,则设置为空
        String[] captcha = captchaUtil.generateCaptcha();
        redisTemplateUtil.set("captcha" + phone, captcha[0], 5 * 60);
        req.setTemplateParamSet(captcha);
        // 通过 client 对象调用 SendSms 方法发起请求,注意请求方法名与请求对象是对应的,返回的 res 是一个 SendSmsResponse 类的实例,与请求对象对应
        try {
            SendSmsResponse resp = smsClient.SendSms(req);
            log.info(SendSmsResponse.toJsonString(resp));
        } catch (TencentCloudSDKException e) {
            /* 当出现以下错误码时,快速解决方案参考
             * [FailedOperation.SignatureIncorrectOrUnapproved](https://cloud.tencent.com/document/product/382/9558#.E7.9F.AD.E4.BF.A1.E5.8F.91.E9.80.81.E6.8F.90.E7.A4.BA.EF.BC.9Afailedoperation.signatureincorrectorunapproved-.E5.A6.82.E4.BD.95.E5.A4.84.E7.90.86.EF.BC.9F)
             * [FailedOperation.TemplateIncorrectOrUnapproved](https://cloud.tencent.com/document/product/382/9558#.E7.9F.AD.E4.BF.A1.E5.8F.91.E9.80.81.E6.8F.90.E7.A4.BA.EF.BC.9Afailedoperation.templateincorrectorunapproved-.E5.A6.82.E4.BD.95.E5.A4.84.E7.90.86.EF.BC.9F)
             * [UnauthorizedOperation.SmsSdkAppIdVerifyFail](https://cloud.tencent.com/document/product/382/9558#.E7.9F.AD.E4.BF.A1.E5.8F.91.E9.80.81.E6.8F.90.E7.A4.BA.EF.BC.9Aunauthorizedoperation.smssdkappidverifyfail-.E5.A6.82.E4.BD.95.E5.A4.84.E7.90.86.EF.BC.9F)
             * [UnsupportedOperation.ContainDomesticAndInternationalPhoneNumber](https://cloud.tencent.com/document/product/382/9558#.E7.9F.AD.E4.BF.A1.E5.8F.91.E9.80.81.E6.8F.90.E7.A4.BA.EF.BC.9Aunsupportedoperation.containdomesticandinternationalphonenumber-.E5.A6.82.E4.BD.95.E5.A4.84.E7.90.86.EF.BC.9F)
             * 更多错误,可咨询[腾讯云助手](https://tccc.qcloud.com/web/im/index.html#/chat?webAppId=8fa15978f85cb41f7e2ea36920cb3ae1&title=Sms)
             */
            log.error(e.getMessage());
            return "send captcha error";
        }
        return null;
    }
}

4.5、SMSController

package cn.darkiris.controller;

import cn.darkiris.entity.ResponseEntity;
import cn.darkiris.service.SMSService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
public class SMSController {

    @Autowired
    private SMSService smsService;

    @RequestMapping("hello")
    public ResponseEntity<?> hello() {
        return ResponseEntity.Success("hello world!");
    }

    @RequestMapping("/captcha")
    public ResponseEntity<?> captcha(@RequestParam String phone) {
        String str = smsService.captcha(phone);
        if (str != null) {
            return ResponseEntity.Fail(str);
        }
        return ResponseEntity.Success("hello world!");
    }
}

原文地址:https://blog.csdn.net/gyfghh/article/details/143073452

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!