前提准备:
1、需要知道AppID(小程序ID)
2、AppSecret(小程序密钥)
3、调wx.login成功后返回的code
代码如下:
const express = require('express');
const router = express.Router();
const request = require('request')
const APP_URL = 'https://api.weixin.qq.com/sns/jscode2session'router.get('/getopenid', (req, res) => {const js_code = req.query.codeconst ART_APP_ID = ''//AppID(小程序ID)const ART_APP_SECRET = ''//AppSecret(小程序密钥) if (js_code) {request(`${APP_URL}?appid=${ART_APP_ID}&secret=${ART_APP_SECRET}&js_code=${js_code}&grant_type=authorization_code`, (error, response, body) => {if (error) throw errorif (response.statusCode === 200) {const bodyInfo = JSON.parse(body)const openId = bodyInfo.openidres.json({success_code: 200,data: {openId}})} else {res.json({success_code: 400,message: '获取用户信息失败'})}})}})
module.exports = router;