When developing WeChat projects, it is often necessary to debug the interfaces provided by WeChat jssdk, such as recording, sharing, uploading images, etc. However, WeChat jssdk requires binding a secure domain name to 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.
This article mainly introduces the use of ngrok+express to solve the WeChat interface debugging problem in the local environment. Friends who need it can refer to it. I hope it can help everyone.
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 The local web 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 the auth option in the personal center and copy the authtoken here. , as shown below:
(Here we take the window version as an example), then after downloading and decompressing, there will be an ngrok.exe file. Double-click to run and the following command line will appear. :
First we need to complete the ngrok token authentication, 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. The examples in the picture above are some commonly used examples. For the command, 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 security 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 will be started. The following points to note are:
1 :jssha cannot be installed using npm, because when running npm installation will report Chosen SHA variant is not supported
,必须使用官网提供的sample包,下载解压后,选择node版本,打开后将node_module里面jssha文件复制到项目内的node_module里面即可;
2:这里的token值需要和微信测试号中填写的token值一致;
现在我们就可以开始填写测试号的参数了,填写完成微信服务器就会发送请求给你填写的接口了,都正确响应的话就会弹出配置成功。
当然到这还没有结束,因为前端想要调用jssdk的接口还需要通过接口请求完成权限配置,这里大家可以看一下微信jssdk的说明文档,具体引用步骤这里就不赘述了,接口请求大概如下:
这个接口主要就是提交当前的url请求服务端拿到相应的参数,完成权限配置,所以在express中还需要在写一个响应post请求的接口,这个接口做的主要的工作就是拿appid和appSerect(测试号提供)去请求微信提供的接口生成access_token,然后拿这个access_token再去请求微信提供的接口生成tiket,关于这两者文档上都有详细说明。最后生成签名,代码如下
// 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)) });})
这里要注意的是微信返回的access_token 和tiket的都有7200s的有效期,所以要进行缓存,我的代码中没有写缓存的操作代码了,大家有两种方法:
1.拿到access_token和tiket后,直接写在变量中存下来,有效期内就不用继续请求接口了,直接进行签名操作就可以了;过期后,在请求一次就好了,虽然这种方法有点笨,不过好歹有效期还算长。
2.在服务器拿到access_token和tiket后,写入本地的json文件中,具体步骤也不赘述了,然后判断是否过期,过期后就重新请求,没过期就直接读取json文件中的数据进行签名。
最后呢,有两种选择:
第一:把我们的前端项目执行 npm run build 后,把dist文件放入我们的服务器文件夹中,可以直接用express的static中间件
app.use(express.static('./dist'))
然后微信开发者工具,输入分配的域名打开我们的项目,这样我们不用设置代理了,不过需要执行build,项目大一点的话还是有点浪费时间的;
第二:就是为我们的开发环境在申请一个域名,因为现在脚手架的热更新其实就是启动了一个webpack-dev-sever的微服务器,申请域名是后填写开发的端口号就可以了,使得开发地址和我们的服务器地址的二级域名相同,不过对于服务器的接口,开发环境需要设置一下代理,而且热更新也会失效,需要手动刷新一下,不过相对于第一种方法可能会更好一点。
两种方法运行成功后查看发出请求如果配置成功,控制台会出现配置成功的信息如下:
然后我们就可以愉快的在使用jssdk的接口了,再也不求后端,可以自己在本地测试好所有的接口了,且不是美滋滋。
相关推荐:
The above is the detailed content of ngrok+express solves WeChat interface debugging method. For more information, please follow other related articles on the PHP Chinese website!

不同的电脑系统在调整屏幕亮度的操作方法上会有些不同,最近就有使用win7系统的网友不知道win7怎么调整屏幕亮度,看久了电脑眼睛比较酸痛。下面小编就教下大家win7调整屏幕亮度的方法。具体的操作步骤如下:1、点击win7电脑左下角的“开始”,在弹出的开始菜单中选择“控制面板”打开。2、在打开的控制面板中找到“电源选项”打开。3、也可以用鼠标右键电脑右下角的电源图标,在弹出的菜单中,点击“调整屏幕亮度”,如下图所示。两种方法都可以用。4、在打开的电源选项窗口的最下面可以看到屏幕亮度调整的滚动条,直

