微信网页开发
微信網站一般是先要微信網頁授權后獲取到access_token,才有資格獲取用戶信息的,所以如果用戶在微信客戶端中訪問第三方網頁,公眾號可以通過微信網頁授權機制,來獲取用戶基本信息,進而實現業務邏輯。
第一步是先獲取用戶授權(具體的請看微信開發者文檔):
? ? ? 授權也分兩種:靜態授權和手動授權:
? ? ? ? 關于網頁授權的兩種scope的區別說明
? 1、以snsapi_base為scope發起的網頁授權,是用來獲取進入頁面的用戶的openid的,并且是靜默授權并自動跳轉到回調頁的。用戶感知的就是直接進入了回調頁(往往是業務頁面)
2、以snsapi_userinfo為scope發起的網頁授權,是用來獲取用戶的基本信息的。但這種授權需要用戶手動同意,并且由于用戶同意過,所以無須關注,就可在授權后獲取該用戶的基本信息。?
?3、用戶管理類接口中的“獲取用戶基本信息接口”,是在用戶和公眾號產生消息交互或關注后事件推送后,才能根據用戶OpenID來獲取用戶基本信息。這個接口,包括其他微信接口,都是需要該用戶(即openid)關注了公眾號后,才能調用成功的。
? ? ? ? ? ? ? ? ?
1 /** 2 * 網頁授權獲取用戶openid(靜默授權) 3 */ 4 public function getOpenid($code){ 5 $url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid='. Wxapi::APPID . '&secret=' . Wxapi::APPSECRET . '&code=' . $code . '&grant_type=authorization_code'; 6 $result = json_decode($this->CurlGet($url),true); 7 return $result; 8 }?
?
請參考文檔來理解:https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421140842
?
?
1 /** 2 * 網頁授權獲取用戶基本信息(手動同意) 3 */ 4 public function getUserInfo($code,$refresh_token){ 5 if(!empty($code)){ 6 //code換取網頁授權access_token 7 $url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid='. Wxapi::APPID . '&secret=' . Wxapi::APPSECRET . '&code=' . $code . '&grant_type=authorization_code'; 8 $result = json_decode($this->CurlGet($url),true); 9 }else if(!empty($refresh_token)){ 10 //刷新access_token 11 $url = 'https://api.weixin.qq.com/sns/oauth2/refresh_token?appid=' . Wxapi::APPID . '&grant_type=refresh_token&refresh_token=' . $refresh_token; 12 $result = json_decode($this->CurlGet($url),true); 13 if(!empty($result['errcode'])){ 14 $url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" . Wxapi::APPID . "&redirect_uri=" . $redirect_uri . "&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect";//refresh_token過期失效重新授權 15 header("Location:$url");//跳轉授權頁面 16 } 17 }else{ 18 return array('errcode' => '???','errmsg' => '請傳入code或refresh_token'); 19 } 20 21 //錯誤返回處理 22 if(!empty($result['errcode'])){ 23 return $result; 24 }else{ 25 //拉取用戶信息 26 $url = 'https://api.weixin.qq.com/sns/userinfo?access_token=' . $result['access_token'] . '&openid=' . $result['openid'] . '&lang=zh_CN'; 27 $user_info = json_decode($this->CurlGet($url),true); 28 $user_info['refresh_token'] = $result['refresh_token']; 29 30 return $user_info; 31 } 32 }?
?
相關資料:
json_decode
PHP json_decode() 函數用于對 JSON 格式的字符串進行解碼,并轉換為 PHP 變量。
語法
mixed json_decode ($json [,$assoc = false [, $depth = 512 [, $options = 0 ]]])參數
-
json_string: 待解碼的 JSON 字符串,必須是 UTF-8 編碼數據
-
assoc: 當該參數為 TRUE 時,將返回數組,FALSE 時返回對象。
-
depth: 整數類型的參數,它指定遞歸深度
-
options: 二進制掩碼,目前只支持 JSON_BIGINT_AS_STRING 。
?
CurlGet : 將url發送出去,返回相關數據?
轉載于:https://www.cnblogs.com/laijinquan/p/7483617.html
總結
- 上一篇: handler消息机制入门
- 下一篇: Surf Gym - 100819S