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等等,查了半天資料,發現是自己搭建的環境有些問題。
如果這篇博客還有其他問題,歡迎評論指正!