facebook php business sdk

Get Started with the Facebook Business SDK

This document explains how to install the Facebook Business SDK and test the installation. SDKs are available for Java, JavaScript, PHP, Python, and Ruby. If you have the Marketing API already installed, learn how to update to the Facebook Business SDK.

Before You Start

You will need access to the following:

For Java apps, you can use whatever development environment you like but it must support Maven builds.

Install the SDK

To your Maven project, add the following XML code to the dependency section of your pom.xml file:

Create a Java Class

Test Your Install

Build and run your app. You should see the result in your console logging window. If it complains about an expired token, request a new Page Access Token and retry.

JavaScript (Node.js)

For JavaScript apps, the SDK is distributed as a Node.js package.

Open a command terminal window and create a new project folder. Create, configure, and install your project with the following command:

You can update your configuration settings later by editing the package.json file directly.

Install the SDK

Install the SDK package with the following command:

Modify the Project File

Open the index.js file and add the following code. Replace , and with your values.

Test Your Install

Test your install with the following command:

You should see the result in your terminal window. If it complains about an expired token, request a new Page Access Token and retry.

For PHP apps, use Composer to install the SDK.

Install the SDK

In a new project folder, create composer.json with the following content. Replace , , and with your values.

Install the SDK by running the following command in your terminal window:

Create a Project File

Create a src/test.php file with the following content. Replace , , , and with your values.

Test Your Install

Test your install with the following command:

You should see the result in your terminal window. If it complains about an expired token, request a new Page Access Token and retry.

Python

Install the SDK

Install the SDK with the following command.

Create a Project File

Create the test.py file with the following content. Replace , , , and with your values.

Test Your Install

Test your install with the following command:

You should see the result in your terminal window. If it complains about an expired token, request a new Page Access Token and retry.

For Ruby, the SDK is distributed as a RubyGem package.

Install the SDK

From a terminal window, run the following command from your project folder to install the Facebook Business SDK for Ruby. Depending on your environment, you may need to setup rbenv or rvm, or use sudo before the command.

Create a Project File

Create a test.rb file with the following content. Replace , , and with your values.

Test Your Install

Test your install with the following command:

You should see the result in your terminal window. If it complains about an expired token, request a new Page Access Token and retry.

For Current Marketing API Users

To update to the Facebook Business SDK from the Marketing API follow these steps.

In the the pom.xml file:

Nodejs

In the package.json file:

In the composer.json file:

Python

Learn More

View the source code for the Facebook Business SDK at Github.

Источник

Facebook php business sdk

Facebook Business SDK for PHP

The Facebook Business SDK is a one-stop shop to help our partners better serve their businesses. Partners are using multiple Facebook API’s to server the needs of their clients. Adopting all these API’s and keeping them up to date across the various platforms can be time consuming and ultimately prohibitive. For this reason Facebook has developed the Business SDK bundling many of its APIs into one SDK to ease implementation and upkeep. The Business SDK is an upgraded version of the Marketing API SDK that includes the Marketing API as well as many Facebook APIs from different platforms such as Pages, Business Manager, Instagram, etc.

To get started with the SDK, you must have an app registered on developers.facebook.com.

To manage the Marketing API, please visit your /dashboard» rel=»nofollow»> App Dashboard and add the Marketing API product to your app.

IMPORTANT: For security, it is recommended that you turn on ‘App Secret Proof for Server API calls’ in your app’s Settings->Advanced page.

Obtain An Access Token

When someone connects with an app using Facebook Login and approves the request for permissions, the app obtains an access token that provides temporary, secure access to Facebook APIs.

An access token is an opaque string that identifies a User, app, or Page.

For example, to access the Marketing API, you need to generate a User access token for your app and ask for the ads_management permission; to access Pages API, you need to generate a Page access token for your app and ask for the manage_page permission.

Читайте также:  моложе чем сегодня мы уже не будем никогда

Refer to our Access Token Guide to learn more.

For now, we can use the Graph Explorer to get an access token.

The Facebook Business SDK requires PHP 5.6 or greater.

The Facebook Business SDK uses composer to manage dependencies. Visit the composer documentation to learn how to install composer.

Add the following to your composer.json file:

then install it through composer:

This repository is written following the psr-4 autoloading standard. Any psr-4 compatible autoloader can be used.

The FacebookAds\Api object is the foundation of the Business SDK which encapsulates a FacebookAds\Session and is used to execute requests against the Graph API.

To instantiate an Api object you will need a valid access token:

