1.導入阿里短信服務sdk
<dependency> <groupId>com.aliyun</groupId> <artifactId>aliyun-java-sdk-core</artifactId> <version>3.3.1</version> </dependency> <dependency> <groupId>com.aliyun</groupId> <artifactId>aliyun-java-sdk-dysmsapi</artifactId> <version>1.0.0</version> </dependency>
2.yml配置阿里服務的一些信息
sms:
accessId: 填自己真實的配置
accessKey: 填自己真實的配置
signName: 填自己真實的配置
codeTemplate: 填自己真實的配置
product: Dysmsapi
domain: dysmsapi.aliyuncs.com
3.整合SmsService
import com.alibaba.fastjson.JSONObject; import com.aliyuncs.DefaultAcsClient; import com.aliyuncs.IAcsClient; import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest; import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse; import com.aliyuncs.exceptions.ClientException; import com.aliyuncs.http.MethodType; import com.aliyuncs.profile.DefaultProfile; import com.aliyuncs.profile.IClientProfile; import com.ijuvenile.utils.redis.RedisService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; import java.util.Random; import java.util.UUID; @Service public class SmsService { @Value("${sms.accessId}") private String accessId; @Value("${sms.accessKey}") private String accessKey; @Value("${sms.signName}") private String signName; @Value("${sms.codeTemplate}") private String codeTemplate; @Value("${sms.product}") private String product; //短信API產品名稱(短信產品名固定,無需修改) @Value("${sms.domain}") private String domain; //dysmsapi.aliyuncs.com @Autowired private RedisService redisService;(有問題私聊我) /** * 根據用戶輸入的phone發送驗證碼 * @param phone 電話號碼 */ public void sendSmsCode(String phone){ if(!phone.matches("^1[3|4|5|7|8][0-9]{9}$")){ System.out.println("手機號碼格式不正確"); return; } //判斷用戶輸入的電話號碼是否頻繁發送 if(isSendOfen(phone)){ System.out.println("發送短信頻繁,請稍后再試"); return; } Sms sms = makeCode(phone); //制作驗證碼,6位隨機數字 JSONObject smsJson=new JSONObject(); smsJson.put("code",sms.getCode()); smsJson.put("product","Dysmsapi"); SendSmsResponse sendSmsResponse=null; try { sendSmsResponse = send(phone,signName,codeTemplate,smsJson); } catch (ClientException e) { e.printStackTrace(); System.out.println("短信驗證碼發送失敗"); return; } if(sendSmsResponse.getCode() != null && sendSmsResponse.getCode().equals("OK")) { //短信發送成功,將短信記錄到redis中 redisCode(sms); System.out.println("短信發送成功"); } } //將驗證碼緩存到redis中,10分鍾過后自動清除該緩存 private void redisCode(Sms sms) { redisService.set(sms.getPhone(),10L,sms); } //隨機生成6位數的短信碼 private Sms makeCode(String phone) { Random random = new Random(); StringBuilder code = new StringBuilder(); for(int i=0;i<6;i++){ int next =random.nextInt(10); code.append(next); } return new Sms(phone,code.toString(),System.currentTimeMillis()); } //判斷驗證功發送時候頻繁 private boolean isSendOfen(String phone) { if(redisService.get(phone)==null) { return false; }else{ //判斷上一次記錄的時間和當前時間進行對比,如果兩次相隔時間小於120s,視為短信發送頻繁 Sms sms=redisService.get(phone,Sms.class); //兩次發送短信中間至少有2分鍾的間隔時間 if(sms.getTime()+120*1000>=System.currentTimeMillis()) { return true; } return false; } } /** * 驗證短信 * @param phone * @param code * @return */ public boolean validSmsCode(String phone, String code){ //取出所有有關該手機號的短信驗證碼 if(redisService.get(phone)==null){ System.out.println("短信驗證失敗"); return false; } Sms sms=redisService.get(phone,Sms.class); if (sms.getCode().equals(code)){ System.out.println("短信驗證成功"); //刪除掉該redis redisService.delete(phone); return true; } return false; } /** * 發信 * @param phone * @param signName * @param templateCode * @param params * @return * @throws ClientException */ SendSmsResponse send(String phone, String signName, String templateCode, JSONObject params) throws ClientException { //初始化ascClient,暫時不支持多region(請勿修改) IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessId, accessKey); DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", product, domain); IAcsClient acsClient = new DefaultAcsClient(profile); //組裝請求對象 SendSmsRequest request = new SendSmsRequest(); //使用post提交 request.setMethod(MethodType.POST); //必填:待發送手機號。支持以逗號分隔的形式進行批量調用,批量上限為1000個手機號碼,批量調用相對於單條調用及時性稍有延遲,驗證碼類型的短信推薦使用單條調用的方式 request.setPhoneNumbers(phone); //必填:短信簽名-可在短信控制台中找到 request.setSignName(signName); //必填:短信模板-可在短信控制台中找到 request.setTemplateCode(templateCode); //可選:模板中的變量替換JSON串,如模板內容為"親愛的${name},您的驗證碼為${code}"時,此處的值為 //友情提示:如果JSON中需要帶換行符,請參照標准的JSON協議對換行符的要求,比如短信內容中包含\r\n的情況在JSON中需要表示成\\r\\n,否則會導致JSON在服務端解析失敗 request.setTemplateParam(params.toJSONString()); request.setOutId(UUID.randomUUID().toString()); //請求失敗這里會拋ClientException異常 return acsClient.getAcsResponse(request); } }
4.sMs.java
public class Sms { private String phone; //電話號碼 private String code; //短信驗證碼 private Long time; //短信驗證碼生成時間 public Sms() { } public Sms(String phone, String code, Long time) { this.phone = phone; this.code = code; this.time = time; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } public String getCode() { return code; } public void setCode(String code) { this.code = code; } public Long getTime() { return time; } public void setTime(Long time) { this.time = time; } }
轉:https://blog.csdn.net/qq_38662806/article/details/79615408