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:
Related
I'm trying to code a couple of PHP pages for getting users tokens the Twitter API 1.1. I’m using the TwitterOAuth library https://twitteroauth.com/
First page: twitter-go.php
The user opens it and gets redirected to twitter.com for authorizing the app.
I'm guessing this is where the POST oauth/request_token and GET oauth/authorize functions are being used.
Second page: twitter-back.php
The user gets redirected there from twitter once he authorizes the app. It then displays the user Access Token and the user Access Secret (or store them into a database for later use).
I'm guessing this is where the POST oauth/access_token function is being used.
Is this the correct way of getting a user Secret Token and Access Token?
Alright, actually managed to figure it out myself. Here is my code for those who need it:
First page: twitter-go.php
The user opens it and gets redirected to twitter.com for authorizing the app.
<?php
//LOADING LIBRARY
require "twitteroauth/autoloader.php";
use Abraham\TwitterOAuth\TwitterOAuth;
//TWITTER APP KEYS
$consumer_key = 'yourkey';
$consumer_secret = 'yourkey';
//CONNECTION TO THE TWITTER APP TO ASK FOR A REQUEST TOKEN
$connection = new TwitterOAuth($consumer_key, $consumer_secret);
$request_token = $connection->oauth("oauth/request_token", array("oauth_callback" => "http://boulangerie-colas.fr/twitter/twitter-back.php"));
//callback is set to where the rest of the script is
//TAKING THE OAUTH TOKEN AND THE TOKEN SECRET AND PUTTING THEM IN COOKIES (NEEDED IN THE NEXT SCRIPT)
$oauth_token=$request_token['oauth_token'];
$token_secret=$request_token['oauth_token_secret'];
setcookie("token_secret", " ", time()-3600);
setcookie("token_secret", $token_secret, time()+60*10);
setcookie("oauth_token", " ", time()-3600);
setcookie("oauth_token", $oauth_token, time()+60*10);
//GETTING THE URL FOR ASKING TWITTER TO AUTHORIZE THE APP WITH THE OAUTH TOKEN
$url = $connection->url("oauth/authorize", array("oauth_token" => $oauth_token));
//REDIRECTING TO THE URL
header('Location: ' . $url);
?>
Second page: twitter-back.php
The user gets redirected there from twitter once he authorizes the app. It then displays the user Access Token and the user Access Secret.
<?php
/**
* users gets redirected here from twitter (if user allowed you app)
* you can specify this url in https://dev.twitter.com/ and in the previous script
*/
//LOADING LIBRARY
require "twitteroauth/autoloader.php";
use Abraham\TwitterOAuth\TwitterOAuth;
//TWITTER APP KEYS
$consumer_key = 'yourkey';
$consumer_secret = 'yourkey';
//GETTING ALL THE TOKEN NEEDED
$oauth_verifier = $_GET['oauth_verifier'];
$token_secret = $_COOKIE['token_secret'];
$oauth_token = $_COOKIE['oauth_token'];
//EXCHANGING THE TOKENS FOR OAUTH TOKEN AND TOKEN SECRET
$connection = new TwitterOAuth($consumer_key, $consumer_secret, $oauth_token, $token_secret);
$access_token = $connection->oauth("oauth/access_token", array("oauth_verifier" => $oauth_verifier));
$accessToken=$access_token['oauth_token'];
$secretToken=$access_token['oauth_token_secret'];
//DISPLAY THE TOKENS
echo "<b>Access Token : </b>".$accessToken."<br />";
echo "<b>Secret Token : </b>".$secretToken."<br />";
?>
Please remember that you need to be using the using the TwitterOAuth library https://twitteroauth.com/
So I have recently integrated the new Office365 Rest API with PHP and have it working successfully with the Contacts API.
The system will generate the request url and redirect the user back once authentication is complete which works perfectly fine however if you go back to the script it will automatically log you through the process again as Office365 does not force reauthorisation.
Our script currently allows multiple users to sync their accounts with our system however this is only letting one user perform this per browser session.
require_once('./src/Office365_Client.php');
$client = new Office365_Client();
$forward_url = $client->createAuthUrl();
if (isset($_GET['code'])) {
$code = $_GET['code'];
$client->setCode($code);
$responseObj = $client->getTokens();
$access_token = $client->getAccessToken();
$refresh_token = $client->getRefreshToken();
$_SESSION['access_token'] = $access_token;
$_SESSION['instance_url'] = $instance_url;
$icustomer = (isset($_SESSION['icustomer'])) ? $_SESSION['icustomer'] : false;
header("location: " . $_SESSION['redirUrl'] . "?crm=office365&access_token=$access_token&refresh_token=$refresh_token");
//die();
//////////////////////////////////////////////////////////
// LOAD CONTACTS
/////////////////////////////////////////////////////////
//$client->getContactsFolders();
///////////////////////////////////////////////////
} else {
header("location: $forward_url");
}
Ideally it should work as followed:
User visits our website -> We generate Auth URL and the user is redirected to the Login Page for Office365 (They will then to autheticate if previously not done so) -> Once complete this will return them back to our selection screen with their code ready for their access token to be created. If the user wishes to add a different Office365 account they should be able to go through that process again without using a different browser.
Add prompt=login to the authorization request, so:
header("location: $forward_url" . "&prompt=login");
Have you tried logging out? The logout URI is https://login.windows.net/common/oauth2/logout. So you would want to do something like
https://login.windows.net/common/oauth2/logout?post_logout_redirect_uri=<some page in your app>
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 upgrading my existing FB apps, and going absolutely bonkers trying to get a simple PHP iframe canvas app to authorize and authenticate (as well as use SSL). Never looked through so many examples...
Here's where I'm stuck: After the user authorizes the app, and the app authenticates the user (I am able to make a graph request with the token OK), the redirect_uri happens, and the whole page refreshes, leaving Facebook and thenjust shows me the contents of my "Canvas URL" page (with my server's domain), rather than iframed on Facebook.
I currently have this as a crude two step process...
Here's what my code looks like on the first page (index.php):
<?php
require('src/facebook.php');
$app_id = '123456789';
$app_secret = '1234secrets1234';
$canvas_page = "https://apps.facebook.com/123456789/";
$canvas_url = "https://myserver.com/apptest/";
$code = $_REQUEST['code'];
if(!$code){
$display= 'page';
$scope= 'manage_pages, offline_access, read_insights, publish_stream, user_about_me, user_likes, email';
$redirect_url = 'https://myserver.com/apptest/step2.php';
$oauth_url = 'https://www.facebook.com/dialog/oauth?canvas=1&client_id='.$app_id.'&display='.$display.'&redirect_uri='.urlencode($redirect_url).'&scope='.$scope;
$config = array('appId' => $app_id,'secret' => $app_secret,'cookie' => true,'domain' => true);
$facebook_client = new Facebook($config);
echo "<script type=\"text/javascript\">top.location.href = \"".$oauth_url."\";</script>";
}
?>
and the second page (step2.php):
<?php
require('src/facebook.php');
$app_id = '123456789';
$app_secret = '1234secrets1234';
$canvas_page = "https://apps.facebook.com/123456789/";
$canvas_url = "https://myserver.com/apptest/";
if($_REQUEST['code']){
$code=$_REQUEST['code'];
$redirect_url = 'https://myserver.com/apptest/step2.php';
$link="https://graph.facebook.com/oauth/access_token?canvas=1&client_id=".$app_id."&redirect_uri=".urlencode($redirect_url)."&client_secret=".$app_secret."&code=".$code;
$string = file_get_contents($link);
$auth_token=substr($string, 13, 150);
$graph_url = "https://graph.facebook.com/me?access_token=".$auth_token;
$user = json_decode(file_get_contents($graph_url));
echo("Hello " . $user->name);
}
Again, once the user has authorized the app, and the app has authenticated the user, the graph call works.
Any ideas?
When navigating to the OAuth dialog the web page (not the frame your app is in) is navigated to the OAuth URL. To get back into the Facebook iframe after authentication you need to set the OAuth redirect URL to the canvas_page URL. The code shown above is navigating to the URL of myserver when redirected so your app takes up the entire page (because you left the Facebook iframe when navigating to the OAuth dialog). Your code at canvas_url needs to determine if it is being entered from authorization (success or failure) or if it is being entered with a valid access token after authentication.
Also your canvas_page URL appears to be comprised of the facebook apps host and your application ID. It should be the facebook apps host and your application name (the redirect URL should be the same as the "Canvas Page" URL on your app's developer page).
Well I did get this working. On the app > settings > basic I hadn't set a namespace, so the URL it gave me for the app on facebook was like this: https://apps.facebook.com/123456789/ and now with the namespace they changed it to: https://apps.facebook.com/myappname. So that may have been it. I tried to carefully follow the simple PHP autorization demo on this page: https://developers.facebook.com/docs/appsonfacebook/tutorial/ and it seems to work ok now.
Thanks for the help!
I use a request dialog in my app where the user can send requests to their friends. Once the user sends the request i redirect the app to a page where it posts on the users page. I use the below code to get an access_token:
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://graph.facebook.com/oauth/access_token?client_id='.APP_ID.'&client_secret='.APP_SECRET.'&redirect_uri=http://www.facebook.com/pages/Cosmetics/167231286678063?sk=app_233227910028874&grant_type=client_credentials');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST,0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER,0);
$token = curl_exec($ch);
$me = $facebook->api('/me?'.$token);
but when I try to post on the wall it shows this error:
Fatal error: Uncaught OAuthException: Invalid OAuth access token signature.
I'm not sure on how exactly you are trying to authenticate.. It might be ok doing a request that way, but the method I use is the one documented here: http://developers.facebook.com/docs/authentication/
That is, you first redirect the user to a Facebook page in order to make him accept permissions. Once he accepts, he gets redirected to an URL you provided, with a code=### get argument you need to perform a server-side request in order to get the real access_token you need..
Example redirect url:
$my_url = 'http://www.example.com';
"http://www.facebook.com/dialog/oauth?client_id=". $app_id ."&redirect_uri=". urlencode($my_url);
Then, when the user clicks on Accept, he gets redirected to, for example
http://www.example.com?code=ABCDEF
Then, on the server-side, you need to get the access_token making a call like this:
"https://graph.facebook.com/oauth/access_token?"
. "client_id=" . $app_id . "&redirect_uri=" . urlencode($my_url)
. "&client_secret=" . $app_secret . "&code=" . $code;
Then double check the returned text from that call, and try getting
"https://graph.facebook.com/me?access_token=". $access_token;
(You can also check this by hand)
EDIT
Also, you probably need some more permissions from the user in order to publishi on his stream. So, ask for permissions adding a scope=publish_stream get to the first (user authorization) URL.
Why don't you use PHP SDK 3.0.1 ?
Its easy if you use the sdk provided by facebook, here's the sample for authentication using php sdk 3.0.1:
<?php
// Requires Facebook PHP SDK 3.0.1: https://github.com/facebook/php-sdk/
require ('facebook.php');
define('FACEBOOK_APP_ID',"YOUR-APP-ID-HERE");
define('FACEBOOK_SECRET',"YOUR-APP-API-SECRET-HERE");
define('REDIRECT_URI',"YOUR-REDIRECT-URL-HERE");
define('PERMISSIONS_REQUIRED', "publish_stream,user_photos");
$user = null;
$facebook = new Facebook(array(
'appId' => FACEBOOK_APP_ID,
'secret' => FACEBOOK_SECRET,
'cookie' => true
));
$user = $facebook->getUser(); // Get the UID of the connected user, or 0 if the Facebook user is not connected.
if($user == 0) {
// If the user is not connected to your application, redirect the user to authentication page
/**
* Get a Login URL for use with redirects. By default, full page redirect is
* assumed. If you are using the generated URL with a window.open() call in
* JavaScript, you can pass in display=popup as part of the $params.
*
* The parameters:
* - redirect_uri: the url to go to after a successful login
* - scope: comma separated list of requested extended perms
*/
$login_url = $facebook->getLoginUrl($params = array('redirect_uri' => REDIRECT_URI,'scope' => PERMISSIONS_REQUIRED));
echo ("<script> top.location.href='".$login_url."'</script>");
} else {
// if the user is already connected, then fetch access_token and user's information or show some content to logged in user.
try
{
$access_token = $facebook->getAccessToken(); // Gives you current user's access_token
$user = $facebook->api('/me'); // Gets User's information based on permissions the user has granted to your application.
} catch(FacebookApiException $e){
$results = $e->getResult();
// Print results if you want to debug.
}
}
?>
You're using &grant_type=client_credentials which gives you an access token for your app as a whole, not for your current user. To get an access token for your current user you need to redirect them to the same url, but without the &grant_type=client_credentials and then Facebook will redirect them back to your redirect_uri and send along the access_token you need. Alternatively you can use the Javascript SDK to obtain an access token through a pop up window without redirecting them.
Here's a link to another question for how to authenticate with the JS SDK and no redirect: Facebook Authentication Without Redirect?
What you are doing there is getting the application access token:
App Login allows you to take various administrative actions for your
app, such as retrieving Insights data or approving Requests. Graph API
calls that require an app access token are clearly denoted in the API
reference.
What you need is a user access token with some permissions, in your case it would be publish_stream.