200字范文,内容丰富有趣,生活中的好帮手!
200字范文 > springboot如何去集成腾讯云的短信服务

springboot如何去集成腾讯云的短信服务

时间:2024-01-07 03:29:49

相关推荐

springboot如何去集成腾讯云的短信服务

1、先去申请一个微信公众号,通过微信公众号,以个人的名义去申请腾讯短信服务。

2、 填写你注册公众号要注册成啥类型的,如果是自己玩或者自己测试的话我推荐大家呢去注册这个订阅号他这个呢比较好注册,然后去填写自己的相关的信息。

3注册成功了,就会生成这个界面

4、然后我们去设置公众号的设置里面去把他的那个隐私设置给打开

5、去腾讯云的短信服务哪里去免费注册一个(默认呢腾讯云是送的客户100条的免费的短信发送个数)。

6、然后单击,免费试用,进去了以后呢他左侧的选项栏里面呢有一个这个快速入门,点击创建自己的签名以及自己的短信模板去申请去给腾讯工作人员去申请。

7、点击概括这个里面有人家官方给你写好的ipA文档

8、导入腾讯云的依赖

<!--腾讯云--><dependency><groupId>com.tencentcloudapi</groupId><artifactId>tencentcloud-sdk-java</artifactId><version>3.1.270</version><!-- 注:这里只是示例版本号(可直接使用),可获取并替换为 最新的版本号,注意不要使用4.0.x版本(非最新版本) --></dependency><dependency><groupId>com.alibaba</groupId><artifactId>fastjson</artifactId><version>1.2.28</version></dependency>

9 、编写java代码,这里呢我是自己封装了一个工具包。

