请求第三方阿里发送验证码
生活随笔
收集整理的這篇文章主要介紹了
请求第三方阿里发送验证码
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
第一步,發送驗證碼
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()); //短信模板coderequest.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;}第二步,校驗驗證碼是否正確
/*** 發送短信驗證碼* 實現:發送完成短信驗證碼后,需要將驗證碼保存到redis中* @param phone* @return*/public ErrorResult sendCheckCode(String phone) {//把手機號為key,code為值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);String code="123456";//判斷驗證碼是否發送成功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;}編寫配置類
import lombok.Data; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.PropertySource;@Data @Configuration @PropertySource("aliyun.properties")//加載指定的配置文件 @ConfigurationProperties(prefix = "aliyun.sms")//加載配置文件以aliyun.sms開頭的 public class AliyunSMSConfig {private String regionId;private String accessKeyId;private String accessKeySecret;private String domain;private String signName;private String templateCode; }配置文件
```xml aliyun.sms.regionId = cn-hangzhou aliyun.sms.accessKeyId = LTAI5tCix6mvUNvDWFYe9waGaliyun.sms.accessKeySecret = 0EUNiz7mCWnVpatLi5QMopPvfAG9lqaliyun.sms.domain= dysmsapi.aliyuncs.com aliyun.sms.signName= 聚賢莊aliyun.sms.templateCode= SMS_208640690總結
以上是生活随笔為你收集整理的请求第三方阿里发送验证码的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 实现一个C语言版本的圣诞树(附源代码)
- 下一篇: PCI Express 协议基础