Recently, when developing h5
an application , it is necessary to activate the scan function of WeChat. Then you have to use WeChat JS-SDK
, how to JS-SDK
use ? (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.
1. Ngrok intranet penetration
What is Ngrok?
Ngrok
is a reverse proxy that establishes a secure channel between a public endpoint and web
a server .
Ngrok
It 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 ngrok
running 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 . ngrok
Here's an example based mac
on , installed via the command line:
brew install ngrok/ngrok/ngrok
After the installation is successful, you can ngrok -h
view :
locally bound authorization token
Log in and go to dashboard.ngrok.com/get-started… , copy your authorization token:
Then authorize: ngrok authtoken 复制的授权令牌
.
Intranet penetration, obtain domain name link
Our front-end case runs demo
on a port number 3000
, so we can perform intranet penetration for local services under this port number:
$ ngrok http 3000
如上图,访问 https://55e4-121-33-184-45.ngrok-free.app
即访问了 http://localhost:3000
。
配置 JS-SDK 域名白名单
进入 测试号管理 配置域名 55e4-121-33-184-45.ngrok-free.app
:
获取 Access Token
我们获取到测试公众号的 appID
和 appsecret
:
然后,通过调用[get] https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET
可以获取 access token
:
获取 Jsapi Ticket
通过 access_token
,我们通过调用 [get] https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=ACCESS_TOKEN&type=jsapi
可以获取 Jsapi Ticket
:
获取签名
我们已经获取到 jsapi_ticket
,之后,通过 微信 js 签名工具 完成签名:
- 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 功能
下面我们结合 react
的 demo
代码:
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-SDK
of , and then jsApiList
declared js
the 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:
The in the figure
signature
is 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:port
map , such as: frontend.internal:3000
. Accessing a project http://frontend.internal:3000
means 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 2
one . 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 1
first does not hinder the progress of the project.