Notes on the JS-SDK wx.config/ready/error processing function provided by WeChat

Introduction

WeChat JSSDK is a JavaScript toolkit for WeChat public account development. It provides many convenient interfaces and methods to facilitate developers to develop richer and more interactive applications on the WeChat public platform. Through WeChat JSSDK, developers can implement a series of functions based on WeChat official accounts, such as: sharing to Moments, sharing to conversations, activating WeChat payment, obtaining geographical location, etc. WeChat JSSDK can be used for the development of WeChat public accounts, WeChat mini programs and other platforms.

If you want to use the JS-SDK provided by WeChat, one of the steps is to use wx.config to inject configuration information for permission verification.

However, wx.config is a client-side asynchronous operation. If you need to call the relevant interface when the page is loaded, you must ensure that the wx.config permissions are verified before calling the interface.

wx.config({
    
    
  debug: true, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。
  appId: '', // 必填,公众号的唯一标识
  timestamp: , // 必填,生成签名的时间戳
  nonceStr: '', // 必填,生成签名的随机串
  signature: '',// 必填,签名
  jsApiList: [] // 必填,需要使用的JS接口列表
});

Handle successful verification through ready interface

wx.ready(function(){
    
    
  // config信息验证后会执行ready方法,所有接口调用都必须在config接口获得结果之后,config是一个客户端的异步操作,所以如果需要在页面加载时就调用相关接口,则须把相关接口放在ready函数中调用来确保正确执行。对于用户触发时才调用的接口,则可以直接调用,不需要放在ready函数中。
});

Handle failed verification through error interface

wx.error(function(res){
    
    
  // config信息验证失败会执行error函数,如签名过期导致验证失败,具体错误信息可以打开config的debug模式查看,也可以在返回的res参数中查看,对于SPA可以在这里更新签名。
});

important

WeChat provides thewx.ready function, although the document sayswx.ready is a function executed when the verification is successful, but it will be called whether the permission verification succeeds or fails.

That is to say, if the permission verification passes, only thewx.ready function will be called. If the permission verification fails, the function will be called first wx.error function, and then call wx.ready.

So it is not safe to call the interface inwx.ready. We need to call the interface only after actual verification.

Reference information:

https://developers.weixin.qq.com/doc/offiaccount/OA_Web_Apps/JS-SDK.html

Guess you like

Origin blog.csdn.net/m0_37680500/article/details/131568874