Facebook GRAPH api list videos from page - facebook

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.

Related

How can I get the amount spent / Faceook Marketing API

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}}'

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 graph error invalid signature

been wrestling with the facebook graph api a while now and am still not able to get what I want.
What am I missing? I have this code just as a test:
<?php
// );
$fb = new Facebook\Facebook([
'app_id' => '{313084575421679}',
'app_secret' => '{APP_SECRET}',
'default_graph_version' => 'v2.2',
]);
try {
// Returns a `Facebook\FacebookResponse` object
$response = $fb->get('/me?fields=id,name', '{APP_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;
}
$user = $response->getGraphUser();
echo 'Name: ' . $user['name'];
?>
it gives me this error Graph returned an error: Invalid OAuth access token signature.
later I want to retrieve al, the photo's links so I can create a collage of the pictures in my album.

Facebook api return error

Excuse for my bad english...
I downloaded and installed the facebook connection API. I am redirected to Facebook but once the authorization granted on facebook I encounter the following error: 'My mistake'
script 'index.php'
<?php
require_once __DIR__ . '/facebook_api/autoload.php';
$fb = new Facebook\Facebook([
'app_id' => '88xxxx29',
'app_secret' => 'xxxxxxxxxx',
'default_graph_version' => 'v2.2',
]);
$helper = $fb->getRedirectLoginHelper();
$permissions = ['email', 'user_location', 'user_about_me', 'user_birthday', 'user_actions.books']; // optional
$loginUrl = $helper->getLoginUrl('https://www.mywebsite.fr/fb-login-callback.php', $permissions);
echo 'Connexion';
?>
script 'fb-login-callback.php'
<?php
session_save_path("sessions/");
session_start();
require_once __DIR__ . '/facebook_api/autoload.php';
$fb = new Facebook\Facebook([
'app_id' => '88xxxx29',
'app_secret' => ‘xxxxxxxxxx',
'default_graph_version' => 'v2.2',
]);
$helper = $fb->getRedirectLoginHelper();
try {
$accessToken = $helper->getAccessToken();
} catch(Facebook\Exceptions\FacebookResponseException $e) {
// When Graph returns an error
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;
}
if (! isset($accessToken)) {
if ($helper->getError()) {
header('HTTP/1.0 401 Unauthorized');
echo "Error: " . $helper->getError() . "\n";
echo "Error Code: " . $helper->getErrorCode() . "\n";
echo "Error Reason: " . $helper->getErrorReason() . "\n";
echo "Error Description: " . $helper->getErrorDescription() . "\n";
} else {
header('HTTP/1.0 400 Bad Request');
echo 'Bad request';
}
exit;
}
// Logged in
echo '<h3>Access Token</h3>';
var_dump($accessToken->getValue());
// The OAuth 2.0 client handler helps us manage access tokens
$oAuth2Client = $fb->getOAuth2Client();
// Get the access token metadata from /debug_token
$tokenMetadata = $oAuth2Client->debugToken($accessToken);
echo '<h3>Metadata</h3>';
var_dump($tokenMetadata);
// Validation (these will throw FacebookSDKException's when they fail)
$tokenMetadata->validateAppId($config['app_id']);
// If you know the user ID this access token belongs to, you can validate it here
//$tokenMetadata->validateUserId('123');
$tokenMetadata->validateExpiration();
if (! $accessToken->isLongLived()) {
// Exchanges a short-lived access token for a long-lived one
try {
$accessToken = $oAuth2Client->getLongLivedAccessToken($accessToken);
} catch (Facebook\Exceptions\FacebookSDKException $e) {
echo "<p>Error getting long-lived access token: " . $helper->getMessage() . "</p>\n\n";
exit;
}
echo '<h3>Long-lived</h3>';
var_dump($accessToken->getValue());
}
$_SESSION['fb_access_token'] = (string) $accessToken;
// User is logged in with a long-lived access token.
// You can redirect them to a members-only page.
//header('Location: https://example.com/members.php');
?>
Error returned :
Acces token meta data contains unexpected app id.
But the id specified in the script is correct...
Metadata
object(Facebook\Authentication\AccessTokenMetadata)#13 (1) { ["metadata":protected]=> array(7) { ["app_id"]=> string(15) "88xxxx29" ["application"]=> string(13) “mywebsite" ["expires_at"]=> object(DateTime)#17 (3) { ["date"]=> string(26) "2015-11-20 17:55:52.000000" ["timezone_type"]=> int(3) ["timezone"]=> string(12) "Europe/Paris" } ["is_valid"]=> bool(true) ["issued_at"]=> object(DateTime)#18 (3) { ["date"]=> string(26) "2015-09-21 18:55:52.000000" ["timezone_type"]=> int(3) ["timezone"]=> string(12) "Europe/Paris" } ["scopes"]=> array(6) { [0]=> string(13) "user_birthday" [1]=> string(13) "user_location" [2]=> string(13) "user_about_me" [3]=> string(5) "email" [4]=> string(18) "user_actions.books" [5]=> string(14) "public_profile" } ["user_id"]=> string(17) "10207379116973089" } }
**Fatal error: Uncaught exception 'Facebook\Exceptions\FacebookSDKException' with message 'Access token metadata contains unexpected app ID.'** in /home/wbs/www/facebook_api/Authentication/AccessTokenMetadata.php:329 Stack trace: #0 /home/wbs/www/fb-login-callback.php(53): Facebook\Authentication\AccessTokenMetadata->validateAppId(NULL) #1 {main} thrown in /home/wbs/www/facebook_api/Authentication/AccessTokenMetadata.php on line 329
You try to access the $config['app_id'] variable, but you have not defined that.
Try this out:
$config =[
'app_id' => '88xxxx29',
'app_secret' => ‘xxxxxxxxxx',
'default_graph_version' => 'v2.2',
];
$fb = new Facebook\Facebook ($config );