提要:
1. 建议对OAuth2.0协议做一个学习。 2. 微信官方文档和微信官网工具要得到充分利用。 比较简单,直接帖源代码了。其中“xxxxxxxxxx”部分,是需要依据自己环境做替换的// 回调地址
$url = urlencode("http://www.xxxxxxxxx.com/GetWxUserInfo.PHP");
// 公众号的id和secret
$appid = 'xxxxxxxxx';
$appsecret = 'xxxxxxxxx';
session_start();
// 获取code码,用于和微信服务器申请token。 注:依据OAuth2.0要求,此处授权登录需要用户端操作
if(!isset($_GET['code']) && !isset($_SESSION['code'])){
echo
'<a href="https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx6c11a252ff1d00c4
&redirect_uri='.$url.'&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect">
<font style="font-size:30">授权';
exit;
}
// 依据code码去获取openid和access_token,自己的后台服务器直接向微信服务器申请即可
if (isset($_GET['code']) && !isset($_SESSION['token'])){
$_SESSION['code'] = $_GET['code'];
$url="https://api.weixin.qq.com/sns/oauth2/access_token?appid=".$appid.
"&secret=".$appsecret."&code=".$_GET['code']."&grant_type=authorization_code";
$res = https_request($url);
$res=(json_decode($res,true));
$_SESSION['token'] = $res;
}
print_r($_SESSION);
// 依据申请到的access_token和openid,申请Userinfo信息。
if (isset($_SESSION['token']['access_token'])){
$url = "https://api.weixin.qq.com/sns/userinfo?access_token=".$_SESSION['token']['access_token']."&openid=".$_SESSION['token']['openid']."&lang=zh_CN";
echo $url;
$res = https_request($url);
$res = json_decode($res,true);
$_SESSION['userinfo'] = $res;
}
print_r($_SESSION);
// cURL函数简单封装
function https_request($url,$data = null)
{
$curl = curl_init();
curl_setopt($curl,CURLOPT_URL,$url);
curl_setopt($curl,CURLOPT_SSL_VERIFYPEER,FALSE);
curl_setopt($curl,CURLOPT_SSL_VERIFYHOST,FALSE);
if (!empty($data)){
curl_setopt($curl,CURLOPT_POST,1);
curl_setopt($curl,CURLOPT_POSTFIELDS,$data);
}
curl_setopt($curl,CURLOPT_RETURNTRANSFER,1);
$output = curl_exec($curl);
curl_close($curl);
return $output;
}
得到正确结果如下:
[userinfo] => Array
(
[openid] => ota_XwQ4r_5nioVmshQq
[nickname] => 野狐
[sex] => 1
[language] => zh_CN
[city] => 杭州
[province] => 浙江
[country] => 中国
[headimgurl] => http://wx.qlogo.cn/mmopen/PiajxSqBRaELwee7rhrt2ibnkC1MEnu04WiaWrw9FkuPBbGOgnrMbynNoEuxicgXOetW5VqQbTrS4fZDXNvAWsz6GQ/0
[privilege] => Array
(
)
)
)