
2021-11-02
338

原创
阿里云短信服务
今天在做项目的时候用到了阿里云的短信服务,我9月份的时候就在申请短信服务,阿里云一直不给我通过,原来发现必须要有上线的项目和应用场景,阿里才给你通过,正好我这个上线了这个博客项目,所有阿里云就给我通过了,我还是很激动的啊,马上用到项目中去
1.申请签名和模板
现在好像比较难申请,必须要有上线的项目,这里我申请了几次才申请好
2.maven引入相关依赖
<dependencies>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
</dependency>
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>aliyun-java-sdk-core</artifactId>
</dependency>
</dependencies>
fastjson是用来做json转换的
3.具体实现方法
public boolean send(Map<String, Object> param, String phone) {
//如果手机号输入为空,直接返回
if (StringUtils.isEmpty(phone)){
return false;
}
//一些相关配置
//accessKeyId和keysecret写自己的
DefaultProfile profile = DefaultProfile.getProfile("default","accessKeyId","keysecret");
IAcsClient client = new DefaultAcsClient(profile);
//设置参数
//固定写法
CommonRequest request = new CommonRequest();
request.setSysMethod(MethodType.POST);
request.setSysDomain("dysmsapi.aliyuncs.com");
request.setSysVersion("2017-05-25");
request.setSysAction("SendSms");
//设置发送相关的参数
request.putQueryParameter("PhoneNumbers",phone);//发送的手机号
//这个是申请号的签名
request.putQueryParameter("SignName","lbq的笔记");
//申请好的模板code
request.putQueryParameter("TemplateCode","SMS_226785978");
request.putQueryParameter("TemplateParam", JSONObject.toJSONString(param));
//最终的发送
try {
CommonResponse response = client.getCommonResponse(request);
boolean success = response.getHttpResponse().isSuccess();
return success;
}catch (Exception e){
e.printStackTrace();
return false;
}
}
4.在接口里用redis设置有效时间
完整代码
//发送短信
@GetMapping("send/{phone}")
public R sendMsm(@PathVariable String phone){
//先从redis中获取验证码,如果获取到直接返回,防止重复发送
String code = redisTemplate.opsForValue().get(phone);
if (!StringUtils.isEmpty(code)){
return R.ok();
}
//生成随机数,传递阿里云进行发送
code = RandomUtil.getFourBitRandom();
Map<String,Object> param = new HashMap<>();
param.put("code",code);
//调用service发送短信
boolean isSend = msmService.send(param,phone);
if (isSend) {
//发送成功,把发送成功验证码放到redis里面
//设置有效时间
redisTemplate.opsForValue().set(phone,code,5, TimeUnit.MINUTES);
return R.ok();
}else{
return R.error().message("短信发送失败");
}
}
5.测试成功
Java