1.調(diào)用wx.login得到code
返回的結(jié)果示例:
{ code:"051nI5Pa1XJkDs0773Pa1OWYOa1nI5PF" errMsg:"login:ok"}
2.拿code換取session_key與openid
這里使用服務(wù)端來請求,以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換成自己小程序的
得到的返回結(jié)果如下:
{ "session_key": "odMd5E1qJI5KJH7OTBVZYg==", "expires_in": 7200, "openid": "oqMjq0BqLl6mRarbByCf9rOAc3k0"}
4.生成用戶或登錄用戶
如果該openid不存在于數(shù)據(jù)庫中,認(rèn)為是新用戶,注冊它,如果openid已存在于數(shù)據(jù)庫,認(rèn)為是老用戶。
php代碼如下:
<?php class User_model extends CI_Model { // 當(dāng)前用戶 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.服務(wù)端生成自己的3rd_session
// 創(chuàng)建隨機(jī)數(shù) private function generate3rdSession() { return md5(mt_rand() . $this->user->openid); }
在registOrUpdate方法的最末尾加上如下代碼調(diào)用:
$response = [ 'thirdSession' => $this->generate3rdSession() ]; echo json_encode($response);
經(jīng)上,3rd_session發(fā)送到了小程序客戶端,接下來要做的是將它保存到storage中,以便于后續(xù)的每次wx.request()調(diào)用。
提示:按照官方文檔的時(shí)序圖來看,以上的隨機(jī)還是真隨機(jī),它不是良好示范,對安全嚴(yán)謹(jǐn)?shù)挠猛荆?jǐn)慎使用。
6.小程序端本地存儲(chǔ)服務(wù)端傳來的3rd_session
//發(fā)起網(wǎng)絡(luò)請求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到服務(wù)端,需要用到官方提供好的解密sdk,https://mp.weixin.qq.com/debug/wxadoc/dev/demo/aes-sample.zip,其中包含了php示例代碼,對它簡單的復(fù)制粘貼如下
// 獲取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,就可以與自己的同一開發(fā)平臺(tái)的帳號體系下的應(yīng)用打通了,否則不會(huì)返回unionid。
這里有個(gè)坑,就是要把require_once放在getUnionId方法體內(nèi),而不是類頂部,因?yàn)闉楦蓴_header("Content-type: application/json")的輸出,導(dǎo)致小程序端拿到的res.data是string而不是json對象。
最后成功存到了數(shù)據(jù)庫,得到自己關(guān)心的信息。
注意要先將小程序掛載在開放平臺(tái)下