Facebook Login Connect With Messenger Sample

repository·main·Indexed 41 days ago

https://github.com/fbsamples/fblogin-sample

Sample implementations for the 'Login Connect With Messenger' feature, demonstrating how to enable communication between apps and logged-in Facebook users. Includes guides for Direct Integrator and Tech Provider setups, webhook implementation for messaging events, and deployment instructions for Heroku and ngrok.

Tokens
3.7K
Snippets
8
Records
15
Agent score
50%

What's inside Facebook Login Connect With Messenger

  1. Overview of FB Login Samples

    main

    The fblogin-sample repository provides sample implementations for the Login Connect With Messenger feature. This feature allows applications to communicate with Facebook logged-in users via Facebook Messenger.

    Depending on your integration type, you should refer to different sample folders:

    • Director Integrator Samples (involving a single App ID): Located in the loginconnect_directintegrator folder.
    • Tech Provider Samples (involving two App IDs): Located in the loginconnectwithmessenger folder.
  2. Install and run the Messenger Bot locally using ngrok

    main

    To run the bot on your local machine and expose it to the internet for Facebook webhooks, follow these steps:

    1. Clone the repository

    git clone https://github.com/fbsamples/fblogin-sample.git
    cd fblogin-sample

    2. Start an ngrok tunnel

    Install ngrok (npm install -g ngrok) and start a tunnel to port 3000:

    ngrok http 3000

    Note the https forwarding URL (e.g., https://1c3b838deacb.ngrok.io).

    3. Install dependencies and configure environment

    npm install
    cp .sample.env .env

    Edit .env and set APP_URL to your ngrok HTTPS URL.

    4. Run the application

    node app.js

    5. Configure Webhook and Profile

    Use the VERIFY_TOKEN defined in your .env file to call the /profile endpoint. This configures your webhook subscription:

    # Replace <VERIFY_TOKEN> with your actual token
    http://localhost:3000/profile?mode=all&verify_token=<VERIFY_TOKEN>
    # Example ngrok command
    ngrok http 3000
    
    # Example profile configuration via browser/cURL
    http://localhost:3000/profile?mode=all&verify_token=your-token-here
  3. Configure Facebook Login for the Messenger App

    main

    After setting up the Messenger webhook, you must configure Facebook Login in the App Dashboard to allow users to connect:

    1. Enable Login: Under Add Product, find Facebook Login and click Set Up.
    2. JavaScript SDK: Enable Login with the JavaScript SDK.
    3. Allowed Domains: Add your ngrok HTTPS URL or Heroku domain to the Allowed Domains for the JavaScript SDK field.
    4. Messenger Integration:
      • Enable Login Connect with Messenger.
      • Add your Page to the Your Pages table.
      • Set the page as the default for this App.
    5. App Domains: Navigate to Settings > Basic and add your domain to the App Domains field.
    6. Save Changes.
  4. Get App ID, App Secret, and Messenger Access Tokens

    main

    Follow these steps to retrieve the necessary credentials from your Facebook App Dashboard:

    1. Retrieve App Credentials

    • Navigate to your app's Basic Settings in the Facebook App Dashboard.
    • Save the App ID and the App Secret.

    2. Grant Messenger Access

    • In the App Dashboard, find Messenger under Add Product and click Set Up.
    • Under Access Tokens, click Add or Remove Pages.
    • Select your desired Page and ensure you allow "Manage and access Page conversations" in Messenger.
    • Once selected, an access token will appear.

    3. Retrieve Page ID

    4. Enable NLP

    • In the Built-In NLP section of the Messenger settings, select your page and enable the toggle.
  5. Deploy the Messenger Bot to Heroku

    main

    To deploy the application to a remote server using Heroku:

    1. Create the Heroku App

    # Install Heroku CLI first, then:
    heroku apps:create

    Note the app name provided (e.g., mystic-wind-83).

    2. Configure Environment Variables

    Set your configuration variables (following the .sample.env template) via the Heroku Dashboard or CLI:

    heroku config:set PAGE_ID=XXXX

    3. Deploy and Verify

    # Deploy the code
    git push heroku master
    
    # View logs
    heroku logs --tail

    4. Configure Webhook

    Call the /profile endpoint using your Heroku URL and the VERIFY_TOKEN from your config:

    http://<YOUR_APP_NAME>.herokuapp.com/profile?mode=all&verify_token=<VERIFY_TOKEN>
    # Create app
    heroku apps:create
    
    # Set config
    heroku config:set PAGE_ID=XXXX
    
    # Deploy
    git push heroku master
    
    # Monitor
    heroku logs --tail
  6. Verify Facebook Request Signatures

    main

    To ensure incoming requests are actually from Facebook, the application uses a middleware function verifyRequestSignature. It validates the x-hub-signature header against a local HMAC-SHA1 hash of the request body using the config.appSecret.

    Implementation Detail: This is applied to the json body parser: app.use(json({ verify: verifyRequestSignature }));.

    If the signature does not match, the function throws an error, preventing unauthorized requests from being processed.

  7. Implement a Facebook Messenger Webhook

    main

    To receive events from Facebook Messenger, you must implement two endpoints in your Express server:

    1. GET /webhook: Used for webhook verification during the subscription process. It must validate the hub.verify_token against your configured VERIFY_TOKEN environment variable and return the hub.challenge value.
    2. POST /webhook: Used to receive actual messaging events. When a user opts in, the payload contains a login_id within entry[].messaging[0].optin.login_id. You can use this ID to send messages back via the Facebook Graph API.

    Note: The server requires an HTTPS listener (e.g., on port 8443) using valid SSL credentials (key.pem and cert.pem) to work with Facebook webhooks.

    // GET /webhook for verification
    app.get("/webhook", (req, res) => {
      let VERIFY_TOKEN = process.env.VERIFY_TOKEN;
      let mode = req.query["hub.mode"];
      let token = req.query["hub.verify_token"];
      let challenge = req.query["hub.challenge"];
    
      if (mode === "subscribe" && token === VERIFY_TOKEN) {
        res.status(200).send(challenge);
      } else {
        res.sendStatus(403);
      }
    });
    
    // POST /webhook for receiving events
    app.post("/webhook", async (req, res) => {
      let body = req.body;
      if (body.object === "page") {
        body.entry.forEach(function(entry) {
          let webhook_event = entry.messaging[0];
          let login_id = webhook_event.optin.login_id;
          // Use login_id to send messages...
        });
        res.status(200).send("EVENT_RECEIVED");
      }
    });
  8. Configure the Webhook for Facebook Messenger

    main

    To verify your webhook with Facebook, implement a GET endpoint at /webhook. The endpoint must handle the hub.mode, hub.verify_token, and hub.challenge query parameters. If the hub.mode is subscribe and the hub.verify_token matches your configured config.verifyToken, you must respond with the hub.challenge value and a 200 status code.

    Endpoint Details:

    • Method: GET
    • Path: /webhook
    • Query Params: hub.mode, hub.verify_token, hub.challenge
    • Success Response: 200 OK with the challenge body.
    // Example logic for the GET /webhook endpoint
    app.get("/webhook", (req, res) => {
      let mode = req.query["hub.mode"];
      let token = req.query["hub.verify_token"];
      let challenge = req.query["hub.challenge"];
    
      if (mode === "subscribe" && token === config.verifyToken) {
        res.status(200).send(challenge);
      } else {
        res.sendStatus(403);
      }
    });
  9. Required Environment Variables

    main

    The server implementation relies on the following environment variables:

    • PORT: The port on which the Express application listens.
    • PAGE_ACCESS_TOKEN: The token used to authenticate requests to the Facebook Graph API for sending messages.
    • VERIFY_TOKEN: A custom string used to validate the webhook subscription request from Facebook.
  10. Configure i18n internationalization settings

    main

    The i18n module is configured to handle multi-language support for the Messenger bot. It uses a directory of locale files and maps specific function names to its translation API.

    Key configuration options:

    • locales: An array of supported locale strings (e.g., en_US, fr_FR, es_ES).
    • defaultLocale: The fallback locale used when a translation is missing (set to en_US).
    • directory: The filesystem path where locale files are stored (uses path.join(__dirname, 'locales')).
    • objectNotation: Enables using dot notation to access nested translation keys.
    • api: Maps internal translation methods to custom function names:
      • __: mapped to translate
      • __n: mapped to translateN (for pluralization)
    const i18n = require("i18n"),
      path = require("path");
    
    i18n.configure({
      locales: [
        "en_US",
        "fr_FR",
        "es_ES",
        "es_LA",
        "pt_BR",
        "id_ID",
        "ar_AR",
        "de_DE",
        "it_IT",
        "ja_JP",
        "ko_KR",
        "ru_RU",
        "th_TH",
        "vi_VN",
        "zh_CN",
        "zh_HK",
        "zh_TW"
      ],
      defaultLocale: "en_US",
      directory: path.join(__dirname, "locales"),
      objectNotation: true,
      api: {
        __: "translate",
        __n: "translateN"
      }
    });
    
    module.exports = i18n;
  11. Handle Login Connect Events via /login_event

    main

    When a user performs a Login Connect action, the application receives a POST request to /login_event. This flow converts an App-Scoped ID (asid) into a unique loginId using a HMAC-SHA256 hash.

    Workflow:

    1. Receive asid in the request body.
    2. Generate loginId using generateLoginID(asid).
    3. Trigger a proactive welcome message using sendMessageUsingLoginID(loginId).
    4. Respond with 200 OK.

    Endpoint Details:

    • Method: POST
    • Path: /login_event
    • Required Body Field: asid (string)
    • Error Responses: 401 Unauthorized if asid is missing.
    // Expected request body
    {
      "asid": "USER_ASID_HERE"
    }