Skip to content

Instantly share code, notes, and snippets.

@tixastronauta
Last active August 28, 2024 15:28
Show Gist options
  • Save tixastronauta/0b9c3b409a7ba96edffc to your computer and use it in GitHub Desktop.
Save tixastronauta/0b9c3b409a7ba96edffc to your computer and use it in GitHub Desktop.
Receiving Facebook Leads on a Webhook

Receiving Facebook Leads on a Webhook

2020 IMPORTANT UPDATE - READ THIS BEFORE CONTINUING

THis gist was created in 2016 and I haven't been working with Facebook Leads ever since. As a result, this guide might not be accurate.

Please check @eladnava's updated step-by-step guide for 2020 here: https://eladnava.com/get-facebook-ad-lead-notifications-in-realtime-with-node-js-webhooks/

1 - Create an App

Head over to developer.facebook.com and create an App

2 - Setup the webhook

On your server, create a facebook webhook that will handle facebook calls. Then create a "leadgen" webhook on you App: https://developers.facebook.com/docs/graph-api/webhooks/v2.5

3 - Get an access token

Get lifetime access token to App (I asked for the following permissions: manage_pages, publish_pages, publish_actions, public_profile)

Note: Token should now be listed in: https://developers.facebook.com/tools/accesstoken/

4 - Subscribe App to Page

Subscribe App to Page using your access token

curl \
-F "access_token=<ACCESS_TOKEN>" \
"https://graph.facebook.com/v2.5/<PAGE_ID>/subscribed_apps"

5 - Handeling Webhook requests

Whenever a Lead is generated you'll receive a request on your facebook webhook with the following body:

{
   "object":"page",
   "entry":[
      {
         "id":"51044240199134611",
         "time":1447342027,
         "changes":[
            {
               "field":"leadgen",
               "value":{
                  "adgroup_id":0,
                  "ad_id":0,
                  "created_time":1447342026,
                  "leadgen_id":55459717045641545,
                  "page_id":516540199134611,
                  "form_id":551111744595541
               }
            }
         ]
      }
   ]
}

Now, grab the lead using the leadgen_id value:

curl -G \
  -d 'access_token=<ACCESS_TOKEN>' \
  https://graph.facebook.com/v2.5/<LEADGEN_ID>

Sample output:

{
   "created_time": "2015-11-12T15:27:06+0000",
   "id": "555971704561545",
   "field_data": [
      {
         "name": "full_name",
         "values": [
            "James Oak"
         ]
      },
      {
         "name": "email",
         "values": [
            "james.oak\u0040example.org"
         ]
      },
      {
         "name": "date_of_birth",
         "values": [
            "April 19, 1987"
         ]
      },
      {
         "name": "gender",
         "values": [
            "male"
         ]
      }
   ],
   "is_tcpa_compliant": false
}
@robsonjustino
Copy link

robsonjustino commented Apr 16, 2016

First, you need create a FacebookAds\Api instance with the access token:

require_once __DIR__ . '/vendor/autoload.php';
use FacebookAds\Api;
use FacebookAds\Object\Lead;

$app_id       = '<APP_ID>';
$app_secret   = '<APP_SECRET>';
$access_token = '<ACCESS_TOKEN>';

Api::init($app_id, $app_secret, $access_token);
$api = Api::instance();

$form = new Lead(<LEAD_ID>);
$form->read();

@tixastronauta
Copy link
Author

tixastronauta commented May 23, 2016

@tophertmo The curl call with the -G parameter it's a simple GET request. From the man pages:

-G, --get

When used, this option will make all data specified with -d, --data, --data-binary or 
--data-urlencode to be used in an HTTP GET request instead of the POST request
that otherwise would be used. The data will be appended to the URL with a '?'
separator.

There are several ways to do it in PHP, the most basic would be:

file_get_contents("https://graph.facebook.com/v2.5/<LEADGEN_ID>?access_token=<ACCESS_TOKEN>");

@douwevdijk
Copy link

