This time I will bring you ngrok+express to debug the WeChat interface in the local environment. What are the precautions for ngrok+express to debug the WeChat interface in the local environment. The following is a practical case, let's take a look.
During the development of WeChat project, it is often necessary to debug the interfaces provided by WeChat jssdk, such as recording, sharing, uploading images and other interfaces, but WeChat jssdk requires binding a secure domain name Only in this way can you use a series of functions it provides. However, using localhost or local IP in the development environment cannot complete the authentication and binding of the domain name, so it cannot be debugged locally. Of course, there is a last resort method, which is to develop it locally, package it and send it to the company's test server, and use the domain name certified by the test server for debugging. Every time you make a change, you have to send a test for debugging. Obviously, this method is very troublesome and very time-consuming. It’s not scientific, so this article will focus on this problem to introduce how to use ngrok and express to solve the debugging problem of WeChat interface in the development environment.
1: First introduce ngrok. The main function of ngrok is to map the local IP to the external network and assign you an available domain name. Through this domain name, external network users can open your local web. The service is also very simple to use, and the official website also has documents and detailed introductions. Here is a brief introduction to how to use it. First, go to ngrok's official website to download the corresponding client of ngrok, and register as a user. You can register through your github account or google account. After the registration is completed, open auth in the personal center. option, copy the authtoken here, as shown below:
(Here we take the window version as an example), then download and unzip it, there will be an ngrok.exe file, double-click to run it The following command line will appear:
First we need to complete the token authentication of ngrok, otherwise an error will occur during operation. Run the command
ngrok authtoken ** *************** //* number is the token in the personal center, just copy it
After the authentication is completed, you can operate it, as shown in the picture above Examples are some commonly used example commands. We use ngrok http. The following parameter is the port number of your local web service. After running, an external domain name will be assigned. Through this domain name, you can access your local web service. ,
However, this domain name will be reassigned a new domain name after the restart, resulting in the need to go to the WeChat public platform to reset the secure domain name and token authentication after the restart. Unfortunately, in ngrok 1.0, the assigned domain name can be fixed each time through ngrok http subdomain=*** (custom domain name) 80, but after version 2.0, free users cannot fix the domain name, only paid users can , although it only costs $5 per month, for people who don’t test it frequently, there is still no desire to buy it. The key is that it only seems to support visaa... However, for fat friends who want a free fixed domain name, there are still solutions. There is sunny-ngrok in China, which allows you to apply for a custom fixed domain name for free. You can check its official website for specific tutorials. It is not very complicated. There are If you have any questions, you can ask me in the comments, I won’t go into details. Of course, there are many other methods to achieve external network mapping, such as using Localtunnel and peanut shell installed by npm, etc. You can learn about it yourself.
2: After getting the domain name, the next thing we have to do is use the domain name to complete the WeChat secure domain name binding. We can go to the WeChat public platform to apply for a test account, but it will not pass when filling in at this time. Because WeChat authentication requires its own server to correctly respond to the configuration request
When you apply for a test account, fill in the URL of the configuration information, and the WeChat server will send a get request to this address. , the get request will carry some parameters. We need to use these parameters to generate a signature and compare it with the signature of WeChat parameters. Only if the comparison is successful, the interface will be configured successfully.
Because WeChat authentication requires its own server, here we need to use express to build a simple server to complete WeChat token authentication and generate signatures. The construction process is also very simple. , refer to express Chinese documentation, here are the steps from the official website:
After the installation is completed, enter the myapp directory and create an app.js file.
var express = require('express'); var crypto = require('crypto') //使用npm安装后引入,用来生成签名 var http = require('request') //express的中间件,使用npm安装,用来发出请求 var jsSHA = require('jssha')//jssha是微信官网提供的nodejs版本签名算法,可以去官网下载官网的sample包 var app = express(); app.use(express.static('./review')) app.get('/weixin',function (req, res) {//这个get接口就是测试号填写的接口,用来响应微信服务器的请求 var token = 'weixin' //注意这里填写token,与微信测试号申请时候填写的token要保持一致 var signature = req.query.signature; var timestamp = req.query.timestamp; var nonce = req.query.nonce; var echostr = req.query.echostr; /* 加密/校验流程如下: */ //1. 将token、timestamp、nonce三个参数进行字典序排序 var array = new Array(token,timestamp,nonce); array.sort(); var str = array.toString().replace(/,/g,""); //2. 将三个参数字符串拼接成一个字符串进行sha1加密 var sha1Code = crypto.createHash("sha1"); var code = sha1Code.update(str,'utf-8').digest("hex"); //3. 开发者获得加密后的字符串可与signature对比,标识该请求来源于微信 if(code===signature){ res.send(echostr) }else{ res.send("error"); } }); var server = app.listen(80, function () { var host = server.address().address; var port = server.address().port; console.log('Example app listening at http://%s:%s', host, port); });
After the creation is completed, run
node app.js
The server is now started. The following points to note are:
1: jssha cannot be installed with npm, because npm installation will report Chosen SHA when running. variant is not supported
, you must use the sample package provided by the official website. After downloading and decompressing, select the node version, open it and copy the jssha file in node_module to the node_module in the project;
2: The token value here needs to be consistent with the token value filled in the WeChat test account;
Now we can start filling in the parameters of the test account. After completing the filling, the WeChat server will send a request to the interface you filled in. , if all responses are correct, a pop-up message indicating successful configuration will appear.
Of course, it’s not over yet, because the front end needs to complete the permission configuration through the interface request if it wants to call the jssdk interface. Here you can take a look at the WeChat jssdk documentation. The specific reference steps will not be repeated here. The interface request is roughly as follows:
This interface is mainly to submit the current url request to the server to get the corresponding parameters and complete the permission configuration, so you need to write another one in express The interface that responds to post request. The main work of this interface is to use the appid and appSerect (provided by the test number) to request the interface provided by WeChat to generate an access_token, and then use this access_token to request the interface provided by WeChat to generate it. tiket, there are detailed instructions on both of these documents. Finally, the signature is generated. The code is as follows
// noncestr生成var createNonceStr = function() { return Math.random().toString(36).substr(2, 15); }; // timestamp时间戳生成var createTimeStamp = function () { return parseInt(new Date().getTime() / 1000) + ''; }; //获取tiket var getTiket= function (data) { //通过access_token获取tiket return new Promise((reslove,reject)=>{ http.get(`https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=${data}&type=jsapi`, function(err,res,body){ if(res.body.tiket){ resoleve(res.body.ticket) }else{ reject(err) } }) })} // 计算签名方法 var calcSignature = function (ticket, noncestr, ts, url) {//使用jssha var str = 'jsapi_ticket=' + ticket + '&noncestr=' + noncestr + '×tamp='+ ts +'&url=' + url; shaObj = new jsSHA(str, 'TEXT'); return shaObj.getHash('SHA-1', 'HEX'); } //返回给前端配置信息的post接口 app.post('/weixin',function(req,res,next){ let appId = '******' let appSecret = '******' let url = `https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${appId}&secret=${appSecret }` http.get(url, function (err, response, body) { getTiket(response.body).then(resolve=>{ let tiket = resolve//tiket let nonceStr = createNonceStr()//随机字符串 let timeStamp = createTimeStamp()//时间戳 let signature = calcSignature(tiket,nonceStr,timeStamp,req.body.url) let obj = { //将前端需要的参数返回 data:{ appId:appId, timestamp:timeStamp, nonceStr:nonceStr, signature:signature } } res.end(JSON.stringify(obj)) }).catch(err=>{}) res.end(JSON.stringify(err)) });})
It should be noted here that the access_token and tiket returned by WeChat have a validity period of 7200s, so they need to be cached. There is no cache operation code written in my code. Everyone has it. Two methods:
1. After getting the access_token and tiket, directly write them in variables and save them. During the validity period, you do not need to continue to request the interface, just perform the signature operation directly; after expiration, request once That's good. Although this method is a bit clumsy, it still has a long validity period.
2. After the server gets the access_token and tiket, write it into the local json file. The specific steps will not be repeated. Then determine whether it has expired. After the expiration, request again. If it has not expired, read the json directly. Sign the data in the file.
Finally, there are two options:
First: After executing npm run build on our front-end project, put the dist file into our server folder, you can use express directly static middleware
app.use(express.static('./dist'))
Then WeChat developer tools, enter the assigned domain name to open our project, so we don’t need to set up an agent, but we need to execute build, which is a bit of a waste of time if the project is larger;
Second: Apply for a domain name for our development environment, because the scaffolding is now hot updated In fact, it is to start a webpack-dev-sever micro-server. After applying for a domain name, just fill in the development port number, so that the development address is the same as the second-level domain name of our server address. However, for the server interface, the development environment requires Set the proxy, and the hot update will also be invalid. You need to refresh it manually, but it may be better than the first method.
After the two methods run successfully, check the request. If the configuration is successful, the console will display the configuration success message as follows:
Then we can be happy Now that I am using the interface of jssdk, I no longer need a backend. I can test all the interfaces locally by myself, and it is not a pleasure.
I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website!
Recommended reading:
How to use JS to change the status of the radio
The corresponding callback function is executed after the JS script is loaded operate
The above is the detailed content of ngrok+express performs local environment WeChat interface debugging. For more information, please follow other related articles on the PHP Chinese website!

