Blogger Information
Blog 8
fans 0
comment 0
visits 7319
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
6.01 浅谈微信网页授权登录流程及代码实例
Allen的php博客
Original
1319 people have browsed it

微信网页授权登录流程:

1、首先通过微信自定义菜单:用户同意授权,页面发生跳转到显示用户信息方法,获取code;

2、通过code换取网页授权access_token,得到取得access_token和openid;

3、将access_token和openid,传入到微信提供的接口当中,拉取用户信息。

实例:

建立Weixin.php控制器:


    // 微信网页授权

    // 获取当前用户的昵称、头像信息

    // 1 第一步:用户同意授权,获取code

    // 2 第二步:通过code换取网页授权access_token

    // 3 第三步:刷新access_token(如果需要)

    // 4 第四步:拉取用户信息(需scope为 snsapi_userinfo和snsapi_base两种方式)

    public function auth()

    {

        //第一步:用户同意授权,获取code

        $redirect = 'http://4aebdc06.ngrok.io/index.php/index/weixin/userinfo'; //转到显示用户信息方法userinfo()

        $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';

        header('Location:'.$url_code);

    }


    // 显示用户信息

    public function userinfo()

    {

        // 获取code

        $code = input('get.code');


        // 第二步:通过code换取网页授权access_token

        $res = $this->model->auth_access_token($code, true); //调用模型auth_access_token()

        $auth_access_token = $res['access_token']; //获取网页授权access_token

        $openid = $res['openid']; //获取公众号的唯一标识


        // 第三步:拉取用户信息(需scope为 snsapi_userinfo)

        $userinfo = $this->model->get_userinfo($auth_access_token,$openid);

        dump($userinfo);


    }



第二、第三步,模型Weixin.php:


    //网页授权access_token

    public function auth_access_token($code)

    {

        $appid = Config::get('app.APPID'); //获取微信开发者ID(AppID)

        $appsecret = Config::get('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,true);

        if(!isset($res['access_token'])){

            return false;

        }

        return $res;


    }


    // 拉取用户信息

    public function get_userinfo($auth_access_token,$openid){

        $url = 'https://api.weixin.qq.com/sns/userinfo?access_token='.$auth_access_token.'&openid='.$openid.'&lang=zh_CN';

        $res = http_Get($url);

        $res = json_decode($res,true);

        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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!