微信获取用户信息

微信获取用户信息_第1张图片
image.png

微信获取用户信息_第2张图片
注意没有http://
    //微信获取用户消息
    public function getUser()
    {
        //获取code
        $appid = $this->appid;
        $redirect_url = urlencode("http://wechat.xhqlzj.com/backed/index/getUserOpenId");
        $url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=".$appid."&redirect_uri=".$redirect_url."&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect";
        header('location:'.$url);
    }

    public function getUserOpenId(){
        $appid = $this->appid;
        $secret = $this->appsecret;
        $code = $_GET["code"];

        //第一步:取全局access_token
        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$appid&secret=$secret";
        $token = $this->http_request($url);
        //第二步:取得openid
        $oauth2Url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=$appid&secret=$secret&code=$code&grant_type=authorization_code";
        $oauth2 = $this->http_request($oauth2Url);

        //第三步:根据全局access_token和openid查询用户信息
        $access_token = $token["access_token"];
        $openid = $oauth2['openid'];
        $get_user_info_url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=$access_token&openid=$openid&lang=zh_CN";
        $userinfo = $this->http_request($get_user_info_url);
        print_r($userinfo);
    }
    /**
     * 请求
     */
    public function http_request($url, $json_transfer_back = 1)
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $data = curl_exec($curl);
        if (curl_errno($curl)) {
            return 'ERROR ' . curl_error($curl);
        }
        curl_close($curl);
        if ($json_transfer_back == 1) {
            $data = json_decode($data, true);
        }

        return $data;
    }

网页访问http://wechat.xhqlzj.com/backed/index/getUser

微信获取用户信息_第3张图片
image.png

微信获取用户信息_第4张图片
image.png

你可能感兴趣的:(微信获取用户信息)