准备

1、域名
2、注册开发者账号
3、开发者后台配置服务器信息

配置服务

搭建HTTP服务

安装NodeJS和NPM

执行下面的命令安装:

1
2
curl --silent --location https://rpm.nodesource.com/setup_8.x | sudo bash -
yum install nodejs -y

编写 HTTP Server 源码

先创建一个工作目录

1
2
root@172.17.0.9:~
# mkdir -p /data/release/weapp

然后进入这个目录

1
2
root@172.17.0.9:~
# cd /data/release/weapp/

创建package.json文件

1
2
root@172.17.0.9:/data/release/weapp
# vi package.json

拷贝下面的内容进去

1
2
3
4
{
"name": "weapp",
"version": "1.0.0"
}

接下来创建app.js文件,拷贝下面内容

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// 引用 express 来支持 HTTP Server 的实现
const express = require('express');

// 创建一个 express 实例
const app = express();

// 实现唯一的一个中间件,对于所有请求,都输出 "Response from express"
app.use((request, response, next) => {
response.write('Response from express');
response.end();
});

// 监听端口,等待连接
const port = 8765;
app.listen(port);

// 输出服务器启动日志
console.log(`Server listening at http://127.0.0.1:${port}`);

这里调用了Express.js监听8765端口。

运行HTTP服务

这里我们用pm2来守护HTTP服务,首先安装pm2

1
2
root@172.17.0.9:/data/release/weapp
# npm install pm2 --global

上一步配置HTTP服务的时候,用到了Express.js,我们要安装相应的依赖

1
2
root@172.17.0.9:/data/release/weapp
# npm install express --save

然后用pm2来启动HTTP服务

1
2
root@172.17.0.9:/data/release/weapp
# pm2 start app.js --watch

查看当前服务信息可通过

1
2
root@172.17.0.9:/data/release/weapp
# pm2 show app

搭建HTTPS服务

安装Nginx

可以直接通过yum来安装

1
2
root@172.17.0.9:/data/release/weapp
# yum install nginx -y

如果这里报错没有nginx包,需要新建配置文件

1
vim /etc/yum.repos.d/nginx.repo

将下面的内容粘贴到配置文件中

1
2
3
4
5
[nginx]
name=nginx repo
baseurl=http://nginx.org/packages/centos/$releasever/$basearch/
gpgcheck=0
enabled=1

然后再执行第一步的安装命令即可。

配置HTTPS反向代理

首先配置nginx的配置文件

1
2
root@172.17.0.9:/etc/nginx/conf.d
# vim ssl.conf

把下面的内容拷进去

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
server {
listen 443;
server_name www.leonlei.top; # 改为绑定证书的域名
# ssl 配置
ssl on;
ssl_certificate 1_www.leonlei.top_bundle.crt; # 改为自己申请得到的 crt 文件的名称
ssl_certificate_key 2_www.leonlei.top.key; # 改为自己申请得到的 key 文件的名称
ssl_session_timeout 5m;
ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:HIGH:!aNULL:!MD5:!RC4:!DHE;
ssl_prefer_server_ciphers on;

location / {
proxy_pass http://127.0.0.1:8765;
}
}

然后将再腾讯云申请的免费SSL证书上传到/etc/nginx目录下

1
2
LeonLeiMBP15-110:gaoshilei$ scp -p /Users/gaoshilei/Downloads/www/Nginx/1_www.leonlei.top_bundle.crt root@115.159.87.164:/etc/nginx/1_www.leonlei.top_bundle.crt 
LeonLeiMBP15-110:gaoshilei$ scp -p /Users/gaoshilei/Downloads/www/Nginx/2_www.leonlei.top.key root@115.159.87.164:/etc/nginx/2_www.leonlei.top.key

然后重启nginx

1
2
root@172.17.0.9:/etc/nginx
# nginx -s reload

配置小程序会话

由于小程序不支持cookies和浏览器的缓存机制,需要创建独立的会话层,这里我们用另外一台服务器用来做会话

安装MongoDB

1
[root@VM_0_13_centos ~]# yum install mongodb-server mongodb -y

安装完成之后查看是否安装成功

1
2
3
4
5
6
[root@VM_0_13_centos ~]# mongod --version
db version v2.6.12
2017-11-27T18:11:21.773+0800 git version: nogitversion
2017-11-27T18:11:21.773+0800 OpenSSL version: OpenSSL 1.0.1e-fips 11 Feb 2013
[root@VM_0_13_centos ~]# mongo --version
MongoDB shell version: 2.6.12

启动MongoDB

创建数据储存和日志的储存目录

1
2
[root@VM_0_13_centos ~]# mkdir -p /data/mongodb
[root@VM_0_13_centos ~]# mkdir -p /data/logs/mongodb

然后使用命令启动MongoDB

1
2
3
4
[root@VM_0_13_centos ~]# mongod --fork --dbpath /data/mongodb --logpath /data/logs/mongodb/weapp.log
about to fork child process, waiting until server is ready for connections.
forked process: 6660
child process started successfully, parent exiting

