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 Nexmo CLI 
  4. Install or update the Nexmo Node client library - required if using Node.
  5. Know how to write a webhook server
  6. 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

Next you'll need to link your Facebook Page to your Nexmo account. This will allow Nexmo to handle the inbound messages and allow you to send messages from the Nexmo Messages API.

IMPORTANT: This process needs to be authenticated by JWT. The JWT generated in this case can be based on any Application ID in your account, as this JWT is only used to authenticate the linking process, and it not used to authenticate application-specific API calls.

You will need to paste in a valid JWT. If you don't have one you can create one as follows:

1. Create a temporary application:

nexmo app:create "Delete Me Later" https://example.com/answer https://example.com/event --keyfile=temp.key

2. Copy the generated Application ID to the clipboard.

3. Generate a JWT with the following command, pasting in your Application ID:

JWT="$(nexmo jwt:generate ./temp.key application_id=YOUR_APP_ID)"

TIP: This JWT will expire after the default 15 minutes.

4. Display the generated JWT:

echo $JWT

5. Copy the JWT to the clipboard.

You are now ready to link your Facebook Page to Nexmo:

6. Click the following link when you have your JWT pasted to the clipboard and you are ready to link your Facebook Page to Nexmo:

You will see your Facebook Pages listed.

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

8. Paste in your JWT in the box provided (2. Provide a valid JWT token).

9. You will receive a message confirm successful subscription.

At this point your Nexmo Account and this Facebook Page are linked.

NOTE: If at some point in the future you want to further link a specific application to this page you can now do this from the Dashboard on the External Accounts tab for the specific Messages and Dispatch application you want to link.

Create a Nexmo Application

You can now create Messages and Dispatch applications in the Dashboard  ). This allows you to set webhooks for each application created - this is important for receiving inbound messages and message status updates.

To create your application:

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

  2. Enter the Application name, which can be anything you like.

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

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

  5. Click the link Generate public/private key pair just below the public key text area. This will create a public/private key pair and the private key will be downloaded by your browser.

  6. Click the Create Application button. You will be taken to phase 2 of the Create Application procedure where you can link external accounts such as Facebook to this application. If you do not have any external accounts listed here, or do not want to link one of those accounts to this application you can click Done.

  7. If there is an external account you want to link this application to, click the corresponding Link button and then click Done.

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-facebook-message.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-facebook-message.sh

Write the code

Add the following to app.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 app.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