云函数获取UnionID失败
用wx.login + code2Session的方式在云函数中获取UnionID失败
云控制台打印出来的解密之后的data
这是我云函数的代码,WXBizDataCrypt用的是官方的Node解密demo的文件
// 云函数入口文件 const cloud = require( 'wx-server-sdk' ) const request = require( 'request' ); const WXBizDataCrypt = require( './WXBizDataCrypt' ) cloud.init() const db = cloud.database(); // 云函数入口函数 exports.main = async (event, context) => { let url = 'https://api.weixin.qq.com/sns/jscode2session?appid=wx80729b3c71a89b47&secret=d7425e5d465a3ee7e6f3a0aca3ab8ab2&js_code=' + event.code + '&grant_type=authorization_code' ; return new Promise((resolve, reject) => { new Promise((resolve, reject) => { try { request(url, function (error, response, body) { if (!error && response.statusCode == 200) { return resolve(body) } else { return reject(err) } }) } catch (err) { return reject(err) } }).then(res => { console.log(res) console.log(JSON.parse(res)) let result = JSON.parse(res); let appId = event.userInfo.appId; let sessionKey = result.session_key; console.log(sessionKey) let encryptedData = event.encryptedData; let iv = event.iv; let pc = new WXBizDataCrypt(appId, sessionKey); let data = pc.decryptData(encryptedData, iv); console.log( "----data--------:" , data) console.log( "-------UnionID--------:" , data.unionId) return resolve( "ok" ) }); }); } |
2 回复
https://developers.weixin.qq.com/miniprogram/dev/framework/open-ability/union-id.html官方文档有说,用你的方法必须是用户已关注公众号