本篇文章你將學到:在自己做的微信網站里,利用oauth2.0網頁授權接口獲取用戶的信息(openid,姓名,性別,地區,頭像等)。如大轉盤等游戲記錄哪個微信用戶獲得什么獎品、H5等小游戲需要把分數與對應用戶捆綁在一起等網頁應用。
微信公眾平台oauth2.0網頁授權能干什么
它是在自己做的網站中不用用戶登錄來獲取微信用戶相關信息的,進而實現相關業務。
說明與注意
1、網頁授權分為兩種,
一種為只獲取openid (基本授權 snsapi_base)
一種為獲取用戶全部信息 (高級授權 snsapi_userinfo)。
2、你的公眾號必須為認證的訂閱號或者認證的服務號。否則沒有此接口權限。
3、你要配置好回調域名:即用戶點擊網址獲取用戶信息后打開哪個域名。
4、如有下圖錯誤請檢查是否配置好回調域名或者公眾號是否認證(我之前一直測試提示如下圖出錯,仔細查找錯誤才發現沒配置回調域名)
怎樣配置回調域名
1、進入https://mp.weixin.qq.com,點擊最下面的”接口權限“菜單(如下圖)
1-1、如果是測試賬號的話,如下圖
(1)打開瀏覽器,這里以IE為例,輸入:http://mp.weixin.qq.com/debug/cgi-bin/sandbox?t=sandbox/login
(2)
(3)用手機登錄你的微信,使用微信中的“掃一掃”功能,掃描上面網頁中的二維碼。在手機上會出現以下界面:
(4)網頁授權獲取用戶基本信息
2、找到‘網頁授權用戶基本信息’,如下圖
3、點擊修改,填寫域名。如:我的回調網址為http://wechatu.xd107.com/home/WeiXin/index 則填寫wechatu.xd107.com。配置回調域名完成。
不管獲取openid還是用戶所有信息都需要首先配置回調域名
4、實際代碼(ThinkPhp框架)
class WeiXinController extends Controller { /** * 這里采用高級授權模式,為了獲取用戶信息 * 這個頁面是用戶進來就能夠剛問的頁面,也就是首次進來的頁面 * 首先訪問的地址 ;http://wechatu.xd107.com/home/WeiXin/index */ public function index() { $appid = 'wx94c43716d8a91f3f'; /*基本授權 方法跳轉地址*/ $redirect_uri = urlencode('http://wechatu.xd107.com/home/WeiXin/getUserInfo'); /*基本授權 snsapi_base*/ //$url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=".$appid."&redirect_uri=".$redirect_uri."&response_type=code&scope=snsapi_base&state=1234#wechat_redirect"; /*高級授權 snsapi_userinfo*/ $url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" . $appid . "&redirect_uri=" . $redirect_uri . "&response_type=code&scope=snsapi_userinfo&state=1234#wechat_redirect"; //跳轉 header('location:' . $url); } /*拉取用戶信息*/ public function getUserInfo() { $appid = 'wx94c43716d8a91f3f'; $appsecret = 'd4624c36b6795d1d99dcf0547af5443d'; /*回調的時候自帶的這個參數*/ $code = $_GET['code']; /*基本授權 snsapi_base*/ //$url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=".$appid."&redirect_uri=".$redirect_uri."&response_type=code&scope=snsapi_base&state=1234#wechat_redirect"; $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" . $appid . "&secret=" . $appsecret . "&code=" . $code . "&grant_type=authorization_code"; $result = json_decode(curlPost($url,$parm = null),true); /*取出數組中的access_token這個值*/ $access_token = $result['access_token']; $openid = $result['openid']; $URL2 = "https://api.weixin.qq.com/sns/userinfo?access_token=" . $access_token . "&openid=" . $openid . "&lang=zh_CN"; $responseInfo = json_decode(curlPost($URL2,$parameter = null),true); $_SESSION['headimgurl'] = $responseInfo['headimgurl']; var_dump($responseInfo); die; $this->headimgurl = $responseInfo['headimgurl']; $this->userInfo = $responseInfo; $this->display(); } }
5、流程圖(百度腦圖)
說明:開始詳解:(1)網頁授權分為兩種,(2)微信公眾賬號和用戶的微信聯系字段為【openid】
6、具體步驟: