文档出处:https://mp.weixin.qq.com/debug/wxadoc/dev/api/api-login.html
步骤:
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()调用。
提示:按照官方文档的时序图来看,以上的随机还是真随机,它不是良好示范,对安全严谨的用途,谨慎使用。
unionid.png
注意要先将小程序挂载在开放平台下
bind.png










网友评论