How can I get the amount spent / Faceook Marketing API - facebook

I'm working on Facebook Marketing API (v6.0) and trying to get the amount spent of each adset I have, actually I've started with Graph API explorer but I found nothing called spend and amount spent as a field, so after a while I got this trick which actually return false data , so the equation is like the following: daily_budget - budget_remaining = amount_spent , so let's assume that we have 900 - 800 = it returns 100 in my application while in business manager I got 50, here is my endpoint api
public function facebookData()
{
$fb = new \Facebook\Facebook([
'app_id' => 'xxxxx',
'app_secret' => 'xxxxxxx',
'default_graph_version' => 'v6.0',
//'default_access_token' => '{access-token}', // optional
]);
try {
// Returns a `FacebookFacebookResponse` object
$response = $fb->get(
'/act_xxxxxx/?fields=business,adsets.limit(1000){name,budget_remaining,daily_budget}',
'my_accesstoken'
);
} catch(FacebookExceptionsFacebookResponseException $e) {
echo 'Graph return=<i></i>ed an error: ' . $e->getMessage();
exit;
} catch(FacebookExceptionsFacebookSDKException $e) {
echo 'Facebook SDK returned an error: ' . $e->getMessage();
exit;
}
$data = $response->getGraphObject()->getProperty('adsets');
try
{
foreach ($data as $ad) {
\App\FacebookAd::UpdateOrCreate([
'ad_id' => $ad['id'],
],[
'name' => $ad['name'],
'budget_remaining' => substr($ad['budget_remaining'],0,-2),
'daily_budget' => substr($ad['daily_budget'],0,-2),
'total' => substr($ad['daily_budget'],0,-2) - substr($ad['budget_remaining'],0,-2), // remove last two zeros
'account_id' => "unset",
]);
}
}
catch(\Exception $e)
{
Log::error($e->getMessage());
}
}

Try to use insights.
https://developers.facebook.com/docs/marketing-api/reference/ads-insights/
In your link, add next "insights{spend}". So it will give:
'/act_xxxxxx/?fields=business,adsets.limit(1000){name,insights{spend}}'

Related

upload video to facebook group using Graph API

I'm using to GRAPH API to upload videos to my pages. I want to upload them to my groups too.
This is what I'm doing to upload video to pages and it is working.
$fb = new Facebook([
'app_id' => APP_ID,
'app_secret' => APP_SECRET,
'default_graph_version' => 'v2.2',
]);
$data = [
'title' => $title,
'description' => $description,
'source' => $fb->videoToUpload(WWW_ROOT . '../' . $path . $file),
];
try {
$result = $fb->post('/me/videos', $data, $user->access_token);
return $result;
} catch (FacebookResponseException $e) {
$response['status'] = false;
$response['message'] = 'Graph Returned an error: '. $e->getMessage();
return $response;
} catch (FacebookSDKException $e) {
$response['status'] = false;
$response['message'] = 'Facebook SDK returned an error: ' . $e->getMessage();
return $response;
}
This is working fine. But not working for group.
The problem that could be is that I don't have access_token of group and thus using user's access_token
How to get access_token?
To get access token of pages, I am doing
try {
$userPages = $fb->get('/me/accounts', $accessToken->getValue());
$userPages = $userPages->getDecodedBody()['data'];
} catch (FacebookResponseException $e) {
echo 'Graph returned an error: ' . $e->getMessage();
exit;
} catch (FacebookSDKException $e) {
echo 'Facebook SDK returned an error: ' . $e->getMessage();
exit;
}
which return an array of pages with id, name, category and access_token.
[
0 => [
'name' => 'my page name',
'category' => 'Education',
'id' => 1234567890,
'access_token' => 'hkjh3k42j4j4l1kj4h1lj'
],
]
But when I get groups using
try {
$userGroups = $fb->get('me/groups', $accessToken->getValue());
$userGroups = $userGroups->getDecodedBody()['data'];
} catch (FacebookResponseException $e) {
echo 'Graph returned an error: ' . $e->getMessage();
exit;
} catch (FacebookSDKException $e) {
echo 'Facebook SDK returned an error: ' . $e->getMessage();
exit;
}
I only returns
[
0 => [
'name' => 'my group name',
'privacy' => 'OPEN',
'id' => 1234567890
]
]
and there is no access token.
How can I get access token of the group?
Here $accessToken->getValue() is the access_token of user when he authenticates the app.

Facebook GRAPH api list videos from page

I am trying to list all videos from a Facebook Fan Page an i got some problems. I keep getting Facebook SDK returned an error: You must provide an access token.. I tried using the access token, but no use.
CODE :
use Facebook;
use Facebook\FacebookApp;
use Facebook\FacebookRequest;
use FileUpload\FacebookFile;
use FileUpload\FacebookVideo;
use Facebook\Authentication\AccessToken;
$expires = time() + 60 * 60 * 2;
$accessToken = new Facebook\Authentication\AccessToken('mytoken1234567890', $expires);
var_dump($accessToken);
$fb = new Facebook\Facebook([
'app_id' => 'XXX',
'app_secret' => 'XXX',
'access_token' => "mytoken1234567890",
'default_graph_version' => 'v2.5',
]);
$request = $fb->request('POST', '/uniladmag/videos');
try
{
$response = $fb->getClient()->sendRequest($request);
}
catch(Facebook\Exceptions\FacebookResponseException $e)
{
echo 'Graph returned an error: ' . $e->getMessage();
exit;
} catch(Facebook\Exceptions\FacebookSDKException $e)
{
// When validation fails or other local issues
echo 'Facebook SDK returned an error: ' . $e->getMessage();
exit;
}
$graphNode = $response->getGraphNode();
print_r($graphNode);
?>
OUTPUT :
object(Facebook\Authentication\AccessToken)#2 (2) {
["value":protected]=>
string(17) "mytoken1234567890"
["expiresAt":protected]=>
object(DateTime)#3 (3) {
["date"]=>
string(26) "2017-02-14 18:20:13.000000"
["timezone_type"]=>
int(3)
["timezone"]=>
string(13) "Europe/Berlin"
}
}
Facebook SDK returned an error: You must provide an access token.
What solutions do i have? Do i miss something?
Thanks.

