为了账号安全,请及时绑定邮箱和手机立即绑定

小程序的登录

标签:
小程序

交互流程

官方交互流程

小程序端

示例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 点赞

若觉得本文不错,就分享一下吧!

评论

作者其他优质文章

正在加载中
  • 推荐
  • 评论
  • 收藏
  • 共同学习,写下你的评论
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦
今天注册有机会得

100积分直接送

付费专栏免费学

大额优惠券免费领

立即参与 放弃机会
意见反馈 帮助中心 APP下载
官方微信

举报

0/150
提交
取消