Facebook Marketing API and Ads Insight Access - facebook

I'm building a small program that works with various APIs to automate reporting services we offer some clients.
One of the things we report on is Facebook Ads performance.
I've been building out this program using the Facebook Marketing API & Ads Insight APi https://developers.facebook.com/docs/marketing-apis
I've gone through the whole process of setting up a Facebook 'App' and getting the relevant app tokens.
However, I've hit a wall since development access only allows for 5 Ad Accounts.
To apply for basic access, the marketing API is asking for the development platform and a whole bunch of other things that aren't relevant to my program. I'm not building an 'app' intended for public release in the traditional sense; rather, I just want to integrate with these APIs on a basic level to automate some internal tasks.
It seems mind-boggling to me that I wouldn't be able to do something like this, but this is what the Facebook documentation seems to be suggesting.
If anyone else has familiarity with this kind of issue, I'd love to know if there is a workaround.

Submit your app for review to get more than 10 ad accounts. Use the "Platform" of Website. Select Native or desktop app; app secret NOT embedded in the client. The rest of it can be mostly ignored, but you will need to include some screen shots of your app and a description of how it works and what it does. A real human will review it, and you can get help in the Facebook Developers group here:
https://www.facebook.com/groups/fbdevelopers
Youwill get a pass/fail only...no comments. Don't be surprised if they reject it first time around. Do not resubmit and hope for a better response the second time around -- they'll eventually lock you out for a few days. Post a help question to the group.

Derks, I currently am building dashboard with over 40 clients and I am able to display everyone of them and their insights data etc. with basic development level. I have code if you want to take a look only thing I am trying to accomplish now is making a date range picker but, you are more than welcome enough to take a look at what I have just to get a general idea.
Here are the Use objects from Facebook
<?php
require_once __DIR__ . '/vendor/autoload.php';
use FacebookAds\Api;
use FacebookAds\Object\AdUser;
use Facebook\Facebook;
use Facebook\Exceptions\FacebookResponseException;
use Facebook\Exceptions\FacebookSDKException;
use FacebookAds\Object\Campaign;
use FacebookAds\Object\Fields\AdsInsightsFields;
use FacebookAds\Object\Ad;
use FacebookAds\Object\Fields\AdSetFields;
use FacebookAds\Object\AdCampaign;
use FacebookAds\Object\Fields\AdFields;
use FacebookAds\Object\Fields;
use FacebookAds\Object\Fields\AdImageFields;
use FacebookAds\Object\AdAccount;
use FacebookAds\Object\AdSet;
use FacebookAds\Object\AdCreative;
use FacebookAds\Object\Fields\AdCreativeFields;
use FacebookAds\Object\Fields\AdCreativePhotoDataFields;
use FacebookAds\Object\AdCreativeLinkData;
use FacebookAds\Object\Fields\AdCreativeLinkDataFields;
use FacebookAds\Object\Fields\CampaignFields;
use FacebookAds\Object\Page;
use FacebookAds\Object\Fields\AdPreviewFields;
use FacebookAds\Object\Values\AdPreviewAdFormatValues;
use FacebookAds\Object\AdVideo;
?>
Here is the general code I am trying
<?php
// Init PHP Sessions
session_start();
$fb = new Facebook([
'app_id' => 'xxxxxxxxx',
'app_secret' => 'xxxxxxxxxxx',
]);
$helper = $fb->getRedirectLoginHelper();
if (!isset($_SESSION['enter api key here'])) {
$_SESSION['enter api key here'] = null;
}
if (!$_SESSION['enter api key here']) {
$helper = $fb->getRedirectLoginHelper();
try {
$_SESSION['enter api key here'] = (string) $helper->getAccessToken();
} catch(FacebookResponseException $e) {
// When Graph returns an error
echo 'Graph returned an error: ' . $e->getMessage();
exit;
} catch(FacebookSDKException $e) {
// When validation fails or other local issues
echo 'Facebook SDK returned an error: ' . $e->getMessage();
exit;
}
}
if ($_SESSION['enter api key here']) {
//echo "You are logged in!";
// Initialize a new Session and instantiate an API object
Api::init(
'xxxxxxxxx', // App ID
'xxxxxxxxx', //app_secret
$_SESSION['enter api key here'] // Your user access token
);
?>
<div id="fbdata"></div> <?php
$account = new AdAccount('act_xxxxxxxxxx');
$params = array(
'date_preset'=> 'last_28d',
'thumbnail_width' => 200,
'thumbnail_height' => 150,
'level' => 'campaign',
'limit' => '15'
);
$fields = array(
AdsInsightsFields::CAMPAIGN_NAME,
AdsInsightsFields::CAMPAIGN_ID,
AdsInsightsFields::IMPRESSIONS,
AdsInsightsFields::CLICKS,
AdsInsightsFields::REACH,
AdsInsightsFields::SPEND,
AdsInsightsFields::CPM,
AdsInsightsFields::CPC,
AdsInsightsFields::ACTIONS,
);
$field = array(
AdCreativeFields::TITLE,
AdCreativeFields::THUMBNAIL_URL,
AdCreativeFields::BODY,
);
$params1 = array(
'time_range' => array(
'since' => (new \DateTime($beginDate))->format('Y-m-d'),
'until' => (new \DateTime($lastDate))->format('Y-m-d'),
),
'thumbnail_width' => 200,
'thumbnail_height' => 150,
'level' => 'ad',
'limit' => '5'
);
$adcreatives = $account->getAdCreatives($field, $params1);
?>
<table class="fbtable">
<tr>
<th>Title</th>
<th>Ad Image</th>
<th>Ad Body</th>
</tr>
<?php
foreach($adcreatives as $t2){
echo"<tr>
<td>$t2->title</td>
<td><img src='$t2->thumbnail_url'/></td>
<td>$t2->body</td>
</tr>";
}
$insights = $account->getInsights($fields, $params);?>
<table class="fbtable">
<tr>
<th>Campaign ID</th>
<th>Campaign Name</th>
<th>Impressions</th>
<th>Clicks</th>
<th>Reach</th>
<th>Spend</th>
<th>Total Actions</th>
<th>CPM</th>
<th>CPC</th>
</tr>
<?php
foreach($insights as $i) {
$impress = number_format((float)$i->impressions);
$reach = number_format((float)$i->reach);
$totalAction = number_format((float)$i->actions);
$cpc = number_format($i->cpc, 2, '.', '');
$cpm = number_format($i->cpm, 2, '.', '');
echo"<tr class='fbtable'>
<td>$i->campaign_id</td>
<td>$i->campaign_name</td>
<td>$impress</td>
<td>$i->clicks</td>
<td>$reach</td>
<td>$$i->spend</td>
<td>$totalAction</td>
<td>$$cpm</td>
<td>$$cpc</td>
</tr>";
}
}else {
$permissions = ['ads_management'];
$loginUrl = $helper->getLoginUrl('http://where you want login to be.com', $permissions);
echo 'Log in with Facebook';
}
?>
I will help much as I can #Derks and I believe the only thing you may need to do is figure out way for the program or whatever your building know who is who.

