Blogger Information
Blog 59
fans 0
comment 1
visits 48380
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
微信网页授权步骤—2018年6月1日
白猫警长的博客
Original
1232 people have browsed it

控制器:网页授权步骤(controller/weixin.php)

 // 微信网页授权
    // 获取当前用户的昵称、头像信息
    // 1 第一步:用户同意授权,获取code
    // 2 第二步:通过code换取网页授权access_token
    // 3 第三步:刷新access_token(如果需要)
    // 4 第四步:拉取用户信息(需scope为 snsapi_userinfo)
   public function auth()
   {
    $redirect = 'http://0e22edf9.ngrok.io';   //此回调域名必须与网页授权域名一致,并存储给变量,
    $url_code = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid='.config('app.appid').'&redirect_uri='.urlEncode($redirect).'&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect';     //获取code
    header('Location:'.$url_code);  
   }

    // 显示用户信息
    public function userinfo()
    {
        // 获取code
        $code = input('get.code');

        // 第二步:通过code换取网页授权access_token
        $res = $this->model->auth_access_token($code,false);
        $auth_access_token = $res['access_token'];
        $openid = $res['openid'];

        // 第三步:拉取用户信息(需scope为 snsapi_userinfo)
        $userinfo = $this->model->get_userinfo($auth_access_token,$openid);
        dump($userinfo);
    }

运行实例 »


模型(model/weixin.php):

  //网页授权access_token
    public function auth_access_token($code)
    {
        $appid = config('app.appid');
        $appsecret = config('app.appsecret');
        $url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid='.$appid.'&secret='.$appsecret.'&code='.$code.'&grant_type=authorization_code';
        $res = http_Get($url);
        $res = json_decode($res);
        if(!isset($res['access_token'])){
            return false;
        }
        return $res;
    }

运行实例 »



Correction status:qualified

Teacher's comments:
Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
0 comments
Author's latest blog post