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?
Related
I am trying to integrate facebook api in laravel.
I had update my composer.
I am stuck with the error :
Symfony\Component\Debug\Exception\FatalErrorException thrown with
message "Illuminate\View\Engines\PhpEngine::main(): Failed opening
required
'C:\xampp\htdocs\mero-theatre-sm-integration\storage\framework\viewsfb/fb/src/Facebook/autoload.php'
(include_path='C:\xampp\php\PEAR')"
<?php
session_start();
require_once __DIR__ .'fb/fb/src/Facebook/autoload.php';
$fb = new Facebook\Facebook([
'app_id' => '369611640182768',
'app_secret' => '909...................',
'default_graph_version' => 'v2.12',
]);
$helper = $fb->getRedirectLoginHelper();
$permissions = ['email']; // 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 {
// getting short-lived access token
$_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;
// setting default access token to be used in script
$fb->setDefaultAccessToken($_SESSION['facebook_access_token']);
}
// redirect the user back to the same page if it has "code" GET variable
if (isset($_GET['code'])) {
header('Location: ./');
}
// getting basic info about user
try {
$profile_request = $fb->get('/me?fields=name,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();
session_destroy();
// redirecting user back to app login page
header("Location: ./");
exit;
} catch (Facebook\Exceptions\FacebookSDKException $e) {
// When validation fails or other local issues
echo 'Facebook SDK returned an error: ' . $e->getMessage();
exit;
}
// printing $profile array on the screen which holds the basic info about user
print_r($profile);
// Now you can redirect to another page and use the access token from $_SESSION['facebook_access_token']
} else {
// replace your website URL same as added in the developers.facebook.com/apps e.g. if you used http instead of https and you used non-www version or www version of your website then you must add the same here
$loginUrl = $helper->getLoginUrl('https://sohaibilyas.com/fbapp/', $permissions);
echo 'Log in with Facebook!';
}
I've this simply facebook login integration.
I need to pass to the callback (that in this case is this same page) a custom parameter but the new $helper->getLoginUrl does not allow adding params. Previuosly I see that there was a next parameter that can be used to store a string but now it was removed.
It seems that I can't add a custom param neither in the session.
Is there any method to achieve my purpose?
<?php
require '../facebooksrc/autoload.php';
$userdata='/me?fields=name,first_name,last_name,email,gender,location,birthday';
$permissions = ['email, user_location, publish_actions, user_birthday'];
$fb = new Facebook\Facebook([
'app_id' => $appid,
'app_secret' => $appsecret,
'default_graph_version' => 'v2.5',
]);
$helper = $fb->getRedirectLoginHelper();
$_SESSION['FBRLH_state']=$_GET['state'];
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 {
// getting short-lived access token
$_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;
// setting default access token to be used in script
$fb->setDefaultAccessToken($_SESSION['facebook_access_token']);
}
// redirect the user back to the same page if it has "code" GET variable
if (isset($_GET['code'])) {
header('Location: ./');
}
// getting basic info about user
try {
$profile_request = $fb->get($userdata);
$profile = $profile_request->getGraphNode()->asArray();
} 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;
}
$firstname=$profile["first_name"];
$lastname=$profile["last_name"];
// MY INSERT QUERY
} else {
$url="myurl";
$loginUrl = $helper->getLoginUrl($url, $permissions);
//REDIRECT
header("Location: $loginUrl");
}
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.
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>
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>";
}