1、在config目录下,自己创建一个文件,如下:
return[
'smsbao'=>[
'url'=>'http://api.smsbao.com',
'username'=>'amy521',
'apiKey'=>'61c19c46df6e480297ed62bf8f641b8b',
'password'=>md5('Zz13147779328'),
]
];
2、在common.php封装curl请求和第三方发送验证码
//curl 发送请求
if(!function_exists('curl_request')){
function curl_request($url,$post_data='',$method='get',$header='',$type=''){
//初始化
if ($url==''){
return true;
}
$ch =curl_init($url);
//默认是get请求,如果是post请求,设置请求方式和请求参数
if(strtolower($method)=='post'){
curl_setopt($ch,CURLOPT_POST,true);
curl_setopt($ch,CURLOPT_POSTFIELDS,$post_data);
}
//如果是https协议,禁止从服务器验证本地证书
if (strtolower($type)=='https'){
curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,true);
}
//发送请求,获取返回结果
curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
$res = curl_exec($ch);
return $res;
}
}
//发送手机短信验证码
if(!function_exists('send_message')){
function send_message($phone,$code){
$smsapi = config('account.smsbao.url');
$user = config('account.smsbao.username');
$pass =config('account.smsbao.password');
$content ="尊敬的用户,您正在品优购进行账号注册,您的验证码为:{$code},验证有效期为5分钟。";
$sendurl = $smsapi."sms?u=".$user."&p=".$pass."&m=".$phone."&c=".urlencode($content);
return curl_request($sendurl);
}
}
3、在业务逻辑层
namespace app\register\business;
use think\Exception;
use think\facade\Cache;
class Code
{
//发送手机验证码
public static function sendMessage($phone){
$key = 'register_code_'.$phone;
$time_key ='register_time_'.$phone;
$send_time = Cache::get($time_key);
if($send_time && time()-$send_time<60){
throw new Exception('请求次数过多');
}
$code = rand(1000,9999);
//Cache::set($key,$code,300);
//Cache::set($time_key,time(),120);
$result = send_message($phone,$code);
if ($result==0){
return true;
}else{
throw new Exception('发送失败');
}
}
}
4、在控制器
public function sendCard(){
//获取手机号
$phone = \request()->post('phone');
//验证手机号(合法性,查库是否注册过)
$res = Code::sendMessage($phone);
if($res){
return json(['code'=>200,'msg'=>'发送成功','data'=>[]]);
}
}
5、路由
//发送验证码
Route::post('sendCard', 'Login/sendCard');
6、页面
<script src="https://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>
<script>
$('.sendCard').click(function () {
var phone = $('.phone').val();
var preg = /^1[3456789]\d{9}$/
if(phone==''){
$('.phone').next().text('请输入手机号')
return false
}
if (!preg.test(phone)){
$('.phone').next().text('手机号不合法')
return false
}
$.ajax({
url:'sendCard',
data:{
phone:phone
},
dataType:'json',
type:'post',
success:function (res) {
if (res.code==200){
alert(res.msg)
}
}
})
})
</script>