短信可以作為通知,驗證來使用,應用場合非常多,可以是注冊,修改身份信息等等,其最終目的是驗證這個手機號是你本人且是真實的.下面將以互億無線接口為例,做一個用戶找回密碼的程序,來演示接口的調用.這里的PHP框架為ThinkPHP 3,但這并不影響什么,為了突出主題,已將代碼盡可能簡化,好的開始.
## **準備工作**
首先到互億無線官網[www.ihuyi.com](http://www.ihuyi.com/)注冊賬號,完成注冊后可獲得APIID和APIKEY,并會贈送一些免費測試短信,可在控制臺查看.下載接口,會得到reg.php和sms.php, 前者是前臺表單頁面及,后者是短信調用接口,可將sms.php文件放在如下目錄,我這里將其改名為Message.class.php.
:-: 
<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.
密碼修改邏輯完成.通過這個例子,可以了解到短信發送及驗證的原理,以后用其它接口也是萬變不離其宗,本質都差不多.