Facebook Messenger

Facebook Messenger has over 1.2 million users and is among the richest messaging channels available for businesses to reach customers. Engage them with experiences that includes carousels, quick replies, emojis and conversation extensions. Messenger supports it all.

Capabilities

Facebook Messenger supports a wide variety of capabilities as seen in the channel capabilities grid. Below is a detailed view of each capabilities.

Content Types

  • Text

    Full SupportAPI
  • Image

    Full SupportAPI
  • File

    Partial SupportAPI
  • Emoji

    Full SupportAPI
  • GIF

    Full SupportAPI
  • Location

    Partial SupportAPI

Action Types

  • Link

    Full SupportAPI
  • Extension

    Full SupportAPI
  • Postback

    Full SupportAPI
  • Reply

    Full SupportAPI

Structured Messages

  • Compound Message

    Full SupportAPI
  • Carousel

    Full SupportAPI

Indicators

  • Typing

    Full SupportAPI
  • Read

    Full SupportAPI
  • Conversation Start

    Full SupportAPI

Delivery Events

Delivery events allow you to track deliveries of Sunshine Conversations messages to Facebook Messenger by subscribing to the conversation:message:delivery:channel webhook. Failures to deliver a message to Facebook Messenger can be detected by subscribing to the conversation:message:delivery:failure webhook.

The Facebook Messenger message IDs associated with each Sunshine Conversations message are available in delivery event payloads in the externalMessages property.

Configuring Facebook Messenger

A business on Facebook Messenger is represented by a Facebook page, which is owned by a Facebook account. A page owner can grant access to a 3rd party Facebook app, allowing it to interact with that page on the owner’s behalf. This is how the Sunshine Conversations Facebook Messenger integration works.

There are two ways to configure a new integration. If you’re integrating Sunshine Conversations with your own Facebook page, you can do so via the web dashboard. With this option you’re granting Sunshine Conversations’ own Facebook app access to your page. However, if you’re integrating Sunshine Conversations on behalf of your customer then you will need to use the Integration API.

Using the Dashboard

In this option you’re granting Sunshine Conversations access to your own Facebook page. Note that your Facebook account must have Admin access to the page in question. You can check this from your Facebook page by browsing to Settings > Page Roles.

You can find the Sunshine Conversations Messenger integration in the Integrations menu bar tab of the Sunshine Conversations dashboard. When you click Authenticate, you will be redirected to Facebook where you will be prompted to grant Sunshine Conversations access to interact with pages on your behalf.

Facebook Messenger OAuth Prompt

Once your Facebook account is connected to Sunshine Conversations, select your Facebook page and hit save. You should now be able to receive messages from your Facebook page and reply via any of your configured business systems or with the Sunshine Conversations API.

Using the Integration API

If you’re building your own user experience for users integrating their Facebook page with your software, this option is for you. In this scenario after you’ve obtained authorization from the Facebook page owner, you will create the Sunshine Conversations integration via the Integration API. To begin you must first have your own Facebook app with your own company name and logo. This Facebook app represents your business identity in the Facebook platform whenever you request permission to act on behalf of another Facebook user.

Quick Start

Before you submit your App Review you can get a Sunshine Conversations integration up and running quickly on one of your own pages by issuing yourself a page access token via the Facebook dashboard. From your App settings choose Messenger > Settings > Token Generation.

Generate a page token for your own page
Facebook App Permissions

Before you go live your app will need to request some additional Facebook permissions. These permissions grant Sunshine Conversations the ability to configure the integration with your app and successfully exchange messages with end users on Messenger. Adding these permissions will require your Facebook app to pass an App Review. The permissions subject to review are:

  • pages_messaging: add the Messenger product to your app, and then add this permission to your review request from the Messenger section of the Facebook dashboard. This permission is required to enable core functions for the Facebook Messenger integration, including (but not limited to):

    • Sending messages, typing indicators and read-receipts
    • Configure the payload in postback events when the Get Started button is tapped/clicked
    • Management of Persistent Menus

    For more information on the features listed above, refer to the Facebook Messenger Profile API and Send API.

  • pages_manage_metadata: add this permission to your review request from the Permissions and Features sub-section under App Review on the Facebook dashboard. This permission is required in order to configure the Facebook app to send user messages (and other webhook events) to Sunshine Conversations (via webhook).

    For more information on pages_manage_metadata please visit Pages Manage Metadata.

  • pages_show_list: this permission does not require a review request, since it is included by default. It is however, required to be part of the access token to query the list of Pages that a person manages.

  • public_profile: Add this permission to allow apps to view a user’s profile fields in order to authenticate them.

    For more information, see public_profile.

