Facebook Business SDK for PHP

repository·main·Indexed 19 days ago

https://github.com/facebook/facebook-php-business-sdk

A unified PHP library that bundles multiple Facebook APIs, including the Marketing API, Pages, Business Manager, and Instagram. It provides tools for CRUD operations on Graph API objects, bidirectional pagination via Cursors, and a server-side client for the Conversions API with automatic parameter filling via setRequestContext(). The SDK requires PHP 8.0 or greater and is installed via Composer.

Tokens
11.9K
Snippets
45
Records
51
Agent score
74%

What's inside facebook-php-business-sdk

  1. Use Field definitions for objects

    main

    To avoid using hardcoded strings and to benefit from validation, use the field definition classes located in the FacebookAds\Object\Fields namespace. You can use these constants with setData() or via direct property assignment.

    // Using field definitions with setData
    $someObject->setData(array(
      MyObjectFields::ID => 1234,
      MyObjectFields::NAME => 'My Name',
    ));
    
    // Using field definitions with direct assignation
    $someObject->{SomeObjectFields::ID} = 123;
    
    // Equivalent to using string names
    $someObject->id = 123;
  2. Iterate through results using Cursors

    main

    Pagination in the SDK is handled via FacebookAds\Cursor objects returned by connection methods. Cursors are bidirectional and support both forward and reverse iteration.

    Implicit Fetching: By default, cursors do not automatically fetch new pages. If enabled, the cursor will automatically fetch and append new pages as you iterate through the end of the current page. This can lead to many unexpected HTTP requests, so use it with caution.

    use FacebookAds\Object\AdAccount;
    use FacebookAds\Object\Fields\CampaignFields;
    
    $account = new AdAccount('<ACT_ID>');
    $cursor = $account->getCampaigns(['id','name']);
    
    // Enable implicit fetching to automatically load next pages during iteration
    $cursor->setUseImplicitFetch(true);
    
    foreach ($cursor as $campaign) {
        echo $campaign->{CampaignFields::NAME} . PHP_EOL;
    }
    
    // Reverse iteration
    $cursor->end();
    while ($cursor->valid()) {
        echo $cursor->current()->id . PHP_EOL;
        $cursor->prev();
    }
  3. Use Field Enums for object properties

    main

    To maintain code stability and avoid typos, the SDK provides enum-like classes for Graph API field names. These are located in the FacebookAds/Object/Fields directory. You can access object properties using these enums with the curly brace syntax.

    use FacebookAds\Object\AdAccount;
    use FacebookAds\Object\Fields\AdAccountFields;
    
    $account = new AdAccount();
    // Using the enum for the field name
    $account->{AdAccountFields::NAME} = 'My account name';
    echo $account->{AdAccountFields::NAME};
  4. Handle multiple access tokens and sessions

    main

    By default, the SDK uses a static reference to the first Api instance created. To manage multiple sessions (e.g., syncing data for multiple users) in a single script, you have two options:

    1. Mutate the default instance: Use Api::instance() to get the current instance or Api::setInstance($api) to replace the global default.
    2. Explicitly define the instance per object: Pass the specific Api instance to the constructor of any class extending Object\AbstractCrudObject.
    use FacebookAds\Object\Ad;
    $my_ad = new Ad($id, $parent_id=null, $api);
  5. Bootstrap the Facebook Ads SDK

    main

    To use the SDK, you must first include the Composer autoloader and initialize the FacebookAds\\Api class with your application credentials and an access token. This sets up the global state for making requests.

    <?php
    define('SDK_DIR', '/path/to/sdk/'); // Path to the SDK directory 
    
    $loader = include SDK_DIR.'/vendor/autoload.php';
    
    use FacebookAds\Api;
    
    Api::init($app_id, $app_secret, $access_token);
  6. Extend the SDK: Defining Default Fields to Read

    main

    By default, calling read() on an AbstractCrudObject requests no fields. To always request a specific set of fields, extend the target class (e.g., AdAccount) within your own namespace and override the protected static variable $defaultReadFields with an array of desired field constants.

    namespace MyNamespace\Object;
    
    use FacebookAds\Object\Fields\AdAccountFields;
    
    class AdAccount extends FacebookAds\Object\AdAccount {
    
      protected static $defaultReadFields = array(
        AdAccountFields::ID,
        AdAccountFields::NAME,
        AdAccountFields::DAILY_SPEND_LIMIT,
        AdAccountFields::CURRENCY,
      );
    }
    
    // Usage:
    use MyNamespace\Object\AdAccount;
    $adaccount = (new AdAccount($id))->read();
  7. Auto-fill Conversions API parameters with setRequestContext()

    main

    The SDK integrates with the capi-param-builder to automatically extract and fill key event parameters (like fbc, fbp, client_ip_address, etc.) from the incoming HTTP request.

    By calling setRequestContext() on an Event object and passing your server's request data (e.g., $_SERVER), the SDK will automatically populate empty fields during execution. This process is non-destructive (it won't overwrite values you've already set) and handles SHA-256 hashing for customer information automatically.

    use FacebookAds\Object\ServerSide\Event;
    use FacebookAds\Object\ServerSide\UserData;
    use FacebookAds\Object\ServerSide\ActionSource;
    
    $event = (new Event())
      ->setEventName('Purchase')
      ->setEventTime(time())
      ->setUserData((new UserData())->setEmail('joe@eg.com'))
      ->setActionSource(ActionSource::WEBSITE)
      // Pass the server request context to enable auto-filling of fbc, fbp, ip, etc.
      ->setRequestContext($_SERVER);
  8. Debug API requests using CurlLogger

    main

    If you are experiencing issues with the SDK, you can determine if the problem lies with the SDK or the Facebook API by inspecting the raw cURL request being sent. You can do this by attaching a CurlLogger to the Api instance. This will print the exact cURL command to your console, which you can then use to test the request independently.

    require __DIR__ . '/vendor/autoload.php';
    use FacebookAds\Api;
    use FacebookAds\Object\AdAccount;
    use FacebookAds\Logger\CurlLogger;
    
    // Initialize the API
    Api::init($app_id, $app_secret, $access_token);
    $api = Api::instance();
    
    // Attach the logger to see the raw cURL request in the console
    $api->setLogger(new CurlLogger());
    
    $account = new AdAccount($account_id);
    $account->read(array('id'));
  9. Extend the SDK: Requesting Connections with Generic Methods

    main

    If you have extended SDK classes and want to ensure connection helper methods return your custom namespace types instead of the base FacebookAds types, use the generic connection methods: getOneByConnection or getManyByConnection. These allow you to specify the target class name explicitly.

    use FacebookAds\Object\AdAccount;
    use MyNamespace\Object\Ad;
    
    $account = new AdAccount($id);
    $my_adaccount_objects = $account->getManyByConnection(
      Ad::className(), 
      $fields = array(...), 
      $params = array(...)
    );
  10. Run unit and integration tests

    main

    The SDK includes both unit and integration tests. Integration tests require an active Facebook Ad Account, a Facebook Application, and a valid Access Token.

    1. Install dependencies:

    php composer.phar install --dev

    2. Run unit tests only: Use the specific configuration file for unit tests:

    ./vendor/bin/phpunit -c test/phpunit-travis.xml

    3. Run all tests (unit + integration): First, create your integration configuration by copying the template:

    cp test/config.php.dist test/config.php

    Edit test/config.php with your credentials, then execute:

    ./vendor/bin/phpunit -c test/