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.
Related
I used the facebook api to collect users facebook long-lived access token on my website and saved them in a database. now I want to retrieve them from the database and post on their wall. however I received the following error message:
Facebook SDK returned an error: You must provide an access token.
they have already given me the necessary permissions and I have provided access token from database
code:
<?php
define('FACEBOOK_SDK_V4_SRC_DIR', __DIR__.'/src/Facebook/');
require_once(__DIR__.'/src/Facebook/autoload.php');
$fb = new Facebook\Facebook([
'app_id' => '***************',
'app_secret' => '***************',
'default_graph_version' => 'v2.11',
]);
$helper = $fb->getRedirectLoginHelper();
$permissions = ['email','publish_actions','manage_pages','publish_pages'];
// optional
$query = 'SELECT * FROM music_promotion';
$stmt = mysqli_query ($dbc,$query);
while ($row=mysqli_fetch_array($stmt)){
$_SESSION['facebook_access_token'] = $row['fb_access_token'];
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']);
}
try {
//Post property to Facebook
$linkData = [
'link' => 'the link',
'message' => 'the message'
];
$pageAccessToken = $_SESSION['facebook_access_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();
} 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;
}
}
}
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>
Here's my code to retrieve user's info from Facebook. I am using PHP SDK.
public function indexAction()
{
$fb = new Facebook\Facebook([
'app_id' => '934741473308351',
'app_secret' => 'de001d018a7769eb17eb11300e772a0c',
'default_graph_version' => 'v2.5',
'default_access_token' => isset($_SESSION['facebook_access_token']) ? $_SESSION['facebook_access_token'] : 'APP-ID|APP-SECRET'
]);
try {
if(isset($_SESSION['facebook_access_token'])){
$response = $fb->get('/me');
$userNode = $response->getGraphUser();
Mage::log("Email====>Before".$userNode->getFirstName());
// echo 'Name: ' . $user['first_name'];
$this->_redirectUrl('/app-new/app/#/myAccount');
exit;
}
//redirect, or do whatever you want
} 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();
}
$helper = $fb->getRedirectLoginHelper();
$permissions = ['email', 'user_likes']; // optional
$loginUrl = $helper->getLoginUrl(Mage::getBaseUrl().'facebook/facebook/authenticate', $permissions);
echo $loginUrl;
}
public function authenticateAction(){
Mage::log("Authenticate=======");
$fb = new Facebook\Facebook([
'app_id' => '934741473308351',
'app_secret' => 'de001d018a7769eb17eb11300e772a0c',
'default_graph_version' => 'v2.5',
]);
$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)) {
// Logged in!
Mage::log("Access Token=================>".(string) $accessToken);
$oAuth2Client = $fb->getOAuth2Client();
// Exchanges a short-lived access token for a long-lived one
$fb->setDefaultAccessToken((string) $accessToken);
$_SESSION['facebook_access_token'] = (string) $accessToken;
try {
$response = $fb->get('/me');
$userNode = $response->getGraphUser();
Mage::log("Email====>Before".$userNode->getFirstName());
$customer = $this->checkIfUserExists($userNode);
$this->_redirectUrl('/app-new/app/#/myAccount');
exit;
} 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;
}
}
}
I got the result first, but I am not getting result after that. Is it due to access taken or something else. What am I doing wrong here
You are missing a new feature of v2.4 of the Graph API, it´s called "Declarative Fields". You now have to add a field parameter to specify the fields you want to get, else you will only get id and name: https://developers.facebook.com/docs/apps/changelog#v2_4
Also, make sure your login works correctly and you get asked for the email permission when you authorize your App.
when I publish a post to my page, it's working fine, but when I post to page through set page ID instead of "me",
the response as the following:
Graph returned an error: (#200) Permissions error
the source code as the following:
require_once 'src/Facebook/autoload.php';
//*
$config = array();
$config['appId'] = 'xxxxxxxxxxxxxxxxxxxxxxxxx';
$config['app_id'] = $config['appId'];
$config['secret'] = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';
$config['app_secret'] = $config['secret'];
define('APP_ID', $config['appId']);
define('APP_SECRET', $config['secret']);
//$config['fileUpload'] = false; // optional
$config['default_graph_version'] = 'v2.5';
$config['page_id'] = 'xxxxxxxxxxxxxxxxxxxxxxxx';
$config['facebook']['permissions'] = array(
'email',
'user_location',
'user_birthday',
'publish_actions',
'publish_pages',
'manage_pages',
'public_profile',
);
$fb = new Facebook\Facebook($config);
if(isset($_SESSION['fb_access_token'])) {
$accessToken = $_SESSION['fb_access_token'];
} else {
$helper = $fb->getRedirectLoginHelper();
try {
$accessToken = $helper->getAccessToken();
if(isset($accessToken)) {
$oAuth2Client = $fb->getOAuth2Client();
// longlived access token
if (!$accessToken->isLongLived()) {
$accessToken = $oAuth2Client->getLongLivedAccessToken($accessToken);
}
}
} 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;
}
}
if(isset($accessToken)) {
// Logged in!
$_SESSION['fb_access_token'] = (string) $accessToken;
try {
$response = $fb->get('/'.$config['page_id'].'/feed', $accessToken);
} 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;
}
} else {
$helper = $fb->getRedirectLoginHelper();
$redirect_url = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
$loginUrl = $helper->getLoginUrl($redirect_url, [ 'manage_pages', 'publish_pages', 'publish_actions' ]);
echo 'Log in with Facebook!';
}
on other action in same page
$page_access_token = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';
// instance
$fb = new Facebook\Facebook([
'app_id' => APP_ID,
'app_secret' => APP_SECRET,
'default_graph_version' => 'v2.4',
]);
$linkData = [
'link' => encodeurl(array('page'=>'page','lang'=>'ar','id'=>$_id,'beg'=>0,'unuse'=>$xtitlex)),
'message' => $xtitlex,
'source' => $publish,//$fb->fileToUpload($publish),
'caption' => DOMAIN_,
"picture" => $publish,
"name" => $xtitlex,
"description" => $xdescriptionx
];
try {
//
$response = $fb->post('/'.$config['page_id'].'/feed', $linkData, $page_access_token);
} catch(Facebook\Exceptions\FacebookResponseException $e) {
//print_r($linkData);
echo 'Graph returned an error: ' . $e->getMessage();
exit;
} catch(Facebook\Exceptions\FacebookSDKException $e) {
echo 'Facebook SDK returned an error: ' . $e->getMessage();
exit;
}
?>
Most likely, you are not using a Page Token with the correct permissions. Make sure you are using a Page Token instead of a User Token and make sure it includes publish_pages. You can test your Token in the debugger: https://developers.facebook.com/tools/debug/
Make sure the Page ID shows up, and the publish_pages permission.
First check if the Access Token you used is generated as "Page Access Token" not "User Token". It is a bit tricky and took me a moment.
go to "https://developers.facebook.com/tools/explorer/"
drop down "User Token" menu
pick "Page Access Token"
blue button "Generate Access Token"
copy and use new token
Every time you add or remove Permissions, token changes!
Screenshot
My app types was business and I just added all the permissions from the given list and after I added all permissions, Facebook asked me to review permissions, I simply kept clicking on OK and everything worked, the error went