授权页面链接:
https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx14f******33aca21&redirect_uri=http://****.************.com/wechat/php/oauth_response.php&response_type=code&scope=snsapi_userinfo&state=STATE&connect_redirect=1#wechat_redirect
授权页面会跳转到一个带有code参数的页面,页面地址没变,简单点说就是页面刷新了个你所需要的code参数
<?php //获取地址链接中的code参数 $location = $_SERVER["QUERY_STRING"]; $data = strstr($location,'&',true); $code = substr($data, 5); //curl 的post请求 function CurlPost($url, $data) { $curl = curl_init(); curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE); curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE); curl_setopt($curl, CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1); curl_setopt($curl, CURLOPT_URL, $url); if(!empty($data)) { curl_setopt($curl, CURLOPT_POST, true); curl_setopt($curl, CURLOPT_POSTFIELDS, $data); } curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); $result = curl_exec($curl); curl_close($curl); return $result; } //get请求 function CurlGet($url) { return CurlPost($url, ""); } //通过code换取网页授权access_token $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=wx14f******33aca21&secret=332cab69b**********e5481b9bfe6ce&code=".$code."&grant_type=authorization_code"; $rs = json_decode(CurlGet($url)); //请求成功返回access_token if(isset($rs->{'access_token'})){ //保存access_token $access_token = $rs->{'access_token'}; $openid = $rs->{'openid'}; //请求成功返回errcode }else if (isset($rs->{'errcode'})) { //# code... } //拉取用户信息(需scope为 snsapi_userinfo) $user = json_decode(CurlGet("https://api.weixin.qq.com/sns/userinfo?access_token=".$access_token."&openid=".$openid."&lang=zh_CN")); echo $user->{'nickname'}; ?>