交互流程
小程序端
示例xfdg
- wx.checkSession 微信端校验会话有效性,不用每次都去微信服务端请求code
- sessionId是服务的根据code和sessionKey生成的,客户端没有的话需要重新来一遍
- 当微信会话失效的时候,也需要重新请求code,再生成sessionId传给客户端
import { wnLogin } from "./utils/api.js";
App({
onLaunch: function () {
let _this = this
wx.checkSession({
success () {
// 微信session有效 判断本地是否存储了服务器的sessionId
if (!wx.getStorageSync('sessionId')) {
// 没有code 还是需要执行重新登录操作
console.log('wx session success but token invalid')
_this.imLogin()
}
},
fal () {
console.log('wx session fail')
_this.imLogin()
}
})
},
imLogin: function () {
// 登录微信服务器
wx.login({
success: res => {
// 发送 res.code 到后台换取 openId, sessionKey, unionId
wnLogin(res.code).then(result => {
// 存储本地 session_id
console.log(result)
if (result.code === 0) {
wx.setStorageSync('sessionId', result.data.sessionId)
} else {
wx.showToast({
title: result.msg,
icon: 'loading'
})
}
}).catch(err => {
console.log(err)
})
}
})
},
globalData: {
userInfo: null
}
})
后端
代码
namespace app\wnapi\controller;
use app\BaseController;
use app\common\model\User;
class Wn extends BaseController
{
/**
* 用户登录
* @return \think\response\Json
*/
public function login()
{
// 根据openid判断用户是否存在 不存在则存储
$code = $this->request->get('code');
$wx_info = $this->app->wn_service->getOpenId($code);
if ($wx_info && isset($wx_info['openid'])) {
// 存在则更新 session_id
// 返回给前端 session_id,前端存储下来
$user = User::where(['wn_openid' => $wx_info['openid']])->findOrEmpty();
if ($user->isEmpty()) {
$user->wn_openid = $wx_info['openid'];
$user->create_time = time();
$user->update_time = time();
}
$user->wn_session_id = md5($wx_info['session_key']. $wx_info['openid']);
$user->save();
return json([
'code' => 0,
'msg' => '登录成功',
'data' => [
'sessionId' => $user->wn_session_id
],
'time' => time()
]);
} else {
return json([
'code' => -1,
'msg' => $wx_info['errmsg'],
'data' => [],
'time' => time()
]);
}
}
}
点击查看更多内容
为 TA 点赞
评论
共同学习,写下你的评论
评论加载中...
作者其他优质文章
正在加载中
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