背景:由于公司可能需要在微信群里面使用打卡功能,因此做了个技术调研。
方案:微信在更新分享接口后,原有的在onShareAppMessage中直接拿shareTicket已不复存在。根据最新文档显示,需要在App.onLaunch()跟App.onShow()中获取。
Demo核心代码:
index.js
- Page({
-
- /**
- * 页面的初始数据
- */
- data: {
- openGid: ''
- },
-
- /**
- * 生命周期函数--监听页面加载
- */
- onLoad: function (options) {
- let that = this
- wx.showShareMenu({
- 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
- })
- })
- }
- })
index.wxml
- <!--index.wxml-->
- <view wx:if="{{openGid}}" class='groupName'>
- 群名称:<open-data type="groupName" open-gid="{{openGid}}"></open-data>
- </view>
-
- <view wx:else>
- <button bindtap='clickReload'>点击加载群名称</button>
- </view>
-
- <view>{{openGid ? openGid : '无'}}</view>
app.js
- //app.js
- App({
- globalData: {
- shareTicket: '',
- openGid: ''
- },
- onLaunch: function (options) {
-
- },
- onShow: function (options) {
- let that = this
- if (options && options.scene == 1044) {
- 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))
- let js_encryptedData = res.encryptedData
- let js_iv = res.iv
- wx.login({
- success: function (res) {
- let js_code = res.code
- console.log('code-->' + js_code)
- wx.request({
- url: 'xxxxxxxx',
- method: 'POST',
- data: {
- code: js_code,
- appId: 'xxxxx',
- encryptedData: js_encryptedData,
- iv: js_iv
- },
- success: function (res) {
- that.globalData.openGid = res.data.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')
- }
- }
- })
注意事项
1:必须调用这个接口wx.showShareMenu({withShareTicket: true}),否则在App.onLaunch()跟App.onShow()时,你拿不到shareTicket.
2:微信开发者工具可以模拟1044的场景,但是不会显示群名称,因为你不在群里。所以测试的时候,自己拉个微信群,然后分享到测试群,就能拿到群名称。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持w3xue。