facebook webhook php leads

Webhooks for Leads

Webhooks for Leads can send you real-time notifications of changes to your Page’s Lead ads. For example, you can receive real-time updates whenever users click on a lead ad.

First, set up a Page Webhook:

Setting Up Your Endpoint and Webhook Product

Follow our Getting Started guide to create your endpoint and configure the Webhooks product. During configuration, make sure to choose the Page object and subscribe to the leadgen field.

Install Your App

Webhook notifications will only be sent if your Page has installed your Webhooks configured-app, and if the Page has not disabled the App platform in its App Settings. To get your Page to install the app, have your app send a POST request to the Page’s subscribed_apps edge using the Page’s acccess token.

Requirements

Sample Request

Formatted for clarity

Sample Response

To see which app’s your Page has installed, send a GET request instead:

Sample Request

Formatted for clarity

Sample Response

If your Page has not installed any apps, the API will return an empty data set.

Graph API Explorer

If you don’t want to install your app programmatically, you can easily do it with the Graph API Explorer instead:

Common Uses

Getting Page LeadGen Details

Your app can subscribe to a Page’s Leads and get notified anytime a change occurs. For example, here’s a notification sent when a User clicked on a lead ad.

Источник

Webhooks for Lead Ads Tutorial

facebook webhook php leads

facebook webhook php leads

facebook webhook php leads

facebook webhook php leads

To get the most benefit from leads generate from Lead Ads, advertisers should respond to leads quickly. Various sources [1] [2] [3] suggest that responding to leads quickly (within 30 minutes) drastically affects conversion rates. You can achieve this with Facebook Lead Ads using our webhooks (previously known as Realtime Updates API), where your application will receive realtime updates as leads are filled out.

The integration requires setting up the webhook and subscribing the page to the application. The following is a video tutorial that steps through the integration starting with the creation of your Facebook application.

Sample Code from Video

Below are the files created in the video you can use to bootstrap the integration on your platform.

From webhook.php :

This is the file that will be used to verify the endpoint for webhooks and will thereafter be used to handle the data that gets posted in from the webhook subscription.

From platform.php :

This file is intended to mimic your marketing platform or website and show how you might integrate a workflow using the JavaScript SDK.

Источник

Using Webhooks API to Integrate Lead Ads with CRMs

This guide goes through every step to a successful CRM integration using Webhooks. If you are a CRM partner or an independent developer looking to use the Webhooks feature to receieve updates about leads being created for your ads, read on.

Terms and Concepts

We reference the following terms multiple times. So here is a brief description of them:

Prerequisites

Step 1: Set up your App

Step 2: Subscribe the app with Facebook

This step will let Facebook know that my app is interested in leadgen event

2.1 Create a webhook.php file

2.2 Make the api call to create subscription

If the API call is successful, it means that the app was successfully subscribed to receive leadgen RTU from Facebook. After this step you should be able to see this subscription when you navigate to the webhooks section.

facebook webhook php leads

Step 3: Subscribe the Page to Your App

We don’t send payloads to your apps every time someone fills a form and submits a lead on Facebook. Since the lead ads forms are associated with an advertiser’s Facebook page, we filter and send payloads only for leads that belong to those pages which authorized your app to receive the RTU.

Note: The client or advertiser who authorizes your app to listen to the RTU pings need to have ADMIN access on the page. Without this the subscription will not work.

From an advertiser’s perspective, this is how the flow will look like:

Once the above is complete then your app can receive rtu for the subscribed page.

Follow the steps below to achieve this flow:

3.1 Create platform.php file on your webserver

Once you have the file and the FB Login ready in the page, add the following code:

The above code does the following:

You can also use graph API to make this call:

You use the Page access token later to make the API call which will subscribe the advertisers page to your app. Please note that when making the call to retrieve all pages for the user, if a long lived access token is used, then page access token returned will never expire.

3.2 Verify the Subscription

To verify that your app was successfully subscribed to receive RTU for the selected page, make the following GET API call

The response of this api call should contain an entry for your app. Here is a sample API call along with the response as shown in Grah Explorer.

facebook webhook php leads

Step 4: Modify webhooks.php for Incoming RTUs

