推薦(免費):
微信小程式開放檔案: developers.weixin.qq.com/miniprogr...
本部落格僅作為記錄微信小程式登入流程, 具體程式碼請參考微信檔案.
小程式端先呼叫wx.login() 介面獲取登入憑證code , 在success回撥方法中再呼叫wx.getUserInfo() 介面獲取使用者基本資訊(介面成功返回 encryptedData 使用者敏感資訊加密資料 ; iv 加密演演算法的初始向量)
wx.login({ success: function (e) { var code = e.code;//登入憑證 if (code) { //2、呼叫獲取使用者資訊介面 wx.getUserInfo({ success: function (res) { console.log({encryptedData: res.encryptedData, iv: res.iv, code: code}); // 將code, encryptedData ,iv 傳送給伺服器端 ,根據伺服器端返回的資料判斷登入成功或者失敗 }, fail: function () { console.log('獲取使用者資訊失敗') } }) } else { console.log('獲取使用者登入態失敗!' + e.errMsg) } }, fail: function () { callback(false) }})
wx.login檔案地址: developers.weixin.qq.com/miniprogr...
wx.getUserInfo檔案地址: developers.weixin.qq.com/miniprogr...
伺服器端: 獲取小程式端的引數code 呼叫微信 auth.code2Session介面. 成功返回openid, session_key 等, 然後檢視微信官方給出的驗證解密檔案
public function miniProgramLogin($code){ $url = "https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=SECRET&js_code=$code&grant_type=authorization_code"; return json_decode(curl_request($url), true);}//助手函數 curl_requestfunction curl_request($url, $data=null, $method='get', $header = array("content-type: application/json"), $https=true, $timeout = 5){ $method = strtoupper($method); $ch = curl_init();//初始化 curl_setopt($ch, CURLOPT_URL, $url);//存取的URL curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);//只獲取頁面內容,但不輸出 if($https){ curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);//https請求 不驗證證書 curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);//https請求 不驗證HOST } if ($method != "GET") { if($method == 'POST'){ curl_setopt($ch, CURLOPT_POST, true);//請求方式為post請求 } if ($method == 'PUT' || strtoupper($method) == 'DELETE') { curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method); //設定請求方式 } curl_setopt($ch, CURLOPT_POSTFIELDS, $data);//請求資料 } curl_setopt($ch, CURLOPT_TIMEOUT, $timeout); curl_setopt($ch, CURLOPT_HTTPHEADER, $header); //模擬的header頭 //curl_setopt($ch, CURLOPT_HEADER, false);//設定不需要頭資訊 $result = curl_exec($ch);//執行請求 curl_close($ch);//關閉curl,釋放資源 return $result;}
auth.code2Session介面檔案 : developers.weixin.qq.com/miniprogr...
資料解密檔案 (有不同語言的範例程式碼): developers.weixin.qq.com/miniprogr...
解密後的資料:
獲取解密的資料後儲存/更新使用者表.
以上就是詳解 微信小程式授權登入獲取使用者資訊的詳細內容,更多請關注TW511.COM其它相關文章!