h5 official account to share friends and friends

preface

Wechat sharing (using wechat JS-SDK) and wechat JS-SDK are web development kits based on wechat for web developers. Official documents used by JSSDK( Official user manual)

Explain my usage and the record of tramway. I am a public official account of h5 project. Today, I suddenly received the demand to share the contents of a certain two pages. I have done the sharing of WeChat applet and payment applet. I have used the API to modify the title, description, picture and link directly. I think the thief is simple, and the estimated time of work is altogether one day. A handful of bitter tears~~

1. Use steps

1) Install dependent package npm or yarn

npm i --save weixin-js-sdk

2) Here I create a new file wechat. Com in utils JS code is as follows:

import wx from 'weixin-js-sdk'
import {wxShare} from '@/api/wechat.js'
export default {
    init (apiList = [],url) {
       url = process.env.VUE_APP_API_GATEWAYS+url
      let params={
      appId:process.env.VUE_APP_API_APP_ID,
      url:url
     }
      return new Promise((resolve, reject) => {
        wxShare(params).then(res => {
          if (res.code=="0000") {
            wx.config({
              debug: false,
              appId: process.env.VUE_APP_API_APP_ID,
              timestamp:res.data.timestamp,
              nonceStr:res.data.nonceStr,
              signature:res.data.signature,
              jsApiList: apiList
            })
            wx.ready(() => {
              resolve(wx)
            })
            wx.error(function (err) {
              reject(err)
            })
          }
        })
      })
    }
  }

3) Sharing customization of a single page: perform config signature in the mounted page to be shared. What functions are required? When signing, pass in the corresponding jsApiList registration. After signing ok, configure the title, desc, link and imgLink of sharing friends and sharing circle of friends in ready.

First, we introduce wechats in utils js

import utilWechat from '@/utils/wechat'

The code is as follows:

 mounted() {
    let title=document.title//Title of the current page
     let desc="This is the shared description information"//Self configured description information
     let link=process.env.VUE_APP_API_GATEWAYS+this.url//Shared links
     let imgUrl =process.env.VUE_APP_API_GATEWAYS+'/automic.png'//Shared picture links
    //  let link=location.protocol+'//'+location.host+this.url / / this method of obtaining route is also OK
    //  let imgUrl =location.protocol+'//'+location.host+'/'+'automic.png '/ / ditto
//api list. Here, I also registered the new version of sharing friends and sharing circle of friends api in the document, because I don't know whether to use the new version or the old version. After testing, it's still easy to use the old version. If you use the new version, you can use the official manual and the cases of everyone in the community to avoid stepping on the pit
let APILIST=["onMenuShareTimeline","onMenuShareAppMessage",'updateTimelineShareData','updateAppMessageShareData']
    utilWechat.init(APILIST,this.url).then(wx => {
        wx.onMenuShareAppMessage({
            title,
            desc,
            link,
            imgUrl,
            success: function () {
              alert(`Share success`);
            },
            cancel: function () {
              alert(`Cancel sharing`);
            }
        });
        wx.onMenuShareTimeline({
            title,
            desc,
            link,
            imgUrl,
            success: function () {
              alert(`Share success`);
            },
            cancel: function () {
              alert(`Cancel sharing`);
            }
        });
        //New version sharing (outside ready)
        // wx.updateAppMessageShareData({})
        // wx.updateTimelineShareData({})
   });
  },

4) Because I don't require all pages to be customized and shared here, it's convenient and easy for me to package and pass reference title, description, etc. in the project. If each page needs custom sharing, you can set the corresponding custom information for each routing configuration in meta to dynamically read, obtain signatures, and dynamically configure the custom parameters of the page.

2. Step on the pit. Come on

1) The page shares only one link

What official account is usually in the WeChat h5 conversation, and we can enter the official account page directly through the link in WeChat conversation, and jump through the public menu without any difference.

Because the official account menu is temporarily hung with a gray environment, the test environment can only be entered through links. After the test page is customized, I only have one link, why? Click on the link to enter the right corner of the page to share with friends, directly share a link, did not do, no experience, think of what is wrong with their code, WeChat developer tools to test config:ok, login WeChat official account background, also configured js security domain name, there is no clue.

