記錄SpringBoot專案接入使用阿里雲簡訊驗證碼服務
1. 註冊阿里雲賬號,並實名認證
2. 建立AccessKey,用小本本記下AccessKey ID和AccessKey Secret,它們是你訪問阿里雲 API 的金鑰,具有該賬戶完全的許可權
3. 訪問阿里雲簡訊服務
3.1 連結:https://www.aliyun.com/product/sms?spm=5176.19720258.J_9220772140.58.15e32c4a5yRc1L
3.2 選擇想要開通的簡訊套餐,當然也可以先免費試用
3.2 在免費試用列表找到 [簡訊免費使用套餐包]
3.4 選擇0元試用,訂單支付完畢後,訪問簡訊服務控制檯
3.5 配置簡訊簽名和模板,簽名是指簡訊內容前使用“【】”的內容,而模板是指具體內容,程式碼中需要用到的是簽名和模板CODE,模板中的${code}表示需要填充的驗證碼。填寫完畢提交稽核,快的話1-2個小時。
3.6 接著可以開啟OpenAPI看使用示例,需要替換的引數有:手機號碼、簽名、模板、驗證碼。
4. 專案中使用
4.1在pom.xml中加入依賴:
1 <dependency> 2 <groupId>com.aliyun</groupId> 3 <artifactId>aliyun-java-sdk-core</artifactId> 4<version>4.5.3</version> 5 </dependency>
4.2 新建類:SendSms.java
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.zxin.dev.pojo.Constant;
public class SendSms {
public static void send(String signName, String templateCode, String phone, String code) {
// 填寫自己阿里雲賬號的AccessKey ID和AccessKey Secret, regionId為cn-hangzhou
DefaultProfile profile = DefaultProfile.getProfile(Constant.REGION_ID, Constant.ACCESS_KEY_ID, Constant.ACCESS_SECRET);
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("RegionId", "cn-hangzhou");
// 根據需求替換引數
// 簡訊簽名
request.putQueryParameter("SignName", signName);
// 簡訊模板ID
request.putQueryParameter("TemplateCode", templateCode);
// 目標手機號
request.putQueryParameter("PhoneNumbers", phone);
// 驗證碼
request.putQueryParameter("TemplateParam", "{\"code\":"+code+"}");
try {
CommonResponse response = client.getCommonResponse(request);
System.out.println(response.getData());
} catch (ServerException e) {
e.printStackTrace();
} catch (ClientException e) {
e.printStackTrace();
}
}
}
4.3 前端 (vue) 傳送驗證碼和提交表單函式
1 handleSendVerifyCode() { 2 const data = { 3 phone: this.user.phone, 4 purpose: 'register' 5 } 6 sendVerifyCode(data).then(res => { 7 this.$message({ 8 type: 'success', 9 message: res.message 10 }) 11 }) 12 }, 13 handleSubmit() { 14 this.loading = true 15 const data = { 16 name: this.user.name, 17 phone: this.user.phone, 18 verifyCode: this.user.verifyCode 19 } 20 register(data).then(res => { 21 this.loading = false 22 this.drawerVisibleUserRegister = false 23 this.$message({ 24 type: 'success', 25 message: res.message 26 }) 27 }) 28 }
4.4 新建靜態常量類(非必需),根據自己需求:
4.5 寫傳送驗證碼介面和驗證註冊資訊的介面
1 @PostMapping("sendVerifyCode") 2 public JSONObject sendVerifyCode(HttpServletRequest request, @RequestBody Map<String, String> params) { 3 JSONObject resultJson = new JSONObject(); 4 // 自己寫的生成6位隨機數字字元的方法(注意: 驗證碼雖然是字串,但首位也不能為0,否則發出的是5位數。) 5 String verifyCode = StringUtil.getRandom(6); 6 7 // 在不同的表單傳送驗證碼,使用不同的簡訊模板 8 switch (params.get("purpose")){ 9 // 註冊 10 case "register" : 11 SendSms.send(Constant.SIGE_NAME,Constant.TEMPLATE_CODE_REGISTER,params.get("phone"),verifyCode); 12 break; 13 // 修改密碼 14 case "changePassword": 15 SendSms.send(Constant.SIGE_NAME,Constant.TEMPLATE_CODE_CHANGE_PASSWORD,params.get("phone"),verifyCode); 16 break; 17 } 18 JSONObject jsonCode = new JSONObject(); 19 jsonCode.put("phone", params.get("phone")); 20 jsonCode.put("verifyCode", verifyCode); 21 jsonCode.put("createTime", System.currentTimeMillis()); 22 request.getSession().setAttribute("verifyCode", jsonCode); 23 resultJson.put("code", 20000); 24 resultJson.put("message", "簡訊驗證碼傳送成功"); 25 return resultJson; 26 }
1 @PostMapping("register") 2 public JSONObject register(HttpSession session, @RequestBody Map<String, String> params) { 3 String name = params.get("name"); 4 String phone = params.get("phone"); 5 String verifyCode = params.get("verifyCode"); 6 JSONObject resultJson = new JSONObject(); 7 JSONObject sessionVerifyCode = (JSONObject)session.getAttribute("verifyCode"); 8 if (phone.equals(sessionVerifyCode.get("phone")) && verifyCode.equals(sessionVerifyCode.get("verifyCode"))){ 9 resultJson.put("code", 20000); 10 resultJson.put("message", "註冊成功"); 11 }else{ 12 // TODO: 13 resultJson.put("code", 300); 14 resultJson.put("message", "註冊失敗,驗證碼不正確"); 15 } 16 return resultJson; 17 }
5. 結果展示
5.1 傳送驗證碼(還需要設定超時時間,1分鐘內不可重複點選)
5.2 手機收到簡訊
5.3 校驗通過
最後:這個示例中還有很多需要改進的,但作為學習接入阿里雲簡訊服務的demo已經足夠了,其中還有許多小問題,比如getSession = null等等,查了半天資料,發現是自己搭建的環境有些問題。
如果這篇部落格還有其他問題,歡迎評論指正!