主板上的aafp是音频接口;该接口的功能是启用前面板的“3.5mm”插孔,起到传输音频的作用,aafp跳线基本上由两个部分组成,一部分是固定在主板、硬盘等设备上的,由两根或两根以上金属跳针组成,另一部分是跳线帽,是一个可以活动的组件,外层是绝缘塑料,内层是导电材料,可以插在跳线针上。

“cha fan”表示的是机箱风扇;“cha”是“chassis”的缩写,是机箱的意思,“cha fan”接口是主板上的风扇供电接口,用于连接主板与机箱风扇,可以配合温度传感器反馈的信息进行智能的转速调节、控制噪音。

ioioi是指COM接口,即串行通讯端口,简称串口,是采用串行通信方式的扩展接口。COM接口是指数据一位一位地顺序传送;其特点是通信线路简单,只要一对传输线就可以实现双向通信(可以直接利用电话线作为传输线),从而大大降低了成本,特别适用于远距离通信,但传送速度较慢。

link/act是物理数据接口;交换机上的link/act指示灯表示线路是否连接或者活动的状态;通常Link/ACT指示灯用来观察线路是否激活或者通畅;一般情况下,若是线路畅通,则指示灯长亮,若是有数据传送时,则指示灯闪烁。

jbat1是主板电2113池放电跳线接口,对于现在市面上常见的主板来说,它们都设计有CMOS的放电跳线,让用户在操作时更加便捷,它也因此成为了CMOS最常见的放电方法。

sata6g是数据传输速度为“6G/s”的sata接口;sata即“Serial ATA”,也就是串行ATA,是主板接口的名称,现在的硬盘和光驱都使用sata接口与主板相连,这个接口的规格目前已经发展到第三代sata3接口。

dc接口是一种为转变输入电压后有效输出固定电压接口的意思;dc接口是由横向插口、纵向插口、绝缘基座、叉形接触弹片、定向键槽组成,两只叉型接触弹片定位在基座中心部位,成纵横向排列互不相连,应用于手机、MP3、数码相机、便携式媒体播放器等产品中。

pump fan是散热风扇接口。主板上的风扇接口有cpu fun、sys fun、pump fun,对于一般普通用户来说区别不大,一般接哪个都行,而pump fun上的电流更大一点,用于接功率大一点的水冷风扇头。


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

SublimeText3 English version
Recommended: Win version, supports code prompts!

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 Mac version
God-level code editing software (SublimeText3)

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.