微信获取用户信息
2019-09-30 本文已影响0人
这真的是一个帅气的名字
![](https://img.haomeiwen.com/i4424012/25a45ae211ff97fc.png)
![](https://img.haomeiwen.com/i4424012/8341b38dea0aec26.png)
//微信获取用户消息
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
![](https://img.haomeiwen.com/i4424012/5bd6ad8fe82a528f.png)
![](https://img.haomeiwen.com/i4424012/a7b5d1fc35b88838.png)