preface

Do a sharing function, anyway, pretty weird, here is a step

The back end uses egg.js with the following code:

'use strict';

const Subscription = require('egg').Subscription;

class AccessToken extends Subscription {
  static get schedule() {
    return {
      interval: '2h'.// Once every 2 hours
      type: 'all'}; }async subscribe() {
    const config = this.ctx.app.config.wechat_config;
    const url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET'.replace('APPID', config.appId)
      .replace('APPSECRET', config.appSecret);
    const res = await this.ctx.curl(url, {
      dataType: 'json'});console.log(res);//accesstoken
    if (res.data.errcode) {
      return;
    }
    console.log('token ' + res.data.access_token);
    const jsUrl = 'https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=ACCESS_TOKEN&type=jsapi'.replace('ACCESS_TOKEN', res.data.access_token);
    const jsRes = await this.ctx.curl(jsUrl, {
      dataType: 'json'});console.log('ticket ' + jsRes.data.ticket);//ticket
    this.ctx.app.ticket = jsRes.data.ticket;
    this.ctx.app.access_token = res.data.access_token; }}module.exports = AccessToken;
Copy the code
async getJSsdk() {
    const appId = this.ctx.app.config.wechat_config.appId;//appid
    const ticket = this.ctx.app.ticket;// Ticket obtained at initialization
    const nonceStr = Math.random()
      .toString(36)
      .substr(2.15);
    const timestamp = parseInt(new Date().getTime() / 1000);// The timestamp is in seconds
    let url = this.ctx.query.link; // The front-end page address
    url = decodeURIComponent(url);/ / decoding
    const string = 'jsapi_ticket=' + ticket + '&noncestr=' + nonceStr + '&timestamp=' + timestamp + '&url=' + url;
    const hash = crypto.createHash('sha1');
    hash.update(string);
    const signature = hash.digest('hex');// Generate a signature
    this.ctx.body = {
      status: true.message: 'Obtain success',
      data
    };
  };
Copy the code

steps

1. In the vue project public directory index. Introduced in HTML < script SRC = “http://res.wx.qq.com/open/js/jweixin-1.4.0.js” > < / script >

2. Add the following code to share component Mounted:

// If you do not create a meta tag, there will be no description to share
var oMeta = document.createElement('meta');
oMeta.content = 'Casual content';// Write it arbitrarily here
oMeta.name = 'keywords';
document.getElementsByTagName('head') [0].appendChild(oMeta);
var oMeta1 = document.createElement('meta');
oMeta1.content = 'Casual content';// Write it arbitrarily here
oMeta1.name = 'description';
document.getElementsByTagName('head') [0].appendChild(oMeta1);
Copy the code

3. InitJSSDK body:

function initJSSDK() {
    let wechaturl = window.location.href.split(The '#') [0];// A single page application gets everything before #
      let link = encodeURIComponent(wechaturl);
      const jssdk = await getJSSDK(link); // Pass the current page address to the backend interface. Note that this address must be configured in the JS secure domain name
      wx.ready(() = > {
        let shareData = {
          title: this.detail.title,
          desc: this.detail.summary,
          link: location.href, // It must be the address of the js secure domain name (please check the link parameter here)
          imgUrl: window.wechatImg,// It is better to use JPG. There is no constraint on image size
          success: function () {
            console.log(1);
          },
          cancel: function () {
            console.log(2); }}; wx.onMenuShareAppMessage(shareData);// Share with friends
        wx.onMenuShareQQ(shareData);// Share to mobile QQ
        wx.onMenuShareQZone(shareData);// Share to qzone
        wx.onMenuShareTimeline(shareData);// Share it on moments
      });
      wx.error(function (res) {
        console.log(res);
      });
      wx.config({
        debug: true.appId: jssdk.appId, // Mandatory, the unique identifier of the public account
        timestamp: jssdk.timestamp, // Mandatory, generate signature timestamp, accurate to second (back end return)
        nonceStr: jssdk.nonceStr, // Mandatory, generate a random string of signatures (back end return)
        signature: jssdk.signature, // Mandatory, signature (back end return)
        jsApiList: ['onMenuShareAppMessage'.'onMenuShareTimeline'.'onMenuShareQQ'.'onMenuShareQZone']}); }Copy the code

Q&A

Invalid signature: it may be that the backend forgot to decode after the front-end encode address passed, or it may be that the front-end address was passed incorrectly or passed without encode. The error probability of the back-end signature algorithm is relatively small.

There may also be a ticket failure at the back end (this is less likely during development)

Invalid domain: The address passed from the front end to the back end may not be configured in the JS secure domain name

JSSDK version with the above version 1.4, the same code with a new version of the direct line, there is no error.

We haven’t found any problems with Apple as reported online. All tests are good

Leave a message if you have any questions