使用aliyun的短信发送服务
用户登录名称 sms-127@1286242113840900.onaliyun.com
AccessKey ID LTAI5t6jFYKGyZp529NCVV9d
AccessKey Secret hYXc4KtpFiHELEmU5yuLCfstZM7zhS
签名 : XXX
模版CODE : SMS_186613739
配置文件 aliyun.properties
aliyun.sms.regionId=sms-127@1286242113840900.onaliyun.com
aliyun.sms.accessKeyId=LTAI5t6jFYKGyZp529NCVV9d
aliyun.sms.accessKeySecret=hYXc4KtpFiHELEmU5yuLCfstZM7zhS
aliyun.sms.domain=dysmsapi.aliyuncs.com
aliyun.sms.signName=XXX
aliyun.sms.templateCode=SMS_186613739
注意:等号前后不要留有空格。否则签名部分会出错。
在service层处理短信阿里发送业务,通过这个方法实现短信发送到指定手机号码,并且生成随机验证码code返回
/**
* 发送短信验证码
* @param mobile
* @return 返回发送验证的结果
*/
public String sendSms(String mobile) {
DefaultProfile profile = DefaultProfile.getProfile(this.aliyunSMSConfig.getRegionId(),
this.aliyunSMSConfig.getAccessKeyId(), this.aliyunSMSConfig.getAccessKeySecret());
IAcsClient client = new DefaultAcsClient(profile);
String code = RandomUtils.nextInt(100000, 999999) + "";
CommonRequest request = new CommonRequest();
request.setSysMethod(MethodType.POST);
request.setSysDomain(this.aliyunSMSConfig.getDomain());
request.setSysVersion("2017-05-25");
request.setSysAction("SendSms");
request.putQueryParameter("RegionId", this.aliyunSMSConfig.getRegionId());
request.putQueryParameter("PhoneNumbers", mobile); //目标手机号
request.putQueryParameter("SignName", this.aliyunSMSConfig.getSignName()); //签名名称
request.putQueryParameter("TemplateCode", this.aliyunSMSConfig.getTemplateCode()); //短信模板code
request.putQueryParameter("TemplateParam", "{\"code\":\"" + code + "\"}");//模板中变量替换
try {
CommonResponse response = client.getCommonResponse(request);
String data = response.getData();
if (StringUtils.contains(data, "\"Message\":\"OK\"")) {
return code;
}
log.info("发送短信验证码失败~ data = " + data);
} catch (Exception e) {
log.error("发送短信验证码失败~ mobile = " + mobile, e);
}
return null;
}
根据接口和客户端请求参数类型编写controller层
POST请求路径:/user/login
返回请求参数类型JSON格式
{
"phone": "接受验证码手机号码"
}
@Autowired
private SmsService smsService;
/**
* 发送短信验证码接口
* @param param
* @return 返回由spring封装好的ResponseEntity对象
*/
@PostMapping("login")
public ResponseEntity<ErrorResult> sendCheckCode(@RequestBody Map<String , String> param) {
ErrorResult errorResult = null;
//获取手机号码
String phone = param.get("phone");
//调用service层的发送验证码方法获取发送验证码的状态
try{
errorResult= this.smsService.sendCheckCode(phone);
if (null == errorResult) {
//发送验证成功
return ResponseEntity.ok(null);
}
} catch (Exception e) {
log.error("发送验证码失败 phone=" + phone,e);
errorResult = ErrorResult.builder().errCode("000002").errMessage("短信验证码发送失败!").build();
}
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(errorResult);
}
编写service层的sendCheckCode方法,发送验证码
/**
* 发送短信验证码
* 实现业务:调用sendSms方法获取随机验证码,存放在redis中,有效期为5分钟
* @param phone
* @return
*/
public ErrorResult sendCheckCode(String phone) {
String redisKey = "CHECK_CODE_" + phone;
//判断验证码是否失效
if (this.redisTemplate.hasKey(redisKey)) {
String msg = "上次发送的验证码还未失效,请稍后再试!";
return ErrorResult.builder().errCode("000001").errMessage(msg).build();
}
//获取验证码
String code = this.sendSms(phone);
//判断验证码是否为空
if (StringUtils.isEmpty(code)) {
String msg = "发送短信验证码失败";
return ErrorResult.builder().errCode("000000").errMessage(msg).build();
}
//短信发送成功,将验证码存放在redis,有效期为5分钟
this.redisTemplate.opsForValue().set(redisKey,code,Duration.ofMinutes(5));
return null;
}