1.調用wx.login得到code
返回的結果示例:
{ code:"051nI5Pa1XJkDs0773Pa1OWYOa1nI5PF" errMsg:"login:ok"}
2.拿code換取session_key與openid
這里使用服務端來請求,以php為例
$code = $this->input->post('code'); $json = 'https://api.weixin.qq.com/sns/jscode2session?appid='.WxPayConfig::APPID.'&secret='.WxPayConfig::APPSECRET.'&js_code='.$code.'&grant_type=authorization_code'; header("Content-Type: application/json");echo file_get_contents($json);
其中appid與appsecret換成自己小程序的
得到的返回結果如下:
{ "session_key": "odMd5E1qJI5KJH7OTBVZYg==", "expires_in": 7200, "openid": "oqMjq0BqLl6mRarbByCf9rOAc3k0"}
4.生成用戶或登錄用戶
如果該openid不存在于數據庫中,認為是新用戶,注冊它,如果openid已存在于數據庫,認為是老用戶。
php代碼如下:
<?php class User_model extends CI_Model { // 當前用戶 private $user; // 注冊或更新用戶 public function registOrUpdate($data) { if ($this->verify($data)) { $this->update(['session_key' => $data->session_key], ['uid' => $this->user->uid]); } else { $this->regist($data); } $response = [ 'thirdSession' => $this->generate3rdSession() ]; echo json_encode($response); } // 注冊用戶 private function regist($data) { $this->db->insert('user', $data); } // 更新用戶 private function update($user, $condition) { $this->db->update('user', $user, $condition); } // 檢測用戶是否存在 private function verify($data) { $query = $this->db->get_where('user', ['openid'=>$data->openid]); $user = $query->first_row(); $this->user = $user; if ($query->num_rows()) { return true; } return false; } }
5.服務端生成自己的3rd_session
// 創建隨機數 private function generate3rdSession() { return md5(mt_rand() . $this->user->openid); }
在registOrUpdate方法的最末尾加上如下代碼調用:
$response = [ 'thirdSession' => $this->generate3rdSession() ]; echo json_encode($response);
經上,3rd_session發送到了小程序客戶端,接下來要做的是將它保存到storage中,以便于后續的每次wx.request()調用。
提示:按照官方文檔的時序圖來看,以上的隨機還是真隨機,它不是良好示范,對安全嚴謹的用途,謹慎使用。
6.小程序端本地存儲服務端傳來的3rd_session
//發起網絡請求wx.request({ url: 'http://localhost:3000/index.php/WXLogin/getSession', data: { code: res.code }, header: { "content-type": "application/x-www-form-urlencoded" }, method: 'POST', success: function (res) { // 保存3rdSession到storage中 wx.setStorage({ key:"thirdSession", data: res.data.thirdSession }) }, fail: function (res) { console.log(res); } })
需要用到wx.getUserInfo,https://mp.weixin.qq.com/debug/wxadoc/dev/api/open.html#wxgetuserinfoobject,從小程序端傳入$encryptedData, $iv到服務端,需要用到官方提供好的解密sdk,https://mp.weixin.qq.com/debug/wxadoc/dev/demo/aes-sample.zip,其中包含了php示例代碼,對它簡單的復制粘貼如下
// 獲取unionid private function getUnionId($encryptedData, $iv) { require_once __DIR__ . '/../third_party/aes/wxBizDataCrypt.php'; $appid = 'wxcb935c2ec6734f08'; $pc = new WXBizDataCrypt($appid, $sessionKey); $errCode = $pc->decryptData($encryptedData, $iv, $data ); if ($errCode == 0) { $obj = json_decode($data); var_dump($obj->unionId); return [ 'unionid' => $obj->unionId, 'nickname' => $obj->nickName, 'avatarUrl' => $obj->avatarUrl, 'gender' => $obj->gender ]; } else { print($errCode . "\n"); } }
這樣就得到了unionid,就可以與自己的同一開發平臺的帳號體系下的應用打通了,否則不會返回unionid。
這里有個坑,就是要把require_once放在getUnionId方法體內,而不是類頂部,因為為干擾header("Content-type: application/json")的輸出,導致小程序端拿到的res.data是string而不是json對象。
最后成功存到了數據庫,得到自己關心的信息。
注意要先將小程序掛載在開放平臺下