如果我们手头没有手机,只有电脑,但我们必须拍照,我们可以使用电脑内置的监控摄像头拍照,那么如何打开win10监控摄像头,事实上,我们只需要下载一个相机应用程序。打开win10监控摄像头的具体方法。win10监控摄像头打开照片的方法:1.首先,盘快捷键Win+i打开设置。2.打开后,进入个人隐私设置。3.然后在相机手机权限下打开访问限制。4.打开后,您只需打开相机应用软件。(如果没有,可以去微软店下载一个)5.打开后,如果计算机内置监控摄像头或组装了外部监控摄像头,则可以拍照。(因为人们没有安装摄

随着科技的不断发展,机器视觉技术在各个领域得到了广泛应用,如工业自动化、医疗诊断、安防监控等。Java作为一种流行的编程语言,其在机器视觉领域也有着重要的应用。本文将介绍基于Java的机器视觉实践和相关方法。一、Java在机器视觉中的应用Java作为一种跨平台的编程语言,具有跨操作系统、易于维护、高度可扩展等优点,对于机器视觉的应用具有一定的优越性。Java

目前有很多屏幕亮度调整软件,我们可以通过使用软件进行快速调整或者通过显示器上自带的亮度功能进行调整。以下是详细的Win7屏幕亮度调整方式,您可以通过教程中的方法进行快速调整即可。Win7系统电脑怎么调节屏幕亮度教程:1、依次点击“计算机—右键—控制面板”,如果没有也可以在搜索框中进行搜索。2、点击控制面板下的“硬件和声音”,或者点击“外观和个性化”都可以。3、点击“NVIDIA控制面板”,有些显卡可能是AMD或者Intel的,请根据实际情况选择。4、调节图示中亮度滑块即可。5、还有一种方法,就是

Go语言是近年来备受青睐的编程语言,因其简洁、高效、并发等特点而备受开发者喜爱。其中,方法(Method)也是Go语言中非常重要的概念。接下来,本文就将详细介绍Go语言中方法的定义和使用。一、方法的定义Go语言中的方法是带有接收器(Receiver)的函数,它是一个与某个类型绑定的函数。接收器可以是值类型或者指针类型。用于接收者的参数可以在方法名

如今微软的Windows系统已经更新换代到了Windows10版本。很多以前还在使用Windows7系统的用户都想体验这个新版本Windows10系统。下面小编就来说说如何下载win10系统下载的方法,大家快来看看。1、首先下载一个小白重装系统软件,然后点击在线重装,下载win10系统。2、然后就开始系统镜像的下载了。3、系统镜像下载完成就是环境部署了。然后win10系统就下载完成啦。4、重启之后开始安装系统,安装完成就能进入桌面咯。以上就是如何下载win10系统的方法介绍啦,希望能帮助到大家。

PHP是一个广泛使用的服务器端编程语言,它的许多功能和特性可以将其用于各种任务,包括文件下载。在本文中,我们将了解如何使用PHP创建文件下载脚本,并解决文件下载过程中可能出现的常见问题。一、文件下载方法要在PHP中下载文件,我们需要创建一个PHP脚本。让我们看一下如何实现这一点。创建下载文件的链接通过HTML或PHP在页面上创建一个链接,让用户能够下载文件。

使用PHP数组实现数据缓存和存储的方法和技巧随着互联网的发展和数据量的急剧增长,数据缓存和存储成为了我们在开发过程中必须要考虑的问题之一。PHP作为一门广泛应用的编程语言,也提供了丰富的方法和技巧来实现数据缓存和存储。其中,使用PHP数组进行数据缓存和存储是一种简单而高效的方法。一、数据缓存数据缓存的目的是为了减少对数据库或其他外部数据源的访问次数,从而提高


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

Dreamweaver Mac version
Visual web development tools

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Zend Studio 13.0.1
Powerful PHP integrated development environment

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

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