微信小程序 转发到群聊里,获取shareTicket、获取群标识 openGId 【包含前、后端代码】

【官方文档】群转发

【官方文档】获取转发详细信息

效果图查看:

微信小程序 转发到群聊里,获取shareTicket、获取群标识 openGId 【包含前、后端代码】_第1张图片

前端代码如下:

【share.js】:

const app = getApp();
var shareTicket,that, sessionKey, encryptedData;
Page({
  data: {

  },
  onShow: function() {
    that = this;
    var p = new Promise(that.toLogin).then((val) => {
      console.log('成功回调的结果', val);
      sessionKey = val;
    })
  },
  onLoad: function(options) {
    console.log('onLoad=======获取返回的shareTicket', options, app.shareTicket)
    shareTicket = app.shareTicket;
    /*
     * withShareTicket:true
     * 被打开的时候,可以获取一些信息,例如:群标识   
     * onLaunch / onShow  获取到shareTicket
     */
    wx.showShareMenu({
      withShareTicket: true,
      success: (res) => {
        console.log('showShareMenu----onload---success', res);
      },
      fail: () => {
        console.log('fail')
      }
    })
  },
  /**
   * 用户点击右上角 和 button  实现分享
   */
  onShareAppMessage: function(res) {
    if (res.from === 'button') {
      console.log('触发页面内的分享按钮', res.target);
    } else if (res.from === 'menu') {
      console.log('触发右上角的分享按钮')
    }
    console.log(res);
    return {
      title: '你好,我是标题', // 转发标题
      path: '/pages/share/share?id=123', // 当前页面 path ,必须是以 / 开头的完整路径
      imageUrl: '../../images/lemon.png'
    }
  },
  /**
   * 登录
   */
  toLogin: (resolve, reject) => {
    that = this;
    wx.login({
      success: (res) => {
        if (res.code) {
          wx.request({
            url: 'http://localhost:5000/wxapi/wxlogin.do',
            data: {
              code: res.code
            },
            success: (res) => {
              console.log('login.do====', res.data.success)
              if (res.data.success) {
                wx.setStorageSync('session', res.data.module.session_key)
                wx.setStorageSync('openid', res.data.module.openid)
                resolve(res.data.module.session_key)
              } else {
                reject(false)
              }
            },
            fail: (err) => {
              reject(false)
            }
          })
        } else {
          console.log('登录失败', res.errMsg)
        }
      }
    })
  },
  /**
   * getOpenGid 获取群标识openGId
   */
  getOpenGid: function() {
    that = this;
    wx.getShareInfo({
      shareTicket: shareTicket,
      success: (res) => {
        console.log('=====', res);
        wx.request({
          url: 'http://localhost:5000/wxapi/wxgetopenGid.do',
          data: {
            iv: res.iv,
            session: sessionKey,
            encryptedData: res.encryptedData
          },
          method:'post',
          success: (res) => {
            console.log('getopenGid===', res.data.module)
            that.setData({
              openGId: res.data.module.openGId
            })
          }
        })
      },
      fail: (error) => {
        console.log(error)
      }
    })
  }
})

【share.wxml】:



微信小程序 转发到群聊里,获取shareTicket、获取群标识 openGId 【包含前、后端代码】_第2张图片

后端代码如下:

两个接口:登录接口、解密获取openGid接口

const express = require('express');
var router = express.Router();
var WXBizDataCrypt = require('../utils/WXBizDataCrypt')
var db = require('../config/db')
var WxLoginSchema = require('../model/wxlogin')
const request = require('request');
const {APPID,SECRET} = require('../utils/constant');

/**
 * 登录接口
 */
router.get('/wxlogin.do',async(req,res)=>{
    var code = req.query.code;
    var url = 'https://api.weixin.qq.com/sns/jscode2session?appid='+APPID+'&secret='+SECRET+'&js_code='+code+'&grant_type=authorization_code'
    request(url,(err,body)=>{
        if(!err){
            res.json({
                module:JSON.parse(body.body),
                msg:'成功',
                success:true
            })
        }else{
            res.json({
                msg:'失败',
                success:false
            })
        }
    })
})

/**
 * 获取openGid的解密接口
 */
router.post('/wxgetopenGid.do',(req,res)=>{
    
    var iv = req.body.iv;
    var sessionKey = req.body.session;
    var encryptedData = req.body.encryptedData
    var pc = new WXBizDataCrypt(APPID, sessionKey)
    var data = pc.decryptData(encryptedData , iv)
    if(data){
        res.json({
            msg:'解密成功',
            module:data,
            success:true
        })
    }else{
        res.json({
            msg:'解密失败',
            success:true
        })
    }
})

module.exports = router;

 【WXBizDataCrypt.js】解密文件:

var crypto = require('crypto')

function WXBizDataCrypt(appId, sessionKey) {
  this.appId = appId
  this.sessionKey = sessionKey
}

WXBizDataCrypt.prototype.decryptData = function (encryptedData, iv) {
  // base64 decode
  var sessionKey = Buffer.from(this.sessionKey, 'base64')
  encryptedData = Buffer.from(encryptedData, 'base64')
  iv = Buffer.from(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) {
    throw new Error('Illegal Buffer')
  }

  if (decoded.watermark.appid !== this.appId) {
    throw new Error('Illegal Buffer0-----')
  }

  return decoded
}

module.exports = WXBizDataCrypt

【constant.js】常量文件:

const APPID = 'wxedc02b50e390dce8';
const SECRET = '3ff4747eb7c5b6f6ae2bd16e431a14e9';

module.exports = {APPID,SECRET}

----------------完。

你可能感兴趣的:(微信小程序)