Wechat sharing in vue hash mode for parameter transfer

Keywords: PHP Vue JSON

background

In the hash mode of vue project, wechat sharing is needed. Support to pass multi parameter, no parameter, specify jump page, configurable

Implementation ideas

Due to the existence of hash mode symbol, there will be compatibility problems in different platforms. The shared page cannot jump to the specified page. So the idea is to share the page path as a parameter (in this case, it is called the path parameter). After opening the sharing link, we restore the URL according to the path parameter and redirect it.

Main operation

1. Redirection judgment

At the moment of entry, perform url judgment:

1. Need redirect: it mainly depends on whether the path parameter exists.

2. Return to homeUrl: the normal path of the page. Convert the shape as http: / / wxh5. Gek6. COM / bystu /? Path = / Works & Dudu = 2 & haha = 123 to http: / / wxh5. Gek6. COM / bystu / # / works? Dudu = 2 & haha = 123

/**
   * Page redirection - make sure page links are working
   * Support multi parameter, no parameter and specified page
   * @returns {{needRedirect: *, homeUrl: string}}
   */
  urlResetForWcShare: function () {
    let needRedirect = false, homeUrl = '', searchObReal = {}, searchstr = ''
    let oriUrls = window.location.href.split('?')
    // let baseShareURl = 'http://wxh5.gek6.com/bystu/'
    let baseShareURl = window.location.origin + window.location.pathname
    homeUrl = baseShareURl + `#${config.platform[WECHAT.SHARE_PAGE_PATH]}`
    if (oriUrls.length > 1) {
      let searchUrls = oriUrls[1].split('#')
      let searchUrlReal = searchUrls[0]
      let searchOb = qs.parse(searchUrlReal)
      let {path} = searchOb
      config.platform[WECHAT.SHARE_EXTRA_PM_KEYS].forEach(item => searchObReal[item] = searchOb[item])
      if (config.platform[WECHAT.SHARE_EXTRA_PM_KEYS].length)
        searchstr = `?${qs.stringify(searchObReal)}`
      needRedirect = path || config.platform[WECHAT.SHARE_EXTRA_PM_KEYS].length !== Object.keys(searchOb).length
      homeUrl += searchstr
    }
    // alert(`Page redirection baseShareURl: ${window.location.origin + window.location.pathname + `#${config.platform[WECHAT.SHARE_PAGE_PATH]}` + searchstr}`)
    return {
      needRedirect,
      homeUrl,
      search: searchObReal
    }
  }

2. Assemble the shared link url

It mainly carries some parameters: path parameter and other parameters.

/**
   * Assemble the link url shared by wechat
   * @param pm // Incidental parameters
   * @returns {string}
   */
  wrapWcShareLink: function (pm = {}) {
    config.platform[WECHAT.SHARE_EXTRA_PM_KEYS].forEach(item => {
      if (!pm[item])
        throw new Error(`Wechat sharing link lacks additional parameters: ${item}`)
    })
    pm.path = config.platform[WECHAT.SHARE_PAGE_PATH] // according to path To set the initial page as the current root route
    return window.location.origin + window.location.pathname + '?' + qs.stringify(pm)
  },

3. Realize configuration

Read the carrying parameters in the sharing link from the configuration file

 platform: {
    [WECHAT.SHARE_EXTRA_PM_KEYS]: ['dudu'], // WeChat share-With parameter key name set
    [WECHAT.SHARE_PAGE_PATH]: ['/'], // WeChat share-Specified page
  },

Use

1. Root file app.vue:

async created(){
      let urlResetRes = browserUtil.urlResetForWcShare()
      let {needRedirect, homeUrl, search} = urlResetRes
      if (needRedirect) {
        window.location.href = homeUrl
//        location.reload()
      } else {
        let oldDudu = storage.getLocalStorage(LOCALDATA.WORKS_ID)
        if (!oldDudu || search.dudu != oldDudu)
          storage.setLocalStorage(LOCALDATA.WORKS_ID, search.dudu)
        wx_jssdk.sdk_init(homeUrl);
      }
    }

2. Initialize jssdk.

async sdk_init(homeUrl){
        // Get signature data
        let sign;
        try {
            sign = await getSign(homeUrl); // Access interface, get signature data
        } catch (err) {
            console.log(err)
            // alert(JSON.stringify(err))
        }
        // console.log('Get signature successful')
        // console.log(sign);

        wx.config({
            debug: false, // Turn on debugging mode,All called api The return value of will be in the client alert To view the parameters passed in, go to the pc The end is open, and the parameter information will pass log Play, only in pc It will be printed at the end.
            appId: sign.appid, // Required, unique identification of public number
            timestamp: sign.timestamp, // Required, generate signature timestamp
            nonceStr: sign.noncestr, // Required, generate random string of signature
            signature: sign.signature, // Required, signature
            jsApiList: ["onMenuShareTimeline", "onMenuShareAppMessage", "onMenuShareQQ", "onMenuShareQZone", "onMenuShareWeibo", 'updateAppMessageShareData', 'updateTimelineShareData'] // Required, required JS Interface list
        });
    }
homeUrl is the url of the current page.

Posted by jimbo_head on Tue, 22 Oct 2019 10:23:30 -0700