使用命令查看是否启动成功

1
2
[root@VM_0_13_centos ~]# netstat -ltp | grep 27017
tcp 0 0 0.0.0.0:27017 0.0.0.0:* LISTEN 6660/mongod

添加 MongoDB 用户

登录数据库

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
[root@VM_0_13_centos ~]# mongo
MongoDB shell version: 2.6.12
connecting to: test
Welcome to the MongoDB shell.
For interactive help, type "help".
For more comprehensive documentation, see
http://docs.mongodb.org/
Questions? Try the support group
http://groups.google.com/group/mongodb-user
Server has startup warnings:
2017-11-27T18:13:28.129+0800 [initandlisten]
2017-11-27T18:13:28.129+0800 [initandlisten] ** WARNING: Readahead for /data/mongodb is set to 4096KB
2017-11-27T18:13:28.129+0800 [initandlisten] ** We suggest setting it to 256KB (512 sectors) or less
2017-11-27T18:13:28.129+0800 [initandlisten] ** http://dochub.mongodb.org/core/readahead
>

然后创建一个用户

1
2
3
4
5
> use weapp
switched to db weapp
> db.createUser({ user: 'weapp', pwd: 'weapp-dev', roles: ['dbAdmin', 'readWrite']});
Successfully added user: { "user" : "wechatapp", "roles" : [ "dbAdmin", "readWrite" ] }
>

安装Node模块

实现小程序的会话功能,需要安装 connect-mongo 和 wafer-node-session,

1
2
3
[root@VM_0_13_centos ~]# cd /data/release/weapp

[root@VM_0_13_centos /data/release/weapp]# npm install connect-mongo wafer-node-session --save

实现小程序会话

在目录/data/release/weapp中新建文件config.js,然后将下面的代码拷入(注意appID和appSecret)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
module.exports = { 
serverPort: '8765',

// 小程序 appId 和 appSecret
// 请到 https://mp.weixin.qq.com 获取 AppID 和 AppSecret
appId: 'wx9fd292461a087d38',
appSecret: 'b05144b0d40a08337bb2c476dc543f8a',

// mongodb 连接配置,生产环境请使用更复杂的用户名密码
mongoHost: '127.0.0.1',
mongoPort: '27017',
mongoUser: 'weapp',
mongoPass: 'weapp-dev',
mongoDb: 'weapp'
};

然后修改app.js,添加会话逻辑

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
// 引用 express 来支持 HTTP Server 的实现
const express = require('express');
// 引用 wafer-session 支持小程序会话
const waferSession = require('wafer-node-session');
// 使用 MongoDB 作为会话的存储
const MongoStore = require('connect-mongo')(waferSession);
// 引入配置文件
const config = require('./config');

// 创建一个 express 实例
const app = express();

// 添加会话中间件,登录地址是 /login
app.use(waferSession({
appId: config.appId,
appSecret: config.appSecret,
loginPath: '/login',
store: new MongoStore({
url: `mongodb://${config.mongoUser}:${config.mongoPass}@${config.mongoHost}:${config.mongoPort}/${config.mongoDb}`
})
}));

// 在路由 /me 下,输出会话里包含的用户信息
app.use('/me', (request, response, next) => {
response.json(request.session ? request.session.userInfo : { noBody: true });
if (request.session) {
console.log(`Wafer session success with openId=${request.session.userInfo.openId}`);
}
});

// 实现一个中间件,对于未处理的请求,都输出 "Response from express"
app.use((request, response, next) => {
response.write('Response from express');
response.end();
});

// 监听端口,等待连接
app.listen(config.serverPort);

// 输出服务器启动日志
console.log(`Server listening at http://127.0.0.1:${config.serverPort}`);

添加完成重启服务

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
root@172.17.0.9:/data/release/weapp
# pm2 restart app
Use --update-env to update environment variables

>>>> In-memory PM2 is out-of-date, do:
>>>> $ pm2 update
In memory PM2 version: 2.0.18
Local PM2 version: 2.8.0

[PM2] Applying action restartProcessId on app [app](ids: 1)
[PM2] [app](1) ✓
┌──────────┬────┬──────┬───────┬────────┬─────────┬────────┬─────┬───────────┬──────┬──────────┐
│ App name │ id │ mode │ pid │ status │ restart │ uptime │ cpu │ mem │ user │ watching │
├──────────┼────┼──────┼───────┼────────┼─────────┼────────┼─────┼───────────┼──────┼──────────┤
│ app │ 1 │ fork │ 10193 │ online │ 7 │ 0s │ 0% │ 10.2 MB │ root │ enabled │
│ weapp │ 0 │ fork │ 2067 │ online │ 0 │ 19h │ 0% │ 45.5 MB │ root │ disabled │
└──────────┴────┴──────┴───────┴────────┴─────────┴────────┴─────┴───────────┴──────┴──────────┘

WebSocket 服务

