API Facebook Post in album user - php

I use graph v2.10, php sdk 5.5 I try to post on user album if is founded, but my script display an error:
Graph return an error. Permission error.
When an user try to login to my website, user give permissions publish_actions, email, user_photos to app. But graph say permission error.
$albums = $fb->get('/me/albums', $_SESSION['facebook_access_token'])->getGraphEdge()->asArray();
$album = array();
foreach($albums as $k=>$v) {
if($fetch_api['album_name'] == $v['name']) {
$album[$fetch_api['album_name']] = $v['id'] ;
}
}
if(count($album > 0)) {
$data = [
'message' => $_POST['msg'],
'source' => $fb->fileToUpload('images/gallery-img1.jpg'),
];
try {
// Returns a `Facebook\FacebookResponse` object
$response = $fb->post('/'.$album[$fetch_api['album_name']].'/photos', $data, $_SESSION['facebook_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;
}

Related

How to get app_domains attribute array from Facebook API

Following at the Facebook API docs I'm able to return only 4 attributes from my FB app.
My Code:
$user = Auth::user();
try {
$response = $this->facebook->get('/'.$user->facebook_app_id, $user->facebook_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();
dd($graphNode);
This only returns 4 attributes
I need it to also return app_domains. Looking at the docs it looks like it should? Is there a way to return the app_domains array from a FB app? FB app API
Looks like you'll need to use something like this:
$response = $this->facebook->get('/'.$user->facebook_app_id,
['fields' => 'app_domains'],
$user->facebook_access_token
);

Facebook API - Post as page in community groups

With the new feature of connecting pages with groups (https://grytics.com/blog/link-facebook-groups-pages/) I tought, that it would be possible to post as page on group feed via Graph API. All my tries ended up with errors saying:
thereĀ“s no Edge/Node 'groups' on page
require_once "./vendor/autoload.php";
use Facebook\Facebook;
use Facebook\Exceptions\FacebookResponseException;
use Facebook\Exceptions\FacebookSDKException;
use Facebook\Authentication\OAuth2Client;
use Facebook\Authentication\AccessToken;
use Facebook\Helpers\FacebookRedirectLoginHelper;
$fb = new Facebook([
'app_id' => '123456',
'app_secret' => 'abcde',
'default_graph_version' => 'v2.10',
//'default_access_token' => PAGE_TOKEN, // optional
]);
$helper = $fb->getCanvasHelper();
$permissions = ['user_managed_groups', 'publish_actions', 'manage_pages', 'publish_pages'];
$tokenFileName = "./fb-token.txt";
$date = new DateTime();
$cityToPost = 'Berlin';
$autopostGroups = array();
$message = array(
'message' => 'TEST Post: '.$date->getTimestamp(),
'link' => 'https://domain.de'
);
try {
// Refresh longlicedaccesstoken with new one
if (file_exists($tokenFileName)) {
$token = file_get_contents($tokenFileName);
$lastTokenRefresh = time() - filemtime($tokenFileName);
if ($lastTokenRefresh > 60 * 60 * 24 * 7)
{
$oAuth2Client = $fb->getOAuth2Client();
$newToken = $oAuth2Client->getAccessTokenFromCode(
$oAuth2Client->getCodeFromLongLivedAccessToken(
$token
)
);
file_put_contents($tokenFileName, (string) $newToken);
$accessToken = (string) $newToken;
}else{
$accessToken = (string) $token;
}
} else {
$accessToken = $helper->getAccessToken();
}
} catch(FacebookResponseException $e) {
// When Graph returns an error
echo 'Graph returned an error: ' . $e->getMessage();
unlink($tokenFileName);
exit;
} catch(FacebookSDKException $e) {
// When validation fails or other local issues
echo 'Facebook SDK returned an error: ' . $e->getMessage();
unlink($tokenFileName);
exit;
}
if (isset($accessToken)) {
if (file_exists($tokenFileName)) {
$fb->setDefaultAccessToken(file_get_contents($tokenFileName));
} else {
// OAuth 2.0 client handler
$oAuth2Client = $fb->getOAuth2Client();
// Exchanges a short-lived access token for a long-lived one
$longLivedAccessToken = $oAuth2Client->getLongLivedAccessToken((string) $accessToken);
file_put_contents($tokenFileName, (string) $longLivedAccessToken);
$fb->setDefaultAccessToken($longLivedAccessToken);
}
// redirect user back to app when page receives $_GET['code'] variable
if (isset($_GET['code'])) {
echo "<script>window.top.location.href='https://apps.facebook.com/xyz/';</script>";
exit;
}
// validating the access token
try {
$request = $fb->get('/me');
} catch(FacebookResponseException $e) {
// When Graph returns an error
if ($e->getCode() == 190) {
unlink($tokenFileName);
//unset($_SESSION['facebook_access_token']);
$helper = $fb->getRedirectLoginHelper();
$loginUrl = $helper->getLoginUrl('https://apps.facebook.com/xyz/', $permissions);
echo "<script>window.top.location.href='".$loginUrl."'</script>";
exit;
}
} catch(FacebookSDKException $e) {
// When validation fails or other local issues
echo 'Facebook SDK returned an error: ' . $e->getMessage();
exit;
}
// get list of groups managed by user
try {
$requestGroups = $fb->get('/me/groups');
$groups = $requestGroups->getGraphEdge()->asArray();
} 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;
}
foreach ($groups as $group) {
if(strpos($group['name'], 'VENDOR') !== false && strpos($group['name'], $cityToPost) !== false){
array_push($autopostGroups,$group['id']); //Only for debugging
try {
$requestPost = $fb->post('/'.$group['id'].'/feed', $message);
$post = $requestPost->getGraphNode()->asArray();
var_dump($post);
} 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;
}
}
}
// Now you can redirect to another page and use the access token from $tokenFileName
} else {
$helper = $fb->getRedirectLoginHelper();
$loginUrl = $helper->getLoginUrl('https://apps.facebook.com/xyz/', $permissions);
echo "<script>window.top.location.href='".$loginUrl."'</script>";
}
I am new to the fb api, and I am not a english native speaker, so maybe someone is able to clearify that situation?
Thank you!
[EDIT 1]
Added code. Hint: When I change PAGE_TOKEN to USER_TOKEN it works.
[EDIT 2]
Full Code added.
I found a user comment in the FB Group Facebook Developer Community from August:
And no, there is no build-in way to have page posts show up in a group
automatically.

facebook php sdk - access token is empty

I would like to ask a facebook timeline and photo gallery, but the access token is null.
$this->FaceBookApp = new Facebook\Facebook(array(
"app_id" => $this->appID,
"app_secret" => $this->appSecret,
"default_graph_version" => "v2.5"
));
$helper = $this->FaceBookApp->getRedirectLoginHelper();
$permissions = array('user_posts');
$loginUrl = $helper->getLoginUrl( _WEBPAGE .'/facebook-sdk/printAccessToken.php', $permissions);
echo "<script>window.top.location.href='".$loginUrl."'</script>";
callback php:
$helper = $this->FaceBookApp->getCanvasHelper();
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;
}
var_dump($accessToken);
when i try without access token, the
$response = $this->FaceBookApp->get('/'.$userId.'/feed', $this->appID .'|'. $this->appSecret);
var_dump( $response->getDecodedBody() );
is empty array.
Please, help me.

How to set uploaded photo as profile picture in facebook?

I have successfully uploaded picture to facebook using Graph API v5.
But how do i make it default profile picture ?
Following is my upload() function:
//Upload image
function upload($path,$token,$fb)
{
$image = [
'message' => 'My awesome photo upload example.',
'source' => $fb->fileToUpload($path), // $fb is instance
];
try {
// Returns a `Facebook\FacebookResponse` object
$response = $fb->post('/me/photos', $image, $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();
debug_to_console($graphNode);
echo " \n Photo ID: " . $graphNode['id'];
}
https://developers.facebook.com/docs/php/api

Facebook user Graph does not return Email PHP

I am new to the whole Facebook API.
I am creating a login page for users, and the idea is that they login with Facebook.
At the top of login page I have the following code:
$fb = new Facebook\Facebook([
'app_id' => "$fb_appid",
'app_secret' => "$fb_appsecret",
'default_graph_version' => 'v2.2',
]);
Then a little lower I have the login button:
if(isset($fb)){
$helper = $fb->getRedirectLoginHelper();
$permissions = ['email']; // optional
$fb_login_url = $helper->getLoginUrl("$server_url/public/facebook/login-callback", $permissions);
} else $fb_login_url = "";
if(strlen($fb_login_url) >= 1) echo "<a href='$fb_login_url'><i class='fa fa-2x fa-facebook-square'></i></a>";
else echo "<a href='#' disabled='disabled'><i class='fa fa-2x fa-facebook-square'></i></a>";
The code works up until there, if I click the button, I go through to the Facebook portal, click the allow for the permissions and whatever, then it redirects me to login-callback.
The code on login-callback is:
if(isset($fb)){
$helper = $fb->getRedirectLoginHelper();
try {
$accessToken = $helper->getAccessToken();
} catch(Facebook\Exceptions\FacebookResponseException $e) {
$err_message = 'Graph returned an error: ' . $e->getMessage();
access_log("facebook_login","IP:$client_ip\r\nFacebook Error: $err_message");
} catch(Facebook\Exceptions\FacebookSDKException $e) {
$err_message = 'Facebook SDK returned an error: ' . $e->getMessage();
access_log("facebook_login","IP:$client_ip\r\nFacebook Error: $err_message");
}
if (strlen($err_message) <= 0 && isset($accessToken)) {
$_SESSION['facebook_access_token'] = (string) $accessToken;
$fb->setDefaultAccessToken("$accessToken");
try {
$response = $fb->get('/me');
$userNode = $response->getGraphUser();
// $username = $userNode->getName();
// $firstname = $userNode->getFirstName();
// $lastname = $userNode->getLastName();
print_r($userNode);
} catch(Facebook\Exceptions\FacebookResponseException $e) {
$err_message = 'Graph returned an error: ' . $e->getMessage();
access_log("facebook_login","IP:$client_ip\r\nFacebook Error: $err_message");
} catch(Facebook\Exceptions\FacebookSDKException $e) {
$err_message = 'Facebook SDK returned an error: ' . $e->getMessage();
access_log("facebook_login","IP:$client_ip\r\nFacebook Error: $err_message");
}
}
}
The $userNode looks like this:
Facebook\GraphNodes\GraphUser Object
(
[items:protected] => Array
(
[name] => Jacques Koekemoer
[id] => xxxxxxxxxxxxxxxxxx
)
)
I have set the permissions to allow for the email, and if I am not mistaken the public profile is sent automatically.
I have also checked that the button on the login page does have "&scope=email". Below is the code that I have right on the page right now in the login button:
https://www.facebook.com/v2.2/dialog/oauth?client_id=xxxxxxxx&state=xxxxxxxx&response_type=code&sdk=php-sdk-5.0.0&redirect_uri=http%3A%2F%2Fxxxxxxx.xxxxxxxxxxxx.co.za%2Fpublic%2Ffacebook%2Flogin-callback&scope=email
I replaced the client_id, state and domain name because I don't want that information available publicly as I don't know what people can do with it.
Let me know if it is needed to solve the problem.
I used the Facebook guide here to setup and download the SDK.
I solved the problem.
You need to request specific fields from Facebook in the get function.
$response = $fb->get('/me?fields=id,name,email');
This can be found here.
A full list of fields that you can query can be found here.
Example
if (isset($fb)) {
$helper = $fb->getRedirectLoginHelper();
try {
$accessToken = $helper->getAccessToken();
} catch (Facebook\Exceptions\FacebookResponseException $e) {
$err_message = 'Graph returned an error: ' . $e->getMessage();
access_log("facebook_login", "IP:$client_ip\r\nFacebook Error: $err_message");
} catch (Facebook\Exceptions\FacebookSDKException $e) {
$err_message = 'Facebook SDK returned an error: ' . $e->getMessage();
access_log("facebook_login", "IP:$client_ip\r\nFacebook Error: $err_message");
}
if (strlen($err_message) <= 0 && isset($accessToken)) {
$_SESSION['facebook_access_token'] = (string)$accessToken;
$fb->setDefaultAccessToken("$accessToken");
try {
// this here is where you specify the fields
$response = $fb->get('/me?fields=id,name,email');
$userNode = $response->getGraphUser();
/* handle the result */
} catch (Facebook\Exceptions\FacebookResponseException $e) {
$err_message = 'Graph returned an error: ' . $e->getMessage();
access_log("facebook_login", "IP:$client_ip\r\nFacebook Error: $err_message");
} catch (Facebook\Exceptions\FacebookSDKException $e) {
$err_message = 'Facebook SDK returned an error: ' . $e->getMessage();
access_log("facebook_login", "IP:$client_ip\r\nFacebook Error: $err_message");
}
}
}
One of the my friend was trying to the issue from last 5 days. huummm very irritating. which got love in 2 min...
Assumption: using PHP for O2Authentication
Solution:
$loginURL = $fb->getLoginUrl({your redirect URL},['email']);
And job is done.
Thanks & Regards
Jaiswar Vipin Kumar R.
Check you app version if it is version 2.2 or lower, it will work fine , it is not than it will not return. for that you have to request api with scope for email access.

Categories