一篇很基础入门的Messenger开发文档,开发语言基于node.js,初学者建议你认真阅读这篇文章,一篇文章学会Messenger开发
Messenger简介
Messenger是Facebook的聊天软件,类似于微信,基于Messenger的开发就相当于公众号的开发,了解更多,请点击 官方文档
开发准备
1.新建项目
mkdir messenger-webhook // Creates a project directory
cd messenger-webhook // Navigates to the new directory
touch index.js // Creates empty index.js file.
npm init // Creates package.json. Accept default for all questions.
npm install express body-parser --save // Installs the express.js http server framework module,
// and then adds them to the dependencies section of package.json file
复制代码
比较简单,新建完,项目目录如下:
index.js
node_modules
package.json
复制代码
2.创建HTTP服务器,监听服务
'use strict';
// Imports dependencies and set up http server
const
express = require('express'),
bodyParser = require('body-parser'),
app = express().use(bodyParser.json()); // creates express http server
require('dotenv').config();
// Sets server port and logs message on success
app.listen(process.env.PORT, () => console.log('webhook is listening'));
复制代码
此代码用于监听服务器请求,本次项目开发,用的node.js的express框架,其中require('dotenv').config() 作用是加载环境变量.env
3.创建webhook,接收用户事件
app.post('/webhook', (req, res) => {
let body = req.body;
// Checks this is an event from a page subscription
if (body.object === 'page') {
// Iterates over each entry - there may be multiple if batched
body.entry.forEach(function(entry) {
entry.messaging.forEach(messagingEvent => {
if (messagingEvent.message) {
//message为用户向平台发送消息事件
} else if (messagingEvent.postback) {
//postback为用户点击开始按钮,点击固定菜单等回调事件
} else if (messagingEvent.referral) {
//m.me链接,广告,印章等
} else {
console.log("Webhook received unknown messagingEvent: ", messagingEvent);
}
})
});
// Returns a '200 OK' response to all requests
res.status(200).send('EVENT_RECEIVED');
} else {
// Returns a '404 Not Found' if event is not from a page subscription
res.sendStatus(404);
}
});
复制代码
此代码将创建一个 /webhook 端点,用于接收 POST 请求,验证请求是否为 webhook 事件,然后解析消息。Messenger 平台会通过该端点发送所有 webhook 事件。 用户在messenger发消息,监听到的body.object是'page',entry为包含事件数据的阵列,我这里开发了entry.messaging的三种用户基本事件
4.添加webhook验证,验证口令一致
// Adds support for GET requests to our webhook
app.get('/webhook', (req, res) => {
// Your verify token. Should be a random string.
let VERIFY_TOKEN = PAGE_ACCESS_TOKEN;
// Parse the query params
let mode = req.query['hub.mode'];
let token = req.query['hub.verify_token'];
let challenge = req.query['hub.challenge'];
// Checks if a token and mode is in the query string of the request
if (mode && token) {
// Checks the mode and token sent is correct
if (mode === 'subscribe' && token === VERIFY_TOKEN) {
// Responds with the challenge token from the request
console.log('WEBHOOK_VERIFIED');
res.status(200).send(challenge);
} else {
// Responds with '403 Forbidden' if verify tokens do not match
res.sendStatus(403);
}
}
});
复制代码
5.测试webhook
1 本地主机上启动 webhook:
node index.js
复制代码
2 测试 webhook 验证:
curl -X GET "localhost:1337/webhook?hub.verify_token=<YOUR_VERIFY_TOKEN>&hub.challenge=CHALLENGE_ACCEPTED&hub.mode=subscribe"
复制代码
3 测试 webhook请求:
curl -H "Content-Type: application/json" -X POST "localhost:1337/webhook" -d '{"object": "page", "entry": [{"messaging": [{"message": "TEST_MESSAGE"}]}]}'
复制代码
6. 部署webhook
为了能接收通过 HTTPS 发送的请求,必须将 webhook 部署到拥有有效 SSL 证书的服务器中
7. 将 webhook 订阅到 Facebook 应用
到现在,准备工作已经完成,但是还没有app接收webhook事件,最后一步,要将webhook订阅到facebook应用,官方文档很详细,这里不再做教程,官方文档入口
未完待续