Hi, thanks for this. I have a question: I have created a subscribe page where 'PAGE' owners can subscribe their page to my APP. This works, and I am receiving updates from Facebook with the corresponding lead_id('s). However, I receive an error or permission denied when trying to grab it's lead content. It does work when the leads are coming via my own pages but not if the page is owned by someone else. It looks like this is related to the access_token, but the user has subscribed to my app.

Can anyone assist?

@tixastronauta
Copy link
Author

@douwevdijk I was actually dealing with a similar problem a couple of months ago. I could not read leads from a partner's page. He had to escalate my permissions all the way up to Page Administrator in order to read leads' information. Later what we eventually did was exchanging my token to his one - I did create a simple page to enable a non tech guy to retrieve a long-loved token, here: https://github.com/tixastronauta/facebook-leads-example

@Arkango
Copy link

Arkango commented Nov 23, 2016

to recieve webhook whit all leads of single page , then the single file of callabck url contain all of first part . require once , libraries connection to apis and after call weebok or in webhook.php i have only hub challenge , verify token ,after i call my url?

@amizz
Copy link

amizz commented Mar 24, 2017

How about subscribing group feed?

@jeffsantos26
Copy link

Hello,

Please, is it possible get the data Leads programmatically with .Net C# and without API package?
Exists Graph API for .Net to integrate?

Thanks a lot.

@R-Sila
Copy link

R-Sila commented Apr 8, 2017

is it possible to receive ads insights on webhooks ?

@spandansingh
Copy link

same question! is it possible to receive ads insights on webhooks ?

@alfredogon82
Copy link

Hello.
I have been following your indications and i have managed to get a response, however this json response points to a excel file, this file cannot be opened if im not the admin of the application. I need to get the information as a json in real time to save it in the database.
Is this possible? how can i accomplish this?

this is the json im getting as an answer:

string(227) "{"id":"xxxxxxxxxxxxxxx","leadgen_export_csv_url":"https://www.facebook.com/ads/lead_gen/export_csv/?id=8xxxxxxxxxxxxxxxxxxxxx&type=form&source_type=graph_api","locale":"es_LA","name":"Name","status":"ACTIVE"}"

Thanks in advance.

@F-Makhokha
Copy link

@jeffersonsantos26 have you been able to get the .Net app for getting leads?

@mbilgidhis
Copy link

Does the app need to be reviewed/approved to be able to get data for general user?

If it does need to be reviewed/approved, what need to be filled when submitting review.

I ask this question because I successfully accept data using Leads Ads Testing, but when I share ads link to test it with my coworker, the webhook received nothing.

Thank you.

@jeffphpninja
Copy link

jeffphpninja commented Feb 28, 2018

@weisbeym
Copy link

How could I get the lead data into a variable in PHP instead of the form->read()?

@oelbaga
Copy link

oelbaga commented May 14, 2018

This works great except for one thing.

The access_token expires frequently. How do you get the current access token when permissions have already been completed by the page and now you need the current access_token to pull lead values with the leadgen_id in your web hook when access_token generated prior has expired.

@joseamneto
Copy link

joseamneto commented Mar 26, 2019

The app still on dev environment, and I made this call

https://graph.facebook.com/v2.10/444444444?access_token=MyTokenIshereOkOnTheCode

and I get that "Response status code does not indicate success: 404 (Not Found)."
On the parameters : I'm using the sample test : 444444444
The Token Is Ok was generated and it seems OK,

Should facebook, return something ? instead of an error, I know that there is not a lead _id 444444444, but for dev environment, it could exist

{
"error": {
"message": "(#803) Some of the aliases you requested do not exist: 444444444",
"type": "OAuthException",
"code": 803,
"fbtrace_id": "HjPQOJ2tSna"
}
}

@hemendrarajawat
Copy link

Hi, Is it compulsory to make your app 'Live' to receive RTU Leads?

When I am doing the testing from the app's webhook section, I am able to receive the data. But when I do the testing from the Page by creating the lead, it throws an error. Error Code: "102" and Error Message: " Server failure".

What is the root cause of this error and how can I resolve it?

@mandrius
Copy link

Hi, Is it compulsory to make your app 'Live' to receive RTU Leads?

When I am doing the testing from the app's webhook section, I am able to receive the data. But when I do the testing from the Page by creating the lead, it throws an error. Error Code: "102" and Error Message: " Server failure".

What is the root cause of this error and how can I resolve it?

Same issue here.

@sohamnavadiya
Copy link

Hi, Is it compulsory to make your app 'Live' to receive RTU Leads?

When I am doing the testing from the app's webhook section, I am able to receive the data. But when I do the testing from the Page by creating the lead, it throws an error. Error Code: "102" and Error Message: " Server failure".

What is the root cause of this error and how can I resolve it?

Facing same issue. Any solution to this?

@DanielLDorn
Copy link

Same issue here. I can't use the Lead Ads Testing Tool to test the integration. It appears that this is due to the change on 2/1/2019. However, I don't have the proper permissions when testing in Live mode, since the required permissions require App Review, which requires a working application. Anybody have a workaround to testing?

@kumar-jatin
Copy link

While making a call to subscribe app for using leadgen, I am getting this error (To subscribe to the leadgen field, one of these permissions is needed: leads_retrieval). How can I add leads_retrieval permission to page access token?

@josuhe-2020
Copy link

While making a call to subscribe app for using leadgen, I am getting this error (To subscribe to the leadgen field, one of these permissions is needed: leads_retrieval). How can I add leads_retrieval permission to page access token?

Hi @kumar-jatir, could you find the solution to this? I have the same error right now

@SyedSaifAli
Copy link

I think you will just have to add leads_retrieval permission from the graph API Explorer. After doing so, The access token code will be updated. Try using that access token code, and it will allow leads_retrieval
Screen Shot 2020-09-23 at 1 38 37 AM

@joaovictorrx
Copy link

I think you will just have to add leads_retrieval permission from the graph API Explorer. After doing so, The access token code will be updated. Try using that access token code, and it will allow leads_retrieval
Screen Shot 2020-09-23 at 1 38 37 AM

I try this but in token debug that permission dont appear, any solution for this ?

@eladnava
Copy link

eladnava commented Nov 13, 2020

For a step-by-step guide on how to achieve this in 2020 with Node.js, see my blog post:
Get Facebook Ad Lead Notifications with Node.js & Webhooks

@crazy568
Copy link

Hi, Is it compulsory to make your app 'Live' to receive RTU Leads?

When I am doing the testing from the app's webhook section, I am able to receive the data. But when I do the testing from the Page by creating the lead, it throws an error. Error Code: "102" and Error Message: " Server failure".

What is the root cause of this error and how can I resolve it?

Hello,

I resolve the problem whit next CURL.

REGISTER APP TO PAGE curl -i -X POST "https://graph.facebook.com/{pague_id}/subscribed_apps?subscribed_fields=leadgen&access_token={token_id}"

is very important leadgen field

@Ethan-ihealth
Copy link

Hi, I am trying to use fb webhook to retrieve my rtc lead info based on lead id. I can retrieve it by using both the app test button and Lead Ads testing tool provided by fb. But I still can not receive the real lead, could someone help me on this issue?

@manozzreddy
Copy link

Hi, I am trying to use fb webhook to retrieve my rtc lead info based on lead id. I can retrieve it by using both the app test button and Lead Ads testing tool provided by fb. But I still can not receive the real lead, could someone help me on this issue?

I'm also facing the same problem, are you able to resolve this issue?

@smirnov1987
Copy link

Мы пробрасываем лиды из ФБ в телегу и гугл таблицы через Webjack. Сервис работает как часы.
Можно получить месяц халявы и бесплатную настройку по промокоду semen21, напишите его в чат техподдержки на сайте

@machouz
Copy link

machouz commented Apr 16, 2023

For the 2024 version, you can follow my gist Get your FB Lead on custom Webhook: Step by Step

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment