短信可以作为通知,验证来使用,应用场合非常多,可以是注册,修改身份信息等等,其最终目的是验证这个手机号是你本人且是真实的.下面将以互亿无线接口为例,做一个用户找回密码的程序,来演示接口的调用.这里的PHP框架为ThinkPHP 3,但这并不影响什么,为了突出主题,已将代码尽可能简化,好的开始.
## **准备工作**
首先到互亿无线官网[www.ihuyi.com](http://www.ihuyi.com/)注册账号,完成注册后可获得APIID和APIKEY,并会赠送一些免费测试短信,可在控制台查看.下载接口,会得到reg.php和sms.php, 前者是前台表单页面及,后者是短信调用接口,可将sms.php文件放在如下目录,我这里将其改名为Message.class.php.
:-: ![](https://img.kancloud.cn/cb/d5/cbd5b774a5728fc794ee492d2f2f3557_271x169.png)
<br/>
## **ChangePwdController控制器**
点击通过手机号找回密码,通常页面会跳转到手机号输入页面,在这里页面为findByPhone方法
~~~php
<?php
namespace Home\Controller;
use Think\Controller;
class ChangePwdController extends Controller {
//通过手机号找回密码,密码输入模板
public function findByPhone()
{
$this -> display();
}
//手机验证码提交后后跳转到修改密码页面
public function editPwdByPhone()
{
$this -> display();
}
//手机号修改密码的功能实现
public function doEditPwdByPhone()
{
$arr['phone'] = $_SESSION['mobile'];
$data ['password'] = md5(trim(I('post.reuser_password')));
$edit = M( 'user' ) -> where($arr) -> data($data) -> save();
$_SESSION['mobile'] = '';
if ($edit) {
$this -> success ('修改成功,请重新登录!!', U('Index/index'),2);
}else{
$this -> error('修改失败!!');
}
}
}
~~~
<br/>
## **findByPhone模板**
findByPhone模板主要就是点击按钮触发短信发送接口
~~~php
<php>
session_start();
if($_POST){
//echo '<pre>';print_r($_POST);print_r($_SESSION);
if($_POST['mobile']!=$_SESSION['mobile'] or $_POST['mobile_code']!=$_SESSION['mobile_code'] or empty($_POST['mobile']) or empty($_POST['mobile_code'])){
exit('手机验证码输入错误。');
}else{
$_SESSION['mobile'] = '';
$_SESSION['mobile_code'] = '';
exit('注册成功。');
}
}
//短信内容
$_SESSION['send_code'] = random(6,1);
</php>
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>密码找回</title>
</head>
<script type="text/javascript" src="__PUBLIC__/js/jquery.js"></script>
<script language="javascript">
function get_mobile_code(){
$.post('{:U('Message/sms')}', {mobile:jQuery.trim($('#mobile').val()),send_code:<?php echo $_SESSION['send_code'];?>}, function(msg){
alert(jQuery.trim(unescape(msg)));
if(msg=='提交成功'){
RemainTime();
}
});
};
var iTime = 59;
var Account;
function RemainTime(){
document.getElementById('zphone').disabled = true;
var iSecond,sSecond="",sTime="";
if (iTime >= 0){
iSecond = parseInt(iTime%60);
iMinute = parseInt(iTime/60)
if (iSecond >= 0){
if(iMinute>0){
sSecond = iMinute + "分" + iSecond + "秒";
}else{
sSecond = iSecond + "秒";
}
}
sTime=sSecond;
if(iTime==0){
clearTimeout(Account);
sTime='获取手机验证码';
iTime = 59;
document.getElementById('zphone').disabled = false;
}else{
Account = setTimeout("RemainTime()",1000);
iTime=iTime-1;
}
}else{
sTime='没有倒计时';
}
document.getElementById('zphone').value = sTime;
}
</script>
<body>
<form action={:U('Message/msg')} method="post" name="formUser">
<table>
<tr>
<td align="right">手机号<td>
<input id="mobile" name="mobile" type="text" size="25" class="inputBg" /><span style="color:#FF0000"> *</span>
<input id="zphone" type="button" value=" 获取手机验证码 " onClick="get_mobile_code();"></td>
</tr>
<tr>
<td align="right">验证码</td>
<td><input type="text" size="8" name="mobile_code" class="inputBg" /></td>
</tr>
<tr>
<td align="right"></td>
<td><input type="submit" value=" 提交 " class="button"></td>
</tr>
</table>
</form>
</body>
</html>
~~~
上面的ajax发送到了Message/sms
<br/>
## **Message控制器**
这里调用了之前准备的Message类
~~~php
<?php
namespace Home\Controller;
use Think\Controller;
use Common\Util\Message\Message;
class MessageController extends Controller {
public function msg(){
if($_POST){
if($_POST['mobile']!=$_SESSION['mobile'] or $_POST['mobile_code']!=$_SESSION['mobile_code'] or empty($_POST['mobile']) or empty($_POST['mobile_code'])){
exit('手机验证码输入错误。');
}else{
$_SESSION['mobile'] = '';
$_SESSION['mobile_code'] = '';
$this->success ( '验证成功!', U( 'ChangePwd/editPwdByPhone'), 2 );
}
}
//短信内容,random自定义函数
$_SESSION['send_code'] = random(6,1);
}
//接受ajax的函数
public function sms(){
//调用类库
import('Common.Util.Message.Message');
$message = new Message();
$message -> Post();
$message -> xml_to_array();
$message -> receiveAjax(I('post.mobile'),I('post.send_code'));
}
}
~~~
<br/>
## **Message类文件**
~~~php
<?php
namespace Common\Util\Message;
class Message{
//请求数据到短信接口,检查环境是否 开启 curl init。
function Post($curlPost,$url){
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_NOBODY, true);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $curlPost);
$return_str = curl_exec($curl);
curl_close($curl);
return $return_str;
}
//将 xml数据转换为数组格式。
function xml_to_array($xml){
$reg = "/<(\w+)[^>]*>([\\x00-\\xFF]*)<\\/\\1>/";
if(preg_match_all($reg, $xml, $matches)){
$count = count($matches[0]);
for($i = 0; $i < $count; $i++){
$subxml= $matches[2][$i];
$key = $matches[1][$i];
if(preg_match( $reg, $subxml )){
$arr[$key] = $this -> xml_to_array( $subxml );
}else{
$arr[$key] = $subxml;
}
}
}
return $arr;
}
//接收ajax传的值,并进行相关操作
function receiveAjax($mobile,$send_code)
{
//短信接口地址
$target = "http://106.ihuyi.cn/webservice/sms.php?method=Submit";
//获取手机号
$mobile = I('post.mobile');
//获取验证码
$send_code = I('post.send_code');
//生成的随机数,用自定义函数random
$mobile_code = random(4, 1);
if (empty($mobile)) {
exit('手机号码不能为空');
}
//防用户恶意请求
if (empty($_SESSION['send_code']) or $send_code != $_SESSION['send_code']) {
exit('请求超时,请刷新页面后重试');
}
$post_data = "account=C09627491&password=7a144307fb01064ad3803c1010096374&mobile=" . $mobile . "&content=" . rawurlencode("您的验证码是:" . $mobile_code . "。请不要把验证码泄露给其他人。");
//用户名是登录ihuyi.com账号名(例如:cf_demo123)
//查看密码请登录用户中心->验证码、通知短信->帐户及签名设置->APIKEY
$gets = $this -> xml_to_array( $this -> Post($post_data, $target));
if ($gets['SubmitResult']['code'] == 2) {
$_SESSION['mobile'] = $mobile;
$_SESSION['mobile_code'] = $mobile_code;
}
echo $gets['SubmitResult']['msg'];
}
}
?>
~~~
短信发送成功,将会弹窗提示提交成功,这时页面依然在ChangePwd/findByPhone,填入收到的短信验证码后,提交表单到Message/msg来验证验证码是否正确,若正确,跳转到ChangePwd/editPwdByPhone重置密码页面.
**至此,短信发送及验证部分结束**
<br/>
## **editPwdByPhone模板**
~~~
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>通过手机号修改密码</title>
<style type="text/css"> #all{ width:550px; height:auto; overflow: hidden; margin:0 auto; } td{ font-size:14px; } input{ border:solid 1px #ddd; width:200px; height:24px; } table,td{ border-collapse: collapse; padding:10px; } span{ font-size:12px; color:green; display:none; } .active{ border:solid 1px blue; } .error{ border:solid 1px red; } .error-text { color:red; } .success-text{ color:green; } </style>
</head>
<body>
<div>请输入新密码</div>
<div id="all">
<form action="{:U('ChangePwd/doEditPwdByPhone')}" method="post">
<table>
<tr><td>密码</td><td><input remind="请输入6~20位的非空白字符" type="password" name="user_password"><span></span></td></tr>
<tr><td>确认密码</td><td><input type="password" remind="请再次输入密码" name="reuser_password"><span></span></td></tr>
<tr><td></td><td><button>点击提交</button></td></tr>
</table>
</form>
</div>
<script type="text/javascript" src="__PUBLIC__/js/jquery-1.9.0.min.js"></script>
<script language="javascript">
//检测变量的声明
var CPASS = false;
var CREPASS = false;
//绑定获得焦点事件
$('input').focus(function(){
//获取当前元素中remind属性
var remind = $(this).attr('remind');
//显示
$(this).next().html(remind).removeClass().addClass('success-text').show();
//修改元素的边框
$(this).addClass('active');
});
//绑定密码的丧失焦点事件
$('input[name=user_password]').blur(function(){
//获取密码的值
var v = $(this).val();
//声明正则
var reg = /^\S{6,20}$/;
//检测
var res = reg.test(v);
if(!res){
$(this).next().html('密码格式不正确').removeClass().addClass('error-text').show();
$(this).removeClass().addClass('error');
CPASS = false;
}else{
$(this).next().html('√').removeClass().addClass('success-text');
$(this).removeClass();
CPASS = true;
}
});
//确认密码的丧失焦点事件
$('input[name=reuser_password]').blur(function(){
//获取密码的值
var v = $(this).val();
//检测
var res = $('input[name=user_password]').val() == v;
if(!res){
$(this).next().html('两次密码不一致').removeClass().addClass('error-text').show();
$(this).removeClass().addClass('error');
CREPASS = false;
}else{
$(this).next().html('').removeClass().addClass('success-text');
$(this).removeClass();
CREPASS = true;
}
});
//表单提交事件的绑定
$('form').submit(function(){
//触发元素的丧失焦点事件
$('input[name=user_password]').trigger('blur');
$('input[name=reuser_password]').trigger('blur');
//检测元素的值
if(CPASS && CREPASS){
return true;
}
return false;
});
</script>
</body>
</html>
~~~
表单提交地址为ChangePwd/doEditPwdByPhone.
密码修改逻辑完成.通过这个例子,可以了解到短信发送及验证的原理,以后用其它接口也是万变不离其宗,本质都差不多.