Vue+Vue-router WeChat sharing function

Several projects have been developed using the vue and vue-router routing frameworks, and many pits have been encountered, and some searches have not found very ideal answers.

Vue learning is relatively simple, the official documentation is very clear ( https://cn.vuejs.org/v2/guide/ ), you can get started with more demos, and there are many frameworks (vuex, MintUI) , Element, iView, etc.), learn by yourself according to the needs of the project, so I haven't written much about vue.

This time, I mainly share the problems I encountered in WeChat sharing. There will be no problems in sharing on Android machines, mainly because IOS shares various signatures, and the title, content, and pictures do not change.

1. Of course, WeChat JS-SDK should be introduced in WeChat sharing

  WeChat JS-SDK documentation: https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421141115

  Sharing page introduction: http://res.wx.qq.com/open/js/jweixin-1.2.0.js

  The vue framework can be used: https://github.com/yanxi-me/weixin-js-sdk    Command:npm install weixin-js-sdk

  2. Encapsulate the function of WeChat sharing, as follows:

import wx from 'weixin-js-sdk';
import apiUrl from "@/config/apiUrl.js";
export default {
  wxChat : ($vue, param) => {
    let appId = "";
    let timestamp="";
    let nonceStr = "";
    let signature = "";
    let options = {
      title: "",
      desc: "",
      link: "",
      imgUrl: "",
      type: "link",
      dataUrl: "",
      localUrl: ""
    };
    options = Object.assign({}, options, param);
    //
    $vue.$httpPost(apiUrl.weChatShare, {shareLink: options.localUrl}).then((res) =>{
      if(res.data&&res.data.status==="1000") {
        wx.config({
          debug: false,
          appId: res.data.appId, // must be the same as the one for getting Ticket------required, the unique identifier of the
          official account timestamp: res.data.timestamp, //required, generate a signature Timestamp
          nonceStr: res.data.nonceStr, // Required, generate a random string of
          signature signature: res.data.signature, // Required, signature
          jsApiList: [
            'onMenuShareAppMessage', 'onMenuShareTimeline',
            'onMenuShareQQ', ' onMenuShareQZone'
          ]
        });
        //Process the information of verification failure
        wx.error(function (res) {
          console.log('The information returned by verification failure:', res);
        });
        //Process the information of successful verification
        wx. ready(function () {
          //Share to the circle of friends
          wx.onMenuShareTimeline({
            title: options.title, // share title
            link: options.link, // share link
            imgUrl: options.imgUrl, // share icon
            success: function (res) {
              // callback function executed after user confirms sharing
              console.log ("The information returned by the successful sharing to the Moments is:", res);
              showMsg("Shared successfully!");
            },
            cancel: function (res) {
              // The callback function executed after the user cancels the sharing
              console.log(" The information returned when cancel sharing to Moments is: ", res);
            }
          });
          //Share to friends
          wx.onMenuShareAppMessage({
            title: options.title,
            desc: options.desc,
            link: options.link,
            imgUrl: options.imgUrl,
            type: options.type, // share type, music, video or link, if not filled, the default is link
            dataUrl: options.dataUrl, // if type is music or video, data link should be provided, default Empty
            success: function (res) {
              // The callback function executed after the user confirms the sharing
              console.log("The information returned successfully when sharing with friends is:", res);
              showMsg(JSON.stringify(options));
            },
            cancel: function (res) {
              // The callback function executed after the user cancels sharing
              console.log("The information returned by canceling sharing to friends is:", res);
            }
          });
          //Share to QQ
          wx.onMenuShareQQ({
            title: options.title,
            desc: options.desc,
            link: options.link,
            imgUrl: options.imgUrl,
            success: function (res) {
              // The callback function executed after the user confirms the sharing
              console.log("The information returned successfully after sharing to QQ friends is:", res);
            } ,
            cancel: function (res) {
              // The callback function executed after the user cancels sharing
              console.log("The information returned by canceling sharing to QQ friends is:", res);
            }
          });
          //Share to QQ space
          wx. onMenuShareQZone({
            title: options.title,
            desc: options.desc,
            link: options.link,
            imgUrl: options.imgUrl,
            success: function (res) {
              // Callback function executed after user confirms sharing
              console.log("The information returned successfully after sharing to QQ space is:", res);
            },
            cancel: function (res) {
              // The callback function executed after the user cancels sharing
              console.log("Cancel sharing to QQ space and return The message is: ", res);
            }
          });
        });
      } else {
        console.log(res.data.msg);
      }
    }).catch((err) => {
      console.log(err);
    } );
  }
};

3. How to use packaged sharing

  If you use the vue routing hash mode, the address obtained by opening a page in IOS is always the address that was opened at the beginning, not the address of the current page after the jump, so you can make an initialization call on the opened page or initialize the shared page to satisfy (android) , you can get the distinction between different kernels; or use location.href = "" when jumping pages, do not use routing, so you only need to call WeChat initialization on the sharing page. For insurance, you can save the jumped address to localStorage.set("LocalUrl", document.URL) in the router.beforeEach hook.

  Jump page: location.href = "?#/invite?userId=3" ;

import weixin from "@/utils/wechat.js";
initWxChat: function() {
      let url = window.localStorage.getItem("LocalUrl")||window.location.href;
      let param = {
        title: "Courtesy invitation" ,
        desc: "Welcome to the invitation courtesy",
        link: window.location.href,
        imgUrl: this.headPortrait,
        localUrl: url
      };
      weixin.wxChat(this, param);
    }

4. WeChat signature authentication can be passed, but the content of custom sharing is not necessarily easy to use

  This problem is mainly because the shared page has parameters. Since the routing hash mode will automatically add the # sign, WeChat automatically adds its own content in IOS, and then puts the content after the # behind it, so there will be problems in obtaining parameters. , maybe there will be problems with signature authentication, so I thought of adding a special symbol to deal with it, adding a ? sign before the parameter # of the incoming address, and it is best to pass only one parameter, if there are more than one, it will still be There is a problem.

  Get the current page address: let url = window.localStorage.getItem("LocalUrl")||window.location.href;

  Share the authorization authentication page localUrl: http://localhost:9000/?#/invite?userId=3;

  The link of the page to be shared: window.location.href.split('#')[0] + "#/invite_share?userId=3";

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325516732&siteId=291194637