当前位置: 首页 > news >正文

腾讯云短信服务(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";@Beanpublic 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.comhttpProfile.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.A8return 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.htmlprivate static final String SIGN_NAME = "\u6d77\u53e3\u9e22\u5c3e\u7f51\u7edc\u79d1\u6280";private static final String CAPTCHA_TEMPLATE_ID = "2260287";@Autowiredprivate CaptchaUtil captchaUtil;@Autowiredprivate RedisTemplateUtil redisTemplateUtil;@Autowiredprivate SmsClient smsClient;@Overridepublic 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 {@Autowiredprivate 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!");}
}

http://www.mrgr.cn/news/53699.html

相关文章:

  • 双链表的操作
  • Unity3D 如何实现从任意位置与方向出发后按规定方向到达目标点详解
  • 《Python游戏编程入门》注-第2章2
  • VSCode设置用鼠标滚轮控制字体大小
  • C++学习实例:入门,了解其输入输出
  • RHCE的学习(4)
  • MicroPython rp2-LVGL 固件编译记录
  • python-PyQt项目实战案例:制作一个视频播放器
  • Windows 内核层内存泄漏查看工具
  • 利用GPU训练
  • 浏览器实时更新esp32-c3 Supermini http server 数据
  • Spring的起源与发展
  • python办公:批量PDF合并—通用版
  • 【最新华为OD机试E卷-支持在线评测】模拟目录管理 (200分)多语言题解-(Python/C/JavaScript/Java/Cpp)
  • React入门简介
  • Win11电脑快捷键大全
  • Python配合yolov11开发对象检测软件
  • 青城山道观:清幽之境,心灵之旅
  • 银河麒麟(debian)下安装postgresql、postgis
  • Turn-it:调整它:优化线材重构雕塑制造
  • 思维+构造,CF 1936A - Bitwise Operation Wizard
  • 【AI实战连载01】揭秘ComfyUI AI换装工作流方法1-OOTDiffusion!电商卖家用AI一键给模特换装?
  • 数据分析题面试题系列2
  • 【开源免费】基于SpringBoot+Vue.JS社区团购系统(JAVA毕业设计)
  • 【思维导图】C语言—常见概念
  • 06 P1706 全排列问题