Damon Hogan
Damon Hogan

Reputation: 552

How do I write PHP curl code and use proper param formats to pull back Facebook Ads reach estimate

Facebook only provides a shell curl command as an example for how to pull back reach estimate. Like so..

curl -G \
-d "currency=USD" \
-d "targeting_spec=___" \
-d "access_token=___" \
"https://graph.facebook.com/<API_VERSION>/act_<AD_ACCOUNT_ID>/reachestimate"

How do I format all the targeting_specs params correctly and write this for the PHP curl extension?

Upvotes: 1

Views: 139

Answers (1)

Damon Hogan
Damon Hogan

Reputation: 552

A couple of things to note here.

When converting the shell curl command to PHP, one might assume since targeting_spec will have a lot of data, that the best way to get this to the facebook graph is to post the data. However the facebook graph for this graph call will not accept a post, it just returns (invalid post error when you try) so I fount out you need to use a get param string

$postData = array(
        'currency' => 'USD',
        'access_token' => $this->_access_token,
        'targeting_spec' => urlencode(json_encode($targetingArray)),
    );

targeting array will contain targeting data such as genders, age_min, age_max, zips etc, plus any advanced demographics you might have such as behaviors, interests, income, net_worth, etc. These will be need to be eventually formatted in a json string. You can do this by creating a PHP array that matches the json structure and then using json_encode.

To see the end result format for the targeting_spec, follow the examples given in targeting specs docs. See this url https://developers.facebook.com/docs/marketing-api/targeting-specs/v2.3

note: advanced demographics in the targeting specs contain name values in the json and since facebook requires a get string in this case, you will need to urlencode the targeting_spec param json string as shown above.

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://graph.facebook.com/v2.2/" . $this->_ad_account->id . "/reachestimate" .
  '?access_token=' . $postData['access_token'] . '&' .
  'targeting_spec=' . $postData['targeting_spec'] . '&' .
  'currency=' . 'USD'
);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
$result = curl_exec($ch);
curl_close($ch);

Upvotes: 2

Related Questions