我们在做项目中,经常遇见接入一下第三方接口的场景,比如手机号码归属地查询、天气预报、二维码生成、货币汇率、短信验证码以及邮编查询等各种api接口,其中短信验证码是每个项目中几乎是必备的一个第三方接口。
接入验证码分为前端和后端,这里都给列出详细的代码
前端代码
<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>
后端代码
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("验证码错误");
}
真正意义上的能调用是需要获取短信平台的appId和appKey ,如下所示,当然不同平台的appId和appKey的获取方式不同,大家可以随机应变。
验证码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();
}
}
}
验证码选择很重要,选择合适的短信平台不仅可以给项目加分,更能给用户更好的体验,可以用作验证码注册、短信提醒通知,开通服务通知以及扣款通知等场景。