0
votes

I receive an erro of Invalid parameter but it doesnt tell me which invalid parameter is. The error is:

Fatal error: Uncaught exception 'FacebookAds\Http\Exception\AuthorizationException' with message 'Invalid parameter' in C:\AppServ\www\marketing\vendor\facebook\php-ads-sdk\src\FacebookAds\Http\Exception\RequestException.php:140 Stack trace: #0 C:\AppServ\www\marketing\vendor\facebook\php-ads-sdk\src\FacebookAds\Http\Client.php(215): FacebookAds\Http\Exception\RequestException::create(Object(FacebookAds\Http\Response))

1 C:\AppServ\www\marketing\vendor\facebook\php-ads-sdk\src\FacebookAds\Http\Request.php(282):

FacebookAds\Http\Client->sendRequest(Object(FacebookAds\Http\Request))

2 C:\AppServ\www\marketing\vendor\facebook\php-ads-sdk\src\FacebookAds\Api.php(151):

FacebookAds\Http\Request->execute() #3 C:\AppServ\www\marketing\vendor\facebook\php-ads-sdk\src\FacebookAds\Api.php(193): FacebookAds\Api->executeRequest(Object(FacebookAds\Http\Request)) #4 C:\AppServ\www\marketing\vendor\facebook\php-ads-sdk\src\FacebookAds\Object\AbstractCrudObject.php(208): FacebookAds\Api->call('/act_XXXXXXXX...', 'POST', Array) #5 C:\A in C:\AppServ\www\marketing\vendor\facebook\php-ads-sdk\src\FacebookAds\Http\Exception\RequestException.php on line 140

This is my code and it seems that the error is in the last object $ad = new Ad, everything is created fine until the Ad, it shows me this error.

<?php
//date_default_timezone_set('America/Lima');
//require_once('vendor/autoload.php');


//$campaign_id = '6053849657204';

// Configurations
$access_token = 'MYTOKEN';
$app_id = 'MYAPPID';
$app_secret = 'MYAPPSECRET';

$account_id = 'act_MYACCOUNT';
define('SDK_DIR', __DIR__ . ''); // Path to the SDK directory
$loader = include SDK_DIR.'/vendor/autoload.php';
date_default_timezone_set('America/Los_Angeles');
// Configurations - End
if(is_null($access_token) || is_null($app_id) || is_null($app_secret)) {
  throw new \Exception(
    'You must set your access token, app id and app secret before executing'
  );
}
if (is_null($account_id)) {
  throw new \Exception(
    'You must set your account id before executing');
}
use FacebookAds\Api;
Api::init($app_id, $app_secret, $access_token);
/**
 * Step 1 Read the AdAccount (optional)
 */
use FacebookAds\Object\AdAccount;
use FacebookAds\Object\Fields\AdAccountFields;
$account = (new AdAccount($account_id))->read(array(
  AdAccountFields::ID,
  AdAccountFields::NAME,
  AdAccountFields::ACCOUNT_STATUS,
));
echo "\nUsing this account: ";
echo $account->id."\n";
// Check the account is active
if($account->{AdAccountFields::ACCOUNT_STATUS} !== 1) {
  throw new \Exception(
    'This account is not active');
}
/**
 * Step 2 Create the Campaign
 */
use FacebookAds\Object\Campaign;
use FacebookAds\Object\Fields\CampaignFields;
use FacebookAds\Object\Values\AdObjectives;
$campaign  = new Campaign(null, $account->id);
$campaign->setData(array(
  CampaignFields::NAME => 'Noticia 1',
  CampaignFields::OBJECTIVE => AdObjectives::LINK_CLICKS,
));
$campaign->validate()->create(array(
  Campaign::STATUS_PARAM_NAME => Campaign::STATUS_PAUSED,
));
echo "Campaign ID:" . $campaign->id . "\n";
/**
 * Step 3 Search Targeting
 */
