安岳网站建设设计

将想法与焦点和您一起共享

PHP实现微信开放平台扫码登录

为了优化登录,减少用户操作,决定使用微信扫码登录,开发步骤如下

一、登录微信开放平台(https://open.weixin.qq.com/),创建应用申请AppID和AppSecret

二、拿到AppID和AppSecret 后 便可以开始开发了,创建一个唤起微信登录的页面,并跳转到微信扫码页面

    /*微信唤起登录*/
    public function index()
    {
        $type = input('type');
        $this->wxopenConfig = config('wxopen');
        if ($type == 'weixin') {
            $redirect_url = urlencode('http://' . $_SERVER['HTTP_HOST'] . '/snslogin/wx_login');
            $url = "https://open.weixin.qq.com/connect/qrconnect?appid=" . $this->wxopenConfig['appid'] . "&redirect_uri=" . $redirect_url . "&response_type=code&scope=" . $this->wxopenConfig['scope'] . "&state=STATE&connect_redirect=1#wechat_redirect";
            header('Location:' . $url);
        } else {
            echo 'hello word';
        }

    }
//Config.php配置文件
return [
    'wxopen'=>[
        'appid'=>'',
        'appsecret'=>'',
        'scope'=>'snsapi_login'//固定参数,保留即可
    ],
];

用户扫码完成后,微信会有一个同步回调,回调到你刚才设置的地址$redirect_url

    /*微信回调*/
    public function wx_login(){
        $this->wxopenConfig = config('wxopen');
        $code = $_GET['code'];
        //判断是否授权
        if (empty($code)){
            $this->error('授权失败');
        }
        $token_url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid=' . $this->wxopenConfig['appid'] . '&secret=' . $this->wxopenConfig['appsecret'] . '&code=' . $code . '&grant_type=authorization_code';
        //获取token,为了获取access_token 如果没有就弹出错误
        $token = json_decode(file_get_contents($token_url));
        if (isset($token->errcode)) {
            echo '

错误:

' . $token->errcode; echo '

错误信息:

' . $token->errmsg; exit; } $access_token_url = 'https://api.weixin.qq.com/sns/oauth2/refresh_token?appid=' . $this->wxopenConfig['appid'] . '&grant_type=refresh_token&refresh_token=' . $token->refresh_token; //获取access_token ,为了获取微信的个人信息,如果没有就弹出错误 $access_token = json_decode(file_get_contents($access_token_url)); if (isset($access_token->errcode)) { echo '

错误:

' . $access_token->errcode; echo '

错误信息:

' . $access_token->errmsg; exit; } $user_info_url = 'https://api.weixin.qq.com/sns/userinfo?access_token=' . $access_token->access_token . '&openid=' . $access_token->openid . '&lang=zh_CN'; //获取用户信息 $user_info = json_decode(file_get_contents($user_info_url)); if (isset($user_info->errcode)) { echo '

错误:

' . $user_info->errcode; echo '

错误信息:

' . $user_info->errmsg; exit; } //这里转换为数组 $rs = (array)$user_info; die($rs); }

到此已经获取到了微信用户信息,后续再加上自己的业务逻辑即可


本文题目:PHP实现微信开放平台扫码登录
网页网址:http://scanyue.cn/article/djhispj.html