本文實例講述了php版微信公眾平臺之微信網頁登陸授權。分享給大家供大家參考,具體如下:
微信公眾平臺實現微信網頁登陸授權開發其實是非常的簡單了,因為官方的參考程序了,下面小編就看了一站長根據官方參考做的一個網頁登陸授權例子,大家可看看.
文件1:index.php
//換成自己的接口信息$appid = 'XXXXX';header('location:https://open.weixin.qq.com/connect/oauth2/authorize?appid='.$appid.'&redirect_uri=127.0.0.1/oauth.php&response_type=code&scope=snsapi_userinfo&state=123&connect_redirect=1#wechat_redirect');
| 參數 | 是否必須 | 說明 |
| appid | 是 | 公眾號的唯一標識 |
| redirect_uri | 是 | 授權后重定向的回調鏈接地址,請使用urlencode對鏈接進行處理 |
| response_type | 是 | 返回類型,請填寫code |
| scope | 是 | 應用授權作用域,snsapi_base(不彈出授權頁面,直接跳轉,只能獲取用戶openid),snsapi_userinfo(彈出授權頁面,可通過openid拿到昵稱、性別、所在地。并且,即使在未關注的情況下,只要用戶授權,也能獲取其信息) |
| state | 否 | 重定向后會帶上state參數,開發者可以填寫a-zA-Z0-9的參數值 |
| #wechat_redirect | 是 | 無論直接打開還是做頁面302重定向時候,必須帶此參數 |
文件二:oauth.php,代碼如下:
<?php$code = $_GET['code'];$state = $_GET['state'];//換成自己的接口信息$appid = 'XXXXX';$appsecret = 'XXXXX';if (emptyempty($code)) $this->error('授權失敗');$token_url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid='.$appid.'&secret='.$appsecret.'&code='.$code.'&grant_type=authorization_code';$token = json_decode(file_get_contents($token_url));if (isset($token->errcode)) { echo '<h1>錯誤:</h1>'.$token->errcode; echo '<br/><h2>錯誤信息:</h2>'.$token->errmsg; exit;}$access_token_url = 'https://api.weixin.qq.com/sns/oauth2/refresh_token?appid='.$appid.'&grant_type=refresh_token&refresh_token='.$token->refresh_token;//轉成對象$access_token = json_decode(file_get_contents($access_token_url));if (isset($access_token->errcode)) { echo '<h1>錯誤:</h1>'.$access_token->errcode; echo '<br/><h2>錯誤信息:</h2>'.$access_token->errmsg; exit;}$user_info_url = 'https://api.weixin.qq.com/sns/userinfo?access_token='.$access_token->access_token.'&openid='.$access_token->openid.'&lang=zh_CN'; //開源軟件:phpfensi.com//轉成對象$user_info = json_decode(file_get_contents($user_info_url));if (isset($user_info->errcode)) { echo '<h1>錯誤:</h1>'.$user_info->errcode; echo '<br/><h2>錯誤信息:</h2>'.$user_info->errmsg; exit;}//打印用戶信息echo '<pre>';print_r($user_info);echo '</pre>';?>
| 參數 | 描述 |
| openid | 用戶的唯一標識 |
| nickname | 用戶昵稱 |
| sex | 用戶的性別,值為1時是男性,值為2時是女性,值為0時是未知 |
| province | 用戶個人資料填寫的省份 |
| city | 普通用戶個人資料填寫的城市 |
| country | 國家,如中國為CN |
| headimgurl | 用戶頭像,最后一個數值代表正方形頭像大小(有0、46、64、96、132數值可選,0代表640*640正方形頭像),用戶沒有頭像時該項為空. |
| privilege | 用戶特權信息,json數組,如微信沃卡用戶為(chinaunicom) |
| unionid | 只有在用戶將公眾號綁定到微信開放平臺帳號后,才會出現該字段。詳見:獲取用戶個人信息(UnionID機制) |
到此網頁登陸授權開發功能就作完了,如果想要獲取用戶基本信息我們需要看另一個例子,在官方有說明大家可自行搜索哦.
希望本文所述對大家PHP程序設計有所幫助。
新聞熱點
疑難解答
圖片精選