To test if the RTU integration is working and if you are receiving pings from facebook, modify the webhooks.php file to handle the incoming pings, since this is the endpoint which wil:l receive the pings. For now we will error log it by adding the following code

After the above steps, the webhook.php file should look like this:

Step 5: Test the Integration

Video Tutorial

Please check our the real time integration video tutorial to see how the integration will look like.

Can we get multiple entries in one RTU?

Can we get duplicate RTU for the same lead?

What access token should I use to subscribe the advertiser’s page to my app?

The page access token of the advertisers page has expired. How can I get a long term page access token?

I went through the RTU Integration steps but I am not receiving the pings. What can I do to validate that my subscription is in place?

How can I test the Lead Ads Integration without having to spend on creating a real Lead Ad?

Is there anyway to debug the webhooks integration and understand why it might be failing?

Источник

tixastronauta / facebook_leads.md

Receiving Facebook Leads on a Webhook

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.

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

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

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

Subscribe App to Page using your access token

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

Now, grab the lead using the leadgen_id value:

This comment has been minimized.

Copy link Quote reply

mderubertis commented Jan 8, 2016

I am only receiving the below when getting my callback from Facebook. Is there a particular reason as to why this happens?

This comment has been minimized.

Copy link Quote reply

tixastronauta commented Jan 19, 2016

@mderubertis have you subscribed to the «leadgen» webhook on your App panel?

This comment has been minimized.

Copy link Quote reply

tophertmo commented Feb 8, 2016 •

Could you explain what the curl request to grab the lead details would look like in PHP? I don’t understand the ‘-G’ part and receive an ‘Unsupported post request. Please read the Graph API documentation’ error message when trying to translate it.

The official docs suggest doing this but I can’t see where I would insert the access token:

This comment has been minimized.

Copy link Quote reply

robsonjustino commented Apr 16, 2016 •

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

This comment has been minimized.

Copy link Quote reply

tixastronauta commented May 23, 2016 •

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

This comment has been minimized.

Copy link Quote reply

douwevdijk commented Jul 15, 2016

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.

This comment has been minimized.

Copy link Quote reply

tixastronauta commented Oct 24, 2016

This comment has been minimized.

Copy link Quote reply

Arkango commented Nov 23, 2016

This comment has been minimized.

Copy link Quote reply

amizz commented Mar 24, 2017

How about subscribing group feed?

This comment has been minimized.

Copy link Quote reply

jeffsantos26 commented Mar 31, 2017

This comment has been minimized.

Copy link Quote reply

R-Sila commented Apr 8, 2017

This comment has been minimized.

Copy link Quote reply

spandansingh commented May 9, 2017

This comment has been minimized.

Copy link Quote reply

alfredogon82 commented Aug 24, 2017

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:

This comment has been minimized.

Copy link Quote reply

F-Makhokha commented Sep 19, 2017

This comment has been minimized.

Copy link Quote reply

mbilgidhis commented Jan 9, 2018

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.

Источник

Начало работы

В этом документе рассказывается, как настроить Webhook, который будет уведомлять вас о том, что пользователи приложения опубликовали изменения в своих фото. Поняв, как настроить этот Webhook, вы сможете настроить любой.

Для настройки Webhook необходимо:

Эти действия подробно описаны ниже.

Создание конечной точки

Конечная точка должна обрабатывать два типа HTTPS-запросов: запросы подтверждения и уведомления о событиях. Так как оба типа запросов используют протокол HTTPS, на вашем сервере должен быть настроен и установлен действующий сертификат TLS или SSL. Самозаверенные сертификаты не поддерживаются.

В следующих разделах описаны запросы обоих типов и как на них следует отвечать. Вы также можете воспользоваться примером приложения, которое уже настроено для обработки этих запросов.

Запросы подтверждения

Пример запроса подтверждения

Строка, которую мы берем из поля Маркер подтверждения на панели вашего приложения. Вы зададите ее во время настройки Webhooks.

Обработка запросов подтверждения

Когда ваша конечная точка получает запрос подтверждения, она должна:

Если вы настраиваете продукт Webhooks на панели приложений и инициируете таким образом запрос подтверждения, вы увидите на панели, правильно ли ваша конечная точка подтвердила запрос. Если вы настраиваете продукт Webhooks с помощью конечной точки /app/subscriptions API Graph, этот API отправит ответ об успешном или неудачном подтверждении.

