Code Monkey home page Code Monkey logo

facebook-php-business-sdk's Introduction

Facebook Business SDK for PHP

Packagist License Build Status

Introduction

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 serve 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.

Quick Start

Business SDK Getting Started Guide

Pre-requisites

Register An App

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

To manage the Marketing API, please visit your App Dashboard and add the Marketing API product to your app.

IMPORTANT: For security, it is recommended that you turn on 'Require App Secret' 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.

Installation

The Facebook Business SDK requires PHP 8.0 or greater.

Composer

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

Execute the command below in your project root:

composer require facebook/php-business-sdk

This SDK and its dependencies will be installed under ./vendor.

Alternatives

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

Usage

Api main class

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:

use FacebookAds\Api;

// Initialize a new Session and instantiate an Api object
Api::init($app_id, $app_secret, $access_token);

// The Api object is now available through singleton
$api = Api::instance();

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

Fields names

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:

use FacebookAds\Object\AdAccount;

$account = new AdAccount();
$account->name = 'My account name';
echo $account->name;

or using the enums:

use FacebookAds\Object\AdAccount;
use FacebookAds\Object\Fields\AdAccountFields;

$account = new AdAccount();
$account->{AdAccountFields::NAME} = 'My account name';
echo $account->{AdAccountFields::NAME};

Object classes

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

Read Objects

use FacebookAds\Object\AdAccount;

$account = (new AdAccount($account_id))->getSelf();

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.

use FacebookAds\Object\AdAccount;
use FacebookAds\Object\Fields\AdAccountFields;

$fields = array(
  AdAccountFields::ID,
  AdAccountFields::NAME,
);

$account = (new AdAccount($account_id))->getSelf($fields);

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

Create Objects

use FacebookAds\Object\AdSet;
use FacebookAds\Object\AdAccount;
use FacebookAds\Object\Fields\AdSetFields;

$account_id = 'act_123123';
$campaign_id = '123456';

$account = new AdAccount($account_id);
$adset = $account->createAdSet(
    array(),
    array(
      AdSetFields::NAME => 'My Test AdSet',
      AdSetFields::CAMPAIGN_ID => $campaign_id,
      AdSetFields::DAILY_BUDGET => 150,
      AdSetFields::START_TIME => (new \DateTime("+1 week"))->format(\DateTime::ISO8601),
      AdSetFields::END_TIME => (new \DateTime("+2 week"))->format(\DateTime::ISO8601),
      AdSetFields::BILLING_EVENT => 'IMPRESSIONS',
      AdSetFields::TARGETING => array('geo_locations' => array('countries' => array('US'))),
      AdSetFields::BID_AMOUNT => '1000',
    )
);

echo $adset->id;

Update Objects

use FacebookAds\Object\AdSet;
use FacebookAds\Object\Fields\AdSetFields;

$ad_set_id = '123456';

$set = new AdSet($ad_set_id);
$fields = array(
);
$params = array(
  AdSetFields::NAME => 'My new AdSet name',
);
$set->updateSelf($fields, $params);

Delete Objects

use FacebookAds\Object\AdSet;

$ad_set_id = '123456';

$set = new AdSet($ad_set_id);
$set->deleteSelf();

Cursors

Since the release of the Facebook Graph API 2.0, pagination is handled through cursors. Here cursors are defined as in \FacebookAds\Cursor. Cursors are generally returned from connection methods:

use FacebookAds\Object\AdAccount;
use FacebookAds\Object\Fields\CampaignFields;

$account = new AdAccount('<ACT_ID>');
$cursor = $account->getCampaigns(['id','name']);

// Loop over objects
foreach ($cursor as $campaign) {
  echo $campaign->{CampaignFields::NAME}.PHP_EOL;
}

// Access objects by index
if ($cursor->count() > 0) {
  echo "The first campaign in the cursor is: ".$cursor[0]->{CampaignFields::NAME}.PHP_EOL;
}

// Fetch the next page
$cursor->fetchAfter();
// New Objects will be appended to the cursor

Implicit Fetching

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:

$cursor->setUseImplicitFetch(true);

Or globally:

use FacebookAds\Cursor;

Cursor::setDefaultUseImplicitFetch(true);

Reverse Iterations

Cursors are bidirectional, and can be iterated in reverse order:

use FacebookAds\Object\AbstractCrudObject;

/** @var \FacebookAds\Cursor $cursor */
$cursor->setUseImplicitFetch(true);

$cursor->end();
while ($cursor->valid()) {
  echo $cursor->current()->{AbstractCrudObject::FIELD_ID}.PHP_EOL;
  $cursor->prev();
}

Tests

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.

Install dependencies

From the root folder run:

php composer.phar install --dev

Execute unit tests only

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

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

./vendor/bin/phpunit -c test/phpunit-travis.xml path/to/class/file

Execute all tests (unit + integration)

Setup your integration config:

1 - Copy the config file template.

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

2 - Edit test/config.php with your information.

Execute:

./vendor/bin/phpunit -c test/

To run tests individually:

./vendor/bin/phpunit -c test/ path/to/class/file

Debug

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

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

for example:

require __DIR__ . '/vendor/autoload.php';
use FacebookAds\Api;
use FacebookAds\Object\AdAccount;

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

use FacebookAds\Logger\CurlLogger;
$api->setLogger(new CurlLogger());
$account = new AdAccount($account_id);
$account->read(array('id'));

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

curl -G \
  -d 'fields=id' \
  -d 'access_token=<access_token>' \
  https://graph.facebook.com/v3.1/<act_accountid>

SDK Codegen

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

Issue

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.

facebook-php-business-sdk's People

Contributors

alexlupu avatar ashpants avatar daniel15 avatar davit-y avatar donglinw-fb avatar duliomatos avatar heymultiverse avatar jessem avatar jingping2015 avatar jordanrs avatar kongxinzhu avatar leorentkelmendi avatar lintaocui avatar marksliva avatar natewiebe13 avatar neilxchen avatar neovdr avatar nicobn avatar paulbain avatar pruno avatar shootingsyh avatar stcheng avatar tekill avatar vicdus avatar vl-lapikov avatar w43l avatar windsfantasy6 avatar yamsellem avatar yfb avatar zoonman avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

facebook-php-business-sdk's Issues

What is the error in the following code

