微信扫码登录nodejs后端代码


前一篇文章讲解了微信扫码登录前端代码

本章给大家分享微信扫码登录的nodejs版后端代码

async wxLogin(){
    //1、接收前端参数code,并通过公众号的appID和appSecret加上code获取accessToken和用户openid
    let code = this.req.body['code'];
    if (!code) {
      this.success('ok', {
        code: -1,
        msg: '缺少code参数!'
      })
      return
    }

    let url = `https://api.weixin.qq.com/sns/oauth2/access_token?appid=${config.wechat.openSellerPc.appID}&secret=${config.wechat.openSellerPc.appSecret}&code=${code}&grant_type=authorization_code`

    let that = this
    //通过code获取accesstoken和openid
    request(url, async function (error, response, body) {
      if (!error && response.statusCode == 200) {
        let bodyJson = JSON.parse(body)
        if (bodyJson.errcode) {
          that.error(bodyJson.errmsg)
          return
        }
        //2、通过accessToken和openid 获取用户的基本信息
        url = `https://api.weixin.qq.com/sns/userinfo?access_token=${bodyJson.access_token}&openid=${bodyJson.openid}&lang=zh_CN`
        request(url, async function (error, response, body) {
          if (!error && response.statusCode == 200) {
            let userJson = JSON.parse(body)
            //根据unionid去数据库查询是否存在该用户
            let userinfo = await models.ag_seller.findOne({
              where: {
                unionid: userJson.unionid
              }
            })
            /************************以下是我的个人逻辑代码,仅供参考*******************************/
            if(userinfo){
              await that.createLoginLog(userinfo,ip,equipment,1)
              let last_logintime = new Date()
              
              let data = {
                last_logintime: last_logintime,
                nickname: userJson.nickname,
                sex: userJson.sex,
                country: userJson.country,
                province: userJson.province,
                city: userJson.city,
                headimgurl: userJson.headimgurl,
                unionid:userJson.unionid
              }
              await models.ag_seller.update(data, {
                where: {
                  id: userinfo.id
                }
              })
              let user = {
                id: userinfo.id,
                username: userJson.username,
                last_logintime:last_logintime,
                loginip:userinfo.loginip,
                headimgurl:userJson.headimgurl,
                shop_name:userinfo.shop_name
              }
              let token = jwt.sign(user, config.jwt.secret);
              user.token = token
              that.success('ok',user)
            }else{
              that.success('ok', {
                code: -1,
                msg: '用户不存在!'
              })
            }
          } else {
            that.error(body)
          }
        })

      } else {
        that.error(body)
      }
    });
KK资源网分享最优质的的资源,涵盖网站建设、IT技术、主题源码
KK资源吧 » 微信扫码登录nodejs后端代码

发表评论