Related

FaceBook PHP API SDK: suddenly the argument 'link' is not published and /me/feed is not working

I completed this script, that was working fine till this morning, when launching it, suddenly I noticed that the argument "link" of the array $linkData, is not published any longer, (no error returned) while "message" is published.
I also noticed that if I put /me/feed into the object $fb->post, it doesn't work (see the commented line). No errors returned.
While, if I put the code of a group (the code you see is a test group I created to test the script), the argument "message" is published (not the "link")
The scopes are:
user_managed_groups,
user_events,
user_friends,
user_posts,
publish_actions,
user_actions.music,
user_actions.video,
public_profile
The link is referred to the link for which the application is written. the www.example.com URL, is written here for this example. In the real code, I use the URL of the site of the App (that till yesterday was working fine).
Please here the code:
<?php
session_start();
define(__APP_ID__, XXXXXXXXXXXXXXX);
define(__APP_SECRET__, 'YYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYY');
define(__APP_TOKEN__, 'ZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ');
define(__APP_ACCESS_TOKEN__, 'WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW');
require_once '../include/setup.php';
require_once $root_dir.'/include/Facebook/autoload.php';
// Creates the object
$fb = new Facebook\Facebook([
'app_id' => __APP_ID__,
'app_secret' => __APP_SECRET__,
'default_graph_version' => 'v2.2',
]);
$linkData = [
'link' => 'http://www.example.com',
'message' => 'The link above, is not any longer published',
];
$group_id = "1041863359178529";
try {
//$response = $fb->post("/me/feed", $linkData, __APP_ACCESS_TOKEN__); // SUDDENLY it doesn't work any longer
$response = $fb->post("/{$group_id}/feed", $linkData, __APP_ACCESS_TOKEN__);
} catch (Facebook\Exceptions\FacebookResponseException $e) {
echo 'Graph returned an error: ' . $e->getMessage();
exit;
} catch (Facebook\Exceptions\FacebookSDKException $e) {
echo 'Facebook SDK returned an error: ' . $e->getMessage();
exit;
}
$graphNode = $response->getGraphNode();
echo 'Posted with id: ' . $graphNode['id']."\r\n";
?>
EDIT:
Is there anything I can do? Is id depending from the App settings? I changed many parameters to find a solution but I still have the issue.
I did verified that the block, is due FB.
In other words: probably of security reasons (mainly Anti-Spam), FB block repetitive use of the function in short time.
I did try also to wait more than 15 seconds among the iterations, but if I employ it for more than 20-25 time in one day, FB suspends all the required authorizations.
At the time I did post the thread, FB was enabling only the post of the text, and deactivated OpenGraph.
Now, instead, it blocks any kind of sending, including text.

