Facebook Fatal error Session has expired - php

<?php
require_once"includes/strings.php";
require_once"php/function.php";
require_once"php/config.php";
require_once"php/app.php";
$currentFBuserid = "0";
///////FACEBOOK GET USER INFORMATION
session_start();
// Enter the app id and secret below
define('YOUR_APP_ID', '$fbAppID');
define('YOUR_APP_SECRET', '$fbAppSecret');
require_once"php/fbsdk/src/facebook.php";
$facebook = new Facebook(array(
'appId' => $fbAppID,
'secret' => $fbAppSecret,
));
$userId = $facebook->getUser();
if($userId){
$userInfo = $facebook->api('/' + $userId);
}
Okay the issue is simple about every two hours I guess the session expires on my site and the error "Fatal error: Uncaught OAuthException: Error validating access token: Session has expired at unix time 1352329200.
The current unix time is 1352330589. thrown in /home/######/public_html/php/fbsdk/src/base_facebook.php on line 1238"
I'm having an impossible time figuring out what the issue is, no matter how long I scrape this site.
BTW:(refreshing the page solves the issue)
I really need help.
Thank you!

Okay the issue is simple about every two hours I guess the session expires on my site and the error "Fatal error: Uncaught OAuthException: Error validating access token: Session has expired at unix time 1352329200.
User access tokens acquired using the client-side flow expire after two hours.
You can either extend them, or use the server-side flow – both will result in a token that’s valid for 60 days.
https://developers.facebook.com/roadmap/offline-access-removal/
(The latest version of the PHP SDK has a method called setExtendedAccessToken for extending a short-lived token.)
BTW:(refreshing the page solves the issue)
If you are using the JS SDK to do the login, then a refresh of course makes it do a new cross-domain request to Facebook, and will get a fresh short-lived access token.

Related

Facebook long-lived token expires after a few days

When i try to request a long-lived access token from the facebook api it gives back a token and when i test the token in the debugger it says it will never expire, a few hours / a day later i can't make any calls with the token anymore. It suddenly says:
"Any of the pages_read_engagement, pages_manage_metadata, pages_read_user_content, pages_manage_ads, pages_show_list or pages_messaging permission(s) must be granted before impersonating a user's page."
This is how i request the long lived token:
$client = new Client([
'base_uri' => 'https://graph.facebook.com/v12.0/me/accounts?
fields=picture,category_list,name,access_token&access_token=' . $token,
'timeout' => 2.0,
]);
Am i doing something wrong here? Does anyone else have this problem?
(Edit) - The problem occurs when i connect a second time from another website, it seems like when i connect a second site the first token gets disconnected?

Refresh Token for Quickbooks expiring after 1 day

I've built an app that connects to Quickbooks using OAuth 2 with the official Quickbooks PHP SDK.
I get two tokens:
Access token (Expiring after 60 minutes)
Refresh token (Expiring after 100 days)
The Refresh token is used to get a new Access token.
However, by requesting a new access token I also receive a new refresh token that I save in the database.
The previous refresh token will be forced to expire. But the new refresh token is invalid already.
I have built a CRON job that request a new refresh token every 15 minutes. I do get a new refresh token but this one is invalid (Error : "invalid_grant"). (See the code below)
What am I doing wrong here ?
$dataService->setMinorVersion("9");
$OAuth2LoginHelper = $dataService->getOAuth2LoginHelper();
$accessToken = $OAuth2LoginHelper->refreshToken();
$dataService->updateOAuth2Token($accessToken);
$token->previous_token = $token->last_token;
$token->last_token = $accessToken->getRefreshToken();
if($token->last_token != $token->previous_token){
if($token->save()){
mail('mymail', 'New token !', "Token updated!!!!");
}
}

why can't get user access token (offline) to manage pages?

