微信公眾號實現網頁授權登入
阿新 • • 發佈:2018-12-02
微信公眾平臺介面測試號地址:https://mp.weixin.qq.com/debug/cgi-bin/sandbox?t=sandbox/login
開發文件地址:https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421140842
第一步:使用者同意授權,獲取code
<?php $appid = 'APPID'; $redirect_uri = urlencode('http://www.phpzhi.com/test.php');//重定向地址 $url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=$appid&redirect_uri=$redirect_uri&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect"; header("Location:" . $url);
第二步:通過返回的code獲取網頁授權的access_token
<?php $appid = "APPID"; $secret = "APPSECRET"; $code = $_GET["code"]; $oauth2Url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=$appid&secret=$secret&code=$code&grant_type=authorization_code"; $oauth2 = getJson($oauth2Url); //access_token和openid $access_token = $oauth2["access_token"]; $openid = $oauth2['openid']; 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); }
第三步:通過access_token和openid獲取使用者的資訊
$get_user_info_url = "https://api.weixin.qq.com/sns/userinfo?access_token=$access_token&openid=$openid&lang=zh_CN"; $userinfo = getJson($get_user_info_url); //列印使用者資訊 print_r($userinfo); //array('openid' => 'oiuH-xxxxxxxxxxxxx', 'sex' => 1, 'language' => 'zh_CN', 'city' => '南寧', 'province' => '廣西', 'country' => '中國', 'headimgurl' => 'http://thirdwx.qlogo.cn/mmopen/vi_32/LyJOXEvevuUTicVz0LCibBzQw9FI8iaAp6bzN4Q6R1YHd3Sa2nsiaqjtN5kSMgHl4wL1VYf0t4IacY6KaqrN8aJCibA/132', 'privilege' => array() );