Integration Flow Overview

When a user integrates their page with your software, the sequence will typically follows these steps:

  1. Obtain a user access token
  2. Use this token to query a list of the user’s Facebook pages
  3. Present this list to the user and prompt them to choose one
  4. Obtain a page access token for the selected page
  5. Create a new Sunshine Conversations integration using this page access token

The first step is to request a user access token. This step represents the user granting you permission to act on their behalf. This can be done in a number of ways, each with their own strengths and weaknesses that are detailed below.

User Access Token: Facebook JavaScript SDK

The easiest way to implement a user access token flow is by using the Facebook JavaScript SDK. We’ve created a github sample project here that demonstrates this process end-to-end.

The first step is to embed the Facebook SDK script tag into your website. Then you’ll call FB.login(), requesting the scopes manage_mages and pages_messaging as seen below:

FB.login((data) => {
    const userAccessToken = data.authResponse.accessToken;
}, {
    scope: 'manage_pages,pages_messaging'
});

This will prompt the user to grant your app these requested permissions. If the user agrees, an access token will be returned to you in the FB.login() callback.

User Access Token: Build a custom OAuth flow

In this option you’ll be building an OAuth flow based on browser redirects. The advantage with this option is that it doesn’t rely on the Facebook JavaScript SDK’s popup window. Instead, this flow redirects the user to Facebook in order grant access. A browser redirect based flow might be preferable for native apps and mobile devices.

OAuth Flow

The flow begins with redirecting the user’s browser to Facebook, where they will be shown an access grant dialog. Upon granting permission, Facebook will redirect the user back to your site using a predefined callback URL. This callback will include a code that your server side application can then exchange for an access token, using your Facebook app ID and secret. The endpoints your web service will need to implement in order to achieve this flow are detailed in the Facebook article Manually Build a Login Flow.

Page Access Token

You’ll now use the user access token obtained in the previous step to obtain a page access token. You can query the user’s pages with the /me/accounts API.

First, obtain your Facebook App ID and secret from Facebook dashboard. You’ll use these in addition to the user access token to make a server-to-server API call. You must not make this call from the user’s browser because doing so would force you to expose your App secret.

GET https://graph.facebook.com/me/accounts?
    client_id=facebook_app_id
    &client_secret=facebook_app_secret
    &access_token=user_access_token
    &limit=500

The response will include a list of users’ pages and their associated page access tokens. All that’s left to do is to prompt the user to choose which one they wish to integrate. Once the user has selected the page you can now call the Sunshine Conversations integration API to connect their page with Sunshine Conversations, passing along your app id, app secret, and the page access token.

Congratulations! You’re Done!

Impact of Messenger API Updates for Europe

On November 26, 2020, Facebook announced the following breaking change, which will take effect on December 16, 2020.

As part of our efforts to comply with new privacy rules in Europe, we’re making updates that will impact some developers and businesses that use our Messenger API. Beginning December 16th, several Messenger APIs will be unavailable for developers and businesses in Europe, and for people in Europe who connect with businesses globally. These changes will impact some APIs and UI components (listed here) for the following audience:

  • Europe pages in all chats
  • Pages with admins in Europe in all chats
  • Any chats with people in Europe

Impacted countries: All of the 30 European Economic Area (EEA) countries, which includes:

  • All 27 European Union member states
  • Norway
  • Iceland
  • Liechtenstein
  • United Kingdom

Which Sunshine Conversations customers are impacted

All customers who use the Facebook Messenger channel with Sunshine Conversations and meet any of the following criteria:

  • Are based in Europe
  • Have admins based in Europe
  • Have Facebook pages in Europe
  • Are chatting with European visitors (regardless of being based outside of Europe)

How will this impact Sunshine Conversations customers

