The basic configuration

1. Settings – Public Account Settings – Function Settings – Configure JS interface security domain name



Secure domain name configuration rules are as follows

2. Development — Basic configuration



The developer password needs to be reset the first time it is used

Record the developer ID(AppID). The developer password (AppSecret) is used

3.IP whitelist configuration

It is recommended to fill in the current local development IP address and server IP address

Local development address acquisition method



Server IP address (fill in by yourself according to your server’s IP address)

Multiple IP addresses are separated by a carriage return

4. An important step

In: WeChat public account – development – interface permissions to check whether the development interface you want to call is available. If the relevant interface permissions cannot be enabled, it is recommended to use: WeChat public platform – development – developer tools – public platform test account development

To start developing

1. Introducing JS files

Need to call in JS interface pages to introduce the following JS files, support (HTTPS) : http://res.wx.qq.com/open/js/…

2. Verify the configuration by injecting permissions through the config interface (the most important step)

Wx. config({debug: true, // turn on debug mode, return value of all API calls will come out in client alert, if you want to view the incoming parameter, you can open it on PC, parameter information will be printed through the log, only on PC will be printed. AppID: "",// required, timestamp:,// required, timestamp:",// required, random string signature: ",// required, signature jSapilist: [] // Required, need to use the JS interface list});

AppID (front in WeChat public basic configuration have been given a) jsApiList: [‘ uploadImage ‘, ‘updateAppMessageShareData] (example: interface, upload pictures and share custom interface)

JSAPI_TICKET is a temporary ticket used by the public number to call the WeChat JS interface. Normally, jsapi_ticket is valid for 7200 seconds and is obtained through access_token. Due to the very limited number of API calls to obtain jsapi_ticket, frequent refreshing of jsapi_ticket will result in limited API calls and affect their own business, and developers must cache jsapi_ticket globally in their own service.

  1. Refer to the following documentation for access_token (for 7200 seconds, developers must serve in their global cache access_token) : https://developers.weixin.qq…
  2. With the first step to GET the access_token using HTTP GET requests for jsapi_ticket (valid for 7200 seconds, the developer must serve in their global cache jsapi_ticket) : https://api.weixin.qq.com/cgi…

2.1 Signature acquisition and dismantling

The first step, GET, requests the access_token

The validity of the access_token for 7200 seconds (don’t have to be repeated requests) https://api.weixin.qq.com/cgi…

  • Grant_type is to get access_token to fill client_credential
  • The APPID is the unique credentials of the third-party user
  • Secret is the third party user’s unique credential key, AppSecret **

Appid and secret are already available in the previous basic configuration. However, because the developer password (AppSecret) is the password to verify the identity of the developer of the public account, it has a very high security. The access_token request cannot be directly exposed in the front-end code, so the access_token request needs to be done on the back end, where the signature generation process is done.


The back-end services are currently built with Node
// Get the access_token sample var url = `https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${appid}&secret=${secret}`; request(url, function (error, response, body) { if (! Error && response.statusCode == 200) {console.log("access_token value "+ json.parse (body).access_token)}});
Step 2: GET requests jsapi_ticket

Jsapi_ticket valid for 7200 seconds (don’t have to be repeated requests) https://api.weixin.qq.com/cgi… Make the request with the value of access_token obtained in the first step

// var url = `https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=${access_token}&type=jsapi` request(url, function (error, response, body) { if (! Error && response.statusCode == 200) {console.log("jsapi_ticket value "+ json.parse (body).ticket); }});
The third step is to generate the algorithm signature

Const timestamp = parseInt(date.now () / 1000) // const nonceStr = Math.random().toString(36).substr(2, 1) 15) // Generate the random string let jsapi_ticket // Generate the let URL in the second step // The URL used for the signature must be the full URL of the page calling the JS interface (brought in by the front-end request server interface).

NPM install sha1 router. Get ('/', (req, res,)) const sha1 = require('sha1') Next) => {const url = decodeUricomponent (req.query.url)// DecodeUricomponent (req.query.url) Const timestamp = parseInt(date.now () / 1000) const nonceStr = Math.random().toString(36).substr(2, 1) Let jsapi_ticket = "const params = {nonceStr, jsapi_ticket, timestamp, url } const string = Object.keys(params).sort().map(key => `${key.toLowerCase()}=${params[key]}`).join('&') const Json ({// return the parameter to front-end timestamp, signature, nonceStr}); }) module.exports = router;

3. Actual invocation of front-end static pages

<! DOCTYPE HTML > < HTML lang="en"> <head> <meta charset=" utf-8 "> <title>Document</ head> <body> <h1> </h1> < script SRC = "http://res.wx.qq.com/open/js/jweixin-1.4.0.js" > < / script > < script type = "text/javascript" SRC ="js/jquery-2.1.1.min.js"></script> <script> function wxFN(){$. Ajax ({type: "get", url: `http://*************/api/wx?url=${encodeURIComponent(location.href.split('#')[0])}`, success: function(data) { console.log(data); Wx. config({debug: true, // turn on debug mode, return value of all API calls will come out in client alert, if you want to view the incoming parameter, you can open it on PC, parameter information will be printed through the log, only on PC will be printed. Timestamp: data.timestamp; // required, timestamp: data.timestamp; // required, timestamp nonceStr: Data. nonceStr, // Required, Random string signature that generates signature: data.signature, // Required, Signature jSapilist: [' updateAppMessageShareData '] / / required, you need to use the list of JS interface}); }}); } wxFN () wx. Ready (function () {/ / to be before the user can click share button to call first wx. UpdateAppMessageShareData ({title: "', / / share title desc: ", // Share description link: ", // Share link, the link domain name or path must be the same as the current page corresponding to the public number JS secure domain name imgUrl: ", // Share icon success:" Function () {alert(" succeeded ") // set successfully}})}); wx.error(function(res) { console.log('err', res) }); </script> </body> </html>

4 Common errors and solutions (provided by WeChat)

When you call the config interface, pass the parameter debug: true to start the debug mode, and the page will alert an error message. The following are common mistakes and their solutions:

  1. Invalid URL domain is not bound to the appid you are using. Please make sure you specify the correct domain name. It only supports two ports: 80 (HTTP) and 443 (HTTPS), so there is no need to specify the port number. See [directory 1.1.1).
  2. Invalid signature error. It is recommended to check in the following order:

    1. Confirm correct signature algorithm, available tools for checking http://mp.weixin.qq.com/debug/cgi-bin/sandbox?t=jsapisign pages.
    2. Confirm that nonceStr (hump standard capital S in JS), timestamp in the config is consistent with the corresponding nonceStr and timestamp in the signature.
    3. Verify that the URL is the full URL of the page (please confirm on the current page alert(location.href (‘#’)[0])), including the ‘HTTP (s)😕/’ section, as well as the’? The GET parameter part after ‘, but not the part after ‘#’hash.
    4. Verify that the appid in the config is the same as the appid used to get jsapi_ticket.
    5. Make sure that access_token and jsapi_ticket are cached.
    6. Make sure that the URL you get for signing is dynamically fetched, as shown in the example code in PHP. If it is a static HTML page in the front end and the URL is sent to the background for signature through Ajax, the front end needs to use js to get the link of the current page without the ‘#’hash part (can be obtained by location.href. (‘#’)[0], and need encodeURIComponent). Once the page is shared, the WeChat client will add other parameters at the end of your link. If the current link is not dynamically obtained, the shared page will fail to sign face to face.
  3. Permission Value is Offline Verifying This error is due to the fact that the config was not executed correctly or the JSAPI called was not passed in the JSAPilist parameter of the config. It is recommended to check in the following order:

    1. Verify that the config is correct.
    2. If JSAPI is called while the page is loaded, it must be written in the wx.ready callback.
    3. Verify that the JSAPilist parameter of the Config contains the JSAPI.
  4. (The public account does not have permission to use the JSAPI, or the called JSAPI is not passed in the JSAPilist parameter of the config (some interfaces need to be authenticated before use).
  5. The current client version does not support this interface. Please upgrade to the new version.
  6. 6.0.1 config: OK, but after 6.0.2 config is not OK (because there is no permission verification before 6.0.2, so config is OK, but this does not mean that the signature in your config is OK) Please verify in 6.0.2 that the correct signature is generated to ensure that the config is OK in the higher version.
  7. Cannot share on iOS and Android (please confirm that the public account has been authenticated, only the authenticated public account can have the relevant interface permission to share, if indeed authenticated, then check whether the listening interface is triggered in the wx.ready callback function)
  8. Unable to get jsapi_ticket after the service goes live, no problem in my own test. (Because access_token and jsapi_ticket must be cached on their own server, otherwise frequency limits will be triggered when they go online.) Make sure to cache tokens and tickets to reduce the number of server requests to 2, not only to avoid triggering the frequency limit, but also to speed up your own service. At present, 1W is provided for the convenience of the test, and if it exceeds the threshold, the service will no longer be available. Please ensure that there is a certain global cache of ACCESS_TOKEN and JSAPI_icket before the service goes online, both of which are valid for 7200 seconds. Otherwise, the service will no longer be available once the online trigger frequency is limited.
  9. UploadiImage how to upload multiple images (currently only supports uploading one image at a time, multiple images need to wait until the previous image uploaded before calling this interface)
  10. Unable to preview locally selected images (the ChooseImage interface supports preview itself, no additional support is required)
  11. Invalid Signature fails if you skip to link B via link A (for example, if you login via WeChat authorization first). The background signed URL must be the full URL of the current page using the JSSDK, minus the ‘#’ part.
  12. Config :fail error (this is caused by the incomplete config parameters passed in, please make sure that you pass in the correct appId, timestamp, nonceStr, signature and need to use jsApiList)
  13. How to download JSAPI multimedia resources uploaded to WeChat to your own server (see the notes on the Uploadvoice and Uploadiimage interfaces in the documentation)
  14. Android is uploaded to WeChat server through JSSDK, and then downloaded from WeChat to their own server by a third party, there will be noise (WeChat team has fixed this problem, now the background has been optimized and online)
  15. Binding the parent domain, whether its subdomains are also available (yes, legal subdomains are fully supported after binding the parent domain)
  16. In iOS WeChat 6.1 version, the shared pictures outside the link will not be displayed, only the pictures inside the link of the public page or the pictures of WeChat server can be displayed, which has been fixed in 6.2
  17. Do you need to make your own compatibility for the lower version? (JSSDK is compatible with the lower version and does not require any extra work from a third party. However, some interfaces are new to 6.0.2 and can only be called for the new version.)
  18. The payment signature of the public account is invalid, and the transaction cannot be initiated (please ensure that the jweixin.js you use is the official online version, which can not only reduce user traffic, but also may fix some bugs and copy them to a third-party server for use. The official will not provide guarantee for any problems that may occur. The specific payment signature algorithm can be referred to the column of JSSDK WeChat payment.)
  19. Currently, the new H5 feature of pushState is not supported in the Android WeChat client, so using pushState to implement web app pages will result in signing failure. This problem has been fixed in Android6.2
  20. Android6.2 will solve this problem. If you want to support a lower version, you can put the call to UploadiImage in the setTimeout for a delay of 100ms
  21. The require subscribe error indicates that you did not subscribe to the test number. This error will only occur for the test number
  22. The coordinate returned by GetLocation is deviated from that of OpenLocation, because GetLocation returns GPS coordinates, and the Tencent map opened by OpenLocation is Mars coordinates, which requires a third party to convert by itself. Since version 6.2, direct acquisition of Mars coordinates has been supported
  23. View public account (not added) : “MenuItem :addContact” is not displayed, currently only the link from the public account can be displayed, the source must be public account
  24. There is a one-day delay in ICP record data synchronization, so please bind the next day