Facebook api autopost

i use facebook api for auto post from my website.
here is my code, after that i explain my problem:
require_once "Facebook/autoload.php";
$fb = new Facebook\Facebook([
'app_id' => 'xxxxxxx',
'app_secret' => 'xxxxxxxxx',
'default_graph_version' => 'v2.2'
]);
$pageAccessToken = 'xxxxxxxxxxxxxxxxxxxxx';
$linkData = [
'link' => $link,
'message' => $message,
'picture' => $pic
];
try {
$response = $fb->post('/me/feed', $linkData, $pageAccessToken);
} catch (Facebook\Exceptions\FacebookResponseException $e) {
echo 'Graph returned an error: ' . $e->getMessage();
} catch (Facebook\Exceptions\FacebookSDKException $e) {
echo 'Facebook SDK returned an error: ' . $e->getMessage();
}
$graphNode = $response->getGraphNode();
my problem is that, this code work sometimes, not all time.
and in sometime i see these errors:
Severity: Notice
Message: Undefined offset: 1
Filename: Http/GraphRawResponse.php
Line Number: 108
and
Severity: 4096
Message: Argument 4 passed to Facebook\FacebookResponse::__construct() must be of the type array, null given, called in /home/deponews/public_html/application/controllers/Facebook/FacebookClient.php on line 225 and defined
Filename: Facebook/FacebookResponse.php
Line Number: 75
i go to api explorer , and select my page from drop down and at the bottom drop down , select access page token , then select my page name again.
and copy generation token into my page access token.
i don't know why sometimes this code work well , and sometimes its not.
any idea ?
tnx

PHP - Post to Facebook Page using SDK no errors but no posts showing

I'm using the tutorial here http://www.adamboother.com/blog/automatically-posting-to-a-facebook-page-using-the-facebook-sdk-v5-for-php-facebook-api/ to post to a facebook page using the PHP sdk.
I have create the app on Facebook, and I have created the Never Expire Page Access Token, which I have verified using the Access Token Debug Tool https://developers.facebook.com/tools/debug/accesstoken/
However, when I run my test code, it does NOT return any errors, but I get no posts on my page. I get a response back from my print_r($graphNode) of the following
Facebook\GraphNodes\GraphNode Object
(
[items:protected] => Array
(
[id] => 1204777049583245_1264619360265680
)
)
The code for my test post is below, can anyone explain to me WHY I am not getting any posts to show up?
define("FACEBOOK_APP_ID","MY APP ID");
define("FACEBOOK_APP_SECRET","MY APP SECRET");
define("FACEBOOK_APP_TOKEN","MY PAGE ACCESS TOKEN");
define("FACEBOOK_SDK_V4_SRC_DIR",$_SERVER['DOCUMENT_ROOT'].'/socialmedia/Facebook/src/Facebook/');
require_once($_SERVER['DOCUMENT_ROOT'].'/socialmedia/Facebook/src/Facebook/autoload.php');
$fb = new Facebook\Facebook([
'app_id' => FACEBOOK_APP_ID,
'app_secret' => FACEBOOK_APP_SECRET,
'default_graph_version' => 'v2.2',
]);
//Post property to Facebook
$linkData = [
'link' => 'www.yoururl.com',
'message' => 'test message'
];
$pageAccessToken = FACEBOOK_APP_TOKEN;
try {
$response = $fb->post('/me/feed', $linkData, $pageAccessToken);
} 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 '<pre>';
print_r($graphNode);
echo '</pre>';
exit;

Facebook api posting to an Album

The code below posts to a photo album but also posts in the main timeline. Is there a way to only post to the album.
<?php
require_once __DIR__ . '/vendor/autoload.php';
$fb = new Facebook\Facebook([
'app_id' => 'xxxxxxxx',
'app_secret' => 'xxxxxxxxx',
'default_graph_version' => 'v2.5',
//'default_access_token' => '{access-token}', // optional
]);
$data = [
'message' => 'My awesome photo upload example.',
'source' => $fb->fileToUpload('./img/sandy.jpg'),
];
try {
// Returns a `Facebook\FacebookResponse` object
$response = $fb->post('/me/photos/test', $data, '{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 'Photo ID: ' . $graphNode['id'];
?>
Edit: Not working from January of 2017. More info here...
It's an old post, and I've searched a different topic, but if I'm here...
$data = [
'message' => 'My awesome photo upload example.',
'source' => $fb->fileToUpload('./img/sandy.jpg'),
'published' => false,
];