upload video to facebook group using Graph API - facebook

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.

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 SDK returned an error: Access token was not returned from Graph

What does mean the error:
Facebook SDK returned an error: Access token was not returned from Graph.
?
Older code have stopped suddenly and I have to implement a new Facebook Authentication script.
What I do wrong? What I need also?
My code:
if(!session_id()) {
session_start();
}
include_once APP_PATH . "plugins/fbsdk-v5/autoload.php";
use Facebook\Facebook;
use Facebook\Exceptions\FacebookResponseException;
use Facebook\Exceptions\FacebookSDKException;
$fb = new Facebook([
'app_id' => $_SESSION['config']['social_facebook_id'],
'app_secret' => $_SESSION['config']['social_facebook_auth'],
'default_graph_version' => 'v2.2',
]);
$helper = $fb->getRedirectLoginHelper();
$permissions = array('email','public_profile');
try {
if(isset($_SESSION['facebook_access_token'])) {
$accessToken = $_SESSION['facebook_access_token'];
}
else {
$accessToken = $helper->getAccessToken();
}
} catch(FacebookResponseException $e) {
echo 'Graph returned an error: ' . $e->getMessage();
} catch(FacebookSDKException $e) {
echo 'Facebook SDK returned an error: ' . $e->getMessage();
}
if(isset($accessToken)){
if(isset($_SESSION['facebook_access_token'])) {
$fb->setDefaultAccessToken($_SESSION['facebook_access_token']);
}
else {
$_SESSION['facebook_access_token'] = strval($accessToken);
$oAuth2Client = $fb->getOAuth2Client();
$longLivedAccessToken = $oAuth2Client->getLongLivedAccessToken($_SESSION['facebook_access_token']);
$_SESSION['facebook_access_token'] = strval($longLivedAccessToken);
$fb->setDefaultAccessToken($_SESSION['facebook_access_token']);
}
if(isset($_GET['code'])){
header('Location: ./');
}
try {
$profileRequest = $fb->get('/me?fields=id,name,email', $accessToken);
$fbUserProfile = $profileRequest->getGraphNode()->asArray();
} catch(FacebookResponseException $e) {
echo 'Graph returned an error: ' . $e->getMessage();
session_destroy();
header("Location: ./");
exit;
} catch(FacebookSDKException $e) {
echo 'Facebook SDK returned an error: ' . $e->getMessage();
exit;
}
$fbUserData = array(
'oauth_provider'=> 'facebook',
'oauth_uid' => $fbUserProfile['id'],
'first_name' => $fbUserProfile['first_name'],
'last_name' => $fbUserProfile['last_name'],
'email' => $fbUserProfile['email'],
'gender' => $fbUserProfile['gender'],
'locale' => $fbUserProfile['locale'],
'picture' => $fbUserProfile['picture']['url'],
'link' => $fbUserProfile['link']
);
$_SESSION['userData'] = $userData;
$logoutUrl = $helper->getLogoutUrl($accessToken, APP_URL . "users/logout.html");
}
else {
$loginUrl = $helper->getLoginUrl(APP_URL . "users/login-using-facebook.html", $permissions);
}
My new code:
<?php
include_once APP_PATH . "plugins/fbsdk-v5/autoload.php";
use Facebook\Facebook;
use Facebook\Exceptions\FacebookResponseException;
use Facebook\Exceptions\FacebookSDKException;
$fb = new Facebook(array(
'app_id' => $_SESSION['config']['social_facebook_id'],
'app_secret' => $_SESSION['config']['social_facebook_auth'],
'default_graph_version' => 'v2.3',
));
if($_GET['action'] == 'login-using-facebook') { // callback
$helper = $fb->getRedirectLoginHelper();
try {
$accessToken = $helper->getAccessToken();
var_dump($accessToken);
} 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
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);
var_dump($tokenMetadata);
// Validation (these will throw FacebookSDKException's when they fail)
$tokenMetadata->validateAppId($_SESSION['config']['social_facebook_id']); // Replace {app-id} with your 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;
}
var_dump($accessToken->getValue());
}
$_SESSION['fb_access_token'] = strval($accessToken);
}
elseif($_SESSION['fb_access_token']) { // retrieve
try {
// Returns a `Facebook\FacebookResponse` object
$response = $fb->get('/me?fields=id,name', $_SESSION['fb_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;
}
$user = $response->getGraphUser();
echo 'Name: ' . $user['name'];
}
else { // login
$helper = $fb->getRedirectLoginHelper();
$permissions = array('email');
$loginUrl = $helper->getLoginUrl(APP_URL."users/login-using-facebook.html", $permissions);
}
?>
I used developers.facebook.com/docs/php/howto/example_facebook_logi‌​n and developers.facebook.com/docs/php/howto/profilewithgraphapi and it still doesn't work :( I can't understand why the example code is wrong in my script.
Can anybody help me?

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 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,
];

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.