Home > Web Front-end > JS Tutorial > How to use ngrok+express to solve WeChat interface debugging problems

How to use ngrok+express to solve WeChat interface debugging problems

亚连
Release: 2018-06-04 14:56:29
Original
1735 people have browsed it

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

When developing WeChat projects, it is often necessary to debug the interface provided by WeChat jssdk Debugging, such as recording, sharing, image uploading and other interfaces, but WeChat jssdk requires binding a secure domain name to use a series of functions it provides, and using localhost or local IP in the development environment cannot complete domain name authentication and binding, so Unable to debug 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 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);
});
Copy after login

After the creation is completed, run

node app.js

The server will be started, please pay attention to the above The following points are:

1: jssha cannot be installed with npm, because when npm installs it, it 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 + '&timestamp='+ 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))
   });})
Copy after login

这里要注意的是微信返回的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的接口了,再也不求后端,可以自己在本地测试好所有的接口了,且不是美滋滋。

上面是我整理给大家的,希望今后会对大家有帮助。

相关文章:

基于express中路由规则及获取请求参数的方法

javascript变量提升和闭包理解

浅谈angular4.0中路由传递参数、获取参数最nice的写法

The above is the detailed content of How to use ngrok+express to solve WeChat interface debugging problems. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template