Anjaxs

php实现网易云短信验证

<?php

class Sms {

    const APP_KEY = "开发者平台分配的appkey";
    const APP_SECRET = "开发者平台分配的app secret";
    const TEMPLATE_ID = "模板id";
    protected $nonce; //随机数(最大长度128个字符)
    protected $curTime; //当前UTC时间戳
    protected $checkSum;

    public function __construct() {
        $this->nonce = mt_rand(1, 999999);
        $this->curTime = time();
        $this->checkSum = sha1(self::APP_SECRET.$this->nonce.$this->curTime);
    }

    /**
     * 创建资源流上下文
     * @param array $data 传输的数据,以数组形式
     * @return resource
     */
    protected function getContext(array $data) {
        return stream_context_create([
            'http' => [
                'method' => 'POST',
                'header' => [
                    'Content-Type:application/x-www-form-urlencoded;charset=utf-8',
                    "AppKey:".self::APP_KEY,
                    "Nonce:$this->nonce",
                    "CurTime:$this->curTime",
                    "CheckSum:$this->checkSum"
                ],
                'content' =>  http_build_query($data)
            ]
        ]);
    }

    //发送验证码函数
    public function SendSmsCode($mobile){
        $context = $this->getContext([
            'mobile' => $mobile,
            'templateid' => self::TEMPLATE_ID
        ]);
        $html = file_get_contents("https://api.netease.im/sms/sendcode.action", false, $context);
        return $html;
    }

    //验证短信验证码
    public function CheckSmsYzm($mobile, $code):bool{
        $context = $this->getContext([
            'mobile' => $mobile,
            'code'   => $code
        ]);
        $html = file_get_contents("https://api.netease.im/sms/verifycode.action", false, $context);
        if(json_decode($html)->code == 200) {
            return true;
        } else {
            return false;
        }
    }
}

关于使用的一个例子:

在“发送验证码”按钮绑定一个js点击事件。代码如下:

//发送短信验证码
$('#sendCode').bind('click',function () {
    $.ajax({
        url:"{{route('index@SendSmsCode')}}",
        type:"get",
        data:{
            'mobile': $("#reg-phone").val()
        }
    });
});

访问的是下面这个方法

//ajax 发送短信验证
public function SendSmsCode(){
    $sms = new Sms();
    echo $sms->SendSmsCode($_REQUEST['mobile']);
}

如果成功的话,这时你的手机应该就会收到短信通知的验证码了

验证的逻辑:

public function register() {
    $data['phone'] = request('phone', '0','mobile');
    $Code  = request('phone_auth', '0','int');
    $sms = new Sms();
    if($sms->CheckSmsYzm($data['phone'], $Code)) {
        $data['name'] = request('name');
        $data['password'] = md5($_REQUEST['password']);
        $data['created_at'] = time();
        $model = new User();
        $res = $model->insert($data);
        $msg = $res > 0 ? '注册成功' : '注册失败';
        jump('index@index',['msg'=>$msg]);
    } else {
        jump('index@index',['msg'=>"手机验证码错误"]);
    }
}
码字很辛苦,转载请注明来自Anjaxs博客《php实现网易云短信验证》

评论