nodejs服务获取微信用户openid

Posted chi1130

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了nodejs服务获取微信用户openid相关的知识,希望对你有一定的参考价值。

前端代码

接口发送code就可以

<template>
    <view class="brn-wrap">
      <view class="uni-btn-v" v-if="!hasLogin">
        <button @click="handleBeforeLogin">{{ title }}</button>
      </view>
      <view class="uni-btn-v" v-else>
        <button @click="handleTitleClick">{{ title }}</button>
      </view>
    </view>
</template>

  import { requestLogin } from '@/utils/str.js';
  export default {
    props: {
      title: {
        type: String,
        default: '提交发布'
      }
    },
    data() {
      return {
        hasLogin: false
      };
    },
    methods: {
      handleTitleClick() {
        this.$emit('submit');
      },
      handleBeforeLogin() {
        let that = this;
        // 推荐使用wx.getUserProfile获取用户信息,开发者每次通过该接口获取用户个人信息均需用户确认
        // 开发者妥善保管用户快速填写的头像昵称,避免重复弹窗
        wx.getUserProfile({
          desc: '用于完善用户资料', // 声明获取用户个人信息后的用途,后续会展示在弹窗中,请谨慎填写
          success: res => {
            console.log(res);
            that.doLogin(res);
          }
        });
      },
      doLogin(detail) {
        const self = this;
        if (detail.errMsg === 'getUserProfile:ok') {
          console.log('===', detail);
          const options = wx.getLaunchOptionsSync();
          const scene = options.scene + '';
          if (scene.startsWith('CRLAND:')) {
            detail.userInfo.scene = scene.substr(7);
          }
          requestLogin().then(async data => {
            console.log('========', detail.userInfo);
            const obj = {
              ...detail.userInfo,
              userInfo: detail.rawData,
              code: data.code
            };
            const { code, result } = await this.$api.user.login(obj);
            if (code === 200) {
              uni.setStorageSync('userInfo', JSON.stringify(detail.userInfo));
              uni.setStorageSync('token', result.token);
              uni.setStorageSync('userId', result.userId);
              this.hasLogin =true;
              uni.switchTab({
                url: '/pages/index/index'
              });
            } else {
              uni.showModal({
                title: '提示',
                content: e.msg || '登录失败',
                showCancel: false,
                confirmText: '确定',
                success: res => {}
              });
            }
          });
        }
      }
    }
  };

后端代码

后端只需要拿到code就可以,code不能二次使用

const express = require('express')
const http = require('https')
const router = express.Router()
const mongoose = require('mongoose')
const qs = require('querystring')
const User = require('../models/User') //引入模块模型
const vertoken = require('../utils/token') //引入token
const wx = require('../config/wx')

// 登录
router.post('/login', (_req, _res) => {
  console.log(_req.body, ' 页面传入参数')
  let user = Object.assign({}, _req.body)
  var query = {
    appid: wx.appid,
    secret: wx.secret,
    js_code: _req.body.code,
    grant_type: 'authorization_code',
  }
  var content = qs.stringify(query)
  var options = {
    hostname: 'api.weixin.qq.com',
    port: '',
    path: '/sns/jscode2session?' + content,
    method: 'GET',
    header: {
      'content-type': 'application/x-www-form-urlencoded;charset=UTF-8',
    },
  }

  var req = http.request(options, function (res) {
    res.on('data', function (_data) {
      console.log('_data: ', _data)

      let parsData = JSON.parse(_data.toString())
      const { openid } = parsData
      User.find(
        {
          openid,
        },
        (err, users) => {
          if (users && users.length > 0) {
            vertoken.setToken(users[0]._id, users[0].openid).then((token) => {
              _res.json({
                code: 200,
                result: {
                  token,
                  userId:users[0]._id
                },
                message: '登录成功',
              })
            })
          } else {
            user.openid = openid
            new User(user).save().then((val) => {
              vertoken.setToken(val._id, openid).then((token) => {
                _res.json({
                  code: 200,
                  result: {
                    token,
                    userId:val._id
                  },
                  message: '登录成功',
                })
              })
            })
          }
        }
      )
    })
  })

  req.on('error', function (e) {
    console.log('problem with request: ' + e.message)
  })

  req.end()
})

module.exports = router

完整代码

前端
node服务端

以上是关于nodejs服务获取微信用户openid的主要内容,如果未能解决你的问题,请参考以下文章

nodejs服务获取微信用户openid

nodejs+koa+uniapp实现微信小程序登陆获取用户手机号及openId

微信小程序获取用户openid

微信绑定用户服务端代码-根据code获取openId然后绑定用户

如何获取微信用户openid

微信小程序 获取用户openid