i'm trying to write a script to post to a page while the admin is offline.
my application has the manage_pages extended permission of the admin user.
here is my code:
require('php-sdk/src/facebook.php');
$facebook = new Facebook(array(
'appId' => 'MY_APP_ID', // YOUR APP ID
'secret' => 'MY_SECRET', // YOUR API SECRET
'cookie' => true
));
$user_admin_id = 'MY_ADMIN_ID';
$page_id = 'MY_PAGE_ID';
//get the access token to post to my page via the graph api
$accounts = $facebook->api("/" . $user_admin_id . "/accounts");
foreach ($accounts['data'] as $account)
{
if ($account['id'] == $page_id)
{
//found the access token, now we can break out of the loop
$page_access_token = $account['access_token'];
break;
}
}
but I always get this message:
"Fatal error: Uncaught OAuthException: A user access token is required
to request this resource. thrown in
/home/itrade10/public_html/khodiersoftware/php-sdk/src/base_facebook.php
on line 1033"
You forgot to authorize the User, that´s how you get a User Access Token:
https://developers.facebook.com/docs/reference/php/facebook-getLoginUrl/
Don´t forget to add the "manage_pages" permission in the scope Parameter. You will also have to use the Function "setExtendedAccessToken" of the PHP SDK to extend the User Token. After that, you will get a Page Access Token that is valid forever with the /me/accounts endpoint.
If you used getLoginUrl already, then there´s something wrong with that code, you may want to add it to the question.
Before getting the accounts (with /me/accounts, not with your id), get the User ID:
$user = $facebook->getUser();
If you got a valid User Token, your ID will be in the $user Variable.
maybe this one? https://developers.facebook.com/roadmap/offline-access-removal/ also see Getting long-lived access token with setExtendedAccessToken() returns short lived token
The error message is telling you exactly what the problem is... you need to get a user access token to access your page tokens

OAuthException: An active access token must be used to query information about the current user

I've this error, but not always. (I use PHP SDK, latest version).
If I'm logged into facebook and i try to register and login, then the app say it's ok!
Also if i'm not logged into facebook, the app redirect me to login url, and here it's all ok.
But sometimes the app say this exception: OAuthException: An active access token must be used to query information about the current user. and the script redirect the user to loginUrl with a loop-redirect (because the access token isn't valid and user need always of loginUrl)
In the web some say that Facebook create a duplicate of Access Token and then access token of php sdk don't is = facebook.
For fix, the user must deletes cookies, how I can fix this?
Thanks a lot for reply, if code is need reply and I'll post it, have a good day! :)
Try to destroy the Facebook session, then redirect the user to login URI if you receive this error, this way you will get a fresh access token.
Notice: Access token expire after a very short, you can get a long living access token. The latest PHP SDK contains a public function called : setExtendedAccessToken()
you can call this function to automatically exchange the 2-3 hours living access token for a 60 days access token
Eg:
try {
$user = $this->facebooknew->api('/me');
$this->facebooknew->setExtendedAccessToken();
$access_token = $this->facebooknew->getAccessToken();
}
catch(FacebookApiException $e){
$this->facebooknew->destroySession();
header('Location: ' . $this->facebooknew->getLoginUrl($params));
//echo $e;
}

Google Latitude API permanent auth for specific account

I travel a lot and I had a cool idea of making a site, whereiskavi.com, to just show the city I'm in at the time. Simple, I use latitude! Or so I thought.
My research has presented me with a challenge. oauth needs to be prompted from the browser, and obviously I can't authorize every hit. Now I've used apps that don't constantly re-prompt me for authorization, but so far the only way I've been able to do this is to acquire an oauth json string and paste it in, then wait for it to expire. This code below works, but only till an expiration date.
My question - how do I permanently authorize my app to see my account always?
Here's my successful code, so far:
<?php
require_once '../../src/Google_Client.php';
require_once '../../src/contrib/Google_LatitudeService.php';
require_once 'gogeocode-0.2/src/GoogleGeocode.php';
$client = new Google_Client();
$client->setClientId('0000000000000.apps.googleusercontent.com');
$client->setClientSecret('abcdefghijklmnopqrstuvwxyz');
$client->setApplicationName("whereiskavi.com");
$mapsApiKey = 'mApSApIKEy';
$access_token = '{"access_token":"CENSORSHIP_YEAH","token_type":"Bearer","expires_in":3600,"refresh_token":"THIS_MIGHT_BE_SENSITIVE DATA","created":1351291247}';
$client->setAccessToken($access_token);
$service = new Google_LatitudeService($client);
$location = $service->currentLocation->get();
$geo = new GoogleGeocode($mapsApiKey);
$result = $geo->geocode( $location['latitude'].', '.$location['longitude']);
$result = $result['Placemarks'][0];
echo '<h1>'.strtoupper($result['Locality'].', '.$result['AdministrativeArea']).'</h1>';
?>
I really just need to figure out how to have perpetual oauth sessions or something!
My understanding is that the token will live as long as you want it to (Ie. until you revoke it).
I've tried your code above, but am getting the following error:
Fatal error: Uncaught exception 'Google_AuthException' with message 'Error refreshing the OAuth2 token, message: '{ "error" : "invalid_grant" }'
Even tho I have set my clientID/secret etc as configured with Google.
Well, folks, it seems that the API was slightly misleading for me. I've had the same access token in this for almost a month and it seems to keep renewing its self. I'll leave this question open in case anyone has more info - we'll see if it lasts 2 months!

Categories