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

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

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

4 第四步:拉取用户信息(需scope为 snsapi_userinfo)

简单网页授权

//简单授权
    function getBaseInfo(){
        //1.获取到code
        $appid = "wxde8d3eacc9f91cae";
        $redirect_uri = urlencode("http://wx.sunxiaoning.com/index.php/Wx/index/getUserOpenId");
        $url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=".$appid."&redirect_uri=".$redirect_uri."&response_type=code&scope=snsapi_base&state=123#wechat_redirect";
        header('location:'.$url);
        
    }
    function getUserOpenId(){
        //2.获取到网页授权的access_token
        $appid = "wxde8d3eacc9f91cae";
        $appsecret = "3ae10c48de0ec193a7cc695f098c2817";
        $code = $_GET['code'];
        $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=".$appid."&secret=".$appsecret."&code=".$code."&grant_type=authorization_code";
        //3.拉取用户的openid
        $res = $this->http_curl($url,'get');
        var_dump($res);

    }

详细授权

    function getUserDetail(){
        //1.获取到code
        $appid = "wxde8d3eacc9f91cae";
        $redirect_uri = urlencode("http://wx.sunxiaoning.com/index.php/Wx/index/getUserInfo");
        $url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=".$appid."&redirect_uri=".$redirect_uri."&response_type=code&scope=snsapi_userinfo&state=123#wechat_redirect";
        header('location:'.$url);
    }
    function getUserInfo(){
        //2.获取到网页授权的access_token
        $appid = "wxde8d3eacc9f91cae";
        $appsecret = "3ae10c48de0ec193a7cc695f098c2817";
        $code = $_GET['code'];
        $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=".$appid."&secret=".$appsecret."&code=".$code."&grant_type=authorization_code";
        //3.拉取用户的openid
        $res = $this->http_curl($url,'get');
        $access_token = $res['access_token'];
        $openid = $res['openid'];
        //4.拉取用户的详细信息
        $url = "https://api.weixin.qq.com/sns/userinfo?access_token=".$access_token."&openid=".$openid."&lang=zh_CN";
        $res = $this->http_curl($url);
        var_dump($res);

    }
Last modification:June 25, 2018
If you think my article is useful to you, please feel free to appreciate