提要:
1. 建議對OAuth2.0協議做一個學習。
2. 微信官方文檔和微信官網工具要得到充分利用。
比較簡單,直接帖源代碼了。其中“xxxxxxxxxx”部分,是需要依據自己環境做替換的
/** * OAuth2.0微信授權登錄實現 * * @author zzy * @文件名:GetWxUserInfo.php */ // 回調地址 $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 >授權</font></a>'; 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; }
得到正確結果如下:
Array ( [code] => 041GZI4l0tvGHg10N75l05FQ4l0GZI42 [token] => Array ( [access_token] => TWo6w5QMpzTZibu3FPh2k4EdC5bllp4sGeQkC4NbZtj-zti-ctZj1SrrNL1qGCf2lB1-6o3N7kh2bcxl5bxtQqJEGk1cq12l8CzF40R9XvA [expires_in] => 7200 [refresh_token] => Iz3olCrkqPBOJvSSH2bOKvA09Sjvsp1c8Ltm7MvxxPfQXSbvI_WoVmzhjqASzwlMa7TAGgsg3mIJmaHjL7jrJHDqUF1jKbhd6GNDnLtXq0U [openid] => ota_XwQ4r_5nioVmshQ [scope] => snsapi_userinfo ) [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 ( ) ) )
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持幫客之家。