Once instantiated, the Api object will allow you to start making requests to the Graph API.

Due to the high number of field names in the Graph API existing objects, in order to facilitate your code maintainability, enum-like classes are provided. These files are stored under the FacebookAds/Object/Fields directory. You can access object properties in the same manner you would usually do in php:

or using the enums:

Facebook Ads entities are defined as classes under the FacebookAds/Object directory.

For some objects, the Ads API doesn’t return all available fields by default. The first argument of the object’s read method is an array of field names to be requested.

Requesting an high number of fields may cause the response time to visibly increase, you should always request only the fields you really need.

Whenever all object connected to a parent are required (carelessly from the number of HTTP requests) implicit fetching can help reducing the amount of code required. If cursor has Implicit Fetching enabled, while iterating (foreach, Cursor::next(), Cursor::prev()) the page end is reached, the SDK will automatically fetch and append a new page, until cursor end. Implicit Fetching will make you lose control of the number of HTTP request that will be sent and, for this reason, is disabled by default. Implicit Fetching can be enabled for a specific cursor:

Cursors are bi-directional, and can be iterated in reverse order:

The ‘test’ folder contains the test cases. These are logically divided in unit and integration tests. Integration tests require an active Facebook Ad Account, a Facebook Application and a valid Access Token.

Note: we are currently unable to securely and reliably run integration tests on a public CI system. Our integrations with Travis and Scrutinizer (including badges at the top of this file) include only unit tests.

From the root folder run:

Execute unit tests only

To run tests individually (be sure not to be pointing to an integration test file):

Execute all tests (unit + integration)

Setup your integration config:

To run tests individually:

If this SDK is not working as expected, it may be either a SDK issue or API issue.

This can be identified by constructing a raw cURL request and seeing if the response is as expected

When running this code, this cURL request will be printed to the console as:

Our SDK is autogenerated from SDK Codegen. If you want to learn more about how our SDK code is generated, please check this repository.

Since we want to handle bugs more efficiently, we’ve decided to close issue reporting in Github and move to our dedicated bug reporting channel. If you encounter a bug with Business SDK (PHP), please report the issue at our developer bug reporting channel.

About

An SDK built to facilitate application development for Facebook Ads API.

Источник

Facebook php business sdk

This guide assumes you have an app that has been whitelisted for the Facebook Ads API, that you have a fully working development environment with all required dependencies and that are ready to start coding. If you haven’t done this, please see the README file.

We also assume you are somewhat familiar with namespaces in PHP. If not, we recommend you take some time to read the namespace basics in the PHP Manual.

You should also have the documentation for the Facebook Marketing APIs available as you will need to refer to this to understand which combination of parameters are required for the different object types.

The classes within the Facebook Ads SDK are designed to be included using an autoloader compliant with the PSR-4. If you are using Composer to include dependencies, you will find an implementation available within the vendor folder. This guide assumes you are using this autoloader.

To make any request to the Ads API, you will need to have a valid access token and the user has accepted the ads_management permission.

The FacebookAds\Api object is the basis of the Ads SDK which encapsulates a FacebookAds\Session and is used to execute requests against the Graph API.

Читайте также:  Что такое полиуретановая смесь

An easy to use init method is provided:

Making requests to the Graph

Handling Multiple Access Tokens

The first time an Api object is instantiated, we store a static reference to that object within the Api class and this is used as the default instance within the SDK. This saves you from having to pass around a reference to an Api instance within your application.

A common requirement amongst Facebook Ads API developers however is to be able to handle multiple sessions within a single script execution. For example, you may have a process which syncs updated objects for multiple app users into some local datastore.

To enable this, we provide two ways to manage sessions.

When setting class variables on an object of this type we perform some basic validation to ensure the field is a valid field and an \Exception will be thrown if a field name is not found within the field definition for that class.

For each object type, we provide a class enumerating the available fields of that object. These can be found within the FacebookAds\Object\Fields namespace and provide a way to reference fields without using strings. You can alternatively use strings if you find this easier.

For example, you can set the data of an object using the field definitions in the following way:

Alternatively, you can use the string equivalent:

Similarly the same applies for direct assignation:

When requesting multiple objects from the Graph, responses may be returned in pages of data which can be traversed using cursors. We encapsulate this information into a Cursor class which represents the set of objects in the current page along with information about how to access subsequent pages of objects. This class implements the \Iterable and \Countable interfaces.

Reading a single object

See Defining Default Fields within the section about Extending the SDK for an example of how to avoid defining the fields you require every request.

