业务操作流程:输入手机号,发送验证码,收到验证码填写提交验证。常用于短信登录和手机号注册账号。
一、购买短信验证码搭建接口
填写购买的 $appcode
等信息,我们只写了随机生成一个六位数,经过加密变成 token 下发给浏览器。
<?php
$host = "http://yzxtz.market.alicloudapi.com";
$path = "/yzx/notifySms";
$method = "POST";
$appcode = "8ae5612c0e7f4d2ba70ae79e1490bf88";
$headers = array();
array_push($headers, "Authorization:APPCODE " . $appcode);
// 随机6位数
$shu = rand(100000, 999999);
$querys = "phone=".$_GET['phone']."&templateId=TP18040316&variable=num%3A0000%2Cmoney%3A" . $shu;
$bodys = "";
$url = $host . $path . "?" . $querys;
$curl = curl_init();
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl, CURLOPT_FAILONERROR, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HEADER, true);
if (1 == strpos("$".$host, "https://"))
{
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
}
curl_exec($curl);
// 向前端反馈加密的结果
$token = md5(md5(md5($shu. '谁也不知道我是用的密令是啥?')));
echo '{"token": "' . $token .'"}';
?>
二、前端页面搭建
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>验证码登录</title>
<link href="https://cdn.bootcss.com/twitter-bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet">
<style>
.container{
width: 500px;
padding-top:10px;
}
</style>
</head>
<body>
<div class="container" id="app">
<div>
请输入手机号码:
<div class="row">
<input class="form-control col-lg-8" type="password" v-model="phone">
</div>
</div>
<div>
请输入短信验证码:
<div class="row">
<div class="col-lg-16">
<input class="form-control" type="text" v-model="yzm">
</div>
<div class="col-lg-6">
<button class="btn btn-success" :disabled="yifa" @click="fsyzm">
{{yifa ? `已经发送,重新发送(${time})` : '发送验证码'}}
</button>
</div>
</div>
</div>
<div class="row">
<button class="btn btn-success" :disabled="yzm == '' || phone == ''" @click="tj">
提交
</button>
</div>
</div>
<script src="https://cdn.bootcss.com/vue/2.6.10/vue.min.js"></script>
<script src="https://cdn.bootcss.com/axios/0.19.0-beta.1/axios.min.js"></script>
<script type="text/javascript">
new Vue({
el: '#app',
data: {
phone: '',
time: 6,
yifa: false,
yzm: '',
token: ''
},
methods: {
fsyzm(){
this.yifa = true;
// 定时器
this.timer = setInterval(()=>{
this.time --;
if(this.time === 0){
this.yifa = false;
this.time = 6;
}
},1000)
axios.get('/fasong.php?phone=' + this.phone).then(data=>{
// 后端负责发验证码,你负责把token存起来
this.token = data.data.token;
});
},
tj(){
axios.get('/check.php?shu=' + this.yzm + '&token=' + this.token ).then(data=>{
if(data.data === 'ok'){
alert('成功')
}else{
alert('失败')
}
});
}
}
});
</script>
</body>
</html>
三、提交验证
上一步手机收到的验证码会同时经过加密下发给浏览器,我们在页面把手机验证码填写进去,Ajax 请求会携带 token 和填写的验证码,在我们的服务端再次对填写的验证码进行同样的加密,并和携带的 token 进行对比,相等表示登录成功!
<?php
$token = $_GET['token'];
$shu = $_GET['shu'];
// 再次加密,比对
if(md5(md5(md5($shu.'谁也不知道我是用的密令是啥?'))) === $token){
echo 'ok';
}else{
echo 'nook';
}
?>