How to change facebook profile pic using php - php

I want to make a Facebook canvas app for a cause, where I need to change the profile pic of user with his/her permission, I have fetched user's profile pic with selected viewport and placed an overlay of that cause but &makeprofile=1 is not working it redirects me to pic in theater mode. I want something like this app.
<?php
session_start();
require_once __DIR__ . '/Facebook/autoload.php';
$fb = new Facebook\Facebook([
'app_id' => 'app',
'app_secret' => 'secret',
'default_graph_version' => 'v2.6',
]);
$helper = $fb->getCanvasHelper();
$permissions = ['email','publish_actions']; // optionnal
try {
if (isset($_SESSION['facebook_access_token'])) {
$accessToken = $_SESSION['facebook_access_token'];
} else {
$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 (isset($_SESSION['facebook_access_token'])) {
$fb->setDefaultAccessToken($_SESSION['facebook_access_token']);
} else {
$_SESSION['facebook_access_token'] = (string) $accessToken;
// OAuth 2.0 client handler
$oAuth2Client = $fb->getOAuth2Client();
// Exchanges a short-lived access token for a long-lived one
$longLivedAccessToken = $oAuth2Client->getLongLivedAccessToken($_SESSION['facebook_access_token']);
$_SESSION['facebook_access_token'] = (string) $longLivedAccessToken;
$fb->setDefaultAccessToken($_SESSION['facebook_access_token']);
}
// validating the access token
try {
$request = $fb->get('/me');
} catch(Facebook\Exceptions\FacebookResponseException $e) {
// When Graph returns an error
if ($e->getCode() == 190) {
unset($_SESSION['facebook_access_token']);
$helper = $fb->getRedirectLoginHelper();
$loginUrl = $helper->getLoginUrl('https://apps.facebook.com/my-first-qode/', $permissions);
echo "<script>window.top.location.href='".$loginUrl."'</script>";
exit;
}
} catch(Facebook\Exceptions\FacebookSDKException $e) {
// When validation fails or other local issues
echo 'Facebook SDK returned an error: ' . $e->getMessage();
exit;
}
// getting basic info about user
try {
$requestPicture = $fb->get('/me/picture?redirect=false&width=400&height=400');
$profile_request = $fb->get('/me?fields=name,first_name,last_name,email');
$picture = $requestPicture->getGraphUser();
$profile = $profile_request->getGraphNode()->asArray();
} catch(Facebook\Exceptions\FacebookResponseException $e) {
// When Graph returns an error
echo 'Graph returned an error: ' . $e->getMessage();
unset($_SESSION['facebook_access_token']);
echo "<script>window.top.location.href='https://apps.facebook.com/my-first-qode/'</script>";
exit;
} catch(Facebook\Exceptions\FacebookSDKException $e) {
// When validation fails or other local issues
echo 'Facebook SDK returned an error: ' . $e->getMessage();
exit;
}
// priting basic info about user on the screen
print_r($profile);
echo $profile['name'];
echo "<img src='".$picture['url']."'/>";
//image create
$base_image = imagecreatefrompng("mark.png");
// Get the facebook profile image in 200x200 pixels
$photo = imagecreatefromjpeg($picture['url']);
//$photo = imagecreatefromjpeg("http://graph.facebook.com/".$id."/picture?width=200&height=200");
//resizeImage($photo,920,920);
// read overlay
$overlay = imagecreatefrompng("mark.png");
// keep transparency of base image
imagesavealpha($base_image, true);
imagealphablending($base_image, true);
$lwidth = imagesx($photo);
$lheight = imagesy($photo);
// place photo onto base (reading all of the photo and pasting unto all of the base)
imagecopyresampled($base_image, $photo, 0, 0, 0,0, 200, 200, $lwidth, $lheight);
// place overlay on top of base and photo
imagecopy($base_image, $overlay, 0, 0, 0, 0, 200, 200);
// Save as jpeg
imagejpeg($base_image,'sample3.jpg');
//image create
echo '<img src="sample3.jpg" alt="photo_stamp1" />';
/*$data = [
'message' => 'My awesome photo upload example.',
'source' => $fb->fileToUpload('252676_368007166708864_8124350312635670437_n.jpg'),
// Or you can provide a remote file location
//'source' => $fb->fileToUpload('https://example.com/photo.jpg'),
];
try {
$response = $fb->post('/me/photos', $data);
} catch(Facebook\Exceptions\FacebookSDKException $e) {
echo 'Error: ' . $e->getMessage();
exit;
}
$graphNode = $response->getGraphNode();
echo 'Photo ID: ' . $graphNode['id'];
*/
// Now you can redirect to another page and use the access token from $_SESSION['facebook_access_token']
} else {
$helper = $fb->getRedirectLoginHelper();
$loginUrl = $helper->getLoginUrl('https://apps.facebook.com/my-first-qode/', $permissions);
echo "<script>window.top.location.href='".$loginUrl."'</script>";
}

You can´t change the profile picture directly, like it is done in that other App. You MUST redirect the user to the uploaded photo and he can then choose to make it his profile picture on his own. The celebrate pride App is from Facebook.

Related

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.

How to check whether user is admin after click"continue as"

I am creating a facebook quiz, but i had stuck with the following problem a couple of days. When user starts the game and after click "continue as" (the screen where facebook asks to get a couple of users information) i want to check whether that user who enters in the game is admin or not. So far, when user allow to share his informations, he enters in the game as user. I've tried a couple of different solutions, i have tried with sending a couple of different api's, i have read a tons of examples but so far i don't have any luck. At developers.facebook.com where my app is i have set the manage_pages and my user profile is select as a "administrator". This is my login.php script (the commented out code are my checked solutions). Any help will be much appreciated.
<?php
if (session_status() == PHP_SESSION_NONE) {
session_start();
}
include_once ('fb_sdk/src/Facebook/autoload.php');
$fb = new Facebook\Facebook([
'app_id' => '*******',
'app_secret' => '*******',
'default_graph_version' => 'v2.8',
]);
$helper = $fb->getCanvasHelper();
try {
if (isset($_SESSION['facebook_access_token'])) {
$accessToken = $_SESSION['facebook_access_token'];
} else {
$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 (isset($_SESSION['facebook_access_token'])) {
$fb->setDefaultAccessToken($_SESSION['facebook_access_token']);
} else {
$_SESSION['facebook_access_token'] = (string) $accessToken;
// OAuth 2.0 client handler
$oAuth2Client = $fb->getOAuth2Client();
// Exchanges a short-lived access token for a long-lived one
$longLivedAccessToken = $oAuth2Client->getLongLivedAccessToken($_SESSION['facebook_access_token']);
$_SESSION['facebook_access_token'] = (string) $longLivedAccessToken;
$fb->setDefaultAccessToken($_SESSION['facebook_access_token']);
}
// validating the access token
/*try {
$request = $fb->get('/me');
} catch(Facebook\Exceptions\FacebookResponseException $e) {
// When Graph returns an error
if ($e->getCode() == 190) {
unset($_SESSION['facebook_access_token']);
$helper = $fb->getRedirectLoginHelper();
$loginUrl = $helper->getLoginUrl('https://apps.facebook.com/facebookquiz/', $permissions);
echo "<script>window.top.location.href='".$loginUrl."'</script>";
exit;
}
} catch(Facebook\Exceptions\FacebookSDKException $e) {
// When validation fails or other local issues
echo 'Facebook SDK returned an error: ' . $e->getMessage();
exit;
}*/
// getting basic info about user
try {
$profile_request = $fb->get('/me?fields=first_name, last_name, email');
$profile = $profile_request->getGraphNode()->asArray();
} catch(Facebook\Exceptions\FacebookResponseException $e) {
// When Graph returns an error
echo 'Graph returned an error: ' . $e->getMessage();
unset($_SESSION['facebook_access_token']);
echo "<script>window.top.location.href='https://apps.facebook.com/facebookquiz/'</script>";
exit;
} catch(Facebook\Exceptions\FacebookSDKException $e) {
// When validation fails or other local issues
echo 'Facebook SDK returned an error: ' . $e->getMessage();
exit;
}
// priting basic info about user on the screen
$first_name = $profile['first_name'];
$last_name = $profile['last_name'];
$email = $profile['email'];
$fbUserId = $profile['id'];
print_r ($profile);
include_once('database/dbInsert.inc');
include_once('database/db_select.inc');
$fbUser = getUserByFBID($fbUserId);
if($fbUser == false){
$userID = insertUserInfo($fbUserId,$first_name, $last_name, $email);
$_SESSION['user_id'] = $userID;
}else{
$_SESSION['user_id'] = $fbUser->Id;
}
header("Location: index.php");
//redirect if is administrator
} else {
$helper = $fb->getRedirectLoginHelper();
$permissions = ['email', 'public_profile', 'publish_actions', 'manage_pages']; // optionnal 'user_managed_groups'
$loginUrl = $helper->getLoginUrl('https://apps.facebook.com/facebookquiz/login.php', $permissions);
echo "<script>window.top.location.href='".$loginUrl."'</script>";
}
?><?php
if (session_status() == PHP_SESSION_NONE) {
session_start();
}
include_once ('fb_sdk/src/Facebook/autoload.php');
$fb = new Facebook\Facebook([
'app_id' => 'app-if',
'app_secret' => 'app-secret',
'default_graph_version' => 'v2.8',
]);
$helper = $fb->getCanvasHelper();
try {
if (isset($_SESSION['facebook_access_token'])) {
$accessToken = $_SESSION['facebook_access_token'];
} else {
$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 (isset($_SESSION['facebook_access_token'])) {
$fb->setDefaultAccessToken($_SESSION['facebook_access_token']);
} else {
$_SESSION['facebook_access_token'] = (string) $accessToken;
// OAuth 2.0 client handler
$oAuth2Client = $fb->getOAuth2Client();
// Exchanges a short-lived access token for a long-lived one
$longLivedAccessToken = $oAuth2Client->getLongLivedAccessToken($_SESSION['facebook_access_token']);
$_SESSION['facebook_access_token'] = (string) $longLivedAccessToken;
$fb->setDefaultAccessToken($_SESSION['facebook_access_token']);
}
// validating the access token
/*try {
$request = $fb->get('/me');
} catch(Facebook\Exceptions\FacebookResponseException $e) {
// When Graph returns an error
if ($e->getCode() == 190) {
unset($_SESSION['facebook_access_token']);
$helper = $fb->getRedirectLoginHelper();
$loginUrl = $helper->getLoginUrl('https://apps.facebook.com/facebookquiz/', $permissions);
echo "<script>window.top.location.href='".$loginUrl."'</script>";
exit;
}
} catch(Facebook\Exceptions\FacebookSDKException $e) {
// When validation fails or other local issues
echo 'Facebook SDK returned an error: ' . $e->getMessage();
exit;
}*/
// getting basic info about user
try {
$profile_request = $fb->get('/me?fields=first_name, last_name, email');
$profile = $profile_request->getGraphNode()->asArray();
} catch(Facebook\Exceptions\FacebookResponseException $e) {
// When Graph returns an error
echo 'Graph returned an error: ' . $e->getMessage();
unset($_SESSION['facebook_access_token']);
echo "<script>window.top.location.href='https://apps.facebook.com/facebookquiz/'</script>";
exit;
} catch(Facebook\Exceptions\FacebookSDKException $e) {
// When validation fails or other local issues
echo 'Facebook SDK returned an error: ' . $e->getMessage();
exit;
}
// priting basic info about user on the screen
$first_name = $profile['first_name'];
$last_name = $profile['last_name'];
$email = $profile['email'];
$fbUserId = $profile['id'];
print_r ($profile);
include_once('database/dbInsert.inc');
include_once('database/db_select.inc');
$fbUser = getUserByFBID($fbUserId);
if($fbUser == false){
$userID = insertUserInfo($fbUserId,$first_name, $last_name, $email);
$_SESSION['user_id'] = $userID;
}else{
$_SESSION['user_id'] = $fbUser->Id;
}
/*$getPages = (new Facebook\FacebookRequest(
$session,
'GET',
'/me/accounts'
))->execute()->getGraphObject()->asArray();
$pageID = $getPages['data'][0]->id;
$pageAccessToken = $getPages['data'][0]->accessToken;
(new FacebookRequest(
$session,
'POST',
'/' . $pageID . '/feed',
array(
'accessToken' => $pageAccessToken;
'message' => 'Facebook app';
)
))->execute();*/
//foreach ($getPages['data'] as $key) {
//print_r($getPages);
/*echo $key->id;
echo "<br>";
echo $key->name;
echo "<br>";*/
//}
/*$response = $request->execute();
$graphObject = $response->getGraphObject();*/
/*$request = new FacebookRequest(
$_SESSION,
'POST',
'/883093058488924/roles',
array (
'user' => '123456789',
'role' => 'administrators',
)
);
$response = $request->execute();
$graphObject = $response->getGraphObject();
var_dump($graphObject);*/
header("Location: index.php");
//redirect if is administrator
// Now you can redirect to another page and use the access token from $_SESSION['facebook_access_token']
} else {
$helper = $fb->getRedirectLoginHelper();
$permissions = ['email', 'public_profile', 'publish_actions', 'manage_pages']; // optionnal 'user_managed_groups'
$loginUrl = $helper->getLoginUrl('https://apps.facebook.com/facebookquiz/login.php', $permissions);
echo "<script>window.top.location.href='".$loginUrl."'</script>";
}
?>

On executing PHP script in command line, it returns a webscript enclosed in script tags

As the title suggests, I am trying to execute a PHP file on linux command line and it is working fine, I am actually running PHP script to post a status on Facebook graph API, and on executing the script I am getting a webscript enclosed within a script tag,the response I get, how do I execute the response? how do I execute it automatically with out using a browser?
My final aim is to use the the cron tab to schedule the posting of a facebook status by calling this PHP script.
PHP CODE FOR POSTING
> $fb = new Facebook\Facebook([
'app_id' => '1784504901790451',
'app_secret' => '4b7b2673ecd268b962b0f25166955f23',
'default_graph_version' => 'v2.8',
]);
> $helper = $fb->getRedirectLoginHelper();
$permissions = ['email', 'publish_actions']; // optional
try {
if (isset($_SESSION['facebook_access_token'])) {
$accessToken = $_SESSION['facebook_access_token'];
} else {
$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 (isset($_SESSION['facebook_access_token'])) {
$fb->setDefaultAccessToken($_SESSION['facebook_access_token']);
} else {
$_SESSION['facebook_access_token'] = (string) $accessToken;
// OAuth 2.0 client handler
$oAuth2Client = $fb->getOAuth2Client();
// Exchanges a short-lived access token for a long-lived one
$longLivedAccessToken = $oAuth2Client->getLongLivedAccessToken($_SESSION['facebook_access_token']);
$_SESSION['facebook_access_token'] = (string) $longLivedAccessToken;
$fb->setDefaultAccessToken($_SESSION['facebook_access_token']);
}
// validating the access token
try {
$request = $fb->get('/me');
} catch(Facebook\Exceptions\FacebookResponseException $e) {
// When Graph returns an error
if ($e->getCode() == 190) {
unset($_SESSION['facebook_access_token']);
$helper = $fb->getRedirectLoginHelper();
$loginUrl = $helper->getLoginUrl('http://localhost/AutoPHPfb/', $permissions);
echo "<script>window.top.location.href='".$loginUrl."'</script>";
exit;
}
} catch(Facebook\Exceptions\FacebookSDKException $e) {
// When validation fails or other local issues
echo 'Facebook SDK returned an error: ' . $e->getMessage();
exit;
}
// posting on user timeline using publish_actins permission
try {
// message must come from the user-end
$data = [
'message' => 'My awesome photo upload example.',
'source' => $fb->fileToUpload('/var/www/bitvie.cloudapp.net/htdocs/AutoPHPfb/Photos/B612-2015-08-10-10-36-17.jpg'),
// Or you can provide a remote file location
//'source' => $fb->fileToUpload('https://example.com/photo.jpg'),
];
$request = $fb->post('/me/photos', $data);
$response = $request->getGraphNode();
} 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;
}
echo $response['id'];
// Now you can redirect to another page and use the
// access token from $_SESSION['facebook_access_token']
} else {
$helper = $fb->getRedirectLoginHelper();
$loginUrl = $helper->getLoginUrl('http://bitvie.cloudapp.net/AutoPHPfb/PHPprofilepic.php', $permissions);
echo "<script>window.top.location.href='".$loginUrl."'</script>";
}
and here is the reponse I get
<script>window.top.location.href='https://www.facebook.com/v2.8/dialog/oauth?client_id=1784504901790451&state=4a090fd3336bc798d3604bc760538e3f&response_type=code&sdk=php-sdk-5.0.0&redirect_uri=http%3A%2F%2Fbitvie.cloudapp.net%2FAutoPHPfb%2FPHPprofilepic.php&scope=email%2Cpublish_actions'</script>

Facebook canvas app unable to get access token using PHP SDK

Good Noon,
I am trying to create new facebook canvas app. Facebook app tried to get access token from getCanvasHelper() method, but every time I tried to print it shows blank. I am using PHP SDK 5.0.0
$helper = $fb->getCanvasHelper();
$accessToken = $helper->getAccessToken();
Here below is the full sample code. Due to access token issue I am unable to process further.
Any help would be appreciable.
Here below is my sample code.
<?php
session_start();
require_once __DIR__ . '/src/Facebook/autoload.php';
$fb = new Facebook\Facebook([
'app_id' => 'my_app_id_i_have_replce_it_for_security',
'app_secret' => 'my_app_secret_i_have_replce_it_for_security',
'default_graph_version' => 'v2.4',
]);
$helper = $fb->getCanvasHelper();
$permissions = ['user_posts']; // optionnal
try {
if (isset($_SESSION['facebook_access_token'])) {
$accessToken = $_SESSION['facebook_access_token'];
} else {
$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 (isset($_SESSION['facebook_access_token'])) {
$fb->setDefaultAccessToken($_SESSION['facebook_access_token']);
} else {
$_SESSION['facebook_access_token'] = (string) $accessToken;
// OAuth 2.0 client handler
$oAuth2Client = $fb->getOAuth2Client();
// Exchanges a short-lived access token for a long-lived one
$longLivedAccessToken = $oAuth2Client->getLongLivedAccessToken($_SESSION['facebook_access_token']);
$_SESSION['facebook_access_token'] = (string) $longLivedAccessToken;
$fb->setDefaultAccessToken($_SESSION['facebook_access_token']);
}
// validating the access token
try {
$request = $fb->get('/me');
} catch(Facebook\Exceptions\FacebookResponseException $e) {
// When Graph returns an error
if ($e->getCode() == 190) {
unset($_SESSION['facebook_access_token']);
$helper = $fb->getRedirectLoginHelper();
$loginUrl = $helper->getLoginUrl('https://apps.facebook.com/bs-kapil-canvas/', $permissions);
echo "<script>window.top.location.href='".$loginUrl."'</script>";
exit;
}
} catch(Facebook\Exceptions\FacebookSDKException $e) {
// When validation fails or other local issues
echo 'Facebook SDK returned an error: ' . $e->getMessage();
exit;
}
// getting all posts published by user
try {
$posts_request = $fb->get('/me/posts?limit=500');
} 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;
}
$total_posts = array();
$posts_response = $posts_request->getGraphEdge();
if($fb->next($posts_response)) {
$response_array = $posts_response->asArray();
$total_posts = array_merge($total_posts, $response_array);
while ($posts_response = $fb->next($posts_response)) {
$response_array = $posts_response->asArray();
$total_posts = array_merge($total_posts, $response_array);
}
print_r($total_posts);
} else {
$posts_response = $posts_request->getGraphEdge()->asArray();
print_r($posts_response);
}
// Now you can redirect to another page and use the access token from $_SESSION['facebook_access_token']
} else {
$helper = $fb->getRedirectLoginHelper();
$loginUrl = $helper->getLoginUrl('https://apps.facebook.com/bs-kapil-canvas/', $permissions);
echo "<script>window.top.location.href='".$loginUrl."'</script>";
}

Posting to Facebook via Website Application - Internal Server Error

I am using the following code to get a User's posts, with APP_ID, and APP_SECRET replaced with the appropriate fields.
<?php
session_start();
require_once __DIR__ . '/src/Facebook/autoload.php';
$fb = new Facebook\Facebook([
'app_id' => 'APP_ID',
'app_secret' => 'APP_SECRET',
'default_graph_version' => 'v2.5',]);
$helper = $fb->getCanvasHelper();
$permissions = ['user_posts']; // optionnal
try {
if (isset($_SESSION['facebook_access_token'])) {
$accessToken = $_SESSION['facebook_access_token'];
} else {
$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 (isset($_SESSION['facebook_access_token'])) {
$fb->setDefaultAccessToken($_SESSION['facebook_access_token']);
} else {
$_SESSION['facebook_access_token'] = (string) $accessToken;
// OAuth 2.0 client handler
$oAuth2Client = $fb->getOAuth2Client();
// Exchanges a short-lived access token for a long-lived one
$longLivedAccessToken = $oAuth2Client->getLongLivedAccessToken($_SESSION['facebook_access_token']);
$_SESSION['facebook_access_token'] = (string) $longLivedAccessToken;
$fb->setDefaultAccessToken($_SESSION['facebook_access_token']);
}
// validating the access token
try {
$request = $fb->get('/me');
} catch(Facebook\Exceptions\FacebookResponseException $e) {
// When Graph returns an error
if ($e->getCode() == 190) {
unset($_SESSION['facebook_access_token']);
$helper = $fb->getRedirectLoginHelper();
$loginUrl = $helper->getLoginUrl('https://apps.facebook.com/APP_NAMESPACE/', $permissions);
echo "<script>window.top.location.href='".$loginUrl."'</script>";
exit;
}
} catch(Facebook\Exceptions\FacebookSDKException $e) {
// When validation fails or other local issues
echo 'Facebook SDK returned an error: ' . $e->getMessage();
exit;
}
// getting all posts published by user
try {
$posts_request = $fb->get('/me/posts?limit=500');
} 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;
}
$total_posts = array();
$posts_response = $posts_request->getGraphEdge();
if($fb->next($posts_response)) {
$response_array = $posts_response->asArray();
$total_posts = array_merge($total_posts, $response_array);
while ($posts_response = $fb->next($posts_response)) {
$response_array = $posts_response->asArray();
$total_posts = array_merge($total_posts, $response_array);
}
print_r($total_posts);
} else {
$posts_response = $posts_request->getGraphEdge()->asArray();
print_r($posts_response);
}
// Now you can redirect to another page and use the access token from $_SESSION['facebook_access_token']
} else {
$helper = $fb->getRedirectLoginHelper();
$loginUrl = $helper->getLoginUrl('https://apps.facebook.com/APP_NAMESPACE/', $permissions);
echo "<script>window.top.location.href='".$loginUrl."'</script>";
}
When I run it locally on command line (php post.php), I get the following:
<script>window.top.location.href='https://www.facebook.com/v2.5/dialog/oauth?client_id=843019182480437&state=bb8b088f64641baed7d1e4de734ad19b&response_type=code&sdk=php-sdk-5.1.2&redirect_uri=https%3A%2F%2Fapps.facebook.com%2FAPP_NAMESPACE%2F&scope=user_posts
Which means the syntax is correct. When I go to the link I get the following notification by Facebook:
Given URL is not allowed by the Application configuration: One or more of the given URLs is not allowed by the App's settings. It must match the Website URL or Canvas URL, or the domain must be a subdomain of one of the App's domains.
I have set the Website URL to the appropriate value. When I try to access post.php from my server I get an internal server error.
Has anyone else experienced this before?

Categories