短信验证码接入分前端和后端,具体代码如下
前端代码
<html>
<head>
<meta charset="utf-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=0">
<!-- 国内使用 -->
<link rel="stylesheet" href="https://cdn.staticfile.org/amazeui/2.7.2/css/amazeui.min.css">
<script type="text/javascript" charset="utf-8" src="https://cdn.staticfile.org/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript" charset="utf-8" src="https://g.alicdn.com/sd/nch5/index.js?t=2015052012"></script>
<!-- 若您的主要用户来源于海外,请替换使用下面的js资源 -->
<!-- <script type="text/javascript" charset="utf-8" src="//aeis.alicdn.com/sd/nch5/index.js?t=2015052012"></script> -->
<style>
.am-form{
padding: 10px;
}
._nc .stage1 .slider{
left: 0;
right: 0;
}
</style>
</head>
<body>
<div class="am-form">
<div class="am-form-group">
<label for="tel">请输入手机号</label>
<input type="text" class="" id="tel" placeholder="请输入手机号">
</div>
<div id="__nc" style="height: 70px">
<div id="nc"></div>
</div>
<div class="am-form-group">
<label for="code">请输入验证码</label>
<input id="code" type="text" placeholder="请输入验证码">
</div>
<button type="button" class="am-btn am-btn-primary">提交</button>
</div>
<script>
var nc_token = ["CF_APP_1", (new Date()).getTime(), Math.random()].join(':');
var nc=NoCaptcha.init({
renderTo: '#nc',
appkey: 'CF_APP_1',
scene: 'register',
token: nc_token,
trans: {"key1": "code200"},
elementID: ["usernameID"],
is_Opt: 0,
language: "cn",
timeout: 10000,
retryTimes: 5,
errorTimes: 5,
inline:false,
apimap: {
// 'analyze': '//a.com/nocaptcha/analyze.jsonp',
// 'uab_Url': '//aeu.alicdn.com/js/uac/909.js',
},
bannerHidden:false,
initHidden:false,
callback: function (data) {
window.console && console.log(nc_token)
window.console && console.log(data.csessionid)
window.console && console.log(data.sig);
var tel = $('#tel').val();
$.ajax({
url: "sendCode",
type: "post",
data: {
tel:tel
},
dataType: "json",
success: function (result) {
if (result.code == 0) {
alert("验证码已发送!", "green")
} else {
alert("发送失败,请稍后再试!");
nc.reset()
}
},
error: function () {
alert("系统繁忙,请稍后再试!", "red")
}
})
},
error: function (s) {
}
});
NoCaptcha.setEnabled(true);
nc.reset();//请务必确保这里调用一次reset()方法
NoCaptcha.upLang('cn', {
'LOADING':"加载中...",//加载
'SLIDER_LABEL': "请向右滑动验证",//等待滑动
'CHECK_Y':"验证通过",//通过
'ERROR_TITLE':"非常抱歉,这出错了...",//拦截
'CHECK_N':"验证未通过", //准备唤醒二次验证
'OVERLAY_INFORM':"经检测你当前操作环境存在风险,请输入验证码",//二次验证
'TIPS_TITLE':"验证码错误,请重新输入"//验证码输错时的提示
});
</script>
</body>
</html>
给再次获取验证码按钮加一个倒计时
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>获取验证码</title>
<script src="http://hovertree.com/ziyuan/jquery/jquery-1.12.1.min.js"></script>
<script type="text/javascript">
var countdown=60;
function send(){
var obj = $("#btn");
settime(obj);
}
function settime(obj) { //发送验证码倒计时
if (countdown == 0) {
obj.attr('disabled',false);
obj.val("获取验证码");
$("#btn").css("background","#00bc12")
countdown = 60;
return;
} else {
obj.attr('disabled',true);
obj.val("(" + countdown + ")S");
countdown--;
$("#btn").css("background","#ccc")
}
setTimeout(function() {
settime(obj) }
,1000)
}
</script>
<style>
#btn{
width: 180px;
height: 56px;
line-height: 56px;
text-align: center;
background: #00BC12;
border-radius: 8px;
font-size: 22px;
border: 0;
background: #00bc12;
color: #fff;
}
</style>
<body>
<input type="button" id="btn" value="获取验证码" onclick="send()" />
</body>
</html>
后端代码
HttpSession session = req.getSession();
// TODO 验证码有效时间
session.setMaxInactiveInterval(600);
try {
Integer num = RandNumber.getNum();
// TODO 发送验证码通道
Sendsms.Send(num, phone);
session.setAttribute(phone, num);
return R.ok();
} catch (Exception e) {
e.printStackTrace();
logger.error(e.getMessage());
return R.error("fasle");
}
import java.io.Exception;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;
public class Sendsms {
private static String Url = "https://vip.veesing.com/smsApi/verifyCode";
// 发送短信验证码
public static void Send(Integer num, String mobile) {
try {
HttpClient client = new HttpClient();
PostMethod method = new PostMethod(Url);
client.getParams().setContentCharset("UTF-8");
method.setRequestHeader("ContentType", "application/x-www-form-urlencoded;charset=UTF-8");
NameValuePair[] data = {
new NameValuePair("appId", "*********"),
new NameValuePair("appKey", "**********"),
new NameValuePair("templateId", "*******"),
new NameValuePair("mobile", "*******"),
new NameValuePair("variables", "*******")
};
method.setRequestBody(data);
client.executeMethod(method);
String submitResult = method.getResponseBodyAsString();
System.out.println(submitResult);
} catch (Exception e) {
e.printStackTrace();
}
}
}
HttpSession session = req.getSession();
String yzm = String.valueOf(session.getAttribute(username));
logger.info(yzm);
if (yzm == null) {
return R.error("验证码错误");
}
if (yzm != null && !verifycode.equals(yzm)) {
return R.error("验证码错误");
}
短信验证码demo
package com.veesing.test;
import java.io.IOException;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;
import com.alibaba.fastjson.JSONObject;
import com.veesing.utils.Config;
/**
* 短信验证码
* @author MWH
*
*/
public class SmsCodeTest {
public static void main(String[] args) {
// 获取连接
HttpClient client = new HttpClient();
// 短信验证码API接口地址
PostMethod method = new PostMethod("https://vip.veesing.com/smsApi/verifyCode");
// 设置编码
client.getParams().setContentCharset("UTF-8");
method.setRequestHeader("ContentType", "application/x-www-form-urlencoded;charset=utf-8");
// 手机号码,一次只能提交一个手机号码
String phone = "15080929435";
//模板ID(如没有模板ID请先在平台上新增并提交验证码模板,审核通过即可使用)
String templateId = "36";
// 验证码变量(随机数)
Integer num = (int)((Math.random()*9+1)*1000);
String variables = num.toString();
System.out.println("验证码是:"+variables);
// 拼接参数
NameValuePair[] data = {
new NameValuePair("appId", Config.appid),
new NameValuePair("appKey", Config.appkey),
new NameValuePair("phone", phone),
new NameValuePair("templateId", templateId),
new NameValuePair("variables", variables) };
method.setRequestBody(data);
try {
client.executeMethod(method);
String result = method.getResponseBodyAsString();
// 返回结果
System.out.println(result);
JSONObject jsonObject = JSONObject.parseObject(result);
// 返回2000则发送成功(逻辑操作请根据接口文档返回参数自行判断)
if (jsonObject.get("returnStatus").equals("2000")) {
System.out.println("成功!");
} else {
System.out.println("失败!");
}
// 释放连接
method.setRequestHeader("Connection", "close");
method.releaseConnection();
} catch (HttpException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
这里是举例的一个短信验证码平台,不同的短信平台有些不同,可一般都大同小异。
本文演示短信验证码接口地址:https://www.veesing.com/apidocs.html