------------恢復內容開始------------
短信服務是很多項目在登錄注冊時使用的接口,本博客記錄我在項目中簡單實現的短信驗證.
一.注冊阿里雲短信服務https://helpcdn.aliyun.com/product/44282.html
1.這一步官方教程很詳細,按照快速學習逐步完成就可;值得注意的是AccessKey ID 和 AccessKeySecretz在創建用戶時會顯示.注意保存調用接口時需要.
2.申請模板和簽名,使用阿里雲提供例子的模板簽名可以更快通過審核,大概1小時就可以.
二.demo實現
1,官方的demo案例,發送成功證明接口成功調用;
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; /* 添加依賴 pom.xml <dependency> <groupId>com.aliyun</groupId> <artifactId>aliyun-java-sdk-core</artifactId> <version>4.0.3</version> </dependency> */ public class SendSms { public static void main(String[] args) { DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", "添加你的accessKeyId", "添加你的accessSecret"); IAcsClient client = new DefaultAcsClient(profile); String scode = String.valueOf(new Random().nextInt(899999) + 100000);//生成驗證碼 CommonRequest request = new CommonRequest(); request.setMethod(MethodType.POST); request.setDomain("dysmsapi.aliyuncs.com"); request.setVersion("2017-05-25"); request.setAction("SendSms"); request.putQueryParameter("RegionId", "cn-hangzhou"); request.putQueryParameter("PhoneNumbers", "15866668888");//發送到的手機號 request.putQueryParameter("SignName", "尋趣網");//申請的模板 request.putQueryParameter("TemplateCode", "SMS_175584853");//申請的模板
request.putQueryParameter("TemplateParam", "{\"scode\":\""+scode+"[有效期5分鍾]"+"\"}"); try { CommonResponse response = client.getCommonResponse(request); System.out.println(response.getData()); } catch (ServerException e) { e.printStackTrace(); } catch (ClientException e) { e.printStackTrace(); } } }
2.自己寫的從發送到驗證簡單demo
1.controller (pom依賴就是上面注釋部分)
/*獲取驗證碼controller*/ @PostMapping("/getcode") @ResponseBody public String getcode(String phone) { if (chackphone.chackphone(phone)) { String scode = String.valueOf(new Random().nextInt(899999) + 100000); String smsId="SMS_175584853"; DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", "LTAI4FasdfVpCiXfasyyyyyyydfwsBZ", "Y7Qdsf2zayyyyyyysdfaTCzVS2Vpa"); IAcsClient client = new DefaultAcsClient(profile); CommonRequest request = new CommonRequest(); request.setMethod(MethodType.POST); request.setDomain("dysmsapi.aliyuncs.com"); request.setVersion("2017-05-25"); request.setAction("SendSms"); request.putQueryParameter("RegionId", "cn-hangzhou"); request.putQueryParameter("SignName", "尋趣網"); request.putQueryParameter("PhoneNumbers", ""+phone+""); request.putQueryParameter("TemplateCode", ""+smsId+""); request.putQueryParameter("TemplateParam", "{\"scode\":\""+scode+"[有效期5分鍾]"+"\"}"); try { CommonResponse response = client.getCommonResponse(request); System.out.println(response.getData()); } catch (ClientException e) { e.printStackTrace(); }*/ System.out.println(phone); System.out.println(scode); return scode; } else { return "0"; } } }
2.手機號驗證util
/** * @author kpzc * 三大運營商號碼均可驗證(不含衛星通信1349) */ public class chackphone { public static boolean chackphone(String phone) { String regex = "^((13[0-9])|(14[5|7])|(15([0-3]|[5-9]))|(17[013678])|(18[0,5-9]))\\d{8}$"; if (phone.length() != 11) { return false; } else { Pattern p = Pattern.compile(regex); Matcher m = p.matcher(phone); boolean isMatch = m.matches(); if (isMatch) { return true; } else { return false; } } } }
3.登錄頁面
<!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>登錄</title> <meta name="Keywords" content="尋趣"> <meta name="Description" content="尋趣這里更懂你"> <link th:href="@{/css/base.css}" rel="stylesheet"> <link th:href="@{/css/iconfont.css}" rel="stylesheet"> <link th:href="@{/css/reg.css}" rel="stylesheet"> <script th:inline="javascript"> var base = [[${#request.getContextPath()}]]; </script> </head> <body> <div id="ajax-hook"> </div> <div class="wrap" style="background-image:url(img/background.jpg);" > <div class="wpn"> <div class="form-data pos"> <a ><img th:src="@{img/logo.png}" class="head-logo"></a> <div class="change-login"> <p class="account_number on"> 賬號登錄 </p> <p class="message"> 短信登錄 </p> </div> <div class="form1"> <p class="p-input pos"> <label for="username" style="">手機號/用戶名/UID/郵箱</label> <input type="text" id="username"> <span class="tel-warn num-err hide"><em>賬號或密碼錯誤,請重新輸入</em><i class="icon-warn"></i></span> </p> <p class="p-input pos"> <label for="password" style="">請輸入密碼</label> <input type="password" style="display:none"> <input type="password" id="password" autocomplete="new-password"> <span class="tel-warn pass-err hide"><em>賬號或密碼錯誤,請重新輸入</em><i class="icon-warn"></i></span> </p> <!-- <p class="p-input pos code hide"> <label for="veri">請輸入驗證碼</label> <input type="text" id="veri"> <img src="index.html"> <span class="tel-warn img-err hide"><em>賬號或密碼錯誤,請重新輸入</em><i class="icon-warn"></i></span> <!– <a href="javascript:;">換一換</a> –> </p>--> <button id="loginButton1" type="button" class="lang-btn off log-btn" onclick="loginButton1()">登錄1 </button> </div> <div class="form2 hide"> <p class="p-input pos"> <label for="num2">手機號</label> <input type="number" id="num2" > <span class="tel-warn num2-err hide"><em>賬號或密碼錯誤</em><i class="icon-warn"></i></span> </p> <p class="p-input pos"> <label for="veri-code">輸入驗證碼</label> <!-- 發送驗證碼--> <input type="number" id="veri-code"> <a href="javascript:;" id="getcode" class="send">發送驗證碼</a> <span class="time hide"><em>120</em>s</span> <span class="tel-warn error hide">驗證碼錯誤</span> </p> <button id="loginButton2" type="button" class="lang-btn off log-btn" onclick="loginButton2()">登錄2 </button> </div> <div class="r-forget cl"> <a onclick="reg()" href="javascript:;" class="z">賬號注冊</a> <a onclick="getpass()" href="javascript:;" class="y">忘記密碼</a> </div> </br> <div class="third-party"> <a href="javascript:;" class="log-qq icon-qq-round"></a> <a href="javascript:;" class="log-qq icon-weixin"></a> <a href="javascript:;" class="log-qq icon-sina1"></a> </div> <p class="right"> Powered by © 2019 尋趣網 </p> </div> </div> </div> <script th:src="@{/js/jquery.js}"></script> <script th:src="@{/js/agree.js}"></script> <script th:src="@{/js/login.js}"></script> <script th:src="@{/js/yzm.js}"></script> </body> </html>
4.js
$(function () {
/*驗證碼發送*/
$("#getcode").click(function () {
var pNum = $("#num2").val();
$.ajax({
url: base + "/getcode",
type: "post",
data: {'phone': pNum},
dataType: "json",
success: function (data) {
if (data==0){
alert("請檢查手機號!")
return;
}else {
alert(data)
sessionStorage.setItem("scode", data);
}
}
})
});
});
function loginButton1() {
alert("登錄按鈕1")
var usm = $("#username").val()
var pass = $("#password").val()
$.ajax({
url: base + "/login1",
type: "post",
data: {'username': usm, 'password': pass},
dataType: "json",
success: function (data) {
alert(data)
if (data == 0) {
alert("登錄成功")
//$("#errorMsg1").text("成功");
// sessionStorage.setItem("userId", data.userId);
//主頁名字
location.href = base + "/index";
} else {
$("#errorMsg1").text("密碼錯誤!");
}
}
})
};
function loginButton2() {
alert("登錄按鈕2")
var a = sessionStorage.getItem("scode");
var pcode = $("#veri-code").val();
alert(a);
if (pcode == a) {
alert("驗證碼正確");
location.href = base + "/index";
} else {
alert("驗證碼有誤");
}
};
function regButton() {
alert("注冊按鈕")
var nnm = $("#nickname").val();
var tel = $("#num2").val();
var pass = $("#password").val();
var pcode = $("#veri-code").val();
var b = sessionStorage.getItem("scode");
$.ajax({
url: base + "/reg",
type: "post",
data: {'nickname': nnm, 'phone': tel, 'passsword': pass},
dataType: "json",
success: function (data) {
if (pcode == b) {
alert("驗證成功");
if(data==0){
alert("注冊成功!頁面跳轉中...");
location.href = base + "/index";
}
else alert("注冊失敗")
} else {
alert("驗證碼有誤");
}
}
})
};
function getpass() {
location.href = base + "/getpass";
};
function reg() {
location.href = base + "/reg";
};
function gologin() {
location.href = base + "/login";
};
以上就是短信驗證的一個簡單使用
ps:可能會因為缺失css有些問題 ,后續我會更新( o=^•ェ•)o ┏━┓