- Начало работы
- Требования
- Пиксель
- Business Manager
- Маркер доступа
- Через Events Manager (рекомендуемый вариант)
- Использование собственного приложения
- API Conversions в качестве платформы
- Как настроить Facebook Conversion API с помощью GTM Server Side
- Conversions API
- Recommended Steps
- Resources
- API Parameters
- Payload Helper
- Debugging
- Subscription Lifecycle Events
- Facebook Pixel Events
- Business Help Center
- Playbook and Webinar
- Data Processing Options
- Conversions API End-to-End Implementation
- Benefits of Integration
- Overview
- Existing Pixel Users
- General Consent
- Alternatives
- Preparation
- Pick Your Integration Type
- Define Events to Send
- Event Options
- Event Parameters
- Data Freshness
- Available Optimization Types
- Execution
- Direct Integration
- Step 1: Set Up Requirements
- Step 2: Implement the API
- Test Calls (Optional)
- Send and Verify Events
- Step 3: Add Parameters for Deduplication
- Event-based deduplication
- Alternative to event-based deduplication
- Optional Step 4: Explore Business SDK Features
- Integration as a Platform
- Step 1: Set Up Requirements
- Step 2: Send Events on Behalf of Clients
- Facebook Business Extension (FBE) Approach (Recommended)
- Client system user access token
- Client shares pixel to partner’s Business Manager
- Step 3: Attribute Events to Your Platform
Начало работы
Информация на этой странице поможет вам интегрировать API Conversions. Она включает в себя предварительные требования для интеграции и инструкции по созданию маркеров доступа.
Если в вашей компании исходящие запросы проходят через брандмауэр, получите IP-адреса Facebook, как описано в разделе IP-адреса краулера и программные агенты. Учтите, что список адресов часто меняется.
Для событий с сайта, отправленных через API Conversions, требуются параметры данных client_user_agent , action_source и event_source_url , а для других событий требуется только action_source . Эти параметры способствуют повышению качества событий, используемых для показа рекламы, и могут улучшить результаты кампании.
Требования
Пиксель
Прежде чем приступать к реализации API Conversions, правильно реализуйте на своем сайте пиксель Facebook. Мы рекомендуем использовать один и тот же пиксель для событий в браузере и серверных событий.
Business Manager
Для использования API также требуется Business Manager. С помощью Business Manager рекламодатели могут интегрировать рекламу на Facebook со своими внутренними системами и внешними партнерами. Если у вас ещё нет аккаунта Business Manager, создайте его, как описано в этой статье Справочного центра.
Маркер доступа
Для использования API Conversions нужен маркер доступа. Получить маркер доступа можно двумя способами:
Через Events Manager (рекомендуемый вариант)
Для использования API Conversions необходимо сгенерировать маркер доступа, который передается в качестве параметра в каждом вызове API. Выполните в Events Manager следующие действия:
Ссылка Сгенерировать маркер доступа отображается только для пользователей, имеющих права доступа администратора в компании. Другие пользователи ее не видят.
Получив маркер доступа, нажмите кнопку Управление интеграциями на вкладке Обзор в Events Manager. Во всплывающем окне нажмите кнопку Управление рядом с API Conversions. В результате мы автоматически создадим для вас приложение API Conversions и системного пользователя API Conversions. Проходить проверку приложения и запрашивать какие-либо разрешения при этом не требуется.
Теперь для маркеров доступа, созданных на вкладке настроек API Conversions в Events Manager, можно использовать различные версии API Graph. Ранее было возможно использовать только самую новую на момент создания маркера версию. Начиная с версии 12.0 для новых маркеров доступа можно использовать все доступные версии API Graph.
Использование собственного приложения
Если у вас уже есть собственное приложение и системный пользователь, можно сгенерировать маркер в Business Manager. Для этого выполните следующие действия:
Проходить проверку приложения и запрашивать какие-либо разрешения при этом не требуется.
API Conversions в качестве платформы
Вы можете выступать в качестве стороннего партнера, предлагающего функциональные возможности API Conversions клиентам-рекламодателям.
Источник
Как настроить Facebook Conversion API с помощью GTM Server Side
Отслеживание событий на стороне сервера и Conversion API были доступны на Facebook в течение нескольких лет. Но, начиная с 2021 года, FB стал активнее это продвигать. Если у вас есть свой менеджер в Facebook, помогающий с вашей учетной записью, он, скорее всего, позвонит вам и порекомендует настроить Conversion API.
По этому если с вами уже связались или вы сами решили что вам нужно настроить CAPI (Conversion API) прошу под кат. Там я описываю один из рекомендуемых методов настройки, а именно через Google Tag Manager Server Side.
FB CAPITag
Для настройки Facebook Conversion API с помощью Google Tag Manager сервер контейнера нужно сначала настроить работу Universal Analytics или GA4 через GTM SS. Все события которые вы хотите отслеживать в Facebook должны быть настроены в UA/GA4 так как вся информация для отправки запроса в FB CAPI будет формироваться на основе событий отправленных в Google Analytics.
В этой статье я не буду рассказывать, как создать и настроить веб контейнер GTM или отслеживание событий с помощью FB web pixel так как предполагается что вы уже хорошо знакомы с настройкой GTM контейнеров.
Что касается изначальной настройки GTM SS это зависит от того какой сервис вы будете использовать для предоставления серверов для вашего серверного контейнера. У каждого есть свои плюсы и минусы. Вы можете выбрать любой подходящий вам это никак не повлияет на работу FB CAPI.
У каждого провайдера серверов для GTM SS есть своя инструкция по настройке контейнера, по этому будем предполагать что вы воспользовались ею и у вас уже есть работающий GTM SS контейнер и ссылка на него.
В текущих реалиях что использовать UA или GA4 для FB CAPI не имеет значения. FB рекомендует GA4 так как он позволяет более легко передавать дополнительные параметры, но с моего опыта нет никаких проблем в передаче дополнительных данных с помощью UA custom dimensions. Так что если у вас не настроен GA4 ничего страшного.
И так после того как разобрались со всеми зависимостями наконец приступим к настройке.
1) Прежде всего, вам необходимо настроить UA или GA4 в GTM Web для отправки событий в GTM SS. Для этого вам нужно установить transport_url параметр указав в качестве значения ссылку на ваш GTM SS сервер.
GA4 tag
UA tag
2) Теперь нужно настроить GA на сервер контейнере GTM. Для GA4 создайте тег GA4 a для UA тег Universal Analytics. Также нужно создать триггер в соответствии с вашим типом тега. Тип триггера “Custom”, выберите «Some events». Имя клиента равно Universal Analytics или GA4 в зависимости от выбранного вами типа тега.
UA Server Side Tag
UA Trigger
3) Загрузите шаблон тега Facebook из репозитория GitHub и импортируйте его в шаблон тега сервер контейнера. Templates -> Tag Templates -> New. Затем в правом верхнем углу нажмите на точки и выберите импорт. На Github также можно найти и другие FB шаблоны тегов но я использую этот так как он умеет работать с UA а не только с GA4 и имеет больше настроек чем другие.
Server Side Tag Import
Server Side Template
4) Создайте тег Facebook Conversion API внутри GTM SS контейнера. Tag -> New -> Выберите тег Facebook, который вы импортировали на предыдущем шаге. Добавьте свой идентификатор пикселя Facebook и токен доступа к Facebook API (я рекомендую добавить их в качестве переменных, поскольку вам понадобятся эти значения для каждого Facebook тега). Если вы не знаете свой токен доступа к Facebook API, эта документация поможет вам его найти. Добавьте триггер для тега Facebook Conversion API: new trigger -> custom trigger -> event name equals page_view.
5) По такому же принципу вы можете настроить все остальные события которые вас интересуют.
Таким образом у вас будет готова базовая настройка FB CAPI.
Если вы хотите оставить FB Web Pixel вам нужно будет настроить дедупликацию событий. Так как получится что у вас FB web pixel и FB CAPI шлют те же события.
Чтобы настроить дедупликацию FB Conversion API, вам необходимо отправлять уникальный идентификатор события из браузера и с сервера. Одни и те же события из браузера и сервера должны иметь один и тот же идентификатор события. Больше информации про дедупликацию можно найти в документации.
В галерее шаблонов GTM есть Unique Event ID переменная которая создает уникальный ID для каждого события. Используйте эту переменную в FB Web Pixel для отправки event_id а также передавайте ее на сервер с помощью UA custom dimension или GA4 параметра и используйте в FB CAPI теге для отправки того же event_id.
Настройка FB CAPI требует терпения) Так что желаю всем удачи в этом нелегком деле и надеюсь этот пост поможет вам в этом.
Источник
Conversions API
The Conversions API allows advertisers to send web events from their servers directly to Facebook. Server events are linked to a pixel and are processed like browser pixel events. This means that server events are used in measurement, reporting, and optimization in the same way as browser pixel events.
Recommended Steps
- Get Started — See prerequisites to use the API and learn how to create an access token.
- Implement API and start sending requests — Start making POST requests and learn more about dropped events, batch requests, and event transaction time.
- Verify Events — Confirm that we have received your events.
The Conversions API used to be called Server-Side API.
Website events shared using the Conversions API require the following data parameters: client_user_agent , action_source , and event_source_url , while non-web events require only action_source . These parameters contribute to improving the quality of events used for ad delivery and may improve campaign performance.
We’ve released a Limited Data Use feature to give businesses more control over how their data is used in our systems and better support them with their California Consumer Privacy Act (CCPA) compliance efforts.
For the Conversions API, implement this feature by adding data_processing_options , data_processing_options_country , and data_processing_options_state inside each event within the data parameter of your events.
Resources
API Parameters
Required and optional parameters you can use to improve ads attribution and delivery optimization.
Payload Helper
See how your payload should be structured when it is sent to Facebook from your server.
Debugging
Learn how to handle error codes returned by the Conversions API.
Subscription Lifecycle Events
For subscription advertisers. Prerequisites, required parameters, and reporting metrics for subscription events.
Facebook Pixel Events
Business Help Center
Playbook and Webinar
Data Processing Options
Learn more about the Limited Data Use feature and how to implement it for Conversions API.
Источник
Conversions API End-to-End Implementation
The Conversions API supports advertisers’ efforts to provide consumers with appropriate data transparency and control while also helping them to continue providing personal experiences. With the API, you can share data directly from your server, rather than through a browser.
Benefits of Integration
Deeper-Funnel Visibility: The Conversions API allows you to share a wider array of data when compared to the Facebook pixel. With the API, you can make decisions taking into account more information, such as CRM data, lower funnel events (including qualified leads), and multi-site conversion paths across a website and a physical location.
Data Control: When used via a Server-Only implementation (for example, without the Facebook pixel), the Conversions API gives you added control over what data you share. You can choose to append insights to your events, providing data such as product margins or historical information, like customer value scores.
Signal Reliability and Resiliency: Data sharing through the Conversions API may be more reliable than browser-based methods alone, like the Facebook pixel. The API is designed to be less susceptible to issues like a browser crash or connectivity problems. New industry data transmission restrictions may limit the efficacy of cookies and pixel tracking, so the Conversions API helps you have control on sharing signals that may no longer be captured by the pixel.
Overview
You can think about your Conversions API integration in two main stages:
The following is a snapshot of the complete integration process:
Select events to share with Facebook with user consent (if any).
Set up your business’ assets: Facebook pixel, Facebook Application, Business Manager, Server Connection, System User.
Step 1: One event — Sending any event, manually or automated using the system user’s token. Completing this step means you have correctly set up authentication.
Step 2: Fully Integrated — You need to be sending some automated events to be considered integrated. Completing this milestone means you are able to optimize for Conversions API even in the event that you stop using the pixel or the pixel is blocked.
Once you are fully integrated, send enough automated funnel events to be considered fully onboarded. Then, optimize your match rate based on guidance from Event Match Quality.
- The events can be sent via either channel (browser or server) and it is not being double-counted.
- The events are being sent as close to real-time as possible.
- Provide customer information parameters to be used for identity matching.
Existing Pixel Users
If you have an existing Facebook pixel integration, the Conversion API integration should be built as an extension of the pixel integration, instead of as an entirely different connection.
General Consent
If you have logic for controlling consent with respect to sharing pixel data, use the same logic with respect to sharing data via Conversions API.
Alternatives
- If you want to optimize your ads for app events, please use the App Events API.
- If your events are store sales, please use the Offline Conversions API. Offline events that are not store sales are eligible for conversions API.
Preparation
Pick Your Integration Type
To start, select the integration option you would like to implement:
Redundant Setup (Recommended)
Send all events via both pixel and Conversions API. This is the recommended setup for those who would like to keep the pixel on their website, and are able to fully adopt the Conversions API.
To succeed, you must be able to generate a persistent event_id for both pixel and Conversions API events. This means sending the same event_name and event_id on both the pixel and the Conversions API event, in order to deduplicate identical events.
This setup provides performance on par or better than using only the browser pixel. The server can capture events that may not be tracked by the browser, such as purchases that occur on a separate website, lead conversions, or phone calls.
Split Setup
Send different types of events via pixel and Conversions API. For example, you could send PageView and ViewContent via pixel, and Lead or Purchase via Conversions API.
While this option is not as optimal as a redundant setup, you may consider it if you do not want to use a fully redundant setup. Take into consideration that you may need to complete additional work as browser changes are implemented.
Server-Only Implementation
Only send events through the Conversions API, instead of through the browser. We recommend implementing either a redundant setup or a split setup before switching to this approach.
Define Events to Send
Once you have chosen your integration approach, you can define which events you want to send. Signals are most useful if they are matched to Facebook user IDs, so it is important to think through what parameters you are sending us with an event and how often you would like to send them.
Event Options
Send events that are most relevant to your business. See a full list of supported standard and custom Facebook events.
Event Parameters
You can send multiple parameters inside each event. See parameters used by Conversions API to learn more about those fields.
You can add multiple types of IDs to your events, including event_id , external_id and order_id . It’s important to know the difference between these parameters:
Your unique ID for a specific customer.
Learn more about External ID.
A unique ID for a given event.
Used on event deduplication. This field is very important if you are sending events via both browser pixel and conversions API.
A unique ID for a given order. This parameter only works for purchase events and expects an order_id field in custom_data .
This implementation is limited to select Facebook partners. Contact your Facebook representative for access.
Used on purchase event deduplication, if you send events via both browser pixel and conversions API.
- Once you sent us your first order, we discard the second one if:
- You send a second event with the same order_id within a specific time window, and We resolve that the same user completed both orders.
You can deduplicate purchase events within two windows: 48 hours (recommended) or 28 days. This is the window between the first and second instances of the same event.
Data Freshness
We recommend that you send events in real time or in batches based on a specific timeline via the Conversions API. Sending your events in real time or within 1 hour helps ensure that they can be used for attribution and optimized for ad delivery.
Sending your events more than 2 hours after they occurred can cause a significant decrease in performance for ads optimized for those events. Events sent with a delay of 24 hours or more may experience significant issues with attribution and optimized ad delivery.
If you’re sending events with long conversion windows, send the event as close to real time as possible from the point at which the full conversion is completed.
Move on to the next step once you have:
- A list of events to send.
- The specific fields you want to send with each event.
- Defined how frequently you will send events.
Available Optimization Types
The Conversions API offers the following optimization types:
Optimize ad delivery to show ads to people most likely to make a conversion.
Value Optimization (also known as Return on Ads Spend Optimization)
Optimize ad delivery to show ads to people most likely to make a conversion of a specified value, such as purchases over $50.
Dynamic Product Ads
Optimize ad delivery to show ads for specific products to people most likely to purchase those specific products.
Execution
There are two ways to implement your integration:
- Direct Integration — You, as an advertiser, directly implement conversions API.
- Integration as a Platform — You, as a marketing partner, offer conversions API as a service to your clients.
Advertisers using conversions API through one of our marketing partners should follow our partner’s implementation guidelines.
Direct Integration
Step 1: Set Up Requirements
Prior to using the Conversions API, set up the following assets:
When you send events through the Conversions API, they’re processed and stored in the same way as the events you send through your pixel. When you implement the Conversions API, you select which pixel you want to send your events to.
Sending your Conversions API events to a pixel lets you use your Conversions API events in the same way you use your browser-based pixel events for measurement, attribution, and ad delivery optimization. We recommend sending events from the browser and your server to the same Facebook pixel ID.
You need a Business Manager to use the API. Business Manager helps advertisers integrate Facebook marketing efforts across their business and with external partners. If you don’t have a Business Manager, see the Help Center article on how to Create a Business Manager.
To use the Conversions API, you need an access token. There are two ways of getting your access token:
- Via Events Manager (Recommended)
- Using Your Own App
Move on to Implement the API once you have the assets ready. Remember to save IDs for your assets, since you use those on your API calls.
Step 2: Implement the API
Once you are done with the requirements, start the implementation process. While building on the Conversions API, always check the developer documentation.
Test Calls (Optional)
If this is your first time using the API, start with a test call. To do that, you need a payload and a method for making API calls. After the call is completed, check Events Manager to verify the call worked as expected.
Use the Payload Helper to generate a sample payload to be sent with your call. Follow the instructions listed on the tool. Your payload should look something like this:
If you want to test your payload from the Payload Helper, add your pixel ID under Test this Payload and click on Send to Test Events. You should be able to see the event on Events Manager > Your Pixel > Test Events. Learn more about the Test Events Tool.
Once you are satisfied with your payload, decide how you want to make your call. You can use our Graph API Explorer (see Guide) or your own servers. If you are using your servers, you can use CURL or the Facebook SDK—We highly recommend using the SDK.
Independently on your call method, you should call the /
After you complete your first call, verify your events on Events Manager > Your Pixel > Overview.
Move on to Send and Verify Events once you have checked your test events in Events Manager.
Send and Verify Events
To start sending events, make a POST request to the API’s /events edge. Attach a payload to your call —if you need help generating your payload, visit the Payload Helper. See the following resources for more information and code samples:
After you start sending events, go to Events Manager and confirm that we have received the events you sent. Learn how to Verify Your Events.
If your implementation is complementary to a browser pixel, move on to deduplication settings. Otherwise, you are all set! Check Support if you still have questions.
Step 3: Add Parameters for Deduplication
If you’re sending identical events from your pixel and through the Conversions API, you need to set up deduplication for your events sent via both channels. First, read developer documentation to understand the deduplication logic.
Event-based deduplication
If we find the same server key combination ( event_id , event_name ) and browser key combination ( eventID , event ) sent to the same pixel ID within 48 hours, we discard the later sent duplicate events.
To help ensure your events are deduplicated:
- For the corresponding events, make sure the following parameters are set to the same value:
- event_id from your server event and eventID from your browser event
- event_name from your server and browser events
- After you send duplicate events, check Events Manager to see if the correct events are being dropped.
- Ensure that each unique event sent via both pixel and Conversions API has its own event_id . This ID should not be shared with other events.
Alternative to event-based deduplication
While Event ID will always be the best way to deduplicate events, it’s a fairly complex implementation. You can leverage alternative solutions by using external_id or fbp parameters. If you have configured the external_id or fbp parameters to be passed via both browser and server, we will deduplicate events automatically if we see the same event with same external_id or fbp parameters within 48 hours.
Optional Step 4: Explore Business SDK Features
The Facebook Business SDK has advanced features designed especially for Conversions API users:
- Asynchronous Requests — Use this feature if you do not want to block your program’s execution to wait for a request to be completed. With this approach, you make your request and get a signal back from the server once it has been completed. While you wait for the response, the program can keep executing.
- Concurrent Batching — Leverage asynchronous requests to increase throughput by utilizing resources more efficiently. Create batched requests to support use cases like event request workers, cron jobs, and more.
- HTTP Service Interface — Override the Business SDK’s default HTTP service and implement your own custom service with your preferred method or library.
Integration as a Platform
The following instructions are for partners offering conversions API as a service to advertisers.
Step 1: Set Up Requirements
Your app should get the following features and permissions:
Step 2: Send Events on Behalf of Clients
First, follow the direct integration steps and test your integration. Then, you can request authorization to send events on behalf of your clients. You have the following authentication options:
Facebook Business Extension (FBE) Approach (Recommended)
FBE returns all the necessary information needed to send events on behalf of the client via the following process. FBE provides an endpoint to retrieve system user access tokens created in the client’s Business Manager. This process includes permissions to send server events and is done automatically and in a secured way.
The endpoint requires an user access token as input parameter. For new FBE users, call this endpoint the endpoint to fetch the system user access token after you finish setting up FBE. Existing users need to ask for re-authentication before calling the new API endpoint.
На данный момент расширение Facebook Business версии 2 доступно только утвержденным партнерам. Если вы хотите стать одним из них, обратитесь к своему представителю в Facebook. Для FBE необходима возможность manage_business_extension .
Client system user access token
Have your client manually create a System User Access Token via Conversions API inside the Pixel Settings. Then, send events to the advertiser’s Pixel with that token.
A system user or an admin system user must install the app that will be used to generate the access token. With this setup, your app is allowed to call APIs on behalf of this system user or admin system user.
Client shares pixel to partner’s Business Manager
With this option, the client shares their pixel to partner via Business Manager settings or via API, then you can assign the partner system user to the client pixel and you can generate an access token to send server events.
Step 3: Attribute Events to Your Platform
To attribute conversions API events to your platform, use the partner_agent field. This allows you to set your own platform identifier when sending events on behalf of a client. If you are a managed partner, work with your Facebook Representative to agree on an identifier for your platform. This value should be in a format that is less than 23 characters and includes at least two alphabetical characters. Then, send it with each server event.
Always provide an up-to-date setup guide for advertisers looking to activate the integration on your platform.
Источник