Retrieving Leads

Leads can be downloaded and retrieved in different ways

In order to make API requests, you have to request an app review. Dev mode is allowed for some time/number of requests, but when your integration is in production, you should request an app review and switch the app to Live mode. An app in Dev mode could stop working as expected at any moment.

Find more info about app review in our FAQs.

Manual download

You must be an admin to access leads through your Facebook page. Go to your page settings. Then click on Publishing Tools at the top of the header bar:

From the Publishing Tools page, click on "Forms Library" under the section "Lead Ads Form", on the left hand side. In the Forms Library table, you will find a form called "Marketplace Real Estate Lead Gen Form":

by clicking "Download", a dialog will appear, asking if you want to download new leads or leads within a specific time range. After selecting your preference, you will be able to download leads in CSV or XLS format.

Using Leads APIs / webhook

Marketplace Real Estate uses the Marketing Leads API which is already in use across our Ads products and Motors partnerships on Marketplace.

Requirements

You must have a Facebook page (with Admin access) attached to your Business Manager.

Retrieving Leads requires app review

You can set up your app to retrieve test leads in dev mode. After the setup is complete, you have to request an app review and switch the app to live mode in order to receive production leads.

Permissions required:

  • manage_pages
  • leads_retrieval

The app review process could take up to 1-2 weeks including business verification. Please read this guide and prepare required documents in advance.

Public HTTP server

To receive webhook events from the Facebook Platform, your code must be hosted on a public HTTP server that meets has the following:

  • HTTPS support
  • A valid SSL certificate
  • An open port that accepts GET and POST requests

Using Graph API v3.2 or upper versions

Facebook Platform supports versioning and each version is guaranteed to operate for at least two years. A version will no longer be usable two years after the date that the subsequent version is released. So we highly recommend developers to use the most recent API version.

Setup Steps

Lead generation is language agnostic

The examples in this guide are in PHP, but you can write your webhook in whatever server-side language you like best.

Before you begin, make sure your server meets all of the requirements listed above.

1
Create a new PHP file
You need to set up an endpoint that reads two variables (hub.challenge and hub.verify_token). If the verify code is fine, you should reply with the challenge. You can put any string as $token value, this will be used just to verify your endpoint:
<?php
  $token = "<YOUR_VERIFY_TOKEN>";
  $challenge = $_REQUEST['hub.challenge'];
  $verify_token = $_REQUEST['hub.verify_token'];

  if ($verify_token === $token) {
    echo $challenge;
  }
