Join us in San Francisco on the 29/30th of October for two days of developer workshops and technical talks

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 Nexmo Node client library - 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.

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/inbound https://example.com/status --keyfile=temp.key --type=messages

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 your JWT into the box labeled "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 Facebook 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.

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. Generate a new temporary application and an associated JWT using the same process that you used to create the initial link.

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

3. Paste the JWT you generated in step 1 into the "Provide a valid JWT token" text box.

4. Click "Unsubscribe".

5. 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" https://example.com/webhooks/inbound-message https://example.com/webhooks/message-status --keyfile=private.key --type=messages

How to create a Messages and Dispatch application using the Dashboard

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 using the Dashboard:

  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, https://example.com/webhooks/message-status.

  4. Enter the URL for your inbound message webhook, for example, https://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.

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