OAuth.io server-side doesn't refresh Google token - php

At first please do not mark this as duplicated as this is related to server-side (PHP) and not to client-side as other posts.
I'm trying to refresh the token for Google API through Oauth.io. I followed this and many other posts but no luck. Unfortunately Oauth.io documentation is not the best one. I don't have this problem with Twitter and Facebook only Google.
I'm getting refresh_token when I connect for the first time. Then I need to do API call once a day.
{
"access_token":"xxx",
"token_type":"Bearer",
"expires_in":3600,
"refresh_token":"xxx",
"id_token":"xxx",
"provider":"google_analytics"
}
The question is how to refresh Google token through Oauth.io?
The documentation says:
// The auth method automatically refreshes the tokens if needed
$request_object = $oauth->auth('facebook', array(
'credentials' => $credentials
));
and points here, but it doesn't solve the problem. All it does is that I'm getting refresh_token value in response.
UPDATE
According to this post I tried to do:
$request_object->post('https://oauth.io/auth/access_token', array(
'code' => 'xxx', // here I tried access_token, refresh_token
'key' => 'xxx',
'secret' => 'xxx',
));
but all I'm getting is
array(4) {
'status' =>
string(5) "error"
'code' =>
int(401)
'message' =>
string(70) "Bearer token invalid. Follow the oauth2-token link to get a valid one!"
'data' =>
array(1) {
'code' =>
string(17) "UnauthorizedError"
}
}
Still nothing.

Finally I found it. You can refresh the access_token using:
$this->oauth = new OAuth();
$this->oauth->initialize($publicKey, $secretKey);
$refreshedCredentials = $this->oauth->refreshCredentials($oldCredentials, true);
or
$request_object = $oauth->auth('google_analytics', array(
'credentials' => $credentials,
'force_refresh' => true
));
Both answers can be found here. I had it in front of all day long and did not see it.
I prefer using 1st solution as I want to save new access_token so I can reuse it later. And you need to remember that you need to pass refresh_token, which you got with first access_token, along with last access_token to get refreshed access_token - refresh_token doesn't change until user revoke access.

Related

Guzzle Test mock oauth acess token