package com.baidu.util;import com.alibaba.fastjson.JSONObject;import com.baidu.config.configuration;import com.baidu.entity.Request;import com.baidu.entity.SendStatusSet;import mon.Credential;import mon.exception.TencentCloudSDKException;//导入可选配置类import mon.profile.ClientProfile;import mon.profile.HttpProfile;// 导入对应SMS模块的clientimport com.tencentcloudapi.sms.v0111.SmsClient;// 导入要请求接口对应的request response类import com.tencentcloudapi.sms.v0111.models.SendSmsRequest;import com.tencentcloudapi.sms.v0111.models.SendSmsResponse;import java.util.HashSet;import java.util.List;import java.util.Random;import java.util.regex.Pattern;import static com.baidu.config.configuration.sdkAppId;import static com.baidu.config.configuration.signName;public class SendSmsUtil {//腾讯短信验证/**** 参数设置 phon 手机号 sixBitRandom验证码*/public static Boolean sendsms(String phone,String sixBitRandom) throws TencentCloudSDKException {/* 必要步骤:* 实例化一个认证对象,入参需要传入腾讯云账户密钥对secretId,secretKey。* 这里采用的是从环境变量读取的方式,需要在环境变量中先设置这两个值。* 你也可以直接在代码中写死密钥对,但是小心不要将代码复制、上传或者分享给他人,* 以免泄露密钥对危及你的财产安全。* SecretId、SecretKey 查询: https://console./cam/capi */Credential cred = new Credential(configuration.secretId, configuration.secretKey);// 实例化一个http选项,可选,没有特殊需求可以跳过HttpProfile httpProfile = new HttpProfile();// 设置代理(无需要直接忽略)// httpProfile.setProxyHost("真实代理ip");// httpProfile.setProxyPort(真实代理端口);/* SDK默认使用POST方法。* 如果你一定要使用GET方法,可以在这里设置。GET方法无法处理一些较大的请求 */httpProfile.setReqMethod(configuration.request);/* SDK有默认的超时时间,非必要请不要进行调整* 如有需要请在代码中查阅以获取最新的默认值 */httpProfile.setConnTimeout(60);/* 指定接入地域域名,默认就近地域接入域名为 ,也支持指定地域域名访问,例如广州地域的域名为 sms.ap- */httpProfile.setEndpoint(configuration.territory);/* 非必要步骤:* 实例化一个客户端配置对象,可以指定超时时间等配置 */ClientProfile clientProfile = new ClientProfile();/* SDK默认用TC3-HMAC-SHA256进行签名* 非必要请不要修改这个字段 */clientProfile.setSignMethod("HmacSHA256");clientProfile.setHttpProfile(httpProfile);/* 实例化要请求产品(以sms为例)的client对象* 第二个参数是地域信息,可以直接填写字符串ap-guangzhou,支持的地域列表参考 /document/api/382/52071#.E5.9C.B0.E5.9F.9F.E5.88.97.E8.A1.A8 */SmsClient client = new SmsClient(cred, "ap-beijing", clientProfile);/* 实例化一个请求对象,根据调用的接口和实际情况,可以进一步设置请求参数* 你可以直接查询SDK源码确定接口有哪些属性可以设置* 属性可能是基本类型,也可能引用了另一个数据结构* 推荐使用IDE进行开发,可以方便的跳转查阅各个接口和数据结构的文档说明 */SendSmsRequest req = new SendSmsRequest();/* 填充请求参数,这里request对象的成员变量即对应接口的入参* 你可以通过官网接口文档或跳转到request对象的定义处查看请求参数的定义* 基本类型的设置:* 帮助链接:* 短信控制台: https://console./smsv2* 腾讯云短信小助手: /document/product/382/3773#.E6.8A.80.E6.9C.AF.E4.BA.A4.E6.B5.81 *//* 短信应用ID: 短信SdkAppId在 [短信控制台] 添加应用后生成的实际SdkAppId,示例如1400006666 */req.setSmsSdkAppId(sdkAppId);req.setSignName(signName);req.setTemplateId(configuration.templateId);/* 模板参数: 模板参数的个数需要与 TemplateId 对应模板的变量个数保持一致,若无模板参数,则设置为空 */String[] templateParamSet = {sixBitRandom};req.setTemplateParamSet(templateParamSet);/* 下发手机号码,采用 E.164 标准,+[国家或地区码][手机号]* 示例如:+8613711112222, 其中前面有一个+号 ,86为国家码,13711112222为手机号,最多不要超过200个手机号 *//* String[] phoneNumberSet = {"+8621212313123", "+8612345678902", "+8612345678903"};*/final StringBuilder builder = new StringBuilder();builder.append("+86");builder.append(phone);String[] phoneNumberSet = {builder.toString()};req.setPhoneNumberSet(phoneNumberSet);/* 用户的 session 内容(无需要可忽略): 可以携带用户侧 ID 等上下文信息,server 会原样返回 */String sessionContext = "";req.setSessionContext(sessionContext);/* 短信码号扩展号(无需要可忽略): 默认未开通,如需开通请联系 [腾讯云短信小助手] */String extendCode = "";req.setExtendCode(extendCode);/* *//* 国际/港澳台短信 SenderId(无需要可忽略): 国内短信填空,默认未开通,如需开通请联系 [腾讯云短信小助手] *//*String senderid = "";req.setSenderId(senderid);*//* 通过 client 对象调用 SendSms 方法发起请求。注意请求方法名与请求对象是对应的* 返回的 res 是一个 SendSmsResponse 类的实例,与请求对象对应 */SendSmsResponse res = client.SendSms(req);// 输出json格式的字符串回包/* System.out.println(SendSmsResponse.toJsonString(res));*/final String s = SendSmsResponse.toJsonString(res);final JSONObject object = JSONObject.parseObject(s);final Request request = JSONObject.toJavaObject(object, Request.class);final List<SendStatusSet> sendStatusSet = request.getSendStatusSet();String code=null;for (SendStatusSet statusSet : sendStatusSet) {statusSet.setPhoneNumber("*****");code=statusSet.getCode();}if (code.equals("Ok")){return true;}else {return false;}// 也可以取出单个值,你可以通过官网接口文档或跳转到response对象的定义处查看返回字段的定义// System.out.println(res.getRequestId());/* 当出现以下错误码时,快速解决方案参考* [FailedOperation.SignatureIncorrectOrUnapproved](/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](/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](/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](/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)* 更多错误,可咨询[腾讯云助手](/web/im/index.html#/chat?webAppId=8fa15978f85cb41f7e2ea36920cb3ae1&title=Sms)*/}/*** 验证手机号 由于号码段不断的更新,只需要判断手机号有11位,并且全是数字以及1开头* @param phoneNumber 手机号码* @return*/private static boolean matchPhoneNumber(String phoneNumber) {String regex = "^1\\d{10}$";if(phoneNumber==null||phoneNumber.length()<=0){return false;}return Pattern.matches(regex, phoneNumber);}//验证public static void main(String[] args) throws TencentCloudSDKException {final String sixBitRandom = RandomUtil.getSixBitRandom();String phone="139352099";final boolean b = SendSmsUtil.matchPhoneNumber(phone);if (b){if(SendSmsUtil.sendsms(phone, sixBitRandom)){System.out.println("发送成功");}else {System.out.println("发送失败");}}else {System.out.println("请从新输入手机号");}}}