Уведомления о событиях

При настройке продукта Webhooks вы подписываетесь на определенные поля ( fields ) типа object (например, на поле photos объекта user ). При изменении одного из этих полей мы будем отправлять на вашу конечную точку запрос POST с полезными данными JSON, описывающими изменение.

Например, если вы подписались на поле photos объекта user и один из пользователей вашего приложения опубликовал фото, мы отправим вам примерно такой запрос POST :

Полезные данные

Полезные данные содержат объект, описывающий изменение. При настройке продукта Webhooks можно указать, должны ли полезные данные содержать только названия измененных полей или также и их новые значения.

Они всегда имеют формат JSON, поэтому их можно анализировать с помощью стандартных методов и пакетов для анализа JSON.

Мы не храним данные уведомлений о событиях Webhook, которые отправляем вам, поэтому сохраняйте полезные данные, которые могут вам понадобиться.

Как правило, полезные данные содержат перечисленные далее стандартные свойства, однако содержимое и структура этих данных может зависеть от полей, на которые вы подписались. В справочной документации по каждому объекту можно узнать, какие поля будут включены в такие данные.

Массив, который содержит объект, описывающий изменения. Изменения, внесенные в разные объекты одного типа, могут объединяться.

Массив строк с названиями измененных полей. Добавляется, только если вы отключили настройку Включить значения при настройке продукта Webhooks на панели приложения.

Массив, который содержит объект, описывающий измененные поля и их новые значения. Добавляется, только если вы включили настройку Включить значения при настройке продукта Webhooks на панели приложения.

Метка времени UNIX, указывающая, когда было отправлено уведомление о событии (это не время внесения изменения, которое активировало уведомление).

Проверка полезных данных

Как проверить полезные данные:

Ответы на уведомления о событиях

Частота

Уведомления о событиях агрегируются и отправляются пакетом (не более 1000 обновлений). При этом пакетная обработка не гарантируется, поэтому настройте на своих серверах обработку каждого Webhook по отдельности.

В случае сбоя отправки обновления на сервер мы сразу же повторим попытку. Затем, в течение следующих 36 часов, мы будет отправлять обновления повторно, постепенно увеличивая интервалы времени между попытками. В таких случаях ваш сервер должен выполнить дедупликацию. Ответы, не принятые в течение этих 36 часов, будут удалены.

Настройка продукта Webhooks

Когда ваша конечная точка или пример приложения будут готовы, добавьте и настройте продукт Webhooks с помощью панели приложений. Это также можно сделать программным путем, используя конечную точку //subscriptions для всех Webhook, кроме Instagram.

В этом примере с помощью панели мы настроим Webhook, который подписан на все изменения, вносимые в фото пользователей приложения.

facebook webhook php leads

Введите URL конечной точки в поле URL обратного вызова и строку в поле Подтвердить маркер. Мы будем добавлять эту строку во все запросы подтверждения. Если вы используете один из наших примеров приложений, она должна совпадать со строкой, которую вы использовали в переменной TOKEN вашего приложения.

Чтобы в полезные данные уведомлений о событиях включались названия измененных полей и их новые значения, установите переключатель Включить ценность в положение Да.

facebook webhook php leads

После того как вы нажмете кнопку Подтвердить и сохранить, мы отправим на вашу конечную точку запрос, который нужно будет подтвердить. Если ваша конечная точка подтвердит запрос, вы увидите следующее:

facebook webhook php leads

Чтобы завершить процедуру, вам нужно подписаться на отдельные поля. Подпишитесь на поле photos и отправьте тестовое уведомление о событии.

facebook webhook php leads

Если конечная точка настроена правильно, она должна подтвердить полезные данные и выполнить заданный код. Если вы используете наш пример приложения, загрузите URL приложения в браузере. Должны отобразиться полезные данные:

facebook webhook php leads

Дальнейшие действия

Теперь, когда вы знаете, как настроить Webhooks, ознакомьтесь с дополнительными статьями, в которых описана настройка Webhooks для конкретных продуктов.

Источник

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *