微信授权获取个人信息 头像 姓名 地区

<?php
namespace HomeController;

class GetWxUserController extends CommonController {

protected $appid = "wxe4a16ab6c280178c";
protected $secret = "363cbcea8acb647f0b6ff8478d55c1d9";

/**
* 微信授权入口
* scope=snsapi_base/snsapi_userinfo
*/
public function index() {
$appid = 'wxe4a16ab6c280178c';
$loc_url = $_SERVER['HTTP_HOST'];
$redirect_uri = urlencode('http://'.$loc_url.'/GetWxUser/resultCode');
$url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=$appid&redirect_uri=$redirect_uri&response_type=code&scope=snsapi_base&state=1#wechat_redirect";
header("Location:" . $url);

}

/*
* 获取code信息
*/
public function resultCode() {
$code = I('request.code');
if (!empty($code)) {
return $code;
} else {
return NULL;
}
}

/**
* 获取微信用户信息
*/
public function getWXUser() {
$appid = $this->appid;
$secret = $this->secret;
$code = I('request.code');

//第一步:取全局access_token
$url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$appid&secret=$secret";
$token = $this->getJson($url);

//第二步:取得openid
$oauth2Url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=$appid&secret=$secret&code=$code&grant_type=authorization_code";
$oauth2 = $this->getJson($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->getJson($get_user_info_url);

//打印用户信息
// $userinfo = json_decode($userinfo, true);
if($userinfo['errcode'] == 40003){
$return = [
'status' => 40003,
'msg' => '获取失败',
'data' => $userinfo
];
} else {
$return = [
'status' => 200,
'msg' => '获取成功',
'data' => $userinfo
];
}
print_r($return);exit;
return json_encode($return);
}

public function Login(){
$this->display();
}

private function getJson($url) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($ch);
curl_close($ch);
return json_decode($output, true);
}
}

原文地址:https://www.cnblogs.com/zhang-bin/p/10768221.html