Sunshine Conversations customers who use the Facebook Messenger channel will be able to send/receive messages; however, the business/user experience will be adversely affected. Delivery events, typing indicators, and read events will fail silently as Facebook will not be triggering an error for Sunshine Conversations to surface. A breakdown of the impact is outlined below:

  • When a business sends file, audio, or video media attachments, they will render for the user as a URL instead of rendering in conversation. Image attachments will not be impacted.
  • A user will not be able to send file, audio, or video media attachments. They will need to send a URL.
  • Facebook templates sent to users using the Facebook web client will not render. The user will need to open the message in their Android or iOS Messenger app in order to view it.
  • Buttons and templates containing buttons sent to users using the Facebook web client will not render. The user will need to open the message in their Android or iOS Messenger app to view it.
  • If a business tries to send typing indicators to a user, it will fail.
  • A business will not receive channel delivery events.
  • A business and its users will be unable to trigger or receive message read events.
  • A business will not be able to send an integration menu (persistent menu).
  • A business will not receive referral events, except they will continue to receive “Get Started” and “m.me” URLs.
  • A business will not be able to receive user profile information (gender, timezone, locale, profile picture). Id, first and last name will still be available.

Troubleshooting

This section describes a number of problems that commonly affect Facebook integrations and how to solve them.

Missing OAuth Permissions

During the OAuth flow described above, when presented with the authorization dialog, a Facebook page owner may select the “Choose what you allow” option to reduce the scope of access that is granted to Sunshine Conversations. If this is the case, the integration may be in a broken state. Deleting and re-creating the Facebook integration may not resolve the issue because Facebook will remember the user’s chosen scope of access during subsequent OAuth flows. To resolve this issue, access must first be fully revoked from the Facebook dashboard Business Integration page.

Facebook User Password Reset

If a page owner changes their Facebook account password, Sunshine Conversations’ access to that user’s pages will be invalidated. This means that while user messages will continue to be received by Sunshine Conversations, the business will be unable to respond. Facebook unfortunately offers no automated way to refresh the page access token. The integration must be recreated in order to resolve this issue.

You can proactively detect this error case by subscribing to the message:delivery:failure webhook trigger. You will know a Facebook password change is the cause of failed message deliveries by observing an error.code of unauthorized with the following underlyingError.message:

Error validating access token: The session has been invalidated because the user changed their password or Facebook has changed the session for security reasons.

Action Buttons

Facebook Messenger currently supports all available action types.

The number of message actions allowed in a given message or message item is limited by the Facebook Messenger platform. For actions of type reply, the limit is eleven. For all other action types, the limit is three. If the actions array of a message or message item exceeds the number of actions that Facebook Messenger allows, the list will be truncated to fit the limit, and actions beyond the allowed size will be ignored.

Reply

Reply buttons (also known as ‘Quick Replies’) provide a way to present a set of up to 11 buttons in-conversation that contain a title and optional image, and appear prominently above the composer. When a reply button is tapped, the list of buttons that was presented disappears and the text associated to the button is sent as a user message to the business.

These buttons are useful for presenting a list of multiple choice options to a user that are only relevant as an answer to a question being asked of the user at that time. For example, you can use reply buttons to send a set of buttons labelled 0-10 in order to measure NPS at the end of a customer service interaction.

Messenger Reply Buttons

You can send reply buttons via the Post Message API or through the use of messaging shorthand. The latter technique allows you to easily send reply buttons (and other interactive message types) to the user, without adding support for them directly to your application’s code.

Messenger offers full support for carousels which allows you to send a set of horizontally scrollable items that combines text, image and message actions.

Carousel example

You can send carousels containing up to 10 items via the Post Message API. Note that reply and location buttons are not allowed in a carousel.

Persistent Menu

Facebook Messenger Persistent Menu

It’s possible to configure a menu on the Messenger UI by calling the Sunshine Conversations REST API. Messenger allows up to three levels of menu hierarchy and they can contain 1 to 3 menu items at its first level and 1 to 5 menu items for submenus. Menus are configured per app or per integration, not per user. Menu items can be link, postback or submenu type actions.

Webhook Events Workaround

