Home  >  Article  >  WeChat Applet  >  Tutorial on developing WeChat public platform using node.js

Tutorial on developing WeChat public platform using node.js

高洛峰
高洛峰Original
2017-03-14 15:08:091825browse

This article mainly shares with you the tutorial on how to develop WeChat public platform using node.js, and how to develop WeChat. Interested friends can refer to it

How to use nodejs to develop the WeChat public platform?

I won’t say much else. First, let’s briefly introduce the basic principles of the WeChat public platform.

The WeChat server is equivalent to a forwarding server. The terminal (mobile phone, Pad, etc.) initiates a request to the WeChat server, and the WeChat server then forwards the request to the custom service (here is our specific implementation). After the service is processed, it is then forwarded to the WeChat server, and the WeChat server replies with a specific response to the terminal; the communication protocol is: HTTP; the data format is: XML.
The specific process is shown in the figure below:

Tutorial on developing WeChat public platform using node.js

In fact, what we need to do is to respond to HTTP requests. We parse the specific request content according to a specific XML format. After processing, we must also return it according to a specific XML format.

Platform registration

To complete the development of the WeChat public platform, we need to register a WeChat public platform account. The registration steps are as follows:
Open the official website of the WeChat public platform, https://mp.weixin.qq.com/, and click "Register Now".

Then follow the prompts to fill in the basic information, activate the email, select the type, information registration, official account information, and complete the registration.

After the registration is completed, we need to make some basic settings for the official account. Log in to the official account, find [Official Account Settings], and then set the avatar and other information.

nodejs environment construction

We need to find a server on the public Internet so that we can start our nodejs environment. After starting the environment, by setting the access address, we can receive the messages sent by the WeChat server message, and we can also send messages to the WeChat server.

In the public network serverInstallationAfter completing nodejs, we also need to install some modules used by nodejs, such as: express, node-xml, jssha and other modules. It can be installed through the npm command.

We use nodejs to implement sending and receiving messages to the WeChat server, as well as signature authentication with the WeChat server.

In the editing environment on the right, the nodejs environment has been installed for the students. In the following content, we will implement the signature authentication of WeChat server for students.

Create expressFramework

We have installed the express module in the previous course, and have created a file named app.js in our environment on the right document. Now we will complete the express framework in this file. The following code:


var express = require("express");
var path=require('path');
var app = express();
server = require('http').Server(app);
app.set('views',dirname); // 设置视图 
app.set('view engine', 'html'); 
app.engine( '.html', require( 'ejs' ).express );
require('./index')(app); //路由配置文件
server.listen(80,function(){
console.log('App start,port 80.');
});

Then add a file named test.html. Write the following content


<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>汇智网</title>
</head>
<body>
<p><%=issuccess%></p>
</body>
</html>

We will also add a file named index.js to implement our routing. Click the Add File button in the editing environment to add the file, and then we write the following code, in which the GET request is used to verify the legitimacy of the configured URL, and the POST request is used to process WeChat messages. .


module.exports = function(app){
app.get(&#39;/&#39;,function(req,res){
res.render(&#39;test&#39;,{issuccess:"success"})
});
app.get(&#39;/interface&#39;,function(req,res){});
app.post(&#39;/interface&#39;,function(req,res){});
}

In this way, the express framework we need is completed. Of course, we can also add the public public folder and the middleware we want to use. Save the file, click [Submit to run], then click [Access Test] to give it a try. Note the address to access the test, we will use this address in the next section.

WeChat server configuration

We log in to the WeChat public platform, find the basic configuration under developer mode, and then modify the server configuration. As shown in the figure:

Tutorial on developing WeChat public platform using node.js

# First, the URL must be filled in the path where we install nodejs to receive and send data on the public network. We can fill in the address of [Access Test] in the previous section and then add the corresponding route.

The Token must be consistent with our custom server-side token. After filling in, you can click submit. Before submitting, we start app.js (click [Submit to run]). In this way, we can verify whether the signature is valid based on our route matching.

After the configuration is completed, the configuration must be enabled.

Tutorial on developing WeChat public platform using node.js

网址接入

  公众平台用户提交信息后,微信服务器将发送GET请求到填写的URL上,并且带上四个参数:

  参数                     描述
  signature            微信加密签名
  timestamp            时间戳
  nonce                随机数
  echostr              随机字符串

  开发者通过检验signature对请求进行校验(下面有校验方式)。若确认此次GET请求来自微信服务器,请原样返回echostr参数内容,则接入生效,否则接入失败。

  signature结合了开发者填写的token参数和请求中的timestamp参数、nonce参数。

加密/校验流程:

1、将token、timestamp、nonce三个参数进行字典序排序;
2、将三个参数字符串拼接成一个字符串进行sha1加密;
3、开发者获得加密后的字符串可与signature对比,标识该请求来源于微信。
参数排序

  首先我们确认请求是来自微信服务器的get请求,那么就可以在index.js文件中进行添加代码了。然后在app.get(‘/interface',function(req,res){});的function中进行添加。

  先来获取各个参数的值,如下代码:


var token="weixin";
var signature = req.query.signature;
var timestamp = req.query.timestamp;
var echostr = req.query.echostr;
var nonce = req.query.nonce;

我们在这里对token进行设置,让其与微信服务器中设置的token一致。

然后对其中的token、timestamp、nonce进行排序,如下代码:


var oriArray = new Array();
oriArray[0] = nonce;
oriArray[1] = timestamp;
oriArray[2] = token;
oriArray.sort();

这样我们就完成了排序。

参数加密

  在上节中我们已经对参数进行了排序,然后我们在这一节中要将参数组成一个字符串,进行SH-1加密。在加密以前要用到jssha模块,在我们的文件中要引用该模块。


var jsSHA = require(&#39;jssha&#39;);

在上一节课中我们已经对参数排序完成,并存放在数组中,我们可以通过join方法来生成一个字符串,如下代码:


var original = oriArray.join(&#39;&#39;);

最后对该数据进行加密,如下代码:


var jsSHA = require(&#39;jssha&#39;);
var shaObj = new jsSHA(original, 'TEXT');
var scyptoString=shaObj.getHash('SHA-1', 'HEX');

好了这样就生成了我们需要的签名字符串scyptoString。

签名对比

  我们已经得到了我们想要的签名字符串scyptoString,然后我们就可以与来自微信服务器的签名进行对比了,对比通过,则我们就可以接收与发送消息了。


 if(signature == scyptoString){
 //验证成功
 } else {
 //验证失败
 }

The above is the detailed content of Tutorial on developing WeChat public platform using node.js. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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