function gogingtoevent() {
FB.login(function(response) {
if (response.status == 'connected') {
FB.api('/816891388384961/attending',
function (response) {
if (response && !response.error) {
alert('Attending');
}else{
alert (JSON.stringify(response));
}
});
}else{
alert('Not Responding');
}
});
}

Ad Stats Report

Hello,

I upgraded to php version 5.4.36. Installed the composer and installed the The Facebook Ads API SDK and even after that, when I execute the php script, I get the below error

PHP Fatal error: Class 'FacebookAds\Object\AdAccount' not found in /tmp/vendor/facebook/php-ads-sdk/src/FacebookAds/fb.php on line 3

PHP Code

name = 'act_5291585038833333'; echo $account->name; $params = array( 'date_preset'=>'last_28_days', 'data_columns'=>"['adgroup_id','actions','spend']", ); $stats = $account->getReportsStats(null, $params); foreach($stats as $stat) { echo $stat->impressions; echo $stat->actions; } any information will be highly appreciated

i got a error Fatal error: Class 'Facebook\Entities\AccessToken' not found

Hi,
i integrate facebook ads api into my server. 80% of works are completed in server. but finally i got a issue

Fatal error: Class 'Facebook\Entities\AccessToken' not found

Many pages i saw this code

use Facebook\FacebookSession;

so i include facebook sdk into my src folder. but no use. please help me where i put facebook sdk and please guide me how can i solve the issue please help me.

More examples, AdGroup

Sorry, not strictly an issue. But I wonder if there are plans to add more examples? As the SDK format has changed, I'm having a few issues - such as trying to read conversion stats about an ad group. I can't quite figure out how to extract this information so an adgroup example would be perfect!

Invalid appsecret_proof provided in the API argument????

Hi,
I have completed the facebook php ads sdk installation in my server. I got the following error
" Invalid appsecret_proof provided in the API argument????",

while executing this ./vendor/bin/phpunit -c test/. So, please advice us to fix this issue.

InvalidArgumentException thrown when getting an AdAccounts AdVideos from API v2.3

/v2.2/act_<account id>/advideos does not return a published field, /v2.3/act_<account id>/advideos does (see example payload below)

We are using facebook-php-ads-sdk v2.3.0

When we call the getAdVideos method (with no fields specified) on FacebookAdAccount we get an InvalidArgumentException with message: "published is not a field of FacebookAds\Object\AdVideo"

This originates at AbstractCrudObject::setData

public function setData(array $data) {
    foreach ($data as $key => $value) {
      $this->{$key} = $value;
    }
    return $this;
  }

Since AdVideo has no published field, when the above loop tries to set $this->published = true; the exception is thrown

Example (truncated) response to https://graph.facebook.com/v2.3/act_<account id>/advideos showing the published field

{
   "data":[
      {
         "id":"10153079548779999",
         "created_time":"2015-02-06T00:47:59+0000",
         "embed_html":"\u003Ciframe src=\"https:\/\/www.facebook.com\/video\/embed?video_id=10153079548779999\" width=\"640\" height=\"360\" frameborder=\"0\">\u003C\/iframe>",
         "format":[
            {
               "embed_html":"\u003Ciframe src=\"https:\/\/www.facebook.com\/video\/embed?video_id=10153079548779999\" width=\"130\" height=\"73\" frameborder=\"0\">\u003C\/iframe>",
               "filter":"130x130",
               "height":73,
               "picture":"https:\/\/fbcdn-vthumb-a.akamaihd.net\/hvthumb-ak-xpa1\/v\/t15.0-10\/p160x160\/10751484_10153079548948234_10153079548779999_45692_1846_b.jpg?oh=cf67559e145d3263bca51c6d65c9e368&oe=559993A4&__gda__=1436187962_3ce5195f0f021bfd58db8327fbc4e7e4",
               "width":130
            },
            {
               "embed_html":"\u003Ciframe src=\"https:\/\/www.facebook.com\/video\/embed?video_id=10153079548779999\" width=\"480\" height=\"270\" frameborder=\"0\">\u003C\/iframe>",
               "filter":"480x480",
               "height":270,
               "picture":"https:\/\/fbcdn-vthumb-a.akamaihd.net\/hvthumb-ak-xpa1\/v\/t15.0-10\/10751484_10153079548948234_10153079548779999_45692_1846_b.jpg?oh=c3322afcd9f3bc19c2f07d0e3dcb426b&oe=559F214F&__gda__=1437469064_d432d6764194e4ad83ffb2cb61c08318",
               "width":480
            },
            {
               "embed_html":"\u003Ciframe src=\"https:\/\/www.facebook.com\/video\/embed?video_id=10153079548779999\" width=\"640\" height=\"360\" frameborder=\"0\">\u003C\/iframe>",
               "filter":"native",
               "height":360,
               "picture":"https:\/\/fbcdn-vthumb-a.akamaihd.net\/hvthumb-ak-xpa1\/v\/t15.0-10\/10751484_10153079548948234_10153079548779999_45692_1846_b.jpg?oh=c3322afcd9f3bc19c2f07d0e3dcb426b&oe=559F214F&__gda__=1437469064_d432d6764194e4ad83ffb2cb61c08318",
               "width":640
            }
         ],
         "from":{
            "id":"10152896328398234",
            "name":"Bob Smith"
         },
         "icon":"https:\/\/fbstatic-a.akamaihd.net\/rsrc.php\/v2\/yD\/r\/DggDhA4z4tO.gif",
         "name":"foom",
         "picture":"https:\/\/fbcdn-vthumb-a.akamaihd.net\/hvthumb-ak-xpa1\/v\/t15.0-10\/p128x128\/10751484_10153079548948234_10153079548779999_45692_1846_b.jpg?oh=b42d46364120c5870fe441d990bad170&oe=55A7A49F&__gda__=1438055169_0bb3c601a8f7e56145e9b916a615a65a",
         "source":"https:\/\/scontent.xx.fbcdn.net\/hvideo-xpa1\/v\/t43.1792-2\/10921600_755745654516018_992090670_n.mp4?rl=1500&vabr=352&oh=505e56d7b85b24a2854b2c6c46e8287c&oe=552737A4",
         "updated_time":"2015-02-06T00:48:03+0000",
         "published":true
      },
      ...
   ],
   "paging":{
      "cursors":{
         "before":"MTAxNTMwNzk1NDg3NzMyMzQ=",
         "after":"MTAxNTI4OTY5MDk0ODMyMzQ="
      }
   }
}