use FacebookAds\Object\TargetingSearch;
use FacebookAds\Object\Search\TargetingSearchTypes;
use FacebookAds\Object\TargetingSpecs;
use FacebookAds\Object\Fields\TargetingSpecsFields;
$results = TargetingSearch::search(
  $type = TargetingSearchTypes::INTEREST,
  $class = null,
  $query = 'facebook');
// we'll take the top result for now
$target = (count($results)) ? $results->current() : null;
echo "Using target: ".$target->name."\n";
$targeting = new TargetingSpecs();
$targeting->{TargetingSpecsFields::GEO_LOCATIONS}
  = array('countries' => array('PE'));
/*$targeting->{TargetingSpecsFields::INTERESTS} = array(
    array(
        'id' => $target->id,
        'name' => $target->name,
    ),
);*/
/**
 * Step 4 Create the AdSet
 */
use FacebookAds\Object\AdSet;
use FacebookAds\Object\Fields\AdSetFields;
use FacebookAds\Object\Values\OptimizationGoals;
use FacebookAds\Object\Values\BillingEvents;
$adset = new AdSet(null, $account->id);
$adset->setData(array(
  AdSetFields::NAME => 'Latam 1',
  AdSetFields::CAMPAIGN_ID => $campaign->id,
  AdSetFields::DAILY_BUDGET => '150',
  AdSetFields::TARGETING => $targeting,
  AdSetFields::OPTIMIZATION_GOAL => OptimizationGoals::REACH,
  AdSetFields::BILLING_EVENT => BillingEvents::IMPRESSIONS,
  AdSetFields::BID_AMOUNT => '1',
  AdSetFields::START_TIME =>
    (new \DateTime("+1 week"))->format(\DateTime::ISO8601),
  AdSetFields::END_TIME =>
    (new \DateTime("+2 week"))->format(\DateTime::ISO8601),
));
$adset->validate()->create(array(
  AdSet::STATUS_PARAM_NAME => AdSet::STATUS_ACTIVE,
));
echo 'AdSet  ID: '. $adset->id . "\n";
/**
 * Step 5 Create an AdImage
 */
use FacebookAds\Object\AdImage;
use FacebookAds\Object\Fields\AdImageFields;
$image = new AdImage(null, $account->id);
$image->{AdImageFields::FILENAME}
  = dirname(__FILE__).'/image.jpg';
$image->create();
echo 'Image Hash: '.$image->hash . "\n";
/**
 * Step 6 Create an AdCreative
 */

    
    use FacebookAds\Object\AdCreative;
use FacebookAds\Object\AdCreativeLinkData;
use FacebookAds\Object\Fields\AdCreativeLinkDataFields;
use FacebookAds\Object\AdCreativeObjectStorySpec;
use FacebookAds\Object\Fields\AdCreativeObjectStorySpecFields;
use FacebookAds\Object\Fields\AdCreativeFields;

$link_data = new AdCreativeLinkData();
$link_data->setData(array(
  AdCreativeLinkDataFields::MESSAGE => 'MY DESC',
  AdCreativeLinkDataFields::LINK => 'MY WEB',
  AdCreativeLinkDataFields::CAPTION => 'My caption',
  AdCreativeLinkDataFields::IMAGE_HASH =>  $image->hash,
));

$object_story_spec = new AdCreativeObjectStorySpec();
$object_story_spec->setData(array(
  AdCreativeObjectStorySpecFields::PAGE_ID => 'MY PAGE ID',
  AdCreativeObjectStorySpecFields::LINK_DATA => $link_data,
));

$creative = new AdCreative(null, $account->id);

$creative->setData(array(
  AdCreativeFields::NAME => 'Sample Creative',
  AdCreativeFields::OBJECT_STORY_SPEC => $object_story_spec,
));

$creative->create();
    
    
echo 'Creative ID: '.$creative->id . "\n";
/**
 * Step 7 Create an Ad
 */
use FacebookAds\Object\Ad;
use FacebookAds\Object\Fields\AdFields;
$datax = array(
  AdFields::NAME => 'My Ad',
  AdFields::ADSET_ID => $adset->id,
  AdFields::CREATIVE => array(
    'creative_id' => $creative->id,
  ),
);

$ad = new Ad(null, $account->id);
$ad->setData($datax);
$ad->create(array(
  Ad::STATUS_PARAM_NAME => Ad::STATUS_PAUSED,
));
echo 'Ad ID:' . $ad->id . "\n";
1

1 Answers

0
votes

The issue was that you needed to specify a valid Link and Page ID. I figured that out by adding more logging in the code below by adding this piece of code,

use FacebookAds\Logger\CurlLogger;
Api::init($app_id, $app_secret, $access_token);

// Create the CurlLogger
$logger = new CurlLogger();
// To write to a file pass in a file handler
// $logger = new CurlLogger(fopen('test','w'));
// Attach the logger to the Api instance
Api::instance()->setLogger($logger);

Once you've added the above code to your php project, it will console output the curl version of the API calls being executed by the SDK. You can make the API call that was failing in a terminal using curl and get the specific error that the API throws for debugging. (Currently in the PHP SDK the exact error doesn't get propagated up in the exceptions.)

You can check out the complete working code snippet here,

<?php
$access_token = '<ACCESS_TOKEN>';
$app_id = <APP_ID>;
$app_secret = '<APP_SECRET>';
// should begin with "act_" (eg: $account_id = 'act_1234567890';)
$account_id = 'act_<ACCOUNT_ID>';
$page_id = 0; // REPLACE THIS WITH VALID PAGE ID.
// Configurations - End

if (is_null($access_token) || is_null($app_id) || is_null($app_secret)) {
  throw new \Exception(
    'You must set your access token, app id and app secret before executing'
  );
}

if (is_null($account_id)) {
  throw new \Exception(
    'You must set your account id before executing');
}

define('SDK_DIR', __DIR__ . '/..'); // Path to the SDK directory
$loader = include SDK_DIR.'/vendor/autoload.php';

use FacebookAds\Api;
use FacebookAds\Logger\CurlLogger;
Api::init($app_id, $app_secret, $access_token);

// Create the CurlLogger
$logger = new CurlLogger();
// To write to a file pass in a file handler
// $logger = new CurlLogger(fopen('test','w'));
// Attach the logger to the Api instance
Api::instance()->setLogger($logger);

/**
 * Step 1 Read the AdAccount (optional)
 */
use FacebookAds\Object\AdAccount;
use FacebookAds\Object\Fields\AdAccountFields;
$account = (new AdAccount($account_id))->read(array(
  AdAccountFields::ID,
  AdAccountFields::NAME,
  AdAccountFields::ACCOUNT_STATUS,
));
echo "\nUsing this account: ";
echo $account->id."\n";
// Check the account is active
if($account->{AdAccountFields::ACCOUNT_STATUS} !== 1) {
  throw new \Exception(
    'This account is not active');
}
/**
 * Step 2 Create the Campaign
 */
use FacebookAds\Object\Campaign;
use FacebookAds\Object\Fields\CampaignFields;
use FacebookAds\Object\Values\AdObjectives;
$campaign  = new Campaign(null, $account->id);
$campaign->setData(array(
  CampaignFields::NAME => 'Noticia 1',
  CampaignFields::OBJECTIVE => AdObjectives::LINK_CLICKS,
));
$campaign->validate()->create(array(
  Campaign::STATUS_PARAM_NAME => Campaign::STATUS_PAUSED,
));
echo "Campaign ID:" . $campaign->id . "\n";
/**
 * Step 3 Search Targeting
 */
use FacebookAds\Object\TargetingSearch;
use FacebookAds\Object\Search\TargetingSearchTypes;
use FacebookAds\Object\TargetingSpecs;
use FacebookAds\Object\Fields\TargetingSpecsFields;
$results = TargetingSearch::search(
  $type = TargetingSearchTypes::INTEREST,
  $class = null,
  $query = 'facebook');
// we'll take the top result for now
$target = (count($results)) ? $results->current() : null;
echo "Using target: ".$target->name."\n";
$targeting = new TargetingSpecs();
$targeting->{TargetingSpecsFields::GEO_LOCATIONS}
  = array('countries' => array('PE'));
/*$targeting->{TargetingSpecsFields::INTERESTS} = array(
    array(
        'id' => $target->id,
        'name' => $target->name,
    ),
);*/
/**
 * Step 4 Create the AdSet
 */
use FacebookAds\Object\AdSet;
use FacebookAds\Object\Fields\AdSetFields;
use FacebookAds\Object\Values\OptimizationGoals;
use FacebookAds\Object\Values\BillingEvents;
$adset = new AdSet(null, $account->id);
$adset->setData(array(
  AdSetFields::NAME => 'Latam 1',
  AdSetFields::CAMPAIGN_ID => $campaign->id,
  AdSetFields::DAILY_BUDGET => '150',
  AdSetFields::TARGETING => $targeting,
  AdSetFields::OPTIMIZATION_GOAL => OptimizationGoals::REACH,
  AdSetFields::BILLING_EVENT => BillingEvents::IMPRESSIONS,
  AdSetFields::BID_AMOUNT => '1',
  AdSetFields::START_TIME =>
    (new \DateTime("+1 week"))->format(\DateTime::ISO8601),
  AdSetFields::END_TIME =>
    (new \DateTime("+2 week"))->format(\DateTime::ISO8601),
));
$adset->validate()->create(array(
  AdSet::STATUS_PARAM_NAME => AdSet::STATUS_ACTIVE,
));
echo 'AdSet  ID: '. $adset->id . "\n";
/**
 * Step 5 Create an AdImage
 */
use FacebookAds\Object\AdImage;
use FacebookAds\Object\Fields\AdImageFields;
$image = new AdImage(null, $account->id);
$image->{AdImageFields::FILENAME}
  = dirname(__FILE__).'/image.jpg';
$image->create();
echo 'Image Hash: '.$image->hash . "\n";
/**
 * Step 6 Create an AdCreative
 */


    use FacebookAds\Object\AdCreative;
use FacebookAds\Object\AdCreativeLinkData;
use FacebookAds\Object\Fields\AdCreativeLinkDataFields;
use FacebookAds\Object\AdCreativeObjectStorySpec;
use FacebookAds\Object\Fields\AdCreativeObjectStorySpecFields;
use FacebookAds\Object\Fields\AdCreativeFields;

$link_data = new AdCreativeLinkData();
$link_data->setData(array(
  AdCreativeLinkDataFields::MESSAGE => 'MY DESC',
  AdCreativeLinkDataFields::LINK => 'www.google.com',
  AdCreativeLinkDataFields::CAPTION => 'My caption',
  AdCreativeLinkDataFields::IMAGE_HASH =>  $image->hash,
));

$object_story_spec = new AdCreativeObjectStorySpec();
$object_story_spec->setData(array(
  AdCreativeObjectStorySpecFields::PAGE_ID => $page_id,
  AdCreativeObjectStorySpecFields::LINK_DATA => $link_data,
));

$creative = new AdCreative(null, $account->id);

$creative->setData(array(
  AdCreativeFields::NAME => 'Sample Creative',
  AdCreativeFields::OBJECT_STORY_SPEC => $object_story_spec,
));

$creative->create();


echo 'Creative ID: '.$creative->id . "\n";
/**
 * Step 7 Create an Ad
 */
use FacebookAds\Object\Ad;
use FacebookAds\Object\Fields\AdFields;
$datax = array(
  AdFields::NAME => 'My Ad',
  AdFields::ADSET_ID => $adset->id,
  AdFields::CREATIVE => array(
    'creative_id' => $creative->id,
  ),
);

$ad = new Ad(null, $account->id);
$ad->setData($datax);
$ad->create(array(
  Ad::STATUS_PARAM_NAME => Ad::STATUS_PAUSED,
));
echo 'Ad ID:' . $ad->id . "\n";