Reading multiple objects

When you mutate an AdObject, we record which variables have changed and make it easy for you to write these change to the Graph API by calling the update method.

Please note that in some cases the variable name used to update an attribute of an entity differs from the one read from Graph API. Any variable you change will be included in the request to update an object an you will likely receive an \Exception if the field name is incorrect. Please consult the Facebook Developer Documentation to see which fields are required.

Deleting a single object

To delete an object, you only need call the delete method on an instance of that object. Note, you do not have had to have read the object from the Graph API, all you need is the id of the object.

Deleting multiple objects

We provide the static method deleteIds($ids = array(. )) to enable you to delete many objects at the same time. This method returns a boolean value and will only return true if all objects were successfully deleted. A return value of false means one or more failed to be deleted. Please also note that we do not verify the type of the id you have passed into this function.

On object that extends AbstractCrudObject you can call the save method which will call create if the object does not have a value for id set, or will call update a value is present.

For each connection an object has, we provide a helper method to retrieve its related objects. In the case of ObjectObject\AdAccount we provide several of these methods including getAds($required_fields) which will return a Cursor containing a page of Object\Ad objects.

You only need the id of the object on which you want to call a connection method, therefore you do not need to have read the object from the Graph API first.

For cases where these helper methods are not available, see Requesting Connections Without Helper Methods.

Facebook’s targeting can generally be broken down into interests, demographics, behaviors and geo targeting. Many of these need to be queried from the Graph API search endpoint.

To query targeting using the Ads SDK, you can use the Object\TargetingSearch class.

This set of examples will walk you through:

Examples can be found within the examples/ folder of the SDK. This assumes you have bootstrap code with an access token:

1. Reading AdAccounts

The FacebookSession contains the id of the user who has the active session and this can be used to read their AdAccount connections.

2. Creating a Campaign

Now we have an AdAccount for the current user we can go ahead an create our Campaign. All ads within your campaign should have the same objective. You can find the available objectives within the AdObjectives class.

Читайте также:  Что такое подкаст простыми словами и как им пользоваться

In the following example we create a paused campaign so your ads do not go live, however you can omit the status field if you want your ad to run.

3. Searching Targeting

The final thing we need before creating an Ad is some targeting. Many attributes of targeting can be found defined in the developer documentation, however some categories need you to search, such as interests. For this, we provide the TargetingSearch class.

Targeting for the moment is expressed in the form of a multidimensional array:

4. Creating an AdSet

An AdSet is a set of Ad objects and it is best practice to ensure all Ad objects within an AdSet have the same targeting.

5. Create an AdImage

6. Creating an AdCreative

There are many scenarios in which you may want to extend the SDK, and when developing this SDK we attempted to balance extensibility with ease of use for new developers.

Defining Default Fields to Read

Requesting Connections Without Helper Methods

As detailed in the Connections section, we provide helper methods to request objects relative to an object. However, in some cases these methods may not have been implemented, or if you have extended our based objects as in the example of defining default fields to read, calling a connection helper method on a base object will return objects of the \FacebookAds namespace type.

Источник

Получение лидов

Получить лиды можно с помощью Webhooks или путем массового чтения.

Прежде чем начать

Для считывания всех данных лидов и данных на уровне объявления вам понадобятся:

Примечание. Если администраторы Страницы ещё не настраивали лиды и не предоставляли разрешения в Leads Access Manager, это значит, что разрешение на доступ к лидам есть у ВСЕХ администраторов Страницы. Если разрешение на доступ к лидам настроили администраторы компании, его наличие у обычного администратора Страницы будет зависеть от этой настройки.

Начиная с версии 9.0 получение лидов для приложения в режиме разработки не поддерживается. Для тестирования пользователи приложения в режиме разработки могут работать с лидами, предоставленными другим пользователем, имеющим роль в этом приложении. См. статью о ролях в приложении. У приложений в рабочем режиме по-прежнему будет доступ ко всем лидам.

Ограничения числа обращений

Ограничение числа обращений вычисляется по следующей формуле: 200 × 24 × количество лидов, созданных для Страницы Facebook за последние 30 дней. Если количество вызовов за 24 часа превысит это число, запросы будут возвращать ошибку.

Фильтрация по диапазону дат

Отправьте запрос GET к конечной точке /ads/lead_gen/export_csv/ (даты должны быть представлены в формате меток времени POSIX или UNIX ):

В случае успеха приложение получит следующий ответ: