Sending Facebook Messenger messages with the Messages API

You can use the Messages API to send and receive messages using Facebook Messenger.

Before continuing with this tutorial you should review the information on Understanding Facebook messaging.

Prerequisites

  1. Create a Nexmo Account
  2. Install Node JS - required for using the Nexmo Command Line Interface (CLI).
  3. Install the Beta version of the Nexmo CLI
  4. Install or update the Beta version of the Node Server SDK - only required if using Node.
  5. Configure webhooks.
  6. Know how to write a webhook server
  7. Know how to test your webhook server locally

NOTE: This tutorial assumes you have already created a Facebook Profile and a Facebook Page.

The steps

After the prerequisites have been met, the steps are as follows:

  1. Link your Facebook Page to Nexmo
  2. Create a Nexmo Application
  3. Receive a Facebook message
  4. Reply to a Facebook message

Linking your Facebook page to your Nexmo account allows Nexmo to handle inbound messages and enables you to send messages from the Nexmo Messages API.

  1. To link your Facebook page to your Nexmo account click Link your Facebook Page to Nexmo.

  2. Select the Facebook Page you want to connect to your Nexmo account from the drop down list.

  3. Enter the API key and API secret for your Nexmo account.

  4. Click Subscribe. You will receive a message confirm successful subscription.

At this point your Nexmo Account and this Facebook Page are linked. The link between your Nexmo account and Facebook page expires after 90 days. After then you must re-link it.

Once your Facebook page is linked to your Nexmo account, it becomes available for use by any of your applications. To link the Facebook page to a Nexmo application:

  1. Navigate to the Messages and Dispatch applications page.

  2. From the list, select the application you want to link to.

  3. Then, select the Linked external accounts tab from the top navigation.

  4. Click the Link button beside your Facebook Page ensuring that the Provider is messenger.

You're now ready to receive messages users send to you on your Facebook Page.

NOTE: If in the future you want to link a different application to this Facebook page, you only need to repeat the procedure described in Part 2, for the new application.

Re-linking your Facebook page to your Nexmo account

The link between your Nexmo account and Facebook page expires after 90 days. You can re-link it by performing the following steps:

  1. Visit the following page and select the page you want to re-link from the drop down list

  2. Click Unsubscribe.

  3. When the page is successfully unsubscribed, re-link it by clicking Subscribe.

Create a Nexmo Application

There are two alternative methods for creating a Messages and Dispatch application:

  1. Using the Nexmo CLI
  2. Using the Dashboard

Each of these methods is described in the following sections.

How to create a Messages and Dispatch application using the Nexmo CLI

To create your application using the Nexmo CLI, enter the following command into the shell:

nexmo app:create "My Messages App" --capabilities=messages --messages-inbound-url=https://example.com/webhooks/inbound-message --messages-status-url=https://example.com/webhooks/message-status --keyfile=private.key

This creates a Nexmo application with a messages capability, with the webhook URLs configured as specified, and generate a private key file private.key.

How to create a Messages and Dispatch application using the Dashboard

You can create Messages and Dispatch applications in the Dashboard.

To create your application using the Dashboard:

  1. Under Messages and Dispatch in the Dashboard, click Create an application.

  2. Under Name, enter the Application name. Choose a name for ease of future reference.

  3. Click the button Generate public and private key. This will create a public/private key pair and the private key will be downloaded by your browser.

  4. Under Capabilities select the Messages button.

  5. Enter the URL for your inbound message webhook, for example, https://example.com/webhooks/inbound-message.

  6. Enter the URL for your message status webhook, for example, https://example.com/webhooks/message-status.

  7. Click the Create new application button. You are now taken to the next step of the Create Application procedure where you can link a Nexmo number to the application, and link external accounts such as Facebook to this application.

  8. If there is an external account you want to link this application to, click the corresponding Link button.

You have now created your application.

NOTE: Before testing your application ensure that your webhooks are configured and your webhook server is running.

Receive a Facebook message

First make sure your webhook server is running. It should correctly handle both inbound message callbacks and message status callbacks returning at least a 200 to acknowledge each callback. You will need to have this in place so you can obtain the PSID of the Facebook User sending the inbound message. Once you have this you will be able to reply.

When a Facebook message is sent by a Facebook User to your Facebook Page a callback will be sent to your Inbound Message Webhook URL. An example callback is shown here:

{
  "message_uuid":"aaaaaaaa-bbbb-cccc-dddd-0123456789ab",
  "to":{
    "type":"messenger",
    "id":"0000000000000000"
  },
  "from":{
    "type":"messenger",
    "id":"1111111111111111"
  },
  "timestamp":"2020-01-01T14:00:00.000Z",
  "message":{
    "content":{
      "type":"text",
      "text":"Hello from Facebook Messenger!"
    }
  }
}

You will need to extract the from.id value here as this is the ID that you will need to send a reply.

Reply to a Facebook message

You can then use the Messages API to respond to the inbound message received from the Facebook User.

Replace the following variables in the example below with actual values:

Key Description
FB_SENDER_ID Your Page ID. The FB_SENDER_ID is the same as the to.id value you received in the inbound messenger event on your Inbound Message Webhook URL.
FB_RECIPIENT_ID The PSID of the user you want to reply to. The FB_RECIPIENT_ID is the PSID of the Facebook User you are messaging. This value is the from.id value you received in the inbound messenger event on your Inbound Message Webhook URL.

Example

Write the code

Add the following to send-text.sh:

Copy to Clipboard
curl -X POST https://api.nexmo.com/v0.1/messages \
  -H 'Authorization: Bearer '$JWT\
  -H 'Content-Type: application/json' \
  -H 'Accept: application/json' \
  -d $'{
    "from": { "type": "messenger", "id": "'$FB_SENDER_ID'" },
    "to": { "type": "messenger", "id": "'$FB_RECIPIENT_ID'" },
    "message": {
      "content": {
        "type": "text",
        "text": "This is a Facebook Messenger Message sent from the Messages API"
      }
    }
  }'

View full source

Run your code

Save this file to your machine and run it:

bash send-text.sh

Prerequisites

Install dependencies

npm install nexmo@beta

Write the code

Add the following to send-facebook-messenger.js:

Copy to Clipboard
const Nexmo = require('nexmo')

const nexmo = new Nexmo({
  apiKey: NEXMO_API_KEY,
  apiSecret: NEXMO_API_SECRET,
  applicationId: NEXMO_APPLICATION_ID,
  privateKey: NEXMO_APPLICATION_PRIVATE_KEY_PATH
})

nexmo.channel.send(
  { "type": "messenger", "id": "RECIPIENT_ID" },
  { "type": "messenger", "id": "SENDER_ID" },
  {
    "content": {
      "type": "text",
      "text": "This is a Facebook Messenger Message sent from the Messages API"
    }
  },
  (err, data) => { console.log(data.message_uuid); }
);

View full source

Run your code

Save this file to your machine and run it:

node send-facebook-messenger.js

TIP: If testing using Curl you will need a JWT. You can see how to create one in the documentation on creating a JWT.

Further reading