2018-09-22
目前小程序获取群ID只有一个办法,就是分享小程序到微信群后,用户从微信点小程序进来,才能获取群ID。
测试页面test.wxml
<view>
<view wx:if="{{openGid}}" class='groupName'>
群名称:
<open-data type="groupName" open-gid="{{openGid}}"></open-data>
</view>
<view wx:else>
<button class='button' bindtap='clickReload'>点击加载群名称和群ID</button>
</view>
<view class='button'>{{openGid ? openGid : ' '}}</view>
<view>把这个页面在真机上分享到微信群,然后从群里点进来,再点击按钮就能获取群ID</view>
</view>
test.js
const app = getApp()
Page({
/**
* 页面的初始数据
*/
data: {
},
onLoad: function (options) {
let that = this
wx.showShareMenu({
//设为true,获取ShareTicket
withShareTicket: true
})
app.getShareTiket(function (globalData) {
console.log('clickReload---globalData-->' + JSON.stringify(globalData))
that.setData({
openGid: globalData.openGid
})
})
},
clickReload: function () {
let that = this
app.getShareTiket(function (globalData) {
console.log('clickReload---globalData-->' + JSON.stringify(globalData))
that.setData({
openGid: globalData.openGid
})
})
}
})
app.js
wx.cloud.init();
App({
onShow: function (options) {
let that = this
if (options && options.scene == 1044) {
//获取shareTicket
that.globalData.shareTicket = options.shareTicket
}
console.log('onShow---options=--->' + JSON.stringify(options))
},
getShareTiket: function (cb) {
let that = this
if (that.globalData.shareTicket) {
wx.getShareInfo({
shareTicket: that.globalData.shareTicket,
success: function (res) {
console.log('getShareTiket---shareTicket-->' + JSON.stringify(res))
//获取encryptedData、iv
let js_encryptedData = res.encryptedData
let js_iv = res.iv
wx.login({
success: function (res) {
//获取code
console.log('code-->' + res.code)
//调用云函数,破解opengid
wx.cloud.callFunction({
name: 'opengid',
data: {
js_code: res.code,
appId: 'wx7c1126bc182ab756',
encryptedData: js_encryptedData,
iv: js_iv
},
success: function (res) {
console.log('打印opengid' + res.result.openGId);
console.log('res' + JSON.stringify(res));
that.globalData.openGid = res.result.openGId
console.log('getShareTiket---openGid' + that.globalData.openGid)
typeof cb == "function" && cb(that.globalData)
},
fail: function (err) {
console.log('getShareTiket---err' + JSON.stringify(err))
}
})
}
})
}
})
} else {
console.log('不存在shareTicket')
}
},
globalData: {
shareTicket: '',
openGid: ''
}
})
在云函数couldfunctions目录下新建opengid云函数,在opengid目录下用npm安装crypto和request。
opengid/index.js
const cloud = require('wx-server-sdk');
const WXBizDataCrypt = require('./WXBizDataCrypt')
const requestSync = require('./requestSync')
cloud.init();
/*
传入参数
{
data:{
js_code,
encryptedData,
iv
}
}
*/
exports.main = async (event, context) => {
const code = event.js_code;
const appid = event.userInfo.appId;
const encryptedData = event.encryptedData;
const iv = event.iv;
const secret = '填你小程序的secret'
const url = {
url: 'https://api.weixin.qq.com/sns/jscode2session?appid=' + appid + '&secret=' + secret + '&js_code=' + code + '&grant_type=authorization_code'
}
const req = await requestSync(url);
const session = JSON.parse(req);
const sessionKey = session.session_key;
const pc = new WXBizDataCrypt(appid, sessionKey);
const data = pc.decryptData(encryptedData, iv);
return data;
}
另外在opengid目录下新建requestSync.js,获取sessionKey
const request = require("request");
const requestSync = async (url) =>
new Promise((resolve, reject) => {
request(url, (err, response, body) => {
if (err) {
reject(err);
} else {
resolve(body);
}
})
})
module.exports = requestSync
在opengid目录下新建WXBizDataCrypt.js,用来解密,这段代码是微信官网示例代码nodejs版本。
var crypto = require('crypto')
function WXBizDataCrypt(appId, sessionKey) {
this.appId = appId
this.sessionKey = sessionKey
}
WXBizDataCrypt.prototype.decryptData = function (encryptedData, iv) {
// base64 decode
var sessionKey = new Buffer(this.sessionKey, 'base64')
encryptedData = new Buffer(encryptedData, 'base64')
iv = new Buffer(iv, 'base64')
try {
// 解密
var decipher = crypto.createDecipheriv('aes-128-cbc', sessionKey, iv)
// 设置自动 padding 为 true,删除填充补位
decipher.setAutoPadding(true)
var decoded = decipher.update(encryptedData, 'binary', 'utf8')
decoded += decipher.final('utf8')
decoded = JSON.parse(decoded)
} catch (err) {
console.log('try err', err)
throw new Error('Illegal Buffer1')
}
if (decoded.watermark.appid !== this.appId) {
throw new Error('appid unmatch')
}
return decoded
}
module.exports = WXBizDataCrypt
在模拟器上无法获取shareTicket,你要在真机上建一个群,然后分享点击,才能获取shareTicket,进而解出opengid。
代码没有完全调试,直接复制粘贴,可能会报错,如果报错,请留言告知。
整体上看用云函数和原来的服务端开发差不多,熟悉了感觉更方便,毕竟不需要搭建后端了。如果后期微信能像获取openid一样方便的获取群ID那就更好了。现在的过程还是太绕了。
感谢这两位朋友提供的代码,是他们提供轮子。
小程序如何获取群聊的openGid以及名称
小程序用云函数获取opengid
调试过程遇到的坑。
对象不能直接打印出来,需要用JSON.stringify()转成json才能打印出来。