When integrating a Messenger page with Sunshine Conversations for the first time, a setup flow is initiated in which Sunshine Conversations will automatically set a webhook subscription for your app. We do this with a call to the subscriptions API. This call creates a webhook pointing to the Sunshine Conversations platform, and subscribes to all required events. However, due to a new bug in the Facebook platform, the call that Sunshine Conversations makes is not able to add the required events. To work around this issue, after Sunshine Conversations creates a webhook subscription, you must go into the developer dashboard and manually add the required events. To configure this setting:

  1. Head to the Facebook developer dashboard
  2. Select the app that you have just integrated with Sunshine Conversations
  3. In the left sidebar, under “Products”, select “Messenger” and click “Settings”. If you don’t see Messenger in the list of Products, click the ”+” button beside “Products” and add Messenger to your app.
  4. In the Messenger settings page, scroll down to the “Webhooks” section, and click the “Edit Events” button.
  5. In the events dialog, select all of the following events: messages, messaging_postbacks, messaging_optins, message_reads, and messaging_referrals
  6. Click save. Your settings should now look like this Facebook Messenger Webhook Events

Your webhook is now created and correctly configured to receive events from your integrated pages. However, because this flow did not work correctly during the original API call to Sunshine Conversations, your app is not yet subscribed to receive events from the page you just integrated. To subscribe your app to the page, you can either:

  • If you are an admin on the page you would like to subscribe, you can add the subscription manually from the Facebook developer dashboard. In the same section where you configured events in the previous steps, you will see an option to “Select a page to subscribe your webhook to the page events”. Select your page from the dropdown and click Subscribe.
  • If you are not an admin on the page you would like to subscribe, you must delete the integration and re-create it using the Sunshine Conversations API. Sunshine Conversations will now be able to create the subscription automatically, since your webhook is correctly configured.

Your app should now be subscribed to receive updates for the page and webhook events should now be sent to Sunshine Conversations. To verify, send a test message to your page and ensure that a message is indeed received from your Messenger integration.

When integrating a second page for the same Facebook app, or if your webhook is already created and subscribed to the correct events, you will not need to go through this flow again. The bug only affects Facebook apps which do not yet have a webhook configured.

Click-to-Messenger Ads

Facebook supports showing ads that click to Messenger.

As part of the flow, a welcome message can be setup so that a Facebook user is shown a message when the ad is clicked. The welcome message shown to the user cannot be added to the conversation history, but replies to this message will be forwarded through Sunshine Conversations as message:appUser webhooks. However, if your ad includes an action, a different behavior will be triggered depending on the action.

Quick Replies

If you configure the ad’s welcome message to include a quick reply, they will trigger a message:appUser webhook. The message representing the quick reply will have the payload properly set to the payload specified when creating the Facebook ad (see Quick Replies under step 6. of the ad creation guide).

Example payload

The following example is for a Click-to-Messenger ad with a reply action that has the text Continue and the payload continue.

{
    "trigger": "postback",
    "app": {
        "_id": "5698edbf2a43bd081be982f1"
    },
    "messages": [
        {
            "_id": "55c8c1498590aa1900b9b9b1",
            "type": "text",
            "text": "Continue",
            "payload": "continue",
            "role": "appUser",
            "authorId": "c7f6e6d6c3a637261bd9656f",
            "received": 1444348338.704,
            "source": {
                "type": "messenger"
            }
        }
    ],
    "appUser": {
        "_id": "c7f6e6d6c3a637261bd9656f",
        "conversationStarted": true,
        "signedUpAt": "2018-04-02T14:45:46.505Z"
    },
    "client": {
        "_id": "5c9d2f34a1d3a2504bc89511",
        "lastSeen": "2019-04-05T18:23:20.791Z",
        "platform": "messenger",
        "id": "20b2be30cf7e4152865f066930cbb5b2",
        "active": true,
        "primary": true,
        "integrationId": "5c3640f8cd3fa5850931a954"
    },
    "conversation": {
        "_id": "105e47578be874292d365ee8"
    },
    "version": "v1.1"
}

Postback actions

If you configure the ad’s welcome message to include a postback action, they will trigger a postback webhook. For these postback events, the message will not be present, the action._id will be randomly generated and the action.payload will be set to the payload specified when creating the Facebook ad (see Buttons under step 6. of the ad creation guide).

Example payload

The following example is for a Click-to-Messenger ad with a postback action that has the text Tell me more and the payload tell_me_more.