In my tests, I "mock" my OAuth process as follows:
$oauthMiddleware = new OAuth2Middleware(new NullGrantType);
$oauthMiddleware->setAccessToken([
"access_token" => "290473f650...",
"expires_in" => 3600,
"token_type" => "Bearer",
"scope" => "*"
]);
$handlerStack = HandlerStack::create();
$handlerStack->push($oauthMiddleware);
$client = new GuzzleHttpClient([
'handler' => $handlerStack,
RequestOptions::AUTH => 'oauth',
]);
I follow the instructions given in the repository:
use kamermans\OAuth2\GrantType\NullGrantType;
$oauth = new OAuth2Middleware(new NullGrantType);
$oauth->setAccessToken([
// Your access token goes here
'access_token' => 'abcdefghijklmnop',
// You can specify 'expires_in` as well, but it doesn't make much sense in this scenario
// You can also specify 'scope' => 'list of scopes'
]);
But instead of using the manually set access token, it throws:
No access token is present, and there is no way to obtain one with NullGrantType.
I traced the exception back to kamermans\OAuth2\GrantType\NullGrantType::getRawData(). In the documentation, it says, for the exception not to be thrown, setAccessToken() must be called. But as you can see in my code, I do exactly that (correct me if I'm wrong). Does anyone see what I'm doing wrong?

How to post on facebook fan page from a website with PHP?

I need to post an article right after the user create that on their backend.
I'm using sdk-php with this script:
require 'facebook-php-sdk/src/facebook.php';
$config = array(
'appId' => 'xxxxxxxxxxxxxxxxxxxxxxxx',
'secret' => 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
'allowSignedRequest' => false
);
$facebook = new Facebook($config);
$params = array(
"access_token" => "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
"message" => "Message",
"link" => "http://www.myarticle.com",
"picture" => "http://www.myarticle.com/img1.png",
"name" => "Name",
"caption" => "Caption",
"description" => "Description."
);
// post to Facebook
try {
$result = $facebook->api('/THE_PAGE_ID/feed', 'POST', $params);
echo 'Successfully posted to Facebook';
} catch(Exception $e) {
echo $e->getMessage();
}
This script sometimes works, sometimes not and the Exception is "Error validating access token: This may be because the user logged out or may be due to a system error." and sometimes the post is created as "/me" to The_Page_wall.
Any idea?
I guess you're using a so-called short-lived User Access Token. Get an overview of the different kinds of Access Tokens here:
https://developers.facebook.com/docs/facebook-login/access-tokens/
I think you have two scenarios here:
Exchange you short-lived token via this endpoint to long-lived ones
(60 days):
https://developers.facebook.com/docs/facebook-login/access-tokens/#extending
Use Page Access Tokens if you don't need the Posts to be posted by
an actual User, but the Page itself:
https://developers.facebook.com/docs/facebook-login/access-tokens/#pagetokens

Why can't I add an event as a page?

I'm trying to add an event to a page in the name of the page. I'm the admin of the page and I found a lot of stuff to the topic, but, no matter what I do, it ends in the PHP Exception:
Uncaught Exception: You must be an admin of the specified page to perform the requested action.
I can add events with my app in my own profile. So, I think the problem is the Access Token. I tried several ways, but to me the best way seems to be:
Open the Graph API Explorer
Select my Application
Request a new access code with permissions manage_pages, publish_actions, publish_stream, create_event
Request /me/accounts
Get the access_token from the page I want to post to and use it in my script
My test script, that works in my own profile:
require 'src/facebook.php';
$facebook = new Facebook(array(
'appId' => $APPLICATION_ID,
'secret' => $APPLICATION_SECRET,
'cookie' => false,
'fileUpload' => true
));
$event_id = 0;
$event_name = "New Event API Test Event";
$event_start = '2013-12-04';
$event_privacy = "OPEN";
$ret_obj = $facebook->api('/'.$page_id.'/events?access_token='.$access_token, 'POST',
array(
'name' => $event_name,
'start_time' => $event_start,
'privacy_type' => $event_privacy,
'location_id' => $location_id
));
if(isset($ret_obj['id'])) {
echo 'Event with added. ID: ' . $ret_obj['id'];
} else {
echo 'Couldn\'t create event';
}
What I did wrong?
You need a page access token.
Page Access Token – These access tokens are similar to user access
tokens, except that they provide permission to APIs that read, write
or modify the data belonging to a Facebook Page. To obtain a page
access token you need to start by obtaining a user access token and
asking for the manage_pages permission. Once you have the user access
token you then get the page access token via the Graph API.
Doc: https://developers.facebook.com/docs/facebook-login/access-tokens/
Then use GET /me/accounts to get the access token associated to your page.
I found the solution in How to programmatically add an event to a page using Graph API?. I had to add the access_token direct into the event array and everything works as expected:
$ret_obj = $facebook->api('/'.$page_id.'/events', 'POST',
array(
'access_token' => $access_token,
'name' => $event_name,
'start_time' => $event_start,
'privacy_type' => $event_privacy,
'location_id' => $location_id
));
Thanks for the help!

Cannot post to page as app

Facebooks documentation is inadecuate, confusing at best.
I have created an app, I have created a page for my business. I want to post updates on that page from my website as my App using the php-sdk.
I had this working perfectly with other pages/sites but nothing seems to be working any more.
I require offline_access, so I have followed the new endpoint as suggested in their docs.
Sequence of obtaining access_token with longer expiry:
https://www.facebook.com/dialog/oauth?client_id={my_app_id}&redirect_uri=http://my_url.redirect/fb/fb_token.php&scope=publish_stream,offline_access,user_status,read_stream,email,user_groups,manage_pages&response_type=token
returned [TOKEN_1]
https://graph.facebook.com/oauth/access_token?client_id={my_app_id}&client_secret={my_app_secret}&grant_type=fb_exchange_token&fb_exchange_token=[TOKEN_1]
returned [ACCESS_TOKEN]
https://graph.facebook.com/me/accounts?access_token=[ACCESS_TOKEN]
returns list of my pages and apps and their relevant ids and access codes. This is where I got my final [DEFINITIVE_ACCESS_TOKEN] && [PAGE_ID]
$facebook = new Facebook(array(
'appId' => {my_app_id},
'secret' => {my_app_secret},
'cookie' => false,
'oauth' => true
));
try {
$attachment = array(
'access_token' => [DEFINITIVE_ACCESS_TOKEN],
'message' => {my_message},
'name' => {my_title},
'link' => {my_url},
'description' => {my_description},
'picture' => {my_image_url},
);
$publishStream = $facebook->api('/[PAGE_ID]/feed', 'POST', $attachment);
} catch (FacebookApiException $e) {
die($e);
}
This has returned an error message "OAuthException: (#200) Posts where the actor is a page cannot also include a target_id"
Where am I going wrong? Is there a tutorial of getting this to work perfectly anywhere or are we supposed to all be mind readers and guess how it is supposed to be done?
Thanks in advance for any help.
I have noticed you are using offline access
Offline access will no longer be available as of May 1, 2012.
See this
https://developers.facebook.com/roadmap/offline-access-removal/
Make sure you have handling for this.
~K

Post to Facebook Page Wall

I'm just trying to make PHP Connector to Facebook for posting wall posts on a Page.
So i'm not trying to post wall post to profile wall or anything else.
I've read some tutorials and manuals and i decided to use Facebook PHP-SDK (from Naitik Shah)
https://github.com/facebook/php-sdk/
I've created Facebook App to post wallposts through it. I received appId and api secret. I've added application permissions to my Page and tried example code
$facebook = new Facebook(array(
'appId' => 'my app id',
'secret' => 'my api secret',
'cookie' => false,
'domain' => 'domain.com'
));
domain.com => domain from which i'm sending api requests
next ->
$facebook->getSession();
$token = $facebook->getAccessToken();
$facebook->api('/123456789/feed', array(
'access_token' => $token,
'link' => 'http://www.example.com'
));
So i'm trying to post link on wall of page with id 123456789
The request goes through without warnings/errors but nothing is posted in right place and nothing is returned.
Thanks for any idea about this problem.
Used tutorials:
How do you post to the wall on a facebook page (not profile)
http://blog.theunical.com/facebook-integration/5-steps-to-publish-on-a-facebook-wall-using-php/
http://www.moskjis.com/other-platforms/publish-facebook-page-wall-from-your-site
http://tips4php.net/2010/12/automatic-post-to-facebook-from-php-script/
$facebook->api('/123456789/feed', 'post', array(
'access_token' => $token,
'link' => 'http://www.example.com'
));
Note the 'post' part.
If you look at the source for the API via the link you provided, you'll see:
protected function _graph($path, $method='GET', $params=array()) {
if (is_array($method) && empty($params)) {
$params = $method;
$method = 'GET';
}
When you don't have 'post' as the second argument and your array as the third, it goes a get
If you are getting authorisation errors, make sure you have included the following permission:
publish_stream
https://developers.facebook.com/docs/reference/api/post/

Categories