开发人员在开发网站注册、登录时经常需要用到短信验证码功能,下面小编就来详细介绍一下如何集成这个功能。
下面以使用榛子云短信为例:
- 首先注册一个榛子云账号,注册地址: http://sms_developer.zhenzikj.com/zhenzisms_user/register.html
- 注册完毕后从个人登录入口进入,地址:http://sms_developer.zhenzikj.com/zhenzisms_user/login.html
- 进入"应用管理",默认会自动创建一个应用,获取AppId和AppSecret,这两个参数是用于开发的。
- 下载SDK,我用的java开发,所以,下面的例子也以java为例,http://smsow.zhenzikj.com/doc/sdk.html
你可以直接下载jar包导入项目中,也可以使用maven
- 参考开发文档发送短信http://smsow.zhenzikj.com/doc/java_sdk_doc.html
AppId、AppSecret就是我们刚才从应用管理中获取的,apiUrl参数,由于我是个人账号,固定使用https://sms_developer.zhenzikj.com
注: 通过自己注册的都是个人账号,企业账号需要单独联系客服申请
使用很简单,初始化一个ZhenziSmsClient对象,然后调用send()方法发送短信
- 一个完整的例子
一个完整的java发送短信验证码的完整实例,这是一个官方的使用demo,带有60秒倒计时功能。
效果:
源码
短信验证码实现流程
1、构造手机验证码,生成一个6位的随机数字串;
2、使用接口向短信平台发送手机号和验证码,然后短信平台再把验证码发送到制定手机号上
3、将手机号验证码、操作时间存入Session中,作为后面验证使用;
4、接收用户填写的验证码、手机号及其他注册数据;
5、对比提交的验证码与Session中的验证码是否一致,同时判断提交动作是否在有效期内;
6、验证码正确且在有效期内,请求通过,处理相应的业务。
我是java开发者,后端使用了springMvc,前端用的是jsp + jquery
html
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path;
%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>验证码使用演示</title>
<link href="<%=basePath%>/css/register.css" rel="stylesheet" >
<script src="<%=basePath%>/js/jquery-2.1.1.min.js" type="text/javascript"></script>
<script src="<%=basePath%>/js/register.js" type="text/javascript"></script>
<script>
function getBasePath(){
return '<%=basePath%>';
}
</script>
</head>
<body>
<form>
<div class="row">
<label>账号: </label><input name="userId">
</div>
<div class="row">
<label>密码:</label><input name="password">
</div>
<div class="row">
<label>手机号:</label><input name="mobile">
</div>
<div class="row">
<label>验证码:</label>
<input name="verifyCode">
<button type="button" class="sendVerifyCode">获取短信验证码</button>
</div>
<div><button type="button" class="sub-btn">提交</button></div>
</form>
</body>
</html>
js
$(function(){
//短信验证码倒计时
var countdownHandler = function(){
var $button = $(".sendVerifyCode");
var number = 60;
var countdown = function(){
if (number == 0) {
$button.attr("disabled",false);
$button.html("发送验证码");
number = 60;
return;
} else {
$button.attr("disabled",true);
$button.html(number + "秒 重新发送");
number--;
}
setTimeout(countdown,1000);
}
setTimeout(countdown,1000);
}
//发送短信验证码
$(".sendVerifyCode").on("click", function(){
var $mobile = $("input[name=mobile]");
var data = {};
data.mobile = $.trim($mobile.val());
if(data.mobile == ''){
alert('请输入手机号码');
return;
}
var reg = /^1\d{10}$/;
if(!reg.test(data.mobile)){
alert('请输入合法的手机号码');
return ;
}
$.ajax({
url: getBasePath()+"/sendSms",
async : true,
type: "post",
dataType: "text",
data: data,
success: function (data) {
if(data == 'success'){
countdownHandler();
return ;
}
alert(data);
}
});
})
//提交
$(".sub-btn").on("click", function(){
var data = {};
data.userId = $.trim($("input[name=userId]").val());
data.password = $.trim($("input[name=password]").val());
data.mobile = $.trim($("input[name=mobile]").val());
data.verifyCode = $.trim($("input[name=verifyCode]").val());
if(data.userId == ''){
alert("请输入账号");
return ;
}
if(data.password == ''){
alert("请输入密码");
return ;
}
if(data.mobile == ''){
alert("请输入手机号");
return ;
}
if(data.verifyCode == ''){
alert("请输入验证码");
return ;
}
$.ajax({
url: getBasePath()+"/register",
async : true,
type: "post",
dataType: "text",
data: data,
success: function (data) {
if(data == 'success'){
alert("注册成功");
return ;
}
alert(data);
}
});
})
});
这里省略了所有非空、手机号格式验证
流程:
1)填写手机号
2)获取手机号码,调用sendSms.html接口向手机发送短信验证码
3)用户手机接收到验证码后,将其填写到"验证码"文本框中
后端代码
发送短信验证码
package com.zhenzi.sms;
import java.io.IOException;
import java.util.Random;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import com.alibaba.fastjson.JSONObject;
/**
* 获取验证码
*/
public class SendSmsServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
//短信平台相关参数
private String apiUrl = "https://sms_developer.zhenzikj.com";
private String appId = "000000";
private String appSecret = "c384b67bdsserev3343cdda4de5c8";
public SendSmsServlet() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
/**
* 短信平台使用的是榛子云短信(smsow.zhenzikj.com)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
String mobile = request.getParameter("mobile");
JSONObject json = null;
//生成6位验证码
String verifyCode = String.valueOf(new Random().nextInt(899999) + 100000);
//发送短信
ZhenziSmsClient client = new ZhenziSmsClient(apiUrl, appId, appSecret);
String result = "{code:0}";//client.send(mobile, "您的验证码为:" + verifyCode + ",该码有效期为5分钟,该码只能使用一次!");
json = JSONObject.parseObject(result);
if(json.getIntValue("code") != 0){//发送短信失败
renderData(response, "fail");
return;
}
//将验证码存到session中,同时存入创建时间
//以json存放,这里使用的是阿里的fastjson
HttpSession session = request.getSession();
json = new JSONObject();
json.put("mobile", mobile);
json.put("verifyCode", verifyCode);
json.put("createTime", System.currentTimeMillis());
// 将认证码存入SESSION
request.getSession().setAttribute("verifyCode", json);
renderData(response, "success");
return ;
} catch (Exception e) {
e.printStackTrace();
}
renderData(response, "fail");
}
protected void renderData(HttpServletResponse response, String data){
try {
response.setContentType("text/plain;charset=UTF-8");
response.getWriter().write(data);
} catch (Exception e) {
e.printStackTrace();
}
}
}
json工具使用的是阿里的fastjson
appId和appSecret换成你自己的,注册之后可获得
注册地址: http://sms_developer.zhenzikj.com/zhenzisms_user/register.html
提交注册
package com.zhenzi.sms;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.alibaba.fastjson.JSONObject;
/**
* 注册
*/
public class RegisterServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public RegisterServlet() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String userId = request.getParameter("userId");
String password = request.getParameter("password");
String mobile = request.getParameter("mobile");
String verifyCode = request.getParameter("verifyCode");
JSONObject json = (JSONObject)request.getSession().getAttribute("verifyCode");
if(json == null){
renderData(response, "验证码错误");
return ;
}
if(!json.getString("mobile").equals(mobile)){
renderData(response, "手机号错误");
return ;
}
if(!json.getString("verifyCode").equals(verifyCode)){
renderData(response, "验证码错误");
return ;
}
if((System.currentTimeMillis() - json.getLong("createTime")) > 1000 * 60 * 5){
renderData(response, "验证码已过期");
return ;
}
//其他业务代码
renderData(response, "success");
}
protected void renderData(HttpServletResponse response, String data){
try {
response.setContentType("text/plain;charset=UTF-8");
response.getWriter().write(data);
} catch (Exception e) {
e.printStackTrace();
}
}
}
ok,大功告成