I am using LinkedIn API to pull updates from there and display on the website. While using OAuth, I am storing the token in a file and then pull it from there again to prevent the login popup. However, I am not clear once my token expires how will it get refreshed. Following is how I am reading the token from the file -
$config = json_decode(file_get_contents(".service.dat"));
if( isset($config->key) && isset($config->secret) ) {
$this->access_token = new OAuthConsumer($config->key, $config->secret);
}
For authentication I have following to get request token -
function getRequestToken()
{
$consumer = $this->consumer;
$request = OAuthRequest::from_consumer_and_token($consumer, NULL, "GET", $this->request_token_path);
$request->set_parameter("oauth_callback", $this->oauth_callback);
$request->sign_request($this->signature_method, $consumer, NULL);
$headers = Array();
$url = $request->to_url();
$response = $this->httpRequest($url, $headers, "GET");
parse_str($response, $response_params);
$this->request_token = new OAuthConsumer($response_params['oauth_token'], $response_params['oauth_token_secret'], 1);
}
After generating token, I am generting authorize url:
function generateAuthorizeUrl()
{
$consumer = $this->consumer;
$request_token = $this->request_token;
return $this->authorize_path . "?oauth_token=" . $request_token->key;
}
LinkedIn documentation states following about refresh token:
Refreshing an access token is very simple and can happen without an
authorization dialog appearing for the user. In other words, it's a
seamless process that doesn't affect your application's user
experience. Simply have your application go through the authorization
flow in order to fetch a new access token with an additional 60 day
life span.
I am not clear what that means. If I have to redo all the way from obtaining request token again then wouldn't that require me to make http request again and having to popup the login screen? How do I avoid it? Will appreciate suggestion.
Thanks.
Found out. Authorization URL:
https://www.linkedin.com/oauth/v2/authorization
followed by the access token url:
https://www.linkedin.com/oauth/v2/accessToken
was all that I really had to do (passing with the right parameters).
There is also a endpoint to refresh the token once it expire, here is the documentation of the way to do it: https://learn.microsoft.com/en-us/linkedin/shared/authentication/programmatic-refresh-tokens
If You go through the documentation
Linkedin does not provide refresh token you need to again go through the workflow.
Here is the Short Explanation:
To refresh an Access Token, simply go through the authorization process outlined in this document again to fetch a new token. During the refresh workflow, provided the following conditions are met, the authorization dialog portion of the flow is automatically skipped and the user is redirected back to your callback URL, making acquiring a refreshed access token a seamless behind-the-scenes user experience
Refresh your Access Tokens
Related
I am trying to give the tweeter posting UI from my website for users who has twitter account and post tweet into their home page. In addition I like to give access to webcam to cartoonize their face and put that image with the tweet. (my main target is cartoonize image posts)
Initially I take the Codebird PHP library to make a tweet. https://github.com/jublonet/codebird-php
I tested my first post like same example Codebird given in their github page.
require_once ('codebird.php');
\Codebird\Codebird::setConsumerKey('YOURKEY', 'YOURSECRET'); // static, see README
$cb = \Codebird\Codebird::getInstance();
/*You may either set the OAuth token and secret, if you already have them:*/
$cb->setToken('YOURTOKEN', 'YOURTOKENSECRET');
This part work nicely.
But this is only for the app developer. because YOURTOKEN and YOURTOKEN SECRET is in the https://apps.twitter.com/app/ page.
Therefor I try to run this code as given in Codebird sample.
<?php
require_once('./src/codebird.php');
\Codebird\Codebird::setConsumerKey('REPLACE_WITH_MY_CONSUMER_KEY');
$cb = \Codebird\Codebird::getInstance();
/*$cb->setToken('REPLACE_WITH_MY_CONSUMER_TOKEN');
session_start();
if (!empty($_SESSION['oauth_token'])) {
echo 'ttt';
var_dump($_SESSION['oauth_token']);
// get the request token
$reply = $cb->oauth_requestToken([
'oauth_callback' => 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']
]);
// store the token
$cb->setToken($reply->oauth_token, $reply->oauth_token_secret);
$_SESSION['oauth_token'] = $reply->oauth_token;
$_SESSION['oauth_token_secret'] = $reply->oauth_token_secret;
$_SESSION['oauth_verify'] = true;
// redirect to auth website
$auth_url = $cb->oauth_authorize();
header('Location: ' . $auth_url);
die();
} elseif (isset($_GET['oauth_verifier']) && isset($_SESSION['oauth_verify'])) {
// verify the token
$cb->setToken($_SESSION['oauth_token'], $_SESSION['oauth_token_secret']);
unset($_SESSION['oauth_verify']);
// get the access token
$reply = $cb->oauth_accessToken([
'oauth_verifier' => $_GET['oauth_verifier']
]);
// store the token (which is different from the request token!)
$_SESSION['oauth_token'] = $reply->oauth_token;
$_SESSION['oauth_token_secret'] = $reply->oauth_token_secret;
// send to same URL, without oauth GET parameters
header('Location: ' . basename(__FILE__));
die();
}
// assign access token on each page load
$cb->setToken($_SESSION['oauth_token'], $_SESSION['oauth_token_secret']);
$reply = $cb->statuses_update('status=Whohoo, I just Tweeted!');
?>
But it gives this error.
Fatal error: Uncaught Codebird\CodebirdCredentialsException: To call
this API, the OAuth access token must be set.
Any clue for this ? or;
Are there anything easy method like facebook handle this thing very easy. It's redirect to facebook login page and after logged use can post whatever user like from the my website. Therefore any way to do something for the twitter , Like call native login window and getting the token and secret from that login session and post the tweet message from my website ?
I just added callback url from the my application page (https://apps.twitter.com/app) and now it's work perfect. It will automatically redirect to login page (like bellow) if user not logged in or else ask permission to approve to get the token and secret key.
Call back URL from setting tab:
User redirect work fine if user not logged-in:
I have created a FB App to publish posts as page from another site.
Many of the users will be publishing on my page, so I'm trying to create a function without user login or session.
I'm now doing it via creating Page Access Token manually from Graph API Explorer and injecting it into the code.
If I could create the access token in the code without user login, it will be my solution.
Is it possible or anyone knows how to do it?
Any help is appreciated.
P.S: In case anyone wonder my code, it is below.
$config['appId'] = $appId;
$config['secret'] = $secret;
$fb = new \Facebook($config);
$message = array(
'access_token' => $page_access_token, //manually injected
);
$message['message'] = 'message';
$message['link'] = 'link';
$posturl = '/'.$page_id.'/feed';
$result = $fb->api($posturl,'POST',$message);
There is example code in the docs, this is how to post stuff with a specific Access Token:
$response = $fb->post('/{page-id}/feed', $data, '{access-token}');
Source: https://developers.facebook.com/docs/php/howto/example_post_links
Of course you can´t create a Page Token without user login, that would be weird. You can only create a Page Token with a User Token, and you can only get a User Token with login. Extended Page Tokens are valid forever, so you only need to create it once and just store it.
More information about Tokens and how to generate them:
https://developers.facebook.com/docs/facebook-login/access-tokens
http://www.devils-heaven.com/facebook-access-tokens/
I'm using Twitter API with CodeBird (PHP).
Here is a quote from Twitter's docs:
so for users already signed in to twitter.com who have authorized the application, no UI is shown - instead, they are automatically redirected back to the application.
In the case where the user is already signed in to twitter.com and has granted access to the website, this redirect happens immediately.
https://dev.twitter.com/web/sign-in/desktop-browser
Why this does not work for me? Twitter asks user's permission for each time.
My code for obtaining authorization URL:
\Codebird\Codebird::setConsumerKey(
$this->config['twitter']['consumer_key'],
$this->config['twitter']['consumer_secret']
);
$cb = \Codebird\Codebird::getInstance();
$reply = $cb->oauth_requestToken([
'oauth_callback' => 'https://***/login/twitter'
]);
$cb->setToken($reply->oauth_token, $reply->oauth_token_secret);
$this->session->twitter_oauth_token = $reply->oauth_token;
$this->session->twitter_oauth_token_secret = $reply->oauth_token_secret;
$this->session->twitter_oauth_verify = true;
return $this->redirect($cb->oauth_authorize());
Solved!
oauth_authorize will always ask user for a permission.
oauth_authenticate will request it only once and will perform automatic redirect, if access already granted.
I am currently using the fitbit library with a laravel wrapper (see https://github.com/popthestack/fitbitphp).
I am attempting to store the access token once a user authenticates and then subsequently reuse that token instead of having to make a separate request for a new token each time. Is it possible using fitbits oauth 1 implementation to reuse the access tokens or will I need to make a new request using request tokens etc. each time. I apologize in advance, I have a fairly visceral understanding of oauth in the first place but fitbit in particular has been tripping me up. Thanks.
here is the function I have that requests info from fitbit...
public function getFitbit() {
// get data from input
$code = Input::get( 'oauth_token' );
// get fb service
$fb = fitbitOauth::consumer( 'Fitbit' );
// if code is provided get user data and sign in
if ( !empty( $code ) ) {
// This was a callback request from fitbit, get the token
$fb->requestAccessToken(
$_GET['oauth_token'],
$_GET['oauth_verifier']
);
// Send a request now that we have access token
$result = json_decode($fb->request('user/-/profile.json'));
print_r($result);
}
// if not ask for permission first
else {
// get fb authorization
$token = $fb->requestRequestToken();
$url = $fb->getAuthorizationUri(array('oauth_token' => $token->getRequestToken()));
// return to facebook login url
return Redirect::to( (string)$url );
}
}
I can run through the above example. Direct a user to the page where they can authenticate their account. This then redirects to a page that displays their info. If I reload the page with the 'token' and 'verifier' set already it fails. I want to be able to save off their token to a DB and reference it in the future.
I'm trying to create a cron job with a php script for retrieving info about stats of a Fan Pages and I have some questions:
have I to log a user to get the access token and use the Facebook API?
Which kind of token must to use? App token? Page Token?
I've read in several posts in Stackoverflow that only the Page Access token is necessary, but I have no success:
Request: /419788471442322/?fields=access_token
Response: Unsupported get request.
This is the code
//get the app access token
$facebook->setAccessToken($facebook->getAccessToken());
//Format the api call
$fields = array('access_token');
$page_info = $facebook->getInsights($id,"",$fields);
//display the result
print_r($page_info);
public function getInsights($id, $nameapi, $fields = array(), $limit = null)
{
if (isset($fields)) $fields = implode(",",$fields);
if (isset($limit)) $limit = "&limit=".$limit;
try {
echo '/'.$id.'/'.$nameapi.'?fields='.$fields.$limit;
$fbdata = $this->facebook->api('/'.$id.'/'.$nameapi.'?fields='.$fields.$limit);
} catch (FacebookApiException $e) {
$fbdata = $e->getMessage();
}
return $fbdata;
}
By default, the App Access Token will be used and you don´t need to set it with setAccessToken.
The App Access Token is good enough for basic infos and the Page feed, but for getting access to the Insights you need a Page Access Token and that´s a bit more complicated. Actually, in a Cron Job you would need a Page Access Token that is valid forever, basic ones are only valid for 2 hours. "Extended Page Access Token" is exactly what you need.
More info about Access Tokens and how to get an Extended Page Access Token:
https://developers.facebook.com/docs/facebook-login/access-tokens/
http://www.devils-heaven.com/facebook-access-tokens/