ios wechat calling jssdk initialization failed; If the solution in the previous and back-end separation version is adopted;

Question:
Starting from the single page point of Android, wechat developer tool and apple, wechat js initialization is normal, and the initialization fails when Apple page A jumps to page B

Cause of problem:

When jumping from page A to page B, due to the use of Vue router switching and the operation of browser history, the url locked by ios wechat browser is still the url of page A.

At this time, many people will think that since the page route has changed, I can re request the url signature interface. Hehe hehe, you will find an error: invalid signature. But refresh again, and there is no signature problem. What's the reason???

So what are the url parameters you pass when you request the url signature interface? It's probably as follows:
url1, directly location Href (history mode)
url2. Self assembled location origin + ‘/#’ + this.$route.pullPath (hash mode)
At this time, the interface you requested is OK, and you can get the signature data. however

The problem is: the URL signature address you requested and the browser execute jweixin-1 x. The addresses locked during x.js are inconsistent, inconsistent and inconsistent. Your current request may be url1 or url2, and the address locked by wechat is still the URL when entering page A (because jweinwei-1.x.x.js is loaded and executed when entering page A, but jxinwei-1.x.x.js is not executed again when the route changes from A to B). So the problem happens, but you refresh it, jweixin-1 x. X.js is re executed. At this time, the URL locked by wechat browser is your current refreshed URL address, so the signature is successful again.
Mainly because:
[IOS]: on the IOS wechat side, when the route changes, wechat believes that the url of SPA is unchanged.
[Android]: on Android wechat, when the route changes, the url of SPA will change (the official supports SPA changes only in Android version 6.2)

Therefore, the url that initiates the signature must be the url locked by wechat.

Solution A:
The IOS side saves the url of the request signature into the global variable. After route switching, when calling the sharing interface, use the url saved in the global variable to request signature

// Record the url when entering the app
if (typeof window.entryUrl === 'undefined' || window.entryUrl === '') {
    window.entryUrl = location.href.split('#')[0]
}
// When signing, Android does not need to use the previous link. ios needs to
let signLink =  /(Android)/i.test(navigator.userAgent) ? location.href.split('#')[0] : window.entryUrl;

Solution B in vue: version 3.4.0

stay permission.js Medium router.beforeEach Method to add the following code according to the actual location of your actual business. My business doesn't need authentication. It's directly under the white list
// If ios enters for the first time, directly initialize wechat JS
if (isIOS()) {
        if (from.path === '/') {
          requestWxStr().then(r => {
            console.log('ios Initialization complete')
          })
        }
      }
This is the reference code
import router from './router'
import store from './store'
import { Message } from 'element-ui'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import { getToken } from '@/utils/auth'
import { isIOS, requestWxStr } from '@/main'

NProgress.configure({ showSpinner: false })

//Route white list. Add routes to this array and you can access them without logging in
const whiteList = ['/login', '/auth-redirect', '/bind', '/register', '/404']

router.beforeEach((to, from, next) => {
  // console.log("form---permission"+form.path)
  // The progress bar starts when routing is requested
  NProgress.start()
  //If there is a token, there is a logged in token
  if (getToken()) {
    /* has token*/
    //If the user requests the login page with a token, let the user directly jump to the home page to avoid repeated login
    if (to.path === '/login' || to.path === '/wx_login') {
      // Jump directly to the home page, of course, depending on where your route is redirected
      next({ path: '/' })
      //Be sure to close the progress bar
      NProgress.done()
    } else {
      //If a user who already has a token requests another page instead of a login page
      //Just get the user's information from Vuex, which also proves that the user is not logging in for the first time
      if (store.getters.roles.length === 0) {
        // Judge whether the current user has pulled the user_info information
        store.dispatch('GetInfo').then(res => {
          // Pull user_info
          const roles = res.roles
          store.dispatch('GenerateRoutes', { roles }).then(accessRoutes => {
            // Generate an accessible routing table according to roles permissions
            router.addRoutes(accessRoutes) // Dynamically add accessible routing table
            next({ ...to, replace: true }) // The hack method ensures that addRoutes is complete
          })
        }).catch(err => {
          store.dispatch('LogOut').then(() => {
            Message.error(err)
            next({ path: '/' })
          })
        })
      } else {
        next()
      }
    }
  } else {
    console.log('to.path=>', to.path)
    // No token
    if (whiteList.indexOf(to.path) !== -1) {
      // In the login free white list, enter directly

      if (isIOS()) {
        if (from.path === '/') {
          requestWxStr().then(r => {
            console.log('ios Initialization complete')
          })
        }
      }

      next()
    } else {
      next(`/login?redirect=${to.fullPath}`) // Otherwise, redirect all to the login page
      NProgress.done()
    }
  }
})

router.afterEach(() => {
  NProgress.done()
})

stay main.js These two methods can be written in other places


//Extracted public method
/*
* Determine whether the IOS environment
* */
export function isIOS () {
  let isIphone = navigator.userAgent.includes('iPhone')
  let isIpad = navigator.userAgent.includes('iPad')
  return isIphone || isIpad
}

/*
* Obtain wechat signature and inject permission verification configuration
* */
export async function requestWxStr () {
  let url = location.href.split('#')[0]
  getSign(url).then((res) => {
    let jsonData = res
    wx.config({
      // When the debugging mode is enabled, the return values of all APIs called will be alert ed on the client. To view the incoming parameters, you can open them on the pc side, and the parameter information will be printed through log, which will only be printed on the pc side.
      debug: true,
      // Required, the only sign of official account.
      appId: jsonData.appId,
      // Required, time stamp to generate signature
      timestamp: '' + jsonData.timestamp,
      // Required, generate random string of signature
      nonceStr: jsonData.nonceStr,
      // Required, signature
      signature: jsonData.signature,
      // Required, list of JS interfaces to be used, list of all JS interfaces: get login information
      jsApiList: ['checkJsApi', 'getLocation']
    })
  })
}
Use wechat when necessary js Page of
created() {
// If not IOS, start initialization here
    if(!isIOS()){
      requestWxStr()
    }
  }

Through the above modifications, jssdk can be called normally in Android and ios environments. It should be because the wechat of ios is not well compatible with the new H5 features of pushState. This happens in vue's mode: 'history' mode or react using browserHistory. The most pitiful thing is that the official documents do not have any relevant instructions.

When opening a web page on wechat computer, Wx Getlocation prompt function not implement ation; There is no clear official answer to this question, which can be paid continuous attention
pc initialization problem: https://developers.weixin.qq.com/community/develop/doc/00086c34298e180834b96f52456800
spa single page explanation: https://blog.csdn.net/huangpb123/article/details/86183453
Reference links and other solutions:
https://blog.csdn.net/hualvm/article/details/85344076
https://www.jianshu.com/p/12a9e244cfa4
https://www.cnblogs.com/tengrl/p/10429278.html
https://www.cnblogs.com/xueshanshan/p/8692092.html
https://github.com/vuejs/vue-router/issues/481

Keywords: Vue

Added by shinstar on Tue, 08 Mar 2022 01:46:56 +0200