WeChat JS-SDK local debugging

Recently, when developing h5an application , it is necessary to activate the scan function of WeChat. Then you have to use WeChat JS-SDK, how to JS-SDKuse ? (The function is not limited to WeChat scan)

Here, we introduce two methods:

Demo is run on Mac M1; other platforms please verify by yourself

Assuming that you have applied for a public account test account, if you don’t know how to operate it, please go to my previous article - Debugging WeChat official account to obtain user information

OK, let's start the text.

pexels-aline-viana-prado-2465877.jpg

1. Ngrok intranet penetration

What is Ngrok?

Ngrokis a reverse proxy that establishes a secure channel between a public endpoint and weba server .

NgrokIt is an open source project released by a foreign country, and there is also a public service, but it was blocked by the domestic wall. A domestic organization has established and operated a ngrokrunning service, although sometimes not stable, but enough for debugging personnel .

The service is unstable, and I occasionally hang up during debugging, but it does not affect debugging.

Install Ngrok

Download and install the software through Install ngrok . ngrokHere's an example based macon , installed via the command line:

brew install ngrok/ngrok/ngrok

After the installation is successful, you can ngrok -hview :

ngrok-help.png

locally bound authorization token

Log in and go to dashboard.ngrok.com/get-started… , copy your authorization token:

ngrok-token.png

Then authorize: ngrok authtoken 复制的授权令牌.

Intranet penetration, obtain domain name link

Our front-end case runs demoon a port number 3000, so we can perform intranet penetration for local services under this port number:

$ ngrok http 3000

ngrok-http-3000.png

如上图,访问 https://55e4-121-33-184-45.ngrok-free.app 即访问了 http://localhost:3000

配置 JS-SDK 域名白名单

进入 测试号管理 配置域名 55e4-121-33-184-45.ngrok-free.app

js security domain name.png

获取 Access Token

我们获取到测试公众号的 appIDappsecret

Test number information.png

然后,通过调用[get] https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET 可以获取 access token

get-access-token.png

获取 Jsapi Ticket

通过 access_token,我们通过调用 [get] https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=ACCESS_TOKEN&type=jsapi 可以获取 Jsapi Ticket

get-js-ticket.png

获取签名

我们已经获取到 jsapi_ticket,之后,通过 微信 js 签名工具 完成签名:

微信js接口签名校验工具.png

  • jsapi_ticket:通过 getticket 接口获取的 JSAPI 调用凭证
  • noncestr:随机生成的字符串(上图是 jimmy
  • timestamp:当前时间戳(单位:秒)
  • url:需要调用 JS 接口的 URL

引入 js-sdk

这里我直接使用 npm 安装:npm install weixin-js-sdk。当然你也可以使用 script 引入外链 <script src="https://res.wx.qq.com/open/js/jweixin-1.6.0.js"></script>

使用 js-sdk 功能

下面我们结合 reactdemo 代码:

import React, { useState, useEffect } from 'react';
import wx from 'weixin-js-sdk';

function Demo(){
  const [value, setValue] = useState('');
  
  useEffect(() => {
    initJsDdkConfig();
  }, []);
  
  // 初始化 js-sdk 的配置信息
  const initJsDdkConfig = () => {
    wx.config({
      debug: true, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。
      appId: 'wxd14f1f23ebac23ac', // 必填,测试公众号的 app id
      timestamp: '1683904745', // 必填,上图的时间戳
      nonceStr: 'jimmy', // 必填,上图的随机字符串
      signature: '65caaeb958e91f089af2f74a240dffff8c4a5584', // 必填,上图中生成的凭证
      jsApiList: ['scanQRCode'] // 需要使用到 js 接口列表
    });
  }
  
  // 扫描
const scaneMethod = () => {
  wx.ready(function() { // ready 后调用,确保加载了配置
    wx.scanQRCode({
      // 微信扫一扫
      desc: "scanQRCode desc",
      needResult: 1, // 默认为0,扫描结果由微信处理,1则直接返回扫描结果,
      scanType: ["qrCode", "barCode"], // 可以指定扫二维码还是一维码,默认二者都有
      success: function(res) {
        const getCode = res.resultStr; // 当needResult 为 1 时,扫码返回的结果
        // 设置回填
        setValue(getCode);
      },
      fail: function(res) {
        Toast(res.errMsg);
      }
    })
  })
  }
  
  return (
    <div>
      <button onClick={() => scaneMethod()}>扫一扫</button>
      <p>扫描结果:{ value }</p>
    </div>
  )
}

export default Demo;

First, we obtained the configuration information JS-SDKof , and then jsApiListdeclared jsthe interface in scanQRCode. After that, click the scan code button to invoke the scan code function.

The console output of the WeChat development tool is as follows:

相关能力 JS-SDK 绑定.png

The in the figure signatureis regenerated

2. Cooperate with the backend and configure the domain name

This method of back-end cooperation requires the back-end or operation and maintenance colleagues to ip:portmap , such as: frontend.internal:3000. Accessing a project http://frontend.internal:3000means accessing your local project.

Then the next process is exactly the same as that in the Ngrok Intranet Penetration chapter.配置 JS-SDK 域名白名单引入 js-sdk使用 js-sdk 功能

Afterword

Comparing the two methods, the author still likes the first 2one . One is that the stability of access is guaranteed, and the other is that the test environment can be debugged by the way (if the test environment is ip access). However, the 1first does not hinder the progress of the project.

Reference

Guess you like

Origin juejin.im/post/7233788679742242874