微信小程序登录获取openid和unionid

  |  
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
'use strict';
const got = require('got');
const config = require('./app/config/config');

(async () => {
let appid = 微信小程序appid;
let appsecret = 微信小程序secret;
let code = '011fFOne11STVx0r5dme1OKZne1fFOnO';

let WxLoginInfo = (await got.get(`https://api.weixin.qq.com/sns/jscode2session?appid=${appid}&secret=${appsecret}&js_code=${code}&grant_type=authorization_code`, { 'json': true })).body;
console.log('WxLoginInfo==========>', WxLoginInfo);
// 返回值
let { session_key, openid, unionid } = WxLoginInfo || {}; (获取unionid是小程序必须绑定服务号,不然这个值没有)
// {session_key: "YozKPN8fRCbxg/gsFpXWZg==", openid: "o6MbF5J5J6Ay5au3WvnKgYKnh", unionid: "o5NOMjtuRtqcSfwYrScf7OGIDIyM"}
let accessTokenInfo = (await got.get(`https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${appid}&secret=${appsecret}`, { 'json': true })).body;
let { access_token = '', errcode, errmsg } = accessTokenInfo || {};

})();
文章目录