Node.js is a node.js language for Messenger development. You can use node.js for Messenger development

Messenger profile


Messenger is Facebook’s chat software, similar to wechat. Development based on Messenger is equivalent to the development of an official account. For more information, please click on the official document

The development of preparation


1. Create a project

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
Copy the code

Relatively simple, after creating, the project directory is as follows:

index.js	
node_modules
package.json
Copy the code

2. Create an HTTP server and listen to services

'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'));
Copy the code

The node.js express framework requires (‘dotenv’).config() to load the environment variable.env

3. Create webhooks to receive user events

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 sends message events to the platform for users}else if(messagingEvent.postback) {// Postback is a callback event for the user to click the start button, click the fixed menu, etc.}else if(messagingEvent. Referral) {//m.me link, advertisement, stamp, etc.}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' ifevent is not from a page subscription res.sendStatus(404); }});Copy the code

This code creates a/Webhook endpoint that receives a POST request, verifies that the request is a Webhook event, and then parses the message. The Messenger platform sends all Webhook events through this endpoint. When users send messages in Messenger, the body. Object monitored is’ Page ‘and Entry is an array containing event data. Here I developed three basic user events of Entry

4. Add Webhook authentication to verify that the passwords are the same

// 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 donot match res.sendStatus(403); }}});Copy the code

5. Test webhook

1. Start webhook on local host:

node index.js
Copy the code

2 test Webhook verification:

curl -X GET "localhost:1337/webhook? hub.verify_token=
      
       &hub.challenge=CHALLENGE_ACCEPTED&hub.mode=subscribe"
      
Copy the code

3 test webhook request:

curl -H "Content-Type: application/json" -X POST "localhost:1337/webhook" -d '{"object": "page", "entry": [{"messaging": [{"message": "TEST_MESSAGE"}]}]}'
Copy the code

6. Deployment webhook

In order to receive requests sent over HTTPS, Webhook must be deployed to a server with a valid SSL certificate

7. Subscribe webhook to the Facebook app

So far, the preparation work has been completed, but no app has received webhook events. The last step is to subscribe webhook to the Facebook app. The official document is very detailed, and there is no tutorial here

The message template


The user’s events are captured and used to automatically respond to predefined messages. The message template is used to structure messages and present a better and richer user experience. The use of message templates is fundamental to the development of Messenger and is the most used in Messenger development. Messenger predefined supports the following templates:

  • Conventional template
  • A list of the template
  • Button in the template
  • Open atlas template
  • Return receipt template
  • Flight Information template
  • Media template

Template standard format is as follows, among them the message. The attachment. The payload attribute contains specific template for all kinds of types and contents of the details

{
  "recipient": {"id":"<PSID>"// PSID of the sending user},"message": {"attachment": {"type":"template"."payload": {"template_type":"<TEMPLATE_TYPE>". }}}}Copy the code

1. General templates

A regular template is a simple structured message that contains a title, subtitle, image, and up to three buttons: You can also optionally specify the default_action object to set the URL that will open in the Messenger Web page view when the user taps the template. With a focus on regular templates, the rest of the template content is similar, but the difference is that different templates set different properties.

"payload": {
  "template_type":"generic"."elements":[
     {
      "title":"<TITLE_TEXT>"The title, / / news"image_url":"<IMAGE_URL_TO_DISPLAY>"// Message image"subtitle":"<SUBTITLE_TEXT>"// Message content"default_action"{// Default click message jump,typeCan only be web_url"type": "web_url"."url": "<DEFAULT_URL_TO_OPEN>"."messenger_extensions": <TRUE | FALSE>,
        "webview_height_ratio": "<COMPACT | TALL | FULL>"
      },
      "buttons":[<BUTTON_OBJECT>, ...] // button},... ] }Copy the code

Send template multicast

"payload": {
  "template_type":"generic"."elements":[
    <GENERIC_TEMPLATE>,
    <GENERIC_TEMPLATE>,
    ...
  ]
}
Copy the code

You need to add a maximum of 10 regular templates to the elements array of the payload. Note that the maximum number of regular templates is 10.

Sample request

curl -X POST -H "Content-Type: application/json" -d '{ "recipient":{ "id":"
      
       " }, "message":{ "attachment":{ "type":"template", "payload":{ "template_type":"generic", "elements":[ { "title":"Welcome! ", "image_url":"https://petersfancybrownhats.com/company_image.png", "subtitle":"We have the right hat for everyone.", "default_action": { "type": "web_url", "url": "https://petersfancybrownhats.com/view?item=103", "messenger_extensions": false, "webview_height_ratio": "tall", "fallback_url": "https://petersfancybrownhats.com/" }, "buttons":[ { "type":"web_url", "url":"https://petersfancybrownhats.com", "title":"View Website" },{ "type":"postback", "title":"Start Chatting", "payload":"DEVELOPER_DEFINED_PAYLOAD" } ] } ] } } } }'
       "Https://graph.facebook.com/v2.6/me/messages?access_token= < PAGE_ACCESS_TOKEN >"
Copy the code

Back the sample

{
  "recipient_id": "1254477777772919"."message_id": "m_AG5Hz2Uq7tuwNEhXfYYKj8mJEM_QPpz5jdCK48PnKAjSdjfipqxqMvK8ma6AC8fplwlqLP_5cgXIbu7I3rBN0P"
}  
Copy the code

Here’s the template for the button

Url button

{
 "type": "web_url"."url": "<URL_TO_OPEN_IN_WEBVIEW>"."title": "<BUTTON_TEXT>",}Copy the code

The back button

{
 "type": "postback"."title": "<BUTTON_TEXT>"."payload": "<STRING_SENT_TO_WEBHOOK>"
}
Copy the code

Share button

{
 "type": "element_share"."share_contents": { 
   "attachment": {
     "type": "template"."payload"For share buttons that use element_share functionality, only the regular template containing a url button is supported, that is, the button's in the shared contenttypeThe value must be web_URL <GENERIC_TEMPLATE_OBJECT>}}}}Copy the code

Buy button (AVAILABLE to US users only)

{
 "type":"payment"."title":"<BUTTON_TEXT>"."payload":"<STRING_SENT_TO_WEBHOOK>"."payment_summary": {"currency":"<CURRENCY_ABBREVIATION>"."payment_type":"<FIXED_AMOUNT | FLEXIBLE_AMOUNT>"."is_test_payment" : <TRUE | FALSE >, 
   "merchant_name":"<YOUR_BUSINESS_NAME>"."requested_user_info": ["shipping_address"."contact_name"."contact_phone"."contact_email"]."price_list":[
     {
       "label":"<ITEM_NAME>"."amount":"<ITEM_PRICE>"},... ] }}Copy the code

The call button

{
 "type":"phone_number"."title":"<BUTTON_TEXT>"."payload":"<PHONE_NUMBER>"
}
Copy the code

Log in button

{
 "type": "account_link"."url": "<YOUR_LOGIN_URL>"
}
Copy the code

Exit button

{
 "type": "account_unlink"
}
Copy the code

Play the game button

{
 "type":"game_play"."title":"Play"."payload":"{<SERIALIZED_JSON_PAYLOAD>}"."game_metadata": { // Only one of the below
   "player_id": "<PLAYER_ID>"."context_id": "<CONTEXT_ID>"}}Copy the code

2. List template

A list template is a list of 2-4 structured items that optionally display global buttons at the bottom. Each item can contain a thumbnail, title, subtitle, and a button. You can also specify the default_action object to set the URL that will open in the Messenger Web view when the user taps the item.

"payload": {
  "template_type": "list"."top_element_style": "<LARGE | COMPACT>"."elements": [{"title": "<TITLE_TEXT>"."subtitle": "<SUBTITLE_TEXT>"."image_url": "<IMAGE_URL_FOR_THUMBNAIL>"."buttons": [<BUTTON_OBJECT>],
      "default_action": {
        "type": "web_url"."url": "<URL_TO_OPEN_WHEN_ITEM_IS_TAPPED>"."messenger_extensions": <TRUE | FALSE>,
        "webview_height_ratio": "<COMPACT | TALL | FULL>"}},... ] ."buttons": [<BUTTON_OBJECT>]  
}
Copy the code

Note here that by default, the first item in the list will be displayed as a cover image containing superimposed text. You can display the first item as a standard list item by setting “top_element_style”: “compact”.

Sample request

The sample request is similar, see the general template

Back the sample

The same goes for the postback example, see the general template

3. Button template

Button templates can send text messages that can contain up to three buttons. This template is useful for providing message recipients with optional options, such as predefined question responses or actions that can be taken.

"payload": {
  "template_type":"button"."text":"<MESSAGE_TEXT>"."buttons":[
    <BUTTON_OBJECT>, 
    <BUTTON_OBJECT>, 
    ...
  ]
}
Copy the code

Button templates are relatively simple

Since the request example and the postback example are similar, this is not covered below and you can refer directly to the official documentation

4. Open the atlas template

Open map templates send structured messages to which you can add open map urls and optional buttons. Currently, this template only supports sharing songs. Songs are displayed as chat bubbles, where message recipients can see album covers and song previews.

"payload": {
  "template_type":"open_graph"."elements":[
     {
      "url":"<OPEN_GRAPH_URL>"."buttons":[<BUTTON_OBJECT>]             
    }
  ]
}
Copy the code

The development of media template, receipt template and flight information template is relatively rare, so I will not repeat it again. Please refer to the official documents for an in-depth understanding


To be continued