10 、我这里呢我是把我的这个公共的配置属性都提取出来了,或者呢大家呢也可以把这个配置属性呢放到我们的这个application.properties里面已value(“${xx}”)的这个方式呢去取值,这里的secretID 跟sercretKey呢可以去腾讯去设置登录 - 腾讯云

package com.baidu.config;public interface configuration {//idString secretId="*****";//keyString secretKey="*****";//请求方式String request="POST";//地域String territory="";// 应用 ID 可前往 [短信控制台](https://console./smsv2/app-manage) 查看String sdkAppId="1400670952";/* 短信签名内容: 使用 UTF-8 编码,必须填写已审核通过的签名 */// 签名信息可前往 [国内短信](https://console./smsv2/csms-sign) 或 [国际/港澳台短信](https://console./smsv2/isms-sign) 的签名管理查看String signName = "****";/* 模板 ID: 必须填写已审核通过的模板 ID */// 模板 ID 可前往 [国内短信](https://console./smsv2/csms-template) 或 [国际/港澳台短信](https://console./smsv2/isms-template) 的正文模板管理查看String templateId = "****";}

11、 生成随机数并测试(我这里呢生成的是6位的随机验证码)

public class RandomUtil {//生成随机验证码private static final Random random = new Random();//我定义的验证码位数是6位private static final DecimalFormat sixdf = new DecimalFormat("000000");public static String getSixBitRandom() {return sixdf.format(random.nextInt(1000000));}//校验手机号格式 因为呢手机号格式比较多然后我们这里呢采用的是这个手机号位数的校验private static boolean matchPhoneNumber(String phoneNumber) {String regex = "^1\\d{10}$";if(phoneNumber==null||phoneNumber.length()<=0){return false;}//判断正则表达式与我输入的值的长度是否相同return Pattern.matches(regex, phoneNumber);}}

12、编写实体类接收返回的json格式参数

@Data@AllArgsConstructor@NoArgsConstructorpublic class Request {//请求idprivate String RequestId;//发送状态集private List<SendStatusSet> SendStatusSet;}

package com.baidu.entity;import lombok.AllArgsConstructor;import lombok.Data;import lombok.NoArgsConstructor;@Data@AllArgsConstructor@NoArgsConstructor//发送状态集public class SendStatusSet {//序列号private String SerialNo;//电话号码private String PhoneNumber;//费用private Integer Fee;//上下文private String SessionContext;//标识private String Code;//消息private String Message;//异码private String IsoCode;}

13、调用方法完成测试

//验证public static void main(String[] args) throws TencentCloudSDKException {final String sixBitRandom = RandomUtil.getSixBitRandom();String phone="139352099";final boolean b = RandomUtil.matchPhoneNumber(phone);if (b){if(SendSmsUtil.sendsms(phone, sixBitRandom)){System.out.println("发送成功");}else {System.out.println("发送失败");}}else {System.out.println("手机号格式不对请从新输入手机号");}}

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。