{
    "trigger": "postback",
    "app": {
        "_id": "5698edbf2a43bd081be982f1"
    },
    "postbacks": [
        {
            "action": {
                "_id": "571530ee4fae94c32b78b170",
                "type": "postback",
                "text": "Tell me more",
                "payload": "tell_me_more"
            }
        }
    ],
    "appUser": {
        "_id": "c7f6e6d6c3a637261bd9656f",
        "conversationStarted": true,
        "signedUpAt": "2018-04-02T14:45:46.505Z"
    },
    "client": {
        "_id": "5c9d2f34a1d3a2504bc89511",
        "lastSeen": "2019-04-05T18:23:20.791Z",
        "platform": "messenger",
        "id": "20b2be30cf7e4152865f066930cbb5b2",
        "active": true,
        "primary": true,
        "integrationId": "5c3640f8cd3fa5850931a954"
    },
    "conversation": {
        "_id": "105e47578be874292d365ee8"
    },
    "version": "v1.1"
}

Passthrough API

The passthrough API is a way to send message types for which there is no corresponding Sunshine Conversations type or to leverage channel specific feature not folded into the Sunshine Conversations API (e.g. sending messages to a person outside of the normally allowed 24-hour window using Message Tags. To accomplish this, the developer provides Sunshine Conversations with the raw payload to send to the messaging provider’s API, and the Sunshine Conversations platform will “pass it through”.

To use the passthrough API, you first craft a valid Sunshine Conversations message of any type, then you specify an additional override parameter for the channels you would like to use passthrough. Under the channel name (in this case messenger), the payload field contains the exact structure of a valid Facebook Messenger API call to the Send Messages endpoint.

Example using Message Tags:

{
    "role": "appMaker",
    "type": "text",
    "text": "Hey, are you still coming to tonight's event?",
    "override": {
        "messenger": {
            "payload": {
                "message": {
                    "text": "See you at 7:00 tonight?",
                    "quick_replies": [
                        {
                            "content_type": "text",
                            "title": "yes",
                            "payload": "yes"
                        },
                        {
                            "content_type": "text",
                            "title": "No",
                            "payload": "no"
                        }
                    ]
                },
                "tag": "CONFIRMED_EVENT_UPDATE"
            }
        }
    }
}

The above example depicts a simple override example, where the text message will render as “Hey, are you still coming to tonight’s event?” on every channel except Facebook Messenger, where it would render a “See you at 7:00 tonight?” text message along with a Quick Reply on Facebook Messenger while signalling to Facebook that this is a CONFIRMED_EVENT_UPDATE using a Message Tag. Note that all fields under payload in the above example (message, tag, etc.) are Messenger-specific fields, exactly as the Facebook Messenger API would accept them.

Example using Message Receipt:

{
    "role": "appMaker",
    "type": "text",
    "text": "Your order is confirmed!",
    "override": {
        "messenger": {
            "payload": {
                "message": {
                    "attachment": {
                        "type": "template",
                        "payload": {
                            "template_type": "receipt",
                            "recipient_name": "John",
                            "order_number": "111111111111",
                            "currency": "USD",
                            "payment_method": "Visa 2345",
                            "order_url": "http://petersapparel.parseapp.com/order?order_id=123456",
                            "timestamp": "1428444852",
                            "address": {
                                "street_1": "1 Apple Highway",
                                "street_2": "",
                                "city": "Mangle city",
                                "postal_code": "94025",
                                "state": "CA",
                                "country": "US"
                            },
                            "summary": {
                                "subtotal": 75.0,
                                "shipping_cost": 4.95,
                                "total_tax": 6.19,
                                "total_cost": 56.14
                            },
                            "adjustments": [
                                {
                                    "name": "New Customer Discount",
                                    "amount": 20
                                },
                                {
                                    "name": "$10 Off Coupon",
                                    "amount": 10
                                }
                            ],
                            "elements": [
                                {
                                    "title": "Fall Coat",
                                    "subtitle": "Soft and Luxurious",
                                    "quantity": 2,
                                    "price": 50,
                                    "currency": "USD",
                                    "image_url": "https://smooch.io/static_assets/images/shoplifter/double-breasted-coat.jpg"
                                }
                            ]
                        }
                    }
                }
            }
        }
    }
}

Facebook Messenger

This example shows how a Receipt message can be sent using passthrough API on Facebook Messenger.

Reserved Fields

In order to ensure the message is correctly delivered, Sunshine Conversations will automatically set some fields in the payload for you. If you supply these fields, they will be ignored and replaced.

KeyReserved Behaviour
recipientThe identity of Facebook user. Sunshine Conversations will populate this value based on the target user.