preface

This article mainly shares the common wechat H5 real machine debugging method and how to build wechat JS-SDK real machine debugging environment, hoping to help you.

Wechat H5 real machine debugging

Development debug flow

basis

It is recommended to debug the overall page layout and basic logic functions using Chrome or wechat developer tools before entering the next step of real machine debugging. The following methods are commonly used:

  1. Debugging IP address access

    Mobile phone and computer are in the same LAN, such as connected to the same wifi, computer to mobile phone, mobile phone to computer hotspot; Then directly access the IP address of the project in the mobile wechat (e.ghttp://192.168.0.127:8080/) to enter the page, it is recommended to generate a TWO-DIMENSIONAL code and scan it. At this time, the modified items on the PC side will also be synchronized to the mobile side

Advantages: simple operation disadvantages: only look at the style, test button what, page structure, log output and so on what also can not see

  1. usechromeinspectfunction

    The idea is to connect a phone to a computer with a cable, and the phone grants access to the computer (androidEquipment andiosThe device authorization operation is different) and then inchromeIn the accesschrome://inspect/#devicesOpen theinspectHome screen, at this point in the mobile phone to access the page will bechromeCheck the page you want to debug and click in the lower left cornerinspectNow you can open the debug window.

    One thing to noteinspectNeed to scientific online once, otherwise the debugging window cannot load content.

    Advantages: The debugging window on the PC maps to the page operation on the mobile terminal. Disadvantages: It is troublesome to debug ios devices. The debugging window is blocked when I use it

  2. useWechat developer tool version 0.7

    androidEquipment supportweinreRemote debugging andX5 BlinkKernel debugging (supported by some devices), if usedX5 BlinkKernel debugging,inspectPage also need a scientific Internet;iosThe device supports onlyweinreRemote debugging.The official documentationThere is a very detailed introduction, here will not repeat (note that the mobile phone proxy address need not be addedhttp)

Advantages: PC side support debugging wechat JS-SDK, integrated Chrome DevTools, support weinre remote debugging Disadvantages: X5 Blink kernel debugging many devices do not support; Remote debugging does not support HTTPS

  1. usespy-debugger

    Now almost all the web pages on wechat are usedhttpsProtocol, so plan 3 is a little bit urgent, but that’s okay, there’s the killer card, which ispyspyThe artifact. All it takesnpmInstall it and follow the screenshot tutorial from the official documentation below

Advantages: Integrated weinRE + packet capture tool and HTTPS web page debugging Disadvantages: The page is slowly loaded for the first time and is easily disconnected during debugging

The advanced

The above schemes can basically meet the needs of daily development and debugging, but it is a bit difficult to debug wechat JS-SDK on mobile phones, because wechat public account does not support localhost and IP address debugging. I have tried debugging after package deployment, but the debugging cost is too high, and the background brother is also needed to support. So the next start to build wechat JS-SDK real machine debugging environment

Train of thought

Public Test number + local Node service + Intranet penetrating local running project + Request agent + vConsole

To prepare
  • Wechat developer tool 1.x version
  • Intranet penetration tool
    • natapp
    • UTools (Personal use)
  • Two-dimensional code generation
    • Qr code of forage (commonly used by individuals)
    • uTools
In field
  1. Penetrating the Intranet for locally running projects

    The computer runs the project and determines the port number to run, as in8080In order touToolsIntranet penetration plug-in for example, configure the penetration port number and the Internet address, click the lower right corner to connect, after successful access through the Internet address, still support hot update (engineering projects may encounterInvalid Host headerProblems, solutions see practice 4)

  1. After completing Step 1, you can access the local project through the Internet, but it seems to be no different from opening it through the IP address. Don’t panic, the vconsole debut, this demo to vUE project as an example, first install NPM, introduced in the project and initialization, at this time is not to see the page right corner more than a small green button, yes, click it on the right. Debugging interface as shown below, the function is quite complete, you can delude debugging happily

    // main.js
    if(process.env.NODE_ENV ! = ='production') {
      const VConsole = require('vconsole')
      new VConsole()
    }
    Copy the code

  1. Local Node service Starts a local Node service. It has two functions

    1. Used for verification when configuring test public numbersurlSee whether it can correctly respond to Token authenticationThe document, the following code example
    // sign.js
    const checkout = obj= > {
      const { signature, timestamp, nonce } = obj
      // Token configured in public number
      const token = config.token
      // Use sha1 to encrypt and compare with signature
      const string = sort(nonce, timestamp, token),
        sha1 = require('js-sha1')
      return signature === sha1(string)
    }
    
    // router
    router.get('/checkout'.async (ctx, next) => {
      const { echostr, timestamp, nonce, signature } = ctx.query
      // ctx.body = echostr
    
      // Verify the source
      const res = util.checkout({ timestamp, nonce, signature })
      // Return echostr if the visa is correct
      ctx.body = res ? echostr : false
      await next()
    })
    Copy the code
    1. Used to generateWeChat js - SDKThe signature, first getaccess_tokenAnd use it toaccess_tokenTo obtainjsapi_ticketAccording to the signature algorithm, the signature is generated and returned to the front end.access_tokenandjsapi_ticketAll need to be cached locally, valid for 7200 seconds, the following is the signature code example
      // Signature algorithm
      const sign = (jsapi_ticket, url) = > {
      const ret = {
          jsapi_ticket,
          url,  // Do not escape the current URL! Do not escape! Do not escape!
          nonceStr: createNonceStr(), // Random string
          timestamp: createTimestamp()  / / timestamp
        };
        // dictionary collation with url key-value pairs
        const string = raw(ret),
          sha1 = require("js-sha1");
    
        ret.signature = sha1(string);//sha1 encryption generates signature
        ret.appId = config.appId; // Public appId is also returned by the back end
        return ret;
      };
    Copy the code
  2. When the front-end request proxy accesses the web page using an external IP address after the Intranet is penetrated, a cross-domain problem may occur if the requested service address is a real service address. In addition, the request proxy cannot be used to request the local Node service address. First change the request address within the project to the penetration address, and then do the proxy forwarding. Webpack project can be realized by configuring devServer, other can use Nginx, this article takes vue CLI project to configure devServer as an example

    // vue.config.js
    module.exports = {
      devServer: {
        disableHostCheck: true.// Avoid Invalid Host header
        proxy: {
          '/getSignature|checkout': {
            // checkout is used to verify server validity with the public account
    
            // The local project can be overridden if the API name is not getSignature
            // pathRewrite: { "^/api": '/getSignature' }
    
            target: 'http://127.0.0.1:3000' // Proxy to local NOE service address
          },
          '^/other': {
            // Other interfaces can also be proxied
            target: 'http://xxx.xxx.x.x:80'.changeOrigin: true // Change the request host, optional}}}}Copy the code
  3. Configure wechat test public number first find the test number entrance, use wechat scan can register a test number, roughly the interface is as follows

node
node
node

To optimize the

After practical operation, when you visit the VUE project for the first time through the Intranet penetrating address, do you find that the loading page is extremely slow, the screen is blank for a long time, and even the loading fails due to the request timeout, Nani? To do that? Don’t worry, you can optimize it from the following angles

  • changesource mapmodel

    vue-cliBuilt in a development environmentsource mapThe default mode ischeap-module-eval-source-mapIn this mode, the source code is packaged, and the generated package has a large volume, which causes the page rendering to be blocked when the page is loaded. Therefore, it can be used at this timecheap-source-maporevalPatterns (build speedevalMode is much faster.
//vue.config.js
module.exports = {
  configureWebpack: config= > {
    if(process.env.NODE_ENV ! = ='production') {
      config.devtool = 'cheap-source-map'}}}Copy the code

The vendors package is almost 60% smaller and takes 2.68 seconds less to load

  • opengzipThe compression

    Large projects are switching oversource mapPatterns may be found aftervendorsThe package is still large, so we can try to open itgzipCompression (common server configuration).

    Due to theuToolsThe Intranet penetration tool is enabled by defaultgzip, we can not configure, so herevue-cliopengzipExample, usinglocalThe address page is displayed to compare the difference before and after file compression
module.exports = {
  devServer: {
     compress: true.// Enable gzip compression}};Copy the code

em… The volume is smaller, but the loading time is longer, is I make a mistake, know the buddy answer

  • Upgrade Intranet penetration bandwidth(krypton gold)

    natappFor example (non-advertising), the bandwidth of the free channel is only 1M,TCPThe number of connections is limited to 5, but when you charge, the bandwidth goes up to 100 megabits and you fly. However, the general free enough to use, there is a demand can be krypton.

summary

After completing the above steps, you can start debugging happily. If you have other solutions, welcome to add.

Wechat JS-SDK use share

The development of wechat H5 page will encounter many interaction scenarios with wechat, so familiar with the use of wechat JS-SDK can greatly reduce overtime and improve development efficiency; Next, we will talk about the problems we often encounter in the daily development of wechat JS-SDK. If you have not used it, you can take a look at the official documents

invalid signatureSignature error

The most frequent errors, when confirming the variable name spelling, signature algorithm under the premise of no problem, can start from the URL Angle to check, please see the following several cases

  1. To obtainurlAs long ashashThe front part
const url = location.href.split(The '#') [0]
// http://example.com/#login?age=99 -> http://example.com/
Copy the code
  1. Routing Mode difference

    vueRouting, for example, is inhashIn mode, no matter how the route changes, interceptedurlIt doesn’t change; But in thehistoryIn mode, different pages are capturedurlIs different, so the current must be retrieved dynamically when the page switchesurlTo sign, and also to distinguish platform differences, look at the next item
  2. Platform differences (historyMode)
    • androidPlatform, different pages dynamically obtain the current routing pageurlYou can sign it
    • iosPlatform, different pages need to useThe page is displayed for the first timeAt the time of theurlYou have to sign it
  3. encodeThe problem

    The document asks for a signatureurluseencodeURIComponentOtherwise, page sharing will be affected, and then we need to pay attention to the server to geturlAfter mustdecodeURIComponentAfter executing the signature algorithm, otherwiseconfigWill fail
    / / encodeURIComponent before
    'http://example.com/'
    / / after encodeURIComponent
    'http%3A%2F%2example.com%2F'
    // The following escape will also fail
    'http:\/\/example.com\/'
    Copy the code

require subscribeerror

This is typically encountered during local debugging. Scan code to subscribe to the public platform test number can be solved

invalid url domainerror

The security domain name of the JS interface is incorrectly configured. Delete the protocol and port number, and then check the spelling

Interface FaQs

wx.readyandwx.error

After wx.config is called, the two interfaces are used to determine whether the config succeeds. Note the following points

  • The wx.error callback indicates that config must have failed

  • The wx.ready callback executes whether or not config succeeds. , because the following situations will occur:

    1. If the config fails after the first execution of wx.config, the wx.error callback is executed first, followed by the wx.ready callback

    2. But from the second execution of wx.config, only the Wx.ready callback is executed on success, and the wx.error callback is executed after the wx.ready callback on failure

  1. Only performedwx.readyCallback, but still occurs when the interface is calledthe permission value is offline verifyingIn this case, it’s usually becauseconfigIf an exception occurs, try againwx.config

For the above problems, we can use Promise to encapsulate the config method, but the config is only valid for the first time. Therefore, we can judge whether the config succeeds in the end by putting it into the function interface callback

// See demo for a code example
jsSdk.config({
  debug: false,
  appId,
  timestamp,
  nonceStr,
  signature,
  jsApiList
})
return new Promise((resolve, reject) = > {
  // ready not necessarily config success...
  jsSdk.ready((a)= > {
    console.log('ready')
    resolve(jsSdk)
  })
  // Error is executed before ready
  jsSdk.error(err= > {
    console.log('err')
    reject(err)
  })
})
Copy the code

Sharing interface

First of all, it is clear that H5 page cannot actively adjust the sharing menu in the wechat menu through this kind of interface. Degradation processing is generally a pop-up prompt to guide sharing, but there is a risk of account blocking, so use with caution!

  • wx.onMenuShareTimeline,wx.onMenuShareAppMessageWe can get whether the user clicked the share button in the wechat menu, but we cannot judge whether the user really shared it. For example, when the sharing window pops up, clicking “No” to return to the page is also countedsuccessIn the callback. The two interfacesThe abandonedI don’t know when it will be, so try not to use it
  • wx.updateAppMessageShareData,wx.updateTimelineShareDataThese two brothers were trying to get rid of the other two brothers. CutButton click stateAccess to features, such a good product manager where to find…

Image interface

  • wx.chooseImageLocal photo returnedlocalId, similar to usingURL.createObjectURLCreate a file reference,androidThe client can be used directlyimgOf the labelsrcNormal use, howeveriosYou can’t do it. You have to use itwx.getLocalImageDatatobase64Format and then show it
  • wx.uploadImageIt will upload your picture to the wechat server and save it for 3 days (Dachang is rich and powerful), and return the ID corresponding to the picture in the server, which can be used within the validity periodwx.downloadImageCan get the picturelocalId

To complement…

Debug the DEMO

In order to make it easier for you to understand the content of the article, I used vue CLI to complete a demo for you, which can be used after cloning it from Github. The overall project structure is shown as follows, and the project address is VUe-js-SDK-demo

  • Put the project configuration in the root directory for easy configuration
/config/index.js
module.exports = {
  baseUrl: "http://example.com".// Change the IP address here after Intranet penetration is enabled
  appId: "wxxxxxxxxxxxx43".// Test public id appId
  secret: "7acsssssssssssssss5289".// Test public id secret
  token: "candyman" // Test public token, custom
};
Copy the code
  • usenatappFor Intranet penetration (you can skip reading if you use other Intranet penetration tools), clicknatappThe official website is configured with the port number of penetration, and then in/natapp/config.iniFill in your channel number,WindowsThe system directly double-click to open itnatapp.exeCan,MacPlease replace the system with a corresponding client on the official website
[default]
authtoken= Enter your tunnel authTokenCopy the code
  • To configure the wechat test public account, see the above steps
// Initialize the project NPM install // Start the vue project and node service at the same time. NPM run start // Start the vue project separately. NPM run dev // Start the node project separatelyCopy the code
  • After starting the project, it looks like the following. Several APIS were added to facilitate testing. There are secondary packaging SDK examples in demo for your reference

Update log

2020-4-1 Added wechat JS-SDK Config result description

The latter

Although I usually take development notes, it is the first time to share them as articles. If there are any mistakes in the article, please point out them in time and I will correct them as soon as possible.