tp5.1中手机端短信验证码发送及验证

第一步:在application目录里新建一个目录与默认index或home目录同级,比如新建一个wechat目录,wechat目录里面有controller目录controller目录里建里新建Index.php文件,文件内容为如下:

 'wx3cf0f39249eb0xxx',
            'secret' => 'f1c242f4f28f735d4687abb469072xxx',
            'token' => 'TestToken',
            'response_type' => 'array',

            'log' => [
                'level' => 'debug',
                'file' => __DIR__.'/wechat.log',
            ],
        ];

        $app = Factory::officialAccount($config);
        $app->server->push(function ($message) {
            return "您好!欢迎使用 EasyWeChat!";
        });
        $response = $app->server->serve();
        $response->send();
    }
}

第二步:控制器中使用:

201, 'msg'=>'参数缺失']);
        }
        $code = rand(100000,999999);
        $str = "您的验证码是:".$code."请在3分钟内输入【微网通联】";
        redis()->set('phone_'.$phone, $code, 180);
        $target = "http://cf.51welink.com/submitdata/Service.asmx/g_Submit";
        //替换成自己的测试账号,参数顺序和wenservice对应
        $post_data = "sname=dlluodan&spwd=dlluodan123&scorpid=&sprdid=1012818&sdst=".$phone."&smsg=" . rawurlencode($str);
        //$binarydata = pack("A", $post_data);
        $gets = $this->send($post_data, $target);
        if(explode(' ', $gets)[0]) {
            return json(['code'=>200, 'msg'=>'success', 'data'=>$code]);
        } else {
            return json(['code'=>201, 'msg'=>'验证码发送失败,请稍后重试']);
        }
    }

    public function send($data, $target)
    {
        $url_info = parse_url($target);
        $httpheader = "POST " . $url_info['path'] . " HTTP/1.0\r\n";
        $httpheader .= "Host:" . $url_info['host'] . "\r\n";
        $httpheader .= "Content-Type:application/x-www-form-urlencoded\r\n";
        $httpheader .= "Content-Length:" . strlen($data) . "\r\n";
        $httpheader .= "Connection:close\r\n\r\n";
        //$httpheader .= "Connection:Keep-Alive\r\n\r\n";
        $httpheader .= $data;

        $fd = fsockopen($url_info['host'], 80);
        fwrite($fd, $httpheader);
        $gets = "";
        while (!feof($fd)) {
            $gets .= fread($fd, 128);
        }
        fclose($fd);
        if ($gets != '') {
            $start = strpos($gets, ' 0) {
                $gets = substr($gets, $start);
            }
        }
        return $gets;
    }
    //验证码校验方法
    public function check_sms() {
        $uid = input('uid');
        $phone = input('phone');
        $code = input('code');
        $real_name = input('real_name');

        if (!($uid && $phone && $code && $real_name)) {
            return json(['code'=>201, 'msg'=>'参数缺失']);
        }
        if ($code == redis()->get('phone_'.$phone)) {
            User::where('id', $uid)->update(['phone'=>$phone, 'real_name'=>$real_name]);
            return json(['code'=>200, 'msg'=>'success']);
        } else {
            return json(['code'=>201, 'msg'=>'验证码错误,请重新输入']);
        }
    }
}
 

你可能感兴趣的:(TP)