提交 eb2fe760 编写于 作者: 别团等shy哥发育's avatar 别团等shy哥发育

腾讯云短信服务发送验证码

阿里云短信签名申请失败
上级 57e7c771
...@@ -16,6 +16,15 @@ ...@@ -16,6 +16,15 @@
<artifactId>aliyun-java-sdk-core</artifactId> <artifactId>aliyun-java-sdk-core</artifactId>
</dependency> </dependency>
<!--腾讯云sdk-->
<!-- https://mvnrepository.com/artifact/com.tencentcloudapi/tencentcloud-sdk-java -->
<dependency>
<groupId>com.tencentcloudapi</groupId>
<artifactId>tencentcloud-sdk-java</artifactId>
<version>3.1.395</version>
</dependency>
</dependencies> </dependencies>
</project> </project>
\ No newline at end of file
...@@ -4,9 +4,11 @@ import org.springframework.boot.SpringApplication; ...@@ -4,9 +4,11 @@ import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration; import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient; import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.context.annotation.ComponentScan;
@SpringBootApplication(exclude = DataSourceAutoConfiguration.class)//取消数据源自动配置 @SpringBootApplication(exclude = DataSourceAutoConfiguration.class)//取消数据源自动配置
@EnableDiscoveryClient @EnableDiscoveryClient
@ComponentScan(basePackages = {"com.atguigu"})
public class ServiceMsmApplication { public class ServiceMsmApplication {
public static void main(String[] args) { public static void main(String[] args) {
SpringApplication.run(ServiceMsmApplication.class, args); SpringApplication.run(ServiceMsmApplication.class, args);
......
package com.atguigu.yygh.msm.controller; package com.atguigu.yygh.msm.controller;
import com.atguigu.yygh.msm.service.MsmService; import com.atguigu.yygh.msm.service.MsmService;
import com.atguigu.yygh.msm.utils.RandomUtil;
import com.atguigu.yygu.common.result.Result; import com.atguigu.yygu.common.result.Result;
import io.swagger.annotations.Api; import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RestController;
import java.util.concurrent.TimeUnit;
@Api(tags = "短信发送控制器") @Api(tags = "短信发送控制器")
@RestController @RestController
@RequestMapping("/api/msm") @RequestMapping("/api/msm")
...@@ -16,10 +23,30 @@ public class MsmApiController { ...@@ -16,10 +23,30 @@ public class MsmApiController {
@Autowired @Autowired
private MsmService msmService; private MsmService msmService;
@Autowired
private RedisTemplate redisTemplate;
//发送手机验证码 //发送手机验证码
@ApiOperation(value = "发送手机验证码") @ApiOperation(value = "发送手机验证码")
@GetMapping("send/{phone}") @GetMapping("send/{phone}")
public Result sendCode(){ public Result sendCode(@PathVariable String phone){
//从redis获取验证码,如果可以获取到,返回ok
//key:手机号 value:验证码
String code = (String) redisTemplate.opsForValue().get(phone);
if(!StringUtils.isEmpty(code)){
return Result.ok();
}
//如果从redis获取不到,生成验证码
code= RandomUtil.getSixBitRandom();
// boolean isSend=msmService.send(phone,code) //通过整合阿里云短信服务进行发送,调用service方法
boolean isSend=msmService.sendTencent(phone,code); //腾讯云发送
//生成验证码放到redis里面,设置有效时间
if(isSend){
redisTemplate.opsForValue().set(phone,code,5, TimeUnit.MINUTES);
return Result.ok();
}else{
return Result.fail().message("发送短信失败");
}
} }
......
package com.atguigu.yygh.msm.service; package com.atguigu.yygh.msm.service;
public interface MsmService { public interface MsmService {
//阿里云发送手机验证码
boolean send(String phone, String code);
//腾讯云发送手机验证码
boolean sendTencent(String phone, String code);
} }
package com.atguigu.yygh.msm.service.impl; package com.atguigu.yygh.msm.service.impl;
import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.atguigu.yygh.msm.service.MsmService; import com.atguigu.yygh.msm.service.MsmService;
import com.atguigu.yygh.msm.utils.ConstantPropertiesUtils;
import com.atguigu.yygh.msm.utils.Constants;
import com.tencentcloudapi.common.Credential;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import com.tencentcloudapi.common.profile.ClientProfile;
import com.tencentcloudapi.common.profile.HttpProfile;
import com.tencentcloudapi.sms.v20190711.SmsClient;
import com.tencentcloudapi.sms.v20190711.models.SendSmsRequest;
import com.tencentcloudapi.sms.v20190711.models.SendSmsResponse;
import com.tencentcloudapi.sms.v20190711.models.SendStatus;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import java.util.HashMap;
import java.util.Map;
@Service @Service
public class MsmServiceImpl implements MsmService { public class MsmServiceImpl implements MsmService {
//发送手机验证码
@Override
public boolean send(String phone, String code) {
//判断手机号是否为空
if(StringUtils.isEmpty(phone)){
return false;
}
//整合阿里云短信服务
//设置相关参数
DefaultProfile profile = DefaultProfile.
getProfile(ConstantPropertiesUtils.REGION_Id,
ConstantPropertiesUtils.ACCESS_KEY_ID,
ConstantPropertiesUtils.SECRECT);
IAcsClient client = new DefaultAcsClient(profile);
CommonRequest request = new CommonRequest();
//request.setProtocol(ProtocolType.HTTPS);
request.setMethod(MethodType.POST);
request.setDomain("dysmsapi.aliyuncs.com");
request.setVersion("2017-05-25");
request.setAction("SendSms");
//手机号
request.putQueryParameter("PhoneNumbers", phone);
//签名名称
request.putQueryParameter("SignName", "我的谷粒在线教育网站");
//模板code
request.putQueryParameter("TemplateCode", "SMS_180051135");
//验证码 使用json格式 {"code":"123456"}
Map<String,Object> param = new HashMap();
param.put("code",code);
request.putQueryParameter("TemplateParam", JSONObject.toJSONString(param));
//调用方法进行短信发送
try {
CommonResponse response = client.getCommonResponse(request);
System.out.println(response.getData());
return response.getHttpResponse().isSuccess();
} catch (ServerException e) {
e.printStackTrace();
} catch (ClientException e) {
e.printStackTrace();
}
return false;
}
//腾讯云发送手机验证码
@Override
public boolean sendTencent(String phone, String code) {
//判断手机号是否为空
if(StringUtils.isEmpty(phone)) return false;
SendStatus[] returString= {};
try {
/* 必要步骤:
* 实例化一个认证对象,入参需要传入腾讯云账户密钥对secretId,secretKey。
* 这里采用的是从环境变量读取的方式,需要在环境变量中先设置这两个值。
* 你也可以直接在代码中写死密钥对,但是小心不要将代码复制、上传或者分享给他人,
* 以免泄露密钥对危及你的财产安全。
* CAM密匙查询: https://console.cloud.tencent.com/cam/capi*/
Credential cred = new Credential(Constants.SecretID, Constants.SecretKey);
// 实例化一个http选项,可选,没有特殊需求可以跳过
HttpProfile httpProfile = new HttpProfile();
// 设置代理
// httpProfile.setProxyHost("host");
// httpProfile.setProxyPort(port);
/* SDK默认使用POST方法。
* 如果你一定要使用GET方法,可以在这里设置。GET方法无法处理一些较大的请求 */
httpProfile.setReqMethod("POST");
/* SDK有默认的超时时间,非必要请不要进行调整
* 如有需要请在代码中查阅以获取最新的默认值 */
httpProfile.setConnTimeout(60);
/* SDK会自动指定域名。通常是不需要特地指定域名的,但是如果你访问的是金融区的服务
* 则必须手动指定域名,例如sms的上海金融区域名: sms.ap-shanghai-fsi.tencentcloudapi.com */
httpProfile.setEndpoint("sms.tencentcloudapi.com");
/* 非必要步骤:
* 实例化一个客户端配置对象,可以指定超时时间等配置 */
ClientProfile clientProfile = new ClientProfile();
/* SDK默认用TC3-HMAC-SHA256进行签名
* 非必要请不要修改这个字段 */
clientProfile.setSignMethod("HmacSHA256");
clientProfile.setHttpProfile(httpProfile);
/* 实例化要请求产品(以sms为例)的client对象
* 第二个参数是地域信息,可以直接填写字符串ap-guangzhou,或者引用预设的常量 */
SmsClient client = new SmsClient(cred, "ap-guangzhou", clientProfile);
/* 实例化一个请求对象,根据调用的接口和实际情况,可以进一步设置请求参数
* 你可以直接查询SDK源码确定接口有哪些属性可以设置
* 属性可能是基本类型,也可能引用了另一个数据结构
* 推荐使用IDE进行开发,可以方便的跳转查阅各个接口和数据结构的文档说明 */
SendSmsRequest req = new SendSmsRequest();
/* 填充请求参数,这里request对象的成员变量即对应接口的入参
* 你可以通过官网接口文档或跳转到request对象的定义处查看请求参数的定义
* 基本类型的设置:
* 帮助链接:
* 短信控制台: https://console.cloud.tencent.com/sms/smslist
* sms helper: https://cloud.tencent.com/document/product/382/3773 */
/* 短信应用ID: 短信SdkAppid在 [短信控制台] 添加应用后生成的实际SdkAppid,示例如1400006666 */
String sdkappid = Constants.SdkAppid;
req.setSmsSdkAppid(sdkappid);
/* 短信签名内容: 使用 UTF-8 编码,必须填写已审核通过的签名,签名信息可登录 [短信控制台] 查看 */
String sign = Constants.signName;
req.setSign(sign);
/* 国际/港澳台短信 senderid: 国内短信填空,默认未开通,如需开通请联系 [sms helper] */
// String senderid = "";
// req.setSenderId(senderid);
/* 用户的 session 内容: 可以携带用户侧 ID 等上下文信息,server 会原样返回 */
// String session = "xxx";
// req.setSessionContext(session);
/* 短信码号扩展号: 默认未开通,如需开通请联系 [sms helper] */
// String extendcode = "xxx";
// req.setExtendCode(extendcode);
/* 模板 ID: 必须填写已审核通过的模板 ID。模板ID可登录 [短信控制台] 查看 */
String templateID = Constants.templateId;
req.setTemplateID(templateID);
/* 下发手机号码,采用 e.164 标准,+[国家或地区码][手机号]
* 示例如:+8613711112222, 其中前面有一个+号 ,86为国家码,13711112222为手机号,最多不要超过200个手机号*/
String[] phoneNumbers = {"+86"+phone};
req.setPhoneNumberSet(phoneNumbers);
/* 模板参数: 若无模板参数,则设置为空*/
String[] templateParams = {code,"5".toString()};
req.setTemplateParamSet(templateParams);
/* 通过 client 对象调用 SendSms 方法发起请求。注意请求方法名与请求对象是对应的
* 返回的 res 是一个 SendSmsResponse 类的实例,与请求对象对应 */
SendSmsResponse res = client.SendSms(req);
// 输出json格式的字符串回包
// System.out.println(SendSmsResponse.toJsonString(res));
// 也可以取出单个值,你可以通过官网接口文档或跳转到response对象的定义处查看返回字段的定义
// System.out.println(res.getRequestId());
returString=res.getSendStatusSet();
if(!StringUtils.isEmpty(returString)){
return true;
}else{
return false;
}
} catch (TencentCloudSDKException e) {
e.printStackTrace();
return false;
}
}
} }
package com.atguigu.yygh.msm.utils;
/**
* 腾讯云短信服务参数的常量类
*/
public class Constants {
//腾讯云账户密钥对: SecretID
public static final String SecretID = "AKIDAC3ey1nIWT9YhY8RVIo42kBLDp9CyUif";
//腾讯云账户密钥对: SecretKey
public static final String SecretKey = "h7G8j36sNbYEdka9RRAcnNgiTxA5k7D2";
//SdkAppid
public static final String SdkAppid = "1400597291";
//signName :签名
public static final String signName = "全栈开发那些事公众号";
//短信模板id:
public static final String templateId ="1200980";
public static String voicode="";
}
package com.atguigu.yygh.msm.utils;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
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");
public static String getFourBitRandom() {
return fourdf.format(random.nextInt(10000));
}
public static String getSixBitRandom() {
return sixdf.format(random.nextInt(1000000));
}
/**
* 给定数组,抽取n个数据
*
* @param list
* @param n
* @return
*/
public static ArrayList getRandom(List list, int n) {
Random random = new Random();
HashMap<Object, Object> hashMap = new HashMap<Object, Object>();
// 生成随机数字并存入HashMap
for (int i = 0; i < list.size(); i++) {
int number = random.nextInt(100) + 1;
hashMap.put(number, i);
}
// 从HashMap导入数组
Object[] robjs = hashMap.values().toArray();
ArrayList r = new ArrayList();
// 遍历数组并打印数据
for (int i = 0; i < n; i++) {
r.add(list.get((int) robjs[i]));
System.out.print(list.get((int) robjs[i]) + "\t");
}
System.out.print("\n");
return r;
}
}
...@@ -7,7 +7,7 @@ spring.application.name=service-msm ...@@ -7,7 +7,7 @@ spring.application.name=service-msm
spring.jackson.date-format=yyyy-MM-dd HH:mm:ss spring.jackson.date-format=yyyy-MM-dd HH:mm:ss
spring.jackson.time-zone=GMT+8 spring.jackson.time-zone=GMT+8
spring.redis.host=192.168.44.165 spring.redis.host=192.168.159.33
spring.redis.port=6379 spring.redis.port=6379
spring.redis.database= 0 spring.redis.database= 0
spring.redis.timeout=1800000 spring.redis.timeout=1800000
...@@ -21,5 +21,5 @@ spring.redis.lettuce.pool.min-idle=0 ...@@ -21,5 +21,5 @@ spring.redis.lettuce.pool.min-idle=0
spring.cloud.nacos.discovery.server-addr=127.0.0.1:8848 spring.cloud.nacos.discovery.server-addr=127.0.0.1:8848
aliyun.sms.regionId=default aliyun.sms.regionId=default
aliyun.sms.accessKeyId=LT6I0Y5633pX89qC aliyun.sms.accessKeyId=LTAI4G4SV6WtST7UYH776b64
aliyun.sms.secret=jX8D04Dm12I3gGKj345FYSzu0fq8mT aliyun.sms.secret=X9KHNYgztNr9MI5Zp8JffQPZO4uJo5
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册