help with FacebookPermissionException

Hello,

I am getting this error:

Facebook\FacebookPermissionException
(#294) Managing advertisements requires the extended permission ads_management and an application that is whitelisted to access the Ads API

I'm not sure what to try or who to contact. Any help would be greatly appreciated.

Which ID do I use ?

I am using a user id in my campaign creation like so: (All permissions granted etc. on my App and user. )

//    $session = new FacebookSession($variantSpec->account->token);
    $session = FacebookSession::newAppSession(Config::get('facebook.app_id'),Config::get('facebook.app_secret'));

    $api = new Api($session);
    $campaign  = new AdCampaign(null, $user->ad_account_id);

and I get the following error form both attempts:

  • The global ID XXX is not allowed. Please use the application specific ID instead.

So where do I get the Application Specific ID

I tried passing in the same Config::get('facebook.app_id')

thanks in advance

Provide additional error data through RequestException

The API often responds with helpful error messages that aren't available through the Ads SDK, specifically through RequestException. Would you accept an additional public method or two on this class for returning the error_user_title and error_user_msg from https://developers.facebook.com/docs/graph-api/using-graph-api/v2.2#receiving-errorcodes ?

For example: bjeavons@f9a39e2

There could be methods for error subcode, user error title, and user error message. Or, those could be returned as an array from a single method.

Start Time is Null when getStats

Hi ,

$adsets = $campaign->getAdSets(array(
AdSetFields::ACCOUNT_ID,
AdSetFields::CAMPAIGN_STATUS,
AdSetFields::BID_TYPE,
AdSetFields::BID_INFO,
AdSetFields::BUDGET_REMAINING,
AdSetFields::NAME,
AdSetFields::DAILY_BUDGET,
AdSetFields::PROMOTED_OBJECT,
AdSetFields::UPDATED_TIME,
AdSetFields::LIFETIME_BUDGET,
AdSetFields::IS_AUTOBID,
),$params);
foreach ($adsets as $key => $adset) {
var_dump($adset->getStats());
echo '
';
}

Result
object(FacebookAds\Object\AdStats)#483 (1) { ["data":protected]=> array(18) { ["id"]=> string(32) "6025149647218/stats/0/1427871600" ["impressions"]=> int(218) ["topline_id"]=> NULL ["clicks"]=> int(7) ["spent"]=> int(198) ["social_impressions"]=> int(0) ["social_clicks"]=> int(0) ["social_spent"]=> int(0) ["unique_impressions"]=> int(212) ["social_unique_impressions"]=> int(0) ["actions"]=> array(2) { ["post_like"]=> int(2) ["photo_view"]=> int(2) } ["inline_actions"]=> array(14) { ["title_clicks"]=> int(0) ["like"]=> int(0) ["rsvp_yes"]=> int(0) ["rsvp_maybe"]=> int(0) ["post_like"]=> int(3) ["comment"]=> int(0) ["photo_view"]=> int(2) ["link_click"]=> int(0) ["video_play"]=> int(0) ["question_vote"]=> int(0) ["cta_click"]=> int(0) ["item_click_1"]=> int(0) ["item_click_2"]=> int(0) ["item_click_3"]=> int(0) } ["unique_clicks"]=> int(7) ["social_unique_clicks"]=> int(0) ["campaign_id"]=> string(13) "6025149647218" ["start_time"]=> NULL ["end_time"]=> string(24) "2015-04-01T07:00:00+0000" ["is_completed"]=> bool(false) } }

I see start time = NULL

How to get start_time for adset

Thanks

Implicit fetching fails due to null request

When trying out implicit fetch, iteration fails with: "__clone method called on non-object" in Cursor.php line 217.

Sample code that fails

//Some fields
//Some account
$campaigns = $ad_account->getAdCampaigns($fields);
$campaigns->setUseImplicitFetch(true);
foreach($campaigns as $campaign){
            echo $campaign->getData();
        }

Get start day for Campaign

Hi ,

$campaign_new = new AdCampaign($campaign->id) ;
$fields = array(
'actions','spent','clicks','impressions','end_time','start_time',
);
$params = array();
$stats = $campaign_new->getStats($fields,$params);
var_dump($stats);

But function doesn't show start_time and how to parse data from ojbect :
object(FacebookAds\Cursor)#483 (9) { ["response":protected]=> object(FacebookAds\Http\Response)#482 (5) { ["request":protected]=> object(FacebookAds\Http\Request)#480 (10) { ["client":protected]=> object(FacebookAds\Http\Client)#456 (6) { ["requestPrototype":protected]=> object(FacebookAds\Http\Request)#458 (10) { ["client":protected]=> RECURSION ["headers":protected]=> NULL ["method":protected]=> string(3) "GET" ["protocol":protected]=> string(8) "https://" ["domain":protected]=> NULL ["path":protected]=> NULL ["graphVersion":protected]=> NULL ["queryParams":protected]=> NULL ["bodyParams":protected]=> NULL ["fileParams":protected]=> NULL } ["responsePrototype":protected]=> object(FacebookAds\Http\Response)#468 (5) { ["request":protected]=> NULL ["statusCode":protected]=> NULL ["headers":protected]=> NULL ["body":protected]=> NULL ["content":protected]=> NULL } ["defaultRequestHeaders":protected]=> object(FacebookAds\Http\Headers)#470 (1) { ["storage":"ArrayObject":private]=> array(2) { ["User-Agent"]=> string(16) "fb-php-ads-2.3.0" ["Accept-Encoding"]=> string(1) "" } } ["adapter":protected]=> object(FacebookAds\Http\Adapter\CurlAdapter)#466 (3) { ["curl":protected]=> object(FacebookAds\Http\Adapter\Curl\Curl)#467 (1) { ["handle":protected]=> resource(245) of type (curl) } ["opts":protected]=> object(ArrayObject)#471 (1) { ["storage":"ArrayObject":private]=> array(5) { [78]=> int(10) [13]=> int(60) [19913]=> bool(true) [42]=> bool(true) [10065]=> string(109) "/Users/Ken/Sites/adsfacebook/vendor/facebook/php-ads-sdk/src/FacebookAds/Http/../../../fb_ca_chain_bundle.crt" } } ["client":protected]=> *RECURSION } ["caBundlePath":protected]=> string(109) "/Users/Ken/Sites/adsfacebook/vendor/facebook/php-ads-sdk/src/FacebookAds/Http/../../../fb_ca_chain_bundle.crt" ["defaultGraphBaseDomain":protected]=> string(12) "facebook.com" } ["headers":protected]=> object(FacebookAds\Http\Headers)#484 (1) { ["storage":"ArrayObject":private]=> array(2) { ["User-Agent"]=> string(16) "fb-php-ads-2.3.0" ["Accept-Encoding"]=> string(1) "" } } ["method":protected]=> string(3) "GET" ["protocol":protected]=> string(8) "https://" ["domain":protected]=> string(18) "graph.facebook.com" ["path":protected]=> string(20) "/6025149646418/stats" ["graphVersion":protected]=> string(3) "2.3" ["queryParams":protected]=> object(FacebookAds\Http\Parameters)#481 (1) { ["storage":"ArrayObject":private]=> array(3) { ["fields"]=> string(52) "actions,spent,clicks,impressions,end_time,start_time" ["access_token"]=> string(213) "CAALZCQzTpi7UBAK3F6rjTXORgIJnXF1wxq3BluUUtQH2Cm0YMVgdcWuB7f83vERjPSPd3m1VVZBxAsuRw5oNez0wa37mZCgMRJ87guLCnhfI6ehd5a1vLVv4B6Oq1PQmnG5pKB4uGzbEwp7hpMWTg6cI7YTJxuAbrXtUwwJ6D2GUrpOtBhFUjnF3DqXAYWfBfdeD7QjZBxnQiR0pRb59" ["appsecret_proof"]=> string(64) "9e135d0c4855dbd73575646fc37b71b2947541f27d75864696a4c3236301021b" } } ["bodyParams":protected]=> NULL ["fileParams":protected]=> NULL } ["statusCode":protected]=> int(200) ["headers":protected]=> object(FacebookAds\Http\Headers)#485 (1) { ["storage":"ArrayObject":private]=> array(14) { ["http_code"]=> string(15) "HTTP/1.1 200 OK" ["Content-Type"]=> string(31) "application/json; charset=UTF-8" ["Access-Control-Allow-Origin"]=> string(1) "" ["X-FB-Rev"]=> string(7) "1669049" ["ETag"]=> string(42) ""290ffcc1aa378a2302f6353daf5639ec8f3bc774"" ["Pragma"]=> string(8) "no-cache" ["Cache-Control"]=> string(44) "private, no-cache, no-store, must-revalidate" ["Facebook-API-Version"]=> string(4) "v2.3" ["Expires"]=> string(29) "Sat, 01 Jan 2000 00:00:00 GMT" ["Vary"]=> string(15) "Accept-Encoding" ["X-FB-Debug"]=> string(88) "l5nXrAemhNdrH4UUmegGQTPpfiG/ErEjfonPYfS8RLVrbSRlJgcRymlrchpQvCXKOo5IGTbgVE7eCqOC3w/f7w==" ["Date"]=> string(29) "Wed, 01 Apr 2015 01:39:14 GMT" ["Connection"]=> string(10) "keep-alive" ["Content-Length"]=> string(3) "182" } } ["body":protected]=> string(182) "{"data":[{"actions":{"photo_view":4,"post":1,"post_like":4,"page_engagement":9,"post_engagement":9},"spent":358,"clicks":16,"impressions":422,"end_time":"2015-04-01T01:39:14+0000"}]}" ["content":protected]=> array(1) { ["data"]=> array(1) { [0]=> array(5) { ["actions"]=> array(5) { ["photo_view"]=> int(4) ["post"]=> int(1) ["post_like"]=> int(4) ["page_engagement"]=> int(9) ["post_engagement"]=> int(9) } ["spent"]=> int(358) ["clicks"]=> int(16) ["impressions"]=> int(422) ["end_time"]=> string(24) "2015-04-01T01:39:14+0000" } } } } ["objects":protected]=> array(1) { [0]=> object(FacebookAds\Object\AdStats)#487 (1) { ["data":protected]=> array(5) { ["actions"]=> array(5) { ["photo_view"]=> int(4) ["post"]=> int(1) ["post_like"]=> int(4) ["page_engagement"]=> int(9) ["post_engagement"]=> int(9) } ["spent"]=> int(358) ["clicks"]=> int(16) ["impressions"]=> int(422) ["end_time"]=> string(24) "2015-04-01T01:39:14+0000" } } } ["indexLeft":protected]=> int(0) ["indexRight":protected]=> int(0) ["position":protected]=> int(0) ["after":protected]=> NULL ["before":protected]=> NULL ["objectPrototype":protected]=> object(FacebookAds\Object\AdStats)#486 (1) { ["data":protected]=> array(0) { } } ["useImplicitFectch":protected]=> NULL }
Thanks

Travis-ci integration?

Have you considered travis-ci integration for automated testing and reporting?

Since the tests currently use a live FB app and ad account any automated testing may require:

  1. an available test app and ad account for travis' use
  2. or, configure travis testing to not require remote calls and thus no app, account, or access token

I suspect option 2 is the most likely.

Reservation of ReachFrequencyPrediction not working.

The method ReachFrequencyPrediction::reserve() throws an exception 'Array to string conversion' on line 116.

$response->getContent() returns an associative array with the ID of the prediction, but it's typecasted to a string.

Business Manager Objects

Currently the SDK doesn't support the business manager.

At first glance, it looks like we would need:

  1. a systemuser object which would allow systemuser creation and system user token generation.

  2. a page object to add a page to the businessmanager as an owner or agency.

Are there any plans currently to implement these new objects?

List a tag's campaigns

The following code:

(new AdTag($id))->getAdCampaigns($fields);

Returns this error:

(#275) Ad account cannot be determined for this request

Is there a way to limit the tag campaigns list to a given account to avoid this?
Are we supposed to add some permission to the account?

Bonus point: In the tag's docs, it's also said one can list every tags with https://graph.facebook.com/<API_VERSION>/act_<AD_ACCOUNT_ID>/adtags.
Is there a way to do so with this library? Account does not expose a getTags() method

Bonus point: is there a way to find a tag by name?

How do I get Ad Report Stats via the SDK?

I can't figure out how to make calls to reportstats using the SDK.
The class AdAccount do have a method named getReportsStats() which takes an array of fields and an array of parameters as arguments, so I tried something like this:

    $fields = array('account_id', 'total_actions', 'spend'); // The fields I ask for?
    $params = array(
        'data_columns' => array (
            'account_id',
            'total_actions',
            'spend'
        ),
        'date_preset' => 'last_7_days',
    );

    $account = new AdAccount('act_' . $accountID);
    $account->getReportsStats($fields, $params);
    return json_encode($account->getData());        

However this just returns the ad account data, not the actual stats.
When I examined the object $account after the call to getReportsStats() method I found that it did indeed contain the stats. Still getData() doesn't return it. Am I supposed to use some other method to get the stats?

Cursor paging non functional

I encountered an issue with the 2.2.0 version of the ads sdk. When calling getAdCampaigns() on an ad account, the cursor I am receiving only contains 25 objects instead of the 45 that I am expecting.

I was under the impression that you simply need to iterate with a foreach and the cursor handles pagination itself.
Is this a bug or am I doing something incorrectly?

Code:

$campaigns = $ad_account->getAdCampaigns([
                AdCampaignFields::ID,
                AdCampaignFields::ACCOUNT_ID,
                AdCampaignFields::OBJECTIVE,
                AdCampaignFields::NAME,
                AdCampaignFields::STATUS
            ]);
foreach($campaigns as $campaign){
                $return_object[] = $campaign->getData();
            }

error when creating custom audience

The code:

use \FacebookAds\Api;
use \FacebookAds\Object\CustomAudience;
use \FacebookAds\Object\Fields\CustomAudienceFields;

Api::init($app_id, $app_secret, $access_token);

$audience = new CustomAudience(null, $account_id);
$audience->setData(array(
    CustomAudienceFields::NAME => 'test',
    CustomAudienceFields::DESCRIPTION => 'test',
    CustomAudienceFields::DATA_SOURCE => array('EVENT_BASED' => 'WEB_PIXEL_HITS'),
));
$audience->create();

The error:

(#2655) Terms of service has not been accepted

I have 2 questions:

  1. How do I agree to the terms of service? When I create a custom audience through the web interface there is a checkbox each time I create one.
  2. Am I setting the DATA_SOURCE correctly? I want an audience based on hits to a single page. The code I used is based of the docs here, but there is no clear example for the specific scenario I want:
    https://developers.facebook.com/docs/reference/ads-api/custom-audience-targeting/#data_source

error when performing TargetingSearch as per the example

Here is my code:

\FacebookAds\Api::init($app_id, $app_secret, $access_token);
$results = \FacebookAds\Object\TargetingSearch::search(
    $type = \FacebookAds\Object\Search\TargetingSearchTypes::INTEREST,
    $class = null,
    $query = 'facebook'
);
print_r($results);

The error is:
Argument 1 passed to FacebookAds\Cursor::__construct() must implement interface FacebookAds\Http\ResponseInterface, array given, called in /vagrant/app/vendor/facebook/php-ads-sdk/src/FacebookAds/Object/TargetingSearch.php on line 74 and defined in file /vagrant/app/vendor/facebook/php-ads-sdk/src/FacebookAds/Cursor.php at line 84

Permission error accessing reports as analyst

I'm trying to get reports for a Facebook Ads account. I have successfully made a connection and added my account as an Analyst to the business account.

This is the code I'm using to connect:

$session = $this->facebook->getSession();

        $ads = new Api($session);

        $account = new AdAccount('act_' . Config::get('services.facebook.adAccountId'));

        $fields = array('account_id', 'total_actions', 'spend');

        $params = array(
            'data_columns' => array (
                'account_id',
                'total_actions',
                'spend'
            ),
            'date_preset' => 'last_7_days',
        );


        $reports = $account->getReportsStats($fields, $params);

However I'm getting the following error when making the call:

(#273) This Ads API call requires the user to be admin of the ad account. User xxxxxxxx not admin on ad account xxxxxxxxxxxxxxxxxxxxxxx.

Why would I need to be an admin when I can access the reports from the webinterface with an analyst account?

Ad Creation Error

Everything in the script works perfectly, except the last segment of ad group creation. I've spend two hours editing the parameters and also looked at the class parameters at /src/FacebookAds/Object/Fields/AdGroupFields.php

After trying every combination it still spits out the "Invalid parameter" error. Not sure why this is happening. Hope someone can shed light on this.

Cursor Implicit Fetch doesn't work with reportstats.

The response for the <Ad_acct>/reportstats endpoint returns the paging information as follows:

{
  "paging": {
    "next": "<the_url>",
    "previous": "<the_url>",
  }
}

However, the cursor expects to see ["paging"]["cursor"]["after"], as which is returned in the responses for the other endpoints.

Is this a new change to the API?

How to get stats of multiple campaigns using Facebook Ads PHP SDK

Hello,

I write the below code for retrieve single campaign stats.

$fields = array(
'start_time','actions','spent','clicks','impressions','end_time',
);
$params = array();
$campaign = new AdCampaign(123456);
$stats = $campaign->getStats($fields, $params);

here I can able to access the stats. But when use this function loop then I got issue like

Calling : $campaign = new AdCampaign($campaign_id);
Error : "An access token is required to request this resource"

But using graph API I can access the multiple campaigns stats at a time

https://graph.facebook.com/stats?ids=123,456,789&fields=start_time,actions,spent,clicks,impressions,end_time&access_token=...

I need it using Ads API .... Please solve it for me..

DemographicSearchClasses namespace causes autoloader problems.

The DemographicsSearchClasses.php file in src/FacebookAds/Object/Search/ has the namespace:

namespace FacebookAds\Targeting;

This causes problems for the autoloader and on execution of code that uses it you get the error "Fatal error: Class 'FacebookAds\Targeting\DemographicSearchClasses' not found in...".

However when I change the namespace in DemographicSearchClasses to match the folder layout like so: namespace FacebookAds\Object\Search; the problems go away!

Is this a bug or is it something that I am doing wrong?

I can't create ad group!

With Facebook Ad Api, I can't create ad(group) although I have created the Campaign, AdSet, and AdCreative. I have followed instruction of facbook guide(with the all required parameters). I can't find the answer by any googling.... What's wrong? (I just found the change that ADGROUP_STATUS is required now.)

------------ PHP Codes ------------------

use FacebookAds\Object\AdGroup;
use FacebookAds\Object\Fields\AdGroupFields;

$adgroup = new AdGroup(null, $account->id);
$adgroup->setData(array(
AdGroupFields::CREATIVE => array('creative_id' => $creative->id),
AdGroupFields::NAME => 'My First AdGroup',
AdGroupFields::CAMPAIGN_ID => $adset->id,
AdGroupFields::ADGROUP_STATUS => 'ACTIVE',
));

$adgroup->create();

No WebHooks for packagist.

Due to the absence of WebHooks, the dev-master in packagist.org is not the latest. Moreover, the latest tagged version on packagist does not correspond with the latest github release.
Case in point: I cannot fetch the L2 targeting release into my code base.

Please do something about this.

Ads Report Stats Error

I am getting PHP Parse error: syntax error, unexpected T_USE, expecting T_FUNCTION in /FacebookAds/Object/AdAccount.php on line 34

I am on PHP Version 5.3.5

Below is the PHP Code, where I am accessing the class. Please let me know, if you see any issues with the code. I am not a PHP Expert. Thanks.

array ( 'account_id', 'total_actions', 'spend' ), 'date_preset' => 'last_7_days', ); $account = new AdAccount('act_' . $accountID); $reports = $account->getReportsStats($fields, $params); $response = array(); foreach($reports as $report) { $response[] = $report->getData(); } return json_encode($response); ?>

Location of fb_ca_chain_bundle.crt

Suggest that you move the certificate file to Http/Adapter so that the src directory can be a self-contained distribution. This also matches the convention used by the PHP SDK for the Graph API.

Building phar: curl: error setting certificate verify locations

Hi,
I'm building phar with usage of ads sdk and unfortunately I've this error.

  [FacebookAds\Exception\Exception]                                                                                                                                                   
  error setting certificate verify locations:                                                                                                                                         
    CAfile: phar:///home/username/workdir/build/acme.phar/vendor/facebook/php-ads-sdk/src/FacebookAds/Http/Adapter/../../../../fb_ca_chain_bundle.crt  
    CApath: /etc/ssl/certs                                                                                                                                                              

I think it's totally the same error as this one FriendsOfPHP/Goutte#88

Regards.

Unable to get the stats(of campaign, adsets and ads) breaked down by days

$fields = array(
'impressions',
'unique_impressions',
'clicks',
'spent',
);

$params = array(
//'date_preset'=>'last_7_days',
'start_time'=>'2015-03-03',
'end_time'=>'2015-03-08',
'include_deleted' => 'true',
'time_increment'=> 1,

);
$campaign = new AdCampaign('1234');
$stats = $campaign->getStats($fields, $params);

I am only getting the Total of every thing in the response but not the breakdown by day as i mentioned 'time_increment'=> 1, also tried date_preset its not working too.

Also another issue that if i use getReportsStats for getting the campain stats, its giving me every thing fine(with day break up) except the reach/unique_impressions (vast difference from the real one, I mean its a much bigger value than real one)
I am using the following code :

$account = new AdAccount('act_123123');
$params = array(
'date_preset'=>'last_7_days',
'data_columns'=>array(
'campaign_group_id',
'unique_impressions',
'clicks',
'actions',
'spend',
'frequency',
'impressions',
'cpm',
'cpc',
),
'time_increment'=>1,
'sort_by'=>'date_start',
'sort_dir'=>'asc',
'filters'=>array(
array(
'field'=>'campaign_group_id',
'type'=>'in',
'value'=>['12345'],
),
),

        );

$stats = $account->getReportsStats(array(), $params);

Please any help is much appreciated.

Cursor UseImplicitFetch duplicates AbstractObject

If I walk all Abstract Objects with 'useImplicitFectch' activated, when the API fetches the next page the new current object is the last object in previous page.

My example with CustomAudiences:

\FacebookAds\Cursor::setDefaultUseImplicitFetch(true);

$adAccount = new \FacebookAds\Object\AdAccount('act_xxx');

/** @var \FacebookAds\Cursor $cursor */
$cursor = $adAccount->getCustomAudiences(array(
    \FacebookAds\Object\Fields\CustomAudienceFields::ID
));

while ($cursor->key() !== null) {
    /** @var \FacebookAds\Object\CustomAudience $customAudience */
    $customAudience = $cursor->current();
    $customAudienceId = $customAudience->{\FacebookAds\Object\Fields\CustomAudienceFields::ID};

    echo "{$customAudienceId} - {$cursor->count()}\n";

    $cursor->next();
}

Prints:
001 - 25
002 - 25
...
024 - 25
025 - 25
025 - 50

026 - 50
...

Invalid Argument Exception on Creating AdGroup

Using the adgroup_creation.php example to create AdGroup. The rest of the code works fine but receiving "Invalid Parameter" exception. The required field AdGroupFields::ADGROUP_STATUS => 'ACTIVE' was missing, I've added it but still the same issue.

i got a error Undefined class constant 'BURGER'

Hi, I am integrating Facebook ads sdk into my Linux server. For your guidance i install all packages into my server. when i execute

./vendor/bin/phpunit -c test/

This comment i got a error first. xdebug not found error. so i install xdebug into server then i add into composer.json file.

Next i run the following comment

./vendor/bin/phpunit -c test/

i got the error again.

My error is given below

E....EEEEEEEEEEEE.EEPHP Fatal error: Undefined class constant 'BURGER' in /var/www/facebook-php-ads-sdk/test/FacebookAdsTest/Object/ReachFrequencyPredictionTest.php on line 49 PHP Stack trace: PHP 1. {main}() /var/www/facebook-php-ads-sdk/vendor/phpunit/phpunit/phpunit:0 PHP 2. PHPUnit_TextUI_Command::main() /var/www/facebook-php-ads-sdk/vendor/phpunit/phpunit/phpunit:56 PHP 3. PHPUnit_TextUI_Command->run() /var/www/facebook-php-ads-sdk/vendor/phpunit/phpunit/src/TextUI/Command.php:138 PHP 4. PHPUnit_TextUI_TestRunner->doRun() /var/www/facebook-php-ads-sdk/vendor/phpunit/phpunit/src/TextUI/Command.php:186 PHP 5. PHPUnit_Framework_TestSuite->run() /var/www/facebook-php-ads-sdk/vendor/phpunit/phpunit/src/TextUI/TestRunner.php:423 PHP 6. PHPUnit_Framework_TestSuite->run() /var/www/facebook-php-ads-sdk/vendor/phpunit/phpunit/src/Framework/TestSuite.php:751 PHP 7. PHPUnit_Framework_TestCase->run() /var/www/facebook-php-ads-sdk/vendor/phpunit/phpunit/src/Framework/TestSuite.php:751 PHP 8. PHPUnit_Framework_TestResult->run() /var/www/facebook-php-ads-sdk/vendor/phpunit/phpunit/src/Framework/TestCase.php:708 PHP 9. PHPUnit_Framework_TestCase->runBare() /var/www/facebook-php-ads-sdk/vendor/phpunit/phpunit/src/Framework/TestResult.php:643 PHP 10. PHPUnit_Framework_TestCase->runTest() /var/www/facebook-php-ads-sdk/vendor/phpunit/phpunit/src/Framework/TestCase.php:772 PHP 11. ReflectionMethod->invokeArgs() /var/www/facebook-php-ads-sdk/vendor/phpunit/phpunit/src/Framework/TestCase.php:906 PHP 12. FacebookAdsTest\Object\ReachFrequencyPredictionTest->testCrudAccess() /var/www/facebook-php-ads-sdk/vendor/phpunit/phpunit/src/Framework/TestCase.php:906 root@Devel-56:/var/www/facebook-php-ads-sdk# vim /var/www/facebook-php-ads-sdk/test/FacebookAdsTest/Object/ReachFrequencyPredictionTest.php root@Devel-56:/var/www/facebook-php-ads-sdk# ./vendor/bin/phpunit -c test/ PHPUnit 4.3.1 by Sebastian Bergmann

Please help me whats wrong please any one help me

Fatal error: Undefined class constant 'BURGER' in /var/www/facebook-php-ads-sdk/test/FacebookAdsTest/Object/ReachFrequencyPredictionTest.php on line 49

While create adset then I got error 'Invalid parameter'

Hello,
I am using FB Ads API, and successfully created campaigns and get the ID from Facebook. In the next step to create adset with below code then got error.

// Call create using an array of parameters.
$data = array(
AdSetFields::NAME => 'My AdSet',
AdSetFields::BID_TYPE => 'CPC',
AdSetFields::BID_INFO => array(
'CLICKS' => 500,
),
AdSetFields::CAMPAIGN_STATUS => AdSet::STATUS_ACTIVE,
AdSetFields::DAILY_BUDGET => 200,
AdSetFields::CAMPAIGN_GROUP_ID => $campaign_id,
AdSetFields::TARGETING => array(
'geo_locations' => array(
'countries' => array(
'US',
'GB',
),
),
),
);
$ad_set = new AdSet(null, $account->id);
$ad_set->create($data);

Fatal error: Uncaught exception 'FacebookAds\Http\Exception\AuthorizationException' with message 'Invalid parameter' in /www/facebookads/src/FacebookAds/Http/Exception/RequestException.php:129

Get an access token server side

It may sound trivial, but where / how are we supposed to get an access_token?
The doc says "To instantiate an Api object you will need a valid access token" but do not say how.

Is it possible to get one from server-to-server?

ps. this page explains how to generate tokens, but it seems that a web interface is always needed to do so

Graph API resolving to IPV6 sometime.

Graph API requests are resolving to IPV6 some times.

We can force the API to resolve to IPV4 by adding following code snippet after curl_init
curl_setopt($this->handle, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);

bid-info values must be positive integers

My code:

\FacebookAds\Api::init($app_id, $app_secret, $access_token);
$adSet = new \FacebookAds\Object\AdSet(null, $account_id});
$adSet->setData(array(
    \FacebookAds\Object\Fields\AdSetFields::NAME => $name,
    \FacebookAds\Object\Fields\AdSetFields::CAMPAIGN_GROUP_ID => '6017312881528',
    \FacebookAds\Object\Fields\AdSetFields::CAMPAIGN_STATUS => \FacebookAds\Object\AdSet::STATUS_ACTIVE,
    \FacebookAds\Object\Fields\AdSetFields::DAILY_BUDGET => '1',
    \FacebookAds\Object\Fields\AdSetFields::BID_TYPE => 'CPC',
    \FacebookAds\Object\Fields\AdSetFields::BID_INFO => array('CLICKS' => 'min_1_cent'),
    \FacebookAds\Object\Fields\AdSetFields::TARGETING => array(
        'geo_locations' => array('countries' => array('AU')),
    ),
));
$adSet->create();

The error I get is:

exception 'FacebookAds\Http\Exception\AuthorizationException' with message '(#100) bid-info values must be positive integers' in /vagrant/app/vendor/facebook/php-ads-sdk/src/FacebookAds/Http/Exception/RequestException.php:113

The specs say that bid-info should be a JSON object, so I assumed the PHP array should work:
https://developers.facebook.com/docs/reference/ads-api/adset/v2.2

Can you help with the value I should put in here?

Thanks.

no data returned when calling $adCreative->read() without specifying fields

I try to read an AdCreative like this:

Api::init($app_id, $app_secret, $access_token);
$adCreative = new AdCreative($ad_creative_id, $account_id);
$adCreative->read();
print_r($adCreative->getData());

But it results in:

Array
(
    [id] => THE ID
    [title] => 
    [actor_id] => 
    [actor_name] => 
    [name] => 
    [object_id] => 
    [object_story_id] => 
    [object_story_spec] => 
    [body] => 
    [image_hash] => 
    [image_file] => 
    [image_url] => 
    [image_crops] => 
    [video_id] => 
    [actor_image_hash] => 
    [link_url] => 
    [object_url] => 
    [url_tags] => 
    [preview_url] => 
    [follow_redirect] => 
    [object_store_url] => 
    [link_deep_link_url] => 
    [call_to_action_type] => 
    [object_type] => 
)

I then try using $adCreative->getFields() as an argument to $adCreative->read():

Api::init($app_id, $app_secret, $access_token);
$adCreative = new AdCreative($ad_creative_id, $account_id);
$adCreative->read($adCreative->getFields());
print_r($adCreative->getData());

Which throws an exception:

Array
        (
            [message] => (#100) Tried accessing nonexisting field (image_file) on node type (AdCreative)
            [type] => OAuthException
            [code] => 100
        )

I then remove image_file from the list of fields:

Api::init($app_id, $app_secret, $access_token);
$adCreative = new AdCreative($ad_creative_id, $account_id);
$fields = $adCreative->getFields();
foreach ($fields as $k => $v) {
    if ($v = 'image_file') {
        unset($fields[$k]);
    }
}
$adCreative->read($fields);
print_r($adCreative->getData());

Which results again in no data:

Array
(
    [id] => THE ID
    [title] => 
    [actor_id] => 
    [actor_name] => 
    [name] => 
    [object_id] => 
    [object_story_id] => 
    [object_story_spec] => 
    [body] => 
    [image_hash] => 
    [image_file] => 
    [image_url] => 
    [image_crops] => 
    [video_id] => 
    [actor_image_hash] => 
    [link_url] => 
    [object_url] => 
    [url_tags] => 
    [preview_url] => 
    [follow_redirect] => 
    [object_store_url] => 
    [link_deep_link_url] => 
    [call_to_action_type] => 
    [object_type] => 
)

I try making my own fields array, and then remove any that cause an exception, and end up with this list:

Api::init($app_id, $app_secret, $access_token);
$adCreative = new AdCreative($ad_creative_id, $account_id);
$fields = array(
    AdCreativeFields::ID,
    AdCreativeFields::TITLE,
    AdCreativeFields::ACTOR_ID,
    AdCreativeFields::ACTOR_NAME,
    AdCreativeFields::NAME,
    AdCreativeFields::OBJECT_ID,
    AdCreativeFields::OBJECT_STORY_ID,
    AdCreativeFields::OBJECT_STORY_SPEC,
    AdCreativeFields::BODY,
    AdCreativeFields::IMAGE_HASH,
    //AdCreativeFields::IMAGE_FILE,
    AdCreativeFields::IMAGE_URL,
    AdCreativeFields::IMAGE_CROPS,
    AdCreativeFields::VIDEO_ID,
    AdCreativeFields::ACTOR_IMAGE_HASH,
    AdCreativeFields::LINK_URL,
    AdCreativeFields::OBJECT_URL,
    AdCreativeFields::URL_TAGS,
    //AdCreativeFields::PREVIEW_URL,
    //AdCreativeFields::FOLLOW_REDIRECT,
    AdCreativeFields::OBJECT_STORE_URL,
    AdCreativeFields::LINK_DEEP_LINK_URL,
    AdCreativeFields::CALL_TO_ACTION_TYPE,
    AdCreativeFields::OBJECT_TYPE,
);
$adCreative->read($fields);
print_r($adCreative->getData());

Now I get what is expected (i have replaced the actual data incase of any security issue sharing it):

Array
(
    [id] => THE ID
    [title] => AD TITLE
    [actor_id] => THE ACTOR ID
    [actor_name] => 
    [name] => AD NAME
    [object_id] => 
    [object_story_id] => 
    [object_story_spec] => 
    [body] => AD BODY
    [image_hash] => IMAGE HASH
    [image_file] => 
    [image_url] => https://fbcdn-creative-a.akamaihd.net/REMOVED-PATH.png
    [image_crops] => 
    [video_id] => 
    [actor_image_hash] => 
    [link_url] => 
    [object_url] => http://www.example.com/
    [url_tags] => 
    [preview_url] => 
    [follow_redirect] => 
    [object_store_url] => 
    [link_deep_link_url] => 
    [call_to_action_type] => 
    [object_type] => DOMAIN
)

My question is, is this the expected behaviour? Or should I be able to do $adCreative->read() without specifying a field list?

Unsupported get request. Please read the Graph API documentation

Here is my example code:

\FacebookAds\Api::init($app_id, $app_secret, $access_token);
$account = (new \FacebookAds\Object\AdAccount($account_id))->read(array(
    \FacebookAds\Object\Fields\AdAccountFields::ID,
    \FacebookAds\Object\Fields\AdAccountFields::NAME,
    \FacebookAds\Object\Fields\AdAccountFields::ACCOUNT_STATUS
));

Gives the following error:
FacebookAds\Http\Exception\AuthorizationException
Unsupported get request. Please read the Graph API documentation at https://developers.facebook.com/docs/graph-api

I thought perhaps my access_token had expired, so I followed these steps:

I tried with the new access token but got the same message.

Test error: Undefined index images in FacebookAds/Object/AdImage.php:119

When I run phpunit tests on latest master (commits for 2.2.0) there are several errors, including:

FacebookAdsTest\Object\AdCreativeTest::testMultiProductObjectSpec
Undefined index: images

/Users/ben/projects/c/facebook-php-ads-sdk/src/FacebookAds/Object/AdImage.php:119
/Users/ben/projects/c/facebook-php-ads-sdk/src/FacebookAds/Object/AbstractCrudObject.php:324
/Users/ben/projects/c/facebook-php-ads-sdk/test/FacebookAdsTest/Object/AdCreativeTest.php:71
phar:///usr/local/Cellar/phpunit/4.2.6/libexec/phpunit-4.2.6.phar/phpunit/TextUI/Command.php:186
phar:///usr/local/Cellar/phpunit/4.2.6/libexec/phpunit-4.2.6.phar/phpunit/TextUI/Command.php:138

Tracing through the test I see that in the create method that the filename is not used in $params but instead sets it via Parameters#offsetSet(). For some reason this is not working for me (PHP 5.4.33).

Does testMultiProductObjectSpec pass for you?

    // in AdImage#create()
    // ...
    $data = $this->exportData();
    $filename = $data[AdImageFields::FILENAME];
    unset($data[AdImageFields::FILENAME]);
    $params = array_merge($data, $params);
    // ...
    // -- The following would seem to work, but doesn't --
    $request->getFileParams()->offsetSet(AdImageFields::FILENAME, $filename);
    // Which I think causes testMultiProductObjectSpec (and others) to fail

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.