how to get a fresh access_token in facebook? - php

I am using the following script to automatically post to my PAGE while i'm offline every specific interval.
$attachment2 = array('message' => 'titlexxxxx',
'access_token' => 'CAAEHzeckZBHABAErwFP08GdHyuJcTY7gV2kVP08GdHyuJcTY7gV2kVP08GdHyuJcTY7gV2kVP08GdHyuJcTY7gV2kVP08GdHyuJcTY7gV2kVP08GdHyuJcTY7gV2kVf6Homc7ful2koSXv72PYQeP08GdHyuJcTY7gV2kVZCKKQZBAU',
'name' => 'titlexxxxxxxxx',
'caption' => 'titlexxxxxxxxx',
'link' => 'linkurllllll',
'description' => 'dexcccc'
);
$result = $facebook->api('/209311095776218/feed/','post',$attachment2); // the number is the page id
I'm getting the access token manually from the facebook graph explorer, I know this is stupid but I can't figure out how to get a fresh realtime access_token.
The access_token is not changing every long time, but it does change and this is annoying.
I need a detailed example to get a fresh token ...
IMPORTANT: the script is running while I'm Offline.

You get a new access token by going through a login flow https://developers.facebook.com/docs/facebook-login/getting-started-web/
For example in PHP it's something simple as allowing the user to click the result of getLoginUrl()
For pages you can go through scenario 5 described at https://developers.facebook.com/roadmap/offline-access-removal/
Extend your short lived access token for a long lived token
https://graph.facebook.com/oauth/access_token?
client_id=APP_ID&
client_secret=APP_SECRET&
grant_type=fb_exchange_token&
fb_exchange_token=EXISTING_ACCESS_TOKEN
After this when requesting a page access token (`graph.facebook.com/PAGE_ID?fields=access_token), it will not expire.

Related

Refresh token not changing QuickBooks-V3-PHP-SDK OAuth 2.0

As per sdk documentation.
https://intuit.github.io/QuickBooks-V3-PHP-SDK/authorization.html
"That is what refresh token used for. It is used to request a new access token after access token expired, so you can still access to the QBO company after an hour. Just remember, whenever you make a refreshToken API call, always STORE THE LATEST REFRESH TOKEN value in your session or database"
This is the case: So my access token is expired I need to get a new one I'll run the code below.
$loginHelper = new OAuth2LoginHelper($this->clientID, $this->clientSecret);
$token = $loginHelper->refreshAccessTokenWithRefreshToken($this->refreshToken);
Then the token variable in code above will give me the new access token using this code.
$token->getAccessToken();
It was successful I have the new access token now.
However, seems refresh token is not changing quickbooks said "STORE THE LATEST REFRESH TOKEN" but the $token obj returns are the same.
My refresh token use to request new access token is:
string(50) "Q011532218006WxAY7UnIdulGDJAcgnaoTi7pIkHVaaQld9Me3"
then the return of my request:
QuickBooksOnline\API\Core\OAuth\OAuth2\OAuth2AccessToken Object
(
[accessTokenKey:QuickBooksOnline\API\Core\OAuth\OAuth2\OAuth2AccessToken:private] => eyJlbmMiOiJBMTI4Q0JDLUhTMjU2IiwiYWxnIjoiZGlyIn0..llxj6kOGCzFiqBShGPUtbg.rNbEdMvhD0iER3z4IwB-azYbbk9givKxtaiDh7Uch8HbmZLkF7-xckpgiMDk8V5lYwYOCfP1EaPFa0iJlpbNPZdT7RBfPIkEqotTVfP0UNPwC13a37PpYHOvg_Sxbp_5GuOvdIa1RVskn4tY_FIOaCVnTaxuDF4MWNKOxsitHEoYxzVVcdqigTWri9yfIA6ZqO2vTAc92iTsa30L9jYcFeEdaNVaPt7zyM-y_FzY2W72uq8fyYjpv-fmvWMwv94pCJ6VoV82rM7OmLh5sOWORKfcZJ0xDLMrKddUPnA0GVl3mb3E6D-JyQ2-N2AYNW553nryI9f9iuoAqv7f6bXhzmaO-ByN0xtDEt9E48CFN-tyA_qShtwmEUajhsq0XFrUZgR0rtEq2kSvj79v3-sX1P7qCjPPrGK2q12VQ24DbVWnDYDZslYh9nyJGtiZgXu-GWFNKhfaXI76U_ASC2yefrcWu6ioIdDrn8j75B9AZgg3GpBqkT7H2qHWGqieeuJmcuFVoYIJUiztZNrDWYvmCJv_w2KlG911GHqLO7K7AznzpiSdIWwGXVBSxYRBbCVQTFJge1SYkXYOWj1OP9aFttpxRNX_ctiAiqV5IA9JBs_T3H4w6mGYRt4NpXZCMn3Yguwc1LekmCn0r83taHjvOT0_l78c1zv2nWC_ADKgdd1lPLMzQHiNWnHCDIBrRYm0.h0WaCjevbfdig0G-zQM9eA
[tokenType:QuickBooksOnline\API\Core\OAuth\OAuth2\OAuth2AccessToken:private] => bearer
[refresh_token:QuickBooksOnline\API\Core\OAuth\OAuth2\OAuth2AccessToken:private] => Q011532218006WxAY7UnIdulGDJAcgnaoTi7pIkHVaaQld9Me3
[accessTokenExpiresAt:QuickBooksOnline\API\Core\OAuth\OAuth2\OAuth2AccessToken:private] => 1523499723
[refreshTokenExpiresAt:QuickBooksOnline\API\Core\OAuth\OAuth2\OAuth2AccessToken:private] => 1532218006
[accessTokenValidationPeriod:QuickBooksOnline\API\Core\OAuth\OAuth2\OAuth2AccessToken:private] => 3600
[refreshTokenValidationPeriod:QuickBooksOnline\API\Core\OAuth\OAuth2\OAuth2AccessToken:private] => 8721883
[clientID:QuickBooksOnline\API\Core\OAuth\OAuth2\OAuth2AccessToken:private] => Q032lsDMTnotxhcOudLOpyfYuDXfB9xEMWpMRpvFIwW1VV1eyQ
[clientSecret:QuickBooksOnline\API\Core\OAuth\OAuth2\OAuth2AccessToken:private] => Ml3Id7ZgeVNzAbxecHwwwzrBmuKeQXw7kljlwT84
[realmID:QuickBooksOnline\API\Core\OAuth\OAuth2\OAuth2AccessToken:private] =>
[baseURL:QuickBooksOnline\API\Core\OAuth\OAuth2\OAuth2AccessToken:private] =>
)
As per quickbooks developer, "The previous refresh token expires after 24 hours after you create a new one. So you would get the same refresh token from the time you refresh untill the next 24 hours."
Read more: Click Here

Do I still need to use Facebook user access tokens to post to Facebook pages?

I've created and stored permanent facebook page access tokens. Must I still use a user access token each time I want to post to a fb page feed, or can I use only the page access token?
Here is command I'm using to setup the post now:
$page_post = (new FacebookRequest( **$session**, 'POST', '/'. $page_id .'/feed', array(
'access_token' => $access_token,
'name' => 'Randy Steel',
'link' => 'http://www.LIPSapp.com/',
'caption' => 'Example text',
'message' => 'This is my link!',
) ));
Where $session holds the user access token and $access_token holds the permanent page access token.
If, because I have the perm page access token, I can skip getting/updating the
user access token (60 days at best), how would the above command change?
What would the value of $session need to be, or can that parameter be omitted?
Thanks in advance for any help.
With Facebook's new update like 2 years ago, pages acts like normal profile pages. So you only need access tokens of page not administrator's. Access tokens can be changed overtime or can be expired so it's best you to store administrators access token just in cas the access key losts its validity.
If you always want to post "as Page", you can use the stored Page Token - in fact, you HAVE to use the Page Token to post "as Page". You only need the User Token once, for getting an Extended Page Token.
I would not even use the PHP SDK for that, basic CURL calls are good enough. A small example of using CURL with the Facebook API can be found here: http://www.devils-heaven.com/extended-page-access-tokens-curl/

facebook sso state check: CSRF state token does not match one provided

What are the basic steps for setting up a pure server flow facebook SSO, the docs are as usual a little ambiguous?
I set up the flow with javascript popups only to later realise you are not allowed to customise the login buttons.. which when you stick them next google and twitter sso the signin box look terrible.
http://www.codecademy.com/ seem to direct to their own server which then forwards onto a URL like this:
https://www.facebook.com/dialog/oauth?response_type=code
&client_id=212500508799908&
redirect_uri=http%3A%2F%2Fwww.codecademy.com%2Fauth%2Ffacebook%2Fcallback&state=8aac5bc63c5afe8fbabe572021e7750579fefd898d7b4316&
scope=email%2Cpublish_actions
How is this URL being generated? In the facebook docs there is a function "getLoginUrl".. is this being called which generates the correct URL?
I tried directing the user directly from their browser to:
var href = 'https://www.facebook.com/dialog/oauth?' +
'client_id='+app_id+'&'+
'redirect_uri=http://www.mysite.net/authenticate_facebook.php&'+
'scope=email&';+
'state='+$('body').attr('unique');
But the at the facebook php then the following recieving code resulted in errors about the 'state' not matching... I am assuming that the state is not just a random value generate by my server and must be aquired from the facebook server?
require_once(WEBROOT_PRIVATE.'authenticate/facebook-php-sdk/src/facebook.php');
$config = array(
'appId' => 'xxx',
'secret' => 'xxx',
'fileUpload' => false,
'allowSignedRequest' => false
);
$facebook = new \Facebook($config);
$user_id = $facebook->getUser();
if($user_id)
{
try
{
$user_profile = $facebook->api('/me','GET');
}
catch(FacebookApiException $e)
{
error_log($e->getType(), 0);
error_log($e->getMessage(), 0);
}
}
SO, is this correct flow:
1 - Direct the user to my server facebook_auth.php
2 - facebook_auth.php generate the get url and forwards the user onto it
3 - The user, if required logs into facebook, allows my app
4 - my facebook_auth.php script then checks the tokens and talks server to server with facebook to verify the rest
5 - my website then logs the user in
I had a similar issue last week, and tracked it down to the state field being overwritten by multiple calls to getLoginUrl(). Each time you call getLoginUrl(), a new state token is generated in the SDK and stored in the $_SESSION (it's just a random value), so if you call it twice and the user uses the first link to log in, the second call will have reset the SDK's internal state token, and you will get this error in your logs.
The SDK looks for the same state token in the URL coming back after Facebook authorizes the user and redirects them back to your site, and if it doesn't match it will log this error (here's a link to the source).

facebook php sdk - Error #200 when trying to use setExtendedAccessToken

I have been trying for several days now to successfully post to a client's Facebook Page wall from their website. I need to be able to do this without having a user logged in, which I was able to achieve with an extended access token generated by going to the URL provided in the docs.
What I am trying to do is to fetch an extended token using the PHP SDK as in this question - Facebook PHP SDK: getting "long-lived" access token now that "offline_access" is deprecated, however I receive the following error:
(#200) The user hasn't authorized the application to perform this action
The debug of the auth token generated by the Graph API Explorer shows myself as the User and includes the needed manage_pages and status_update scopes. However, if I run me/accounts, the perms array does not list these under the data for the page in question - not sure if this is relevant.
Here is the code that I have attempted to use:
$facebook = new Facebook(array('appId' => 'xxxxxxx', 'secret' => 'xxxxxx'));
$pageID = 'xxxxxxxx';
$facebook->setExtendedAccessToken();
$accessToken = $facebook->getAccessToken();
try {
$page_info = $facebook->api("/$pageID?fields=access_token");
print_r ($page_info);
} catch (FacebookApiException $e) {
echo $e->getMessage();
}
if( !empty($accessToken) ) {
$args = array(
'access_token' => $accessToken,
'message' => "Catch phrase!"
);
$facebook->api("/$pageID/feed","post",$args);
} else {
// Handle error
}
UPDATE
I found that if I echoed the output of getAccessToken() the result was the app ID and the secret separated by an | - is this what I should be receiving? Seems odd to me since all of the other tokens I have seen are random and much longer.
ANY help at all would be appreciated, I have wasted so much time on this so far. It just seems to work for everyone else.
UPDATE 2
Hi Warren! Looks like you're new around these parts, welcome! Thanks for your research into this, do I need to save these tokens into a DB table and check to see if they are expired every time I try to post? I am ONLY posting to a Page as the Page, apparently this requires the Page access_token rather than what I am assuming is the USER access_token. I believe I also read somewhere that the Page access token never expires, although it changes if I refresh the Graph API Explorer page or request a new user token. Very puzzling.. do not know if I even need to deal with getting new tokens in this app or just use a Page access_token that appears to work?
Also just looking at the base_facebook.php file and the following function:
/**
* Returns the access token that should be used for logged out
* users when no authorization code is available.
*
* #return string The application access token, useful for gathering
* public information about users and applications.
*/
protected function getApplicationAccessToken() {
return $this->appId.'|'.$this->appSecret;
}
Shows what you are experiencing the function setExtendedAccessToken() calls getAccessToken() which calls the function above to do the following inside setExtendedAccessToken:
$access_token_response = $this->_oauthRequest(
$this->getUrl('graph', '/oauth/access_token'),
$params = array(
'client_id' => $this->getAppId(),
'client_secret' => $this->getAppSecret(),
'grant_type' => 'fb_exchange_token',
'fb_exchange_token' => $this->getAccessToken(),
)
);
the return of this function is then {"error":{"message":"No user access token specified","type":"OAuthException","code":1}} but because there is no access_token the function just returns false
the fb_exchange_token can not be the app id and app secret combined.
I have done some testing and what I have found out is if you get the user to login, you can get there access token. If you pass this token into setAccessToken then run setExtendedToken. If you then save the toke by running getAccessToken you can use this token later when the user is logged out.
$facebook->setAccessToken($facebook->getAccessToken());
$facebook->setExtendedAccessToken();
$access_token = $facebook->getAccessToken(); // save this for later use
You need to get the user to login to ask them for permission to get access to there account. If you need to get access to a facebook page make sure they are an admin and ask for the manage_page permission.
Hope this helps
From what I have found so far the extended token that is returned when the user is logged in does not expire as you do not get back a unix timestamp so you would have no way of knowing when it expires.
This is what I have done in my application.
Request the user to login to facebook and except the access permissions. Use getAccessToken to get the current access token. With this I pass into getExtendedAccessToken then run getAccessToken again to finally get the extended access token which I store in a database for later use.
$facebook = new Facebook(array(
'appId' => 'YOURAPPID',
'secret' => 'YOURSECRET',
));
$params = array(
'scope'=>'publish_stream,manage_pages'
);
$loginUrl = $facebook->getLoginUrl($params); // Use this to request them to login in then when they are do the following you will need them to return to your app
$facebook = new Facebook(array(
'appId' => 'YOURAPPID',
'secret' => 'YOURSECRET',
));
$facebook->setAccessToken($facebook->getAccessToken());
$facebook->setExtendedAccessToken();
$access_token = $facebook->getAccessToken(); // store $access_token for later use

Facebook-php-sdk "Session has expired at unix time" with offline_access

I want to make wall post to people's friends ( offline )
I took permissions for wall post and offline access.
But most of the users have error when I try to offline wall post
"Fatal error: Uncaught OAuthException: Error validating access token:
Session has expired at unix time 1332190800. The current unix time is
1339803350. thrown in /home/......"
I think access token with offline access never expired ?
If it is expired, How can I take the new access token without touch the people ( offline )
I used this code
$post = array(
'access_token' => "ACCESSTOKEN",
'message' => test",
'link' => 'http://apps.facebook.com/xx',
'description' => 'test'
);
$result = $facebook->api("/FRIENDS_ID/feed/",'post', $post);
The Facebook offline_access permission was deprecated last month. This feature is scheduled to be removed on July 5.
The new workflow requires you to get a long-term access token, which must be renewed every 60 days. There is more information about this here: https://developers.facebook.com/blog/post/2011/05/13/how-to--handle-expired-access-tokens/

Categories