After checking some materials, I found no results. Finally, I found the same problem in the community: The official account page only has one link?

After reading and testing several times, the conclusion is:

1. It's normal to open and share the link of wechat conversation from my collection after collecting the link

2. It is normal to change the link into QR code and enter sharing after scanning the code

3. click through the official account menu of WeChat to share the page is normal.

2) Android is normal and IOS sharing custom configuration is invalid

I'm an Android mobile phone. The first problem is that after understanding the official rules of wechat, wechat sharing returns to normal after passing the conclusion test. After sending the version to the test environment, the title and description of the card configuration shared by ios mobile phone are invalid.

I checked a lot of information,

1. Eliminate the problem that the picture cannot exceed 33k,

2. Eliminate the problem that there can be no special characters in the configured link. It is necessary to encode the special characters and use encodeURIComponent()

3. Exclude direct access to location protocol+'//'+location. host+... To set the link

4. Exclude the hash route interception # front as splicing (the project uses history)

After these problems were eliminated, I suddenly had an idea on my mobile phone to refresh it. Don't be a cache problem. The code version is invalid, and then click share. my god is actually normal. After repeated testing for several times, I eliminated the cache problem. The first sharing is indeed invalid, but it is normal to share after refreshing the page.

I doubt whether there is any difference between ios signature and Android. I began to continue to search the data and find the front-end partner who encountered the same problem. However, he used hash route, that is, this method cannot be used. However, I came to the conclusion that ios signature is different from Android, but confused to use the current route to obtain signature. That's right, the official said.

Try to compare the url of alert before signing, and see that the url of Android and IOS are the current page, so I'm depressed....... Ten thousand words are omitted here

3) It can be determined that the IOS signature is wrong. IOS signs config: invalid signature for the first time. After refreshing the page, config: ok

Therefore, all possible situations were investigated, but none of them were. Finally, it was found that the routing mechanism of IOS was different from that of Android.

The page I need to share is the page that jumps twice after entering the web page, so the route has changed

Although I used the route of the current page (the latest url after the jump) to sign the alert before sharing, the signature failed.

After testing, if you don't jump to the page, ios sharing is effective. When you jump, you change the url of the page:

The problem is:

In terms of ios system's support for Vue's history routing, due to Vue's single page application, although the url I alert is the current page url I want, as long as the page is not refreshed, the url obtained by ios will still enter the first url of the web page (my home page). In this way, the request signature will become a problem of dynamic url inconsistency, which leads to signature failure.

terms of settlement:

In the routing guard, first judge Android and IOS. If it is Android, sign the current page address every time. If it is IOS model, save the url of the first entry in the routing guard. When the route enters the page, judge whether the url of the current page is consistent with the link address of the first entry. If it is inconsistent, use location Replace refresh the page and sign with the refreshed url.

The specific codes are as follows:

//Only the core code is written here. Just insert the code according to the needs
router.beforeEach((to, from, next) => {
        let link=process.env.VUE_APP_API_GATEWAYS+to.fullPath//url of the current page
        //Determine whether it's an Apple phone
        var ua = navigator.userAgent.toLowerCase();
        let newValue = ua.indexOf('iphone')
        if(newValue != -1){ //Apple makes judgments
          if (window.entryUrl === '' || window.entryUrl === undefined || window.entryUrl === null)  {
              window.entryUrl = link
            }
//The entry url is inconsistent with the url that currently needs to be signed. Assign a value, refresh the page and re sign
            if (window.entryUrl !== link) {
              window.entryUrl = link
              window.location.replace(link)
            }
        }else{
            next()
        }  
})

4) After the release to the test environment and the test, the sharing configuration is normal. There are not many codes for stepping on the pit. It's really tempting to have not done this one. It's too difficult for the child. He's stunned, but he's very happy to solve it!

 

Keywords: Javascript wechat

Added by nikkio3000 on Mon, 21 Feb 2022 08:29:46 +0200