侧边栏壁纸
博主头像
小城雨巷 博主等级

行动起来,活在当下

  • 累计撰写 20 篇文章
  • 累计创建 6 个标签
  • 累计收到 4 条评论

目 录CONTENT

文章目录

Spring boot 集成腾讯云短信

Administrator
2023-10-18 / 0 评论 / 0 点赞 / 20 阅读 / 0 字

引入依赖

<!--腾讯云短信服务-->
<dependency>
    <groupId>com.tencentcloudapi</groupId>
    <artifactId>tencentcloud-sdk-java</artifactId>
    <version>3.1.365</version>
</dependency>

yml 配置

# 短信应用参数,登入[腾讯短信控制台] 查找 -------------------------------------
auth:
  tencent-sms-secret-id: AKIDf8LIzQcXBZhaDahY8RTFkyvb1A2cx1pL
  tencent-sms-secret-key: IK5ZuylHWVDeoiLhmb9QQ9cniLipeCUW
  tencent-sms-app-id: 1400577190
# 模板id:必须填写已审核通过的模板 ID
  tencent-sms-template-id: 1164859
# ----------------------------------------------------------------------
  sms-signature: 擒云数字
  sms-verify-code-length: 6
  sms-retry-wait-seconds: 60
  sms-cache-time-out: 300
  sms-cache-key-prefix: LOGIN_SMS_
  phone-verify-regex: ^1\\d{10}$

实例化腾讯请求客户端

 @PostConstruct
    public void postConstruct() {

        Credential cred = new Credential(appProperties.getTencentSmsSecretId(), appProperties.getTencentSmsSecretKey());

        // 实例化一个http选项,可选的,没有特殊需求可以跳过
        HttpProfile httpProfile = new HttpProfile();
        httpProfile.setEndpoint(TENCENT_SMS_ENDPOINT);

        // 实例化一个client选项
        ClientProfile clientProfile = new ClientProfile();
        clientProfile.setHttpProfile(httpProfile);

        // 实例化要请求产品的client对象,clientProfile是可选的
        smsClient = new SmsClient(cred, TENCENT_SMS_PROVIDER_REGION, clientProfile);

        log.info("\n\n[TENCENT SMS CLIENT] Initialized\n\n");
    }

生成腾讯 SMS 请求物件

    /**
     * 生成腾讯 SMS 请求物件
     *
     * @param phoneNumber 手机号码
     * @return SendSmsRequest 请求物价
     */
    private SendSmsRequest createSmsRequest(String phoneNumber) {
        SendSmsRequest req = new SendSmsRequest();
        req.setPhoneNumberSet(new String[]{phoneNumber});
        req.setSmsSdkAppId(appProperties.getTencentSmsAppId());
        req.setSignName(appProperties.getSmsSignature());
        req.setTemplateId(appProperties.getTencentSmsTemplateId());

        return req;
    }

发送验证码

    /**
     * 发送短信验证码
     *
     * @param phoneNumber 手机号码
     * @throws SmsSendException 短信服务异常
     */
    private void sendPhoneNumberCode(String phoneNumber) throws SmsSendException {

        // 实例化一个请求对象,每个接口都会对应一个request对象
        SendSmsRequest req = createSmsRequest(phoneNumber);

        // 生成验证码
        String msgCode = random.ints(appProperties.getSmsVerifyCodeLength(), 0, 10)
                .mapToObj(String::valueOf)
                .collect(Collectors.joining());

        // 模板参数(自定义占位变量): 若无模板参数,则设置为空
        // template content: {1}为您的登录验证码,请于{2}分钟内填写,如非本人操作,请忽略本短信。
        req.setTemplateParamSet(new String[]{msgCode, Integer.toString(appProperties.getSmsCacheTimeOut() / 60)});

        // 返回的resp是一个SendSmsResponse的实例,与请求对象对应
        try {
            SendSmsResponse resp = smsClient.SendSms(req);
            // 输出json格式的字符串回包
            if (resp.getSendStatusSet()[0].getCode() != null && resp.getSendStatusSet()[0].getCode().equals("Ok")) {
                redisCache.setCacheObject(appProperties.getSmsCacheKeyPrefix() + phoneNumber, msgCode,
                        appProperties.getSmsCacheTimeOut(), TimeUnit.SECONDS);
            } else {
                throw new SmsSendException();
            }
        } catch (TencentCloudSDKException e) {
            throw new SmsSendException(e.getMessage(), e);
        }
    }
0

评论区