?>
Save the file, and make it reachable at a URL of your convenience, e.g. https://yourdomain.com/facebook/webhook_verify.php. Check more details in this guide.
2
Create / edit your Facebook app, adding the webhook
If you don't have a Facebook app, you should create one. After that, you'll be able to add the webhook product:
Select Page from the dropdown menu, then click on Subscribe to this object.
Enter the information required:
  • Callback URL: the path to your webhook
  • Verify Token: a token you can choose to verify the request that Facebook will send to the webhook (see above)
  • You should now see a list of possible fields to subscribe. Scroll down, and click on the Subscribe button next to leadgen field.
    You can test your webhooks using the test button next to leadgen. Check on your server if you received the request, for example by:
  • checking access logs
  • reading the raw content of the request body:
    $request_body = file_get_contents('php://input')
  • 3
    Get Business System User Access Token

    Create a system user. Go to your Business Manager > Business Settings > Users > System Users and create a new system user.

    Install app and generate a new Token. You will need to select your app and these permission:

    • manage_pages
    • leads_retrieval

    Copy and save this token as it won't be stored at Facebook. You will use this token to access pages of dealers under your business.

    4
    Assign a page to the system user you created

    In Business Manager > Users > System Users, select your system admin. Click Assign Assets button and then select Page.

    Select a page with Page Admin role.

    5
    Get Page Access Tokens

    You will get all page access tokens assigned to the system admin.

    curl -X GET -G \
     -d 'access_token=<ACCESS_TOKEN>' \
     https://graph.facebook.com/v3.2/me/accounts

    The response example:

    {
      "data": [
        {
            "access_token": "...",
            "category": "Business and Pages",
            "category_list": [
                {
                    "id": "123688294262123",
                    "name": "Real Estate Partner"
                }
            ],
            "name": "Test page",
            "id": "132337234248833",
            "tasks": [
                "ANALYZE",
                "ADVERTISE",
                "MODERATE",
                "CREATE_CONTENT",
                "MANAGE"
            ]
        },
      ]
    }

    This access tokens in the response are long-lived page tokens which has no expiration date and you can hard-code it in simple RTU integrations to get leads data.

    6
    Subscribe pages to the app

    Using the page access tokens, your app need to subscribe pages so Facebook can send webhooks to your webserver.

    use FacebookAds\Api;
    use FacebookAds\Http\RequestInterface;
    
    Api::instance()->call(
      '/' . <PAGE_ID> . '/subscribed_apps',
      RequestInterface::METHOD_POST);
    curl \
      -F 'access_token=<ACCESS_TOKEN>' \
      https://graph.facebook.com/v2.11/<PAGE_ID>/subscribed_apps

    If you are using Graph API v3.2 or upper version, please add one additional parameter in the POST request (read more):

    subscribed_fields=leadgen

    The Facebook app associated with your token is authenticated for page updates; you do not need to specify app ID.

    On success, real time pings occur on events with a delay of up to a few minutes. See Troubleshooting Real-time Integrations.

    Receive leads via webhooks and retrieve leads

    Test webhooks by sending leads from your Marketplace listings

    You can use Lead Ads Testing Tool to send test leads.

    If you do not receive webhooks:

    • Change your app to the public mode
    • Delete existing leads in order to receive webhooks again from the same listing.

    The webhooks is structured as follows.

    {
      "changes": [{
        "field": "leadgen",
        "value": {
          "created_time": 1540269154,
          "page_id": "1935718636547237",
          "form_id": "2217161425198865",
          "leadgen_id": "2219139835001024"
        }
      }],
      "id": "1935718636547237",
      "time": 1540269155
    }

    Use leadgen_id to retrieve data associated with the lead.

    Use page access token of the page associated with the lead.


    Leads will be available for 90 days.

    curl -X GET \ -d 'access_token=<ACCESS_TOKEN>' \ https://graph.facebook.com/v4.0/{lead-id}/
    'use strict'; const bizSdk = require('facebook-nodejs-business-sdk'); const Lead = bizSdk.Lead; const access_token = '<ACCESS_TOKEN>'; const app_secret = '<APP_SECRET>'; const app_id = '<APP_ID>'; const id = '<ID>'; const api = bizSdk.FacebookAdsApi.init(access_token); const showDebugingInfo = true; // Setting this to true shows more debugging info. if (showDebugingInfo) { api.setDebug(true); } const logApiCallResult = (apiCallName, data) => { console.log(apiCallName); if (showDebugingInfo) { console.log('Data:' + JSON.stringify(data)); } }; let fields, params; fields = [ ]; params = { }; const sample_code = (new Lead(id)).get( fields, params ); logApiCallResult('sample_code api call complete.', sample_code);
    require __DIR__ . '/vendor/autoload.php'; use FacebookAds\Object\Lead; use FacebookAds\Api; use FacebookAds\Logger\CurlLogger; $access_token = '<ACCESS_TOKEN>'; $app_secret = '<APP_SECRET>'; $app_id = '<APP_ID>'; $id = '<ID>'; $api = Api::init($app_id, $app_secret, $access_token); $api->setLogger(new CurlLogger()); $fields = array( ); $params = array( ); echo json_encode((new Lead($id))->getSelf( $fields, $params )->exportAllData(), JSON_PRETTY_PRINT);
    from facebook_business.adobjects.lead import Lead from facebook_business.api import FacebookAdsApi access_token = '<ACCESS_TOKEN>' app_secret = '<APP_SECRET>' app_id = '<APP_ID>' id = '<ID>' FacebookAdsApi.init(access_token=access_token) fields = [ ] params = { } print Lead(id).get( fields=fields, params=params, )
    import com.facebook.ads.sdk.*; import java.io.File; import java.util.Arrays; public class SAMPLE_CODE_EXAMPLE { public static void main (String args[]) throws APIException { String access_token = \"<ACCESS_TOKEN>\"; String app_secret = \"<APP_SECRET>\"; String app_id = \"<APP_ID>\"; String id = \"<ID>\"; APIContext context = new APIContext(access_token).enableDebug(true); new Lead(id, context).get() .execute(); } }
    require 'facebook_ads' access_token = '<ACCESS_TOKEN>' app_secret = '<APP_SECRET>' app_id = '<APP_ID>' id = '<ID>' FacebookAds.configure do |config| config.access_token = access_token config.app_secret = app_secret end lead = FacebookAds::Lead.get(id ,'')

    Marketplace Rentals Lead Gen response:

    {
      "created_time": "2019-03-19T04:32:34+0000",
      "id": "2219139835001024",
      "field_data": [{
          "name": "email",
          "values": [
            "joe@fbtest.com"
          ]
        },
        {
          "name": "phone_number",
          "values": [
            "12345678"
          ]
        },
        {
          "name": "free_form_text",
          "values": [
            "Hi!"
          ]
        },
        {
          "name": "first_name",
          "values": [
            "Joe"
          ]
        },
        {
          "name": "last_name",
          "values": [
            "Smith"
          ]
        }
      ],
      "retailer_item_id": "Property_id_400454"
    }

    Retrieve Rental listing detail information

    You can add home_listing parameter in the request. Read the supported fields list.

    curl -X GET \
      -d "access_token=<ACCESS_TOKEN>" \
      "https://graph.facebook.com/v3.3/<lead-id>?fields=id,field_data,home_listing{id,name,property_type,price,address}"

    The response:

    {
      "field_data": [
        {
          "name": "email",
          "values": [
            "joe@fbtest.com"
          ]
        },
        {
          "name": "phone_number",
          "values": [
            "12345678"
          ]
        },
        {
          "name": "free_form_text",
          "values": [
            "Hi!"
          ]
        },
        {
          "name": "first_name",
          "values": [
            "Joe"
          ]
        },
        {
          "name": "last_name",
          "values": [
            "Smith"
          ]
        }
      ],
      "home_listing": {
        "id": "2791933954211104",
        "name": "My second test home sale listing",
        "property_type": "other",
        "price": "$700.00",
        "address": {
          "city": "Menlo Park",
          "country": "USA",
          "latitude": 37.48514,
          "longitude": -122.148387,
          "postal_code": "94025",
          "region": "California",
          "street_address": "1 Hacker Way"
        }
      },
      "id": "345213352829655"
    }

    You can manually download leads in CSV format from Page Settings. Read this guide.

    You can also retrieve all leads you received. You can find {form-id} from this API.

    curl -i -X GET \
     "https://graph.facebook.com/v3.2/{form-id}/leads?access_token={access-token}"

    You can also delete a lead you created. See this API reference.

    curl -i -X DELETE \
     "https://graph.facebook.com/v3.2/{lead-id}?access_token=<access_token>"

    Need help?

    You can contact Facebook's Support team any time you have questions.

    Contact us