安装Node模块

小程序使用ws模块与服务器实现WebSocket通信,所以先安装node依赖

1
2
root@172.17.0.9:/data/release/weapp
# npm install ws --save

实现WebSocket服务

创建websocket.js,写入一下内容

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
// 引入 ws 支持 WebSocket 的实现
const ws = require('ws');

// 导出处理方法
exports.listen = listen;

/**
* 在 HTTP Server 上处理 WebSocket 请求
* @param {http.Server} server
* @param {wafer.SessionMiddleware} sessionMiddleware
*/
function listen(server, sessionMiddleware) {
// 使用 HTTP Server 创建 WebSocket 服务,使用 path 参数指定需要升级为 WebSocket 的路径
const wss = new ws.Server({ server, path: '/ws' });

// 监听 WebSocket 连接建立
wss.on('connection', (ws,request) => {// 要升级到 WebSocket 协议的 HTTP 连接

// 被升级到 WebSocket 的请求不会被 express 处理,
// 需要使用会话中间节获取会话
sessionMiddleware(request, null, () => {
const session = request.session;
if (!session) {
// 没有获取到会话,强制断开 WebSocket 连接
ws.send(JSON.stringify(request.sessionError) || "No session avaliable");
ws.close();
return;
}
// 保留这个日志的输出可让实验室能检查到当前步骤是否完成
console.log(`WebSocket client connected with openId=${session.userInfo.openId}`);
serveMessage(ws, session.userInfo);
});
});

// 监听 WebSocket 服务的错误
wss.on('error', (err) => {
console.log(err);
});
}

/**
* 进行简单的 WebSocket 服务,对于客户端发来的所有消息都回复回去
*/
function serveMessage(ws, userInfo) {
// 监听客户端发来的消息
ws.on('message', (message) => {
console.log(`WebSocket received: ${message}`);
ws.send(`Server: Received(${message})`);
});

// 监听关闭事件
ws.on('close', (code, message) => {
console.log(`WebSocket client closed (code: ${code}, message: ${message || 'none'})`);
});

// 连接后马上发送 hello 消息给会话对应的用户
ws.send(`Server: 恭喜,${userInfo.nickName}`);
}

修改app.js调用WebSocket服务

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
// HTTP 模块同时支持 Express 和 WebSocket
const http = require('http');
// 引用 express 来支持 HTTP Server 的实现
const express = require('express');
// 引用 wafer-session 支持小程序会话
const waferSession = require('wafer-node-session');
// 使用 MongoDB 作为会话的存储
const MongoStore = require('connect-mongo')(waferSession);
// 引入配置文件
const config = require('./config');
// 引入 WebSocket 服务实现
const websocket = require('./websocket');

// 创建一个 express 实例
const app = express();

// 独立出会话中间件给 express 和 ws 使用
const sessionMiddleware = waferSession({
appId: config.appId,
appSecret: config.appSecret,
loginPath: '/login',
store: new MongoStore({
url: `mongodb://${config.mongoUser}:${config.mongoPass}@${config.mongoHost}:${config.mongoPort}/${config.mongoDb}`
})
});
app.use(sessionMiddleware);

// 在路由 /me 下,输出会话里包含的用户信息
app.use('/me', (request, response, next) => {
response.json(request.session ? request.session.userInfo : { noBody: true });
if (request.session) {
console.log(`Wafer session success with openId=${request.session.userInfo.openId}`);
}
});

// 实现一个中间件,对于未处理的请求,都输出 "Response from express"
app.use((request, response, next) => {
response.write('Response from express');
response.end();
});

// 创建 HTTP Server 而不是直接使用 express 监听
const server = http.createServer(app);

// 让 WebSocket 服务在创建的 HTTP 服务器上监听
websocket.listen(server, sessionMiddleware);

// 启动 HTTP 服务
server.listen(config.serverPort);

// 输出服务器启动日志
console.log(`Server listening at http://127.0.0.1:${config.serverPort}`);

完成之后用`pm2重启服务。

更新Nginx代理

需要向配置文件中添加WebSocket支持,修改之前配置好的/etc/nginx/conf.d/ssl.conf

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
# WebSocket 配置
map $http_upgrade $connection_upgrade {
default upgrade;
'' close;
}

server {
listen 443;
server_name www.leonlei.top; # 改为绑定证书的域名
# ssl 配置
ssl on;
ssl_certificate 1_www.leonlei.top.crt; # 改为自己申请得到的 crt 文件的名称
ssl_certificate_key 2_www.leonlei.top.key; # 改为自己申请得到的 key 文件的名称
ssl_session_timeout 5m;
ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:HIGH:!aNULL:!MD5:!RC4:!DHE;
ssl_prefer_server_ciphers on;

# WebSocket 配置
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection $connection_upgrade;

location / {
proxy_pass http://127.0.0.1:8765;
}
}

配置完成重启nginx

1
2
root@172.17.0.9:/etc/nginx/conf.d
# nginx -s reload