The h5 embedded in the applet web-view calls jssdk, and a signature error is reported?

problem arises

The H5 page can call scanQRCode api normally, but it reports a signature error when it is embedded in the applet in the way of web-view.

Troubleshooting

Turn on the debug mode, and print out the configuration information to find that all the information is available, but the signature error is still reported, it seems that the configuration should be no problem; and then found that the page entered for the first time is the page that calls jssdk. If the call is successful, if the page calling jssdk is not the first page entered, a signature error will be reported; because I also encountered the problem of ios calling jssdk reporting signature failure in H5 before. So inference is a problem with signed urls.

solve

The solution is the same as the solution to the problem of ios H5 calling jssdk to report signature failure. The url used by ios to call jssdk signature is not the url of the current page, but the url of the page it entered for the first time to sign, so here we use the small program Try this method too.

//H5 main.js
router.afterEach((to, from) => {
    
    
  // 记录最初进入路由的第一个页面的url
  if (!sessionStorage.wxConfigSignUrl ) {
    
    
  	let wxConfigSignUrl = location.protocol + '//' + location.host + to.fullPath
  	window.sessionStorage.setItem('wxConfigSignUrl ', wxConfigSignUrl)
  }
}
//H5 调用 jssdk
// 微信扫描
export function wxScan(cb) {
    
    
  // 记录最初进入路由的第一个页面的url
  let wxConfigSignUrl = window.sessionStorage.getItem('wxConfigSignUrl')
  const isAdnroid = /Android/i.test(navigator.userAgent)
  // 获取微信JS-SDK配置信息
  let getUrl = isAdnroid ? location.href.split('#')[0] : wxConfigSignUrl
  const env = window.navigator.userAgent
  // 小程序web-view环境需要用最初进入路由的第一个页面的url去签名
  if (/miniProgram/.test(env)) {
    
    
    getUrl = wxConfigSignUrl
  }
  getJsApiConfigApi(getUrl).then(response => {
    
    
    var res = response.data
    if (res.success) {
    
    
      var wxdata = res.data
      wx.config({
    
    
        debug: false,
        appId: wxdata.appId, // 填写自己的appID
        timestamp: wxdata.timestamp,
        nonceStr: wxdata.noncestr,
        signature: wxdata.signature,
        jsApiList: ['checkJsApi', 'scanQRCode']

      })
      wx.ready(function() {
    
    
        wx.checkJsApi({
    
    
          jsApiList: ['scanQRCode'],
          success: function(res) {
    
    
            setTimeout(()=> {
    
    
              cb && cb()
            },1000)
          }
        })
      })

    } else {
    
    
      console.log(res.msg)
    }
  })
}

result

After this modification, the page calling jssdk can be successfully called even when it is not the first page entered, Nice!

Guess you like

Origin blog.csdn.net/Gage__/article/details/105820461