Sending a Facebook message with failover

This tutorial shows you how to use the failover functionality of the Dispatch API.

The example Workflow given here will attempt to send a Facebook message using the Messages API, and if this fails it then attempts to send an SMS message to the user using the Messages API.

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. Send a Facebook message with failover

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/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.

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.

Send a message with failover

Sending an message with failover to another channel is achieved by making a single request to the Dispatch API endpoint.

In this example you will implement the following workflow:

  1. Send a Facebook Messenger message to the user using the Messages API.
  2. If the failover condition is met proceed to the next step. In this example the failover condition is the message not being read.
  3. Send an SMS to the user using the Messages API.
Key Description
FROM_NUMBER The phone number you are sending the message from. Don't use a leading + or 00 when entering a phone number, start with the country code, for example, 447700900000.
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-message-with-failover.sh:

Copy to Clipboard
curl -X POST https://api.nexmo.com/v0.1/dispatch \
  -H 'Authorization: Bearer '$JWT\
  -H 'Content-Type: application/json' \
  -H 'Accept: application/json' \
  -d $'{
    "template":"failover",
    "workflow": [
      {
        "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 via the Dispatch API"
          }
        },
        "failover":{
          "expiry_time": 600,
          "condition_status": "read"
        }
      },
      {
        "from": {"type": "sms", "number": '$FROM_NUMBER'},
        "to": { "type": "sms", "number": '$TO_NUMBER'},
        "message": {
          "content": {
            "type": "text",
            "text": "This is an SMS sent via the Dispatch API"
          }
        }
      }
    ]
  }'

View full source

Run your code

Save this file to your machine and run it:

$ bash send-message-with-failover.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.dispatch.create("failover", [
  {
    "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 Dispatch API"
      }
    },
    "failover":{
      "expiry_time": 600,
      "condition_status": "read"
    }
  },
  {
    "from": {"type": "sms", "number": "FROM_NUMBER"},
    "to": { "type": "sms", "number": "TO_NUMBER"},
    "message": {
      "content": {
        "type": "text",
        "text": "This is an SMS sent from the Dispatch API"
      }
    }
  },
  (err, data) => { console.log(data.dispatch_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