Facebook Real Time Subscriptions Throws Exception Even when challenge is answered

I'm trying to subscribe from my app to Real Time Subscription of Facebook using v2.4 Graph API (after creating a callback function in fbcallback.php) using the code below from my index.php page (the appid and IP address obviously fake in this post):
try {
$response=$fb->sendRequest('POST','/1111/subscriptions',
array(
'object' => 'user',
'callback_url' => 'http://111.111.111.111/fbcallback.php',
'fields' => 'first_name',
'verify_token' => 'thisisaverifystringtestuser',
)
);
$graphNode = $response->getGraphNode();
}catch (Facebook\Exceptions\FacebookSDKException $e) {
echo "exception:" . $e->getMessage(); }
While i'm sure from callback log that Facebook reaches my callback function and i use in it the code below:
<?php
define('VERIFY_TOKEN', 'thisisaverifystringtestuser');
$method = $_SERVER['REQUEST_METHOD'];
if ($method == 'GET' && $_GET['hub_mode'] == 'subscribe' &&
$_GET['hub_verify_token'] == VERIFY_TOKEN) {
echo $_GET['hub_challenge'];
}
?>
i get the Message from my index page code looking like this:
exception:(#2201) response does not match challenge, expected value = '866531638', received='866531638'
Anyone encountered it?
P.S I created a test user from the app dashboard roles and configured him to subscribe to app on creation and also got (but not used) an access token for this user from dashboard also.....since i can't denote a specific user during the subscription proccess from my php code i expect (or wish) this user to be subscribed by my php code...am i wrong?
Looks like your script outputs more than just the hub_challenge value.
When I copy&paste the error message from your posting, and insert it in NotePad++, I get that part shown as
received='?866531638'
^
– so there seems to be some invisible/not display-able character before the actual value.
Make sure your script is saved as UTF-8 without BOM, and that it does not make any other output besides the hub_challenge value either. (That could include stuff outside of <?php … ?> tags as well.)

How to select facebook 'notes' posted via application

There is an application using FQL. Is there an opportunity to select notes posted by the application with the known id? As far as I know, there is no field 'app_id' in the 'note' table.
You can use graph api to get the notes of an app by app_id. http://developers.facebook.com/docs/reference/api/note/ you have to use any valid access token.
Example using php-sdk 3.1.1
<?php
$app_access = "https://graph.facebook.com/oauth/access_token?client_id=AppId&client_secret=YOURSECRET&grant_type=client_credentials";
$app_access_token = file_get_contents($app_access);
$pageid="your_app_or_page_id";
$MEnotes = $facebook->api('/'.$pageid.'/notes/?$app_access_token');
foreach ($MEnotes as $key=>$value) {
foreach ($value as $fkey=>$fvalue) {
$noteID=$fvalue[id];
$noteSubject=$fvalue[subject];
$noteMessage=$fvalue[message];
echo ''.$noteID.'<b> '.$noteSubject.'</b><br />'.$noteMessage.'<hr />';
}};
?>

Facebook Graph API - Same access token for all users

I have been madly trying to get access token for my users since long. I read at many sites to get it somehow by using getSession() and getting access_token from it... it gives me undefined function error.. I googled that too and all solutions said to use the updated SDK but mine is updated and it still won't work... so I finally got another solution to getting access token but this seems to be giving same access token for all users... any idea where the problem lies? All users certainly can't have same token right?
$app_id = $facebook->getAppId();
$app_secret = $facebook->getApiSecret();
function callFb($url, $params)
{
$ch = curl_init();
curl_setopt_array($ch, array(
CURLOPT_URL => $url,
CURLOPT_POSTFIELDS => http_build_query($params),
CURLOPT_RETURNTRANSFER => true,
CURLOPT_VERBOSE => true
));
$result = curl_exec($ch);
curl_close($ch);
return $result;
}
$params=array('client_id'=>$app_id, 'type'=>'client_cred', 'client_secret'=>$app_secret);
$url = "https://graph.facebook.com/oauth/access_token";
$access_token = callFb($url, $params);
$access_token = substr($access_token, strpos($access_token, "=")+1, strlen($access_token));
The issue is that you are asking for type=client_cred, which tells Facebook that you don't want access token for a user, but an access token for the app. This is used for doing things like accessing insights, the realtime updates API, and public data. If you want to get user data, you should not be passing that flag.
If you really do want to roll your own access to the Graph API, you can certainly do that, following the instructions at https://developers.facebook.com/docs/authentication/ .
You say you're using the PHP SDK but I don't see any mention of it anywhere in your code.
The proper way is this:
<?php
require('facebook.php');
$fb = new Facebook(array('appId' => APP_ID, 'secret' => SECRET));
$user = $fb->getUser();
// if we have a valid user, we're logged in
if ($user)
{
// do stuff with the API using the $fb object
}
else
{
// redirect the user to the authentication page
header("Location: ".$fb->getLoginUrl());
}
Example largely paraphrased from Facebook's SDK Github.

Facebook iFrame app - how to fetch Preload FQL result using PHP SDK?

since few years I have an FBML app (a small Flash game) which I'm now trying to convert to an iFrame app. Unfortunately there aren't many docs for Facebook iFrame apps yet.
For my game I need the user's first name, picture, gender and the city.
In my old version I had this preload FQL (created once by a PHP script):
$fql = array('info' => array('pattern' => 'facebook',
'query' => 'SELECT first_name, sex, pic_big, current_location
FROM user WHERE uid={*user*}'));
$fb->api_client->admin_setAppProperties(
array('preload_fql' => json_encode($fql)));
and then my FBML app script had been as simple as:
<?php
require_once('facebook.php');
define('FB_API_ID', 'XXX');
define('FB_AUTH_SECRET', 'YYY');
$fb = new Facebook(FB_API_ID, FB_AUTH_SECRET);
$viewer_id = $fb->require_login();
$data = json_decode($fb->fb_params['info'], true);
$first_name = $data[0][0];
$last_name = $data[0][2];
$female = ($data[0][3] != 'male');
$avatar = $data[0][3];
$city = $data[0][4]['city'];
# and then I'd just construct flashvars attribute
# for the <fb:swf ...> tag and print it
?>
Does anybody please have hints on how to recreate the same script for the iFrame version - i.e. how can I fetch the result of Preload FQL by my iFrame app?
According to an older Facebook blog entry Preload FQL should be accessible by the iFrame apps.
Thank you!
Alex
My own answer after long searching is that Preload FQL results aren't sent to iframe Facebook apps.
That is why Facebook performance doc says:
"Preload FQL Query and Multiquery.
This section applies to FBML canvas pages, but not to websites or IFrame canvas pages."
As Facebook said for Preload FQL
"Facebook will send the result of these FQL queries as JSON-encoded POST parameters to your Canvas URL"
print_r your $_POST and see which variable is the "json-encoded results". You convert json into php object using json_decode
JSON looks like this: {"var":"val","var":"val"}
Also, Facebook already has great docs for iframes. Then you might have missed these great docs:
Facebook Docs Home
http://developers.facebook.com/docs/
Authentication
http://developers.facebook.com/docs/authentication/
Signed Request
http://developers.facebook.com/docs/authentication/signed_request/
iFrame Canvas Apps
http://developers.facebook.com/docs/guides/canvas/
PHP SDK
https://github.com/facebook/php-sdk
Graph API
http://developers.facebook.com/docs/reference/api/
You don't need to call any FQL for the information you are getting. For iFrame you just need to do following steps
Download the PHP SDK of graph api https://github.com/facebook/php-sdk/
Create the object and authorize the app from user
$fbconfig['appid' ] = "your application id";
$fbconfig['api' ] = "your application api key";
$fbconfig['secret'] = "your application secret key";
try{
include_once "facebook.php";
}
catch(Exception $o){
echo '<pre>';
print_r($o);
echo '</pre>';
}
// Create our Application instance.
$facebook = new Facebook(array(
'appId' => $fbconfig['appid'],
'secret' => $fbconfig['secret'],
'cookie' => true,
));
// User location extended permission allow you to get user's current location
$loginparams = array('canvas' => 1,'fbconnect' => 0,'req_perms' => 'user_location');
$loginUrl = $facebook->getLoginUrl($loginparams);
// We may or may not have this data based on a $_GET or $_COOKIE based session.
// If we get a session here, it means we found a correctly signed session using
// the Application Secret only Facebook and the Application know. We dont know
// if it is still valid until we make an API call using the session. A session
// can become invalid if it has already expired (should not be getting the
// session back in this case) or if the user logged out of Facebook.
$session = $facebook->getSession();
$fbme = null;
// Session based graph API call.
if ($session) {
try {
$uid = $facebook->getUser();
$fbme = $facebook->api('/me');
} catch (FacebookApiException $e) {
d($e);
}
}
function d($d){
echo '<pre>';
print_r($d);
echo '</pre>';
}
// You can found all the data in this array.
print_r($fbme);
For more detail you can follow this tutorial http://thinkdiff.net/facebook/php-sdk-graph-api-base-facebook-connect-tutorial/
Hope it works for you