I am connecting to Tumblr (it's the same process as twitter almost identical).
I get all the way through to the verify page, verify the app, then get returned to the previos page, all of the correct stuff is on the querystring but i get a 400 error a bit on the API docs says that this means "invalid input data".
Here's my code:
require("tumblr/tumblroauth/tumblroauth.php");
// Enter your Consumer / Secret Key:
$consumer = $conf['Tumblr']['consumer'];
$secret = $conf['Tumblr']['secret'];
/* Start session and load lib */
if(!isset($_REQUEST['oauth_token']))
{
// Start the Session
session_start();
$connection = new TumblrOAuth($conf['Tumblr']['consumer'], $conf['Tumblr']['secret']);
// this url is correct
$url = "http://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
$temporary_credentials = $connection->getRequestToken($url);
$redirect_url = $connection->getAuthorizeURL($temporary_credentials, FALSE);
echo "going to".$redirect_url; // looks good
//have to use this as headers have started
echo '<script>window.location.href="'.$redirect_url.'";</script>';
}
/* If the oauth_token is old redirect to the connect page. */
if (isset($_REQUEST['oauth_token']) && $_SESSION['oauth_token'] !== $_REQUEST['oauth_token']) {
$_SESSION['oauth_status'] = 'oldtoken';
session_destroy();
}
if(isset($_REQUEST['oauth_token']))
{/* Create TumblroAuth object with app key/secret and token key/secret from default phase */
$connection = new TumblrOAuth($consumer, $secret, $_SESSION['oauth_token'], $_SESSION['oauth_token_secret']);
/* Request access tokens from tumblr */
$access_token = $connection->getAccessToken($_REQUEST['oauth_verifier']);
/* Save the access tokens. Normally these would be saved in a database for future use. */
$_SESSION['access_token'] = $access_token;
/* Remove no longer needed request tokens */
unset($_SESSION['oauth_token']);
unset($_SESSION['oauth_token_secret']);
/* If HTTP response is 200 continue otherwise send to connect page to retry */
if (200 == $connection->http_code) {
/* The user has been verified and the access tokens can be saved for future use */
$_SESSION['status'] = 'verified';
echo 'connection made heres the code:<br/>'.$connection->http_code;
} else {
/* Save HTTP status for error dialog on connnect page.*/
// THIS IS ALWAYS BEING OUTPUT AT THE END
echo "oh no something is wrong code:<br/>".$connection->http_code;
}
}
Please can someone have a look I feel like I have tried everything on the planet to get this to work..
ps using : https://github.com/jacobbudin/tumblroauth
I think your problem is here
$redirect_url = $connection->getAuthorizeURL($temporary_credentials, FALSE);
Try
$redirect_url = $connection->getAuthorizeURL($temporary_credentials);
and let us know if you're still having trouble
Related
So, i have two accounts at google, one is for personal use and one for company use. At the company account i have bought drive quota and it is at 200gb (i think), so im using it as a file storage cloud-server. My idea is to implement some of the files to the company website using google drive php api. As long as i know i can Use Application-Owned Accounts which sounds great, BUT i have to create new account it seems in order to use it with a regular account and if i want to use it with a server-side i will be not be able to use the company files at the regular account. So, im stuck at this situation!? Please, give me some advice. This is all new to me, so i need your help.
EDIT:
What it says from the link i posted above is this:
You may create a regular Google account like any user would, by going through the Google account sign-up flow or by creating an account on your Google Apps domain. Make sure it is then never used by an actual person but only by your application.
OK, but my account it is not new and it HAVE been used before. That mean that i will not be able to use my company account and if that is true, how can i achieve my goal?
i finally did it after days of researching how i can do this, here is a very simple code for how to obtain the access token and after you have it how to take the refresh token which you will need in order to access the user when he is in offline. I still have to understand how can i know when i store those values in the databse, how can i know that this user with the google id is the same user from the database and put the refresh token in the php, so the user dont have to authenticate again and he can do this only once (service account). So this simple code is using SESSIONS in order to store the access token and also the refresh token. It's not using database for the storage, but if you want when i figure out how this is done i can post the code here as well. So, here is the code:
<?php
session_start();
// Set error reporting
error_reporting(E_ALL | E_STRICT);
// Display errors
ini_set("display_errors", 1);
// require pages, you have to change it if your pages are somewhere else!
require_once 'src/Google_Client.php';
require_once "src/contrib/Google_Oauth2Service.php";
require_once "src/contrib/Google_DriveService.php";
/**
* Retrieved stored credentials for the provided user ID.
*
* #param String $userId User's ID.
* #return String Json representation of the OAuth 2.0 credentials.
*/
function getStoredCredentials($userId) {
if (!empty($_SESSION['userid'])) {
return $_SESSION['userid'];
}
}
/**
* Store OAuth 2.0 credentials in the application's database.
*
* #param String $userId User's ID.
* #param String $credentials Json representation of the OAuth 2.0 credentials to store.
*/
function storeCredentials($userId, $credentials) {
$_SERVER['userid'] = $userId;
}
/**
* Build a Drive service object.
*
* #param String credentials Json representation of the OAuth 2.0 credentials.
* #return Google_DriveService service object.
*/
function buildService($credentials) {
$apiClient = new Google_Client();
$apiClient->setUseObjects(true);
$apiClient->setAccessToken($credentials);
return new Google_DriveService($apiClient);
}
/**
* Send a request to the UserInfo API to retrieve the user's information.
*
* #param String credentials OAuth 2.0 credentials to authorize the request.
* #return Userinfo User's information.
* #throws NoUserIdException An error occurred.
*/
function getUserInfo($credentials) {
$apiClient = new Google_Client();
$apiClient->setUseObjects(true);
$apiClient->setAccessToken($credentials);
$userInfoService = new Google_Oauth2Service($apiClient);
$userInfo = null;
try {
$userInfo = $userInfoService->userinfo->get();
} catch (Google_Exception $e) {
print 'An error occurred: ' . $e->getMessage();
}
if ($userInfo != null && $userInfo->getId() != null) {
return $userInfo;
} else {
throw new NoUserIdException();
}
}
function retrieveAllFiles($service) {
$result = array();
$pageToken = NULL;
do {
try {
$parameters = array();
if ($pageToken) {
$parameters['pageToken'] = $pageToken;
}
$files = $service->files->listFiles($parameters);
$result = array_merge($result, $files->getItems());
$pageToken = $files->getNextPageToken();
} catch (Exception $e) {
print "An error occurred: " . $e->getMessage();
$pageToken = NULL;
}
} while ($pageToken);
return $result;
}
function printFile($service, $fileId) {
try {
$file = $service->files->get($fileId);
print "Title: " . $file->getTitle();
print "Description: " . $file->getDescription();
print "MIME type: " . $file->getMimeType();
} catch (apiException $e) {
print "An error occurred: " . $e->getMessage();
}
}
// fill your details from the google console:
$client = new Google_Client();
$client->setApplicationName('***************');
$client->setScopes(array(
'https://www.googleapis.com/auth/drive',
'https://www.googleapis.com/auth/userinfo.email',
'https://www.googleapis.com/auth/userinfo.profile'));
$client->setClientId('***************');
$client->setClientSecret('***************');
$client->setRedirectUri('***************/google-drive-api-php-client/serverside.php');
$client->setApprovalPrompt('force');
$client->setAccessType('offline');
$client->setDeveloperKey('***************');
// a simple code to check if the user have already login to the site and authenticate the site and if he does the site will not ask the user again for authentification and it will use the refresh token to "log" the user in
if (empty($_GET['code'])) {
// if the user visit the website for the first time he need to authentificate (redirecting the website to google)!
if (empty($_SESSION['access_token']) && !isset($_SESSION['refresh_token'])) {
header('Location: ' . $client->createAuthUrl());
// if the user have already visited the site, but the access token have expired use this code
} elseif (empty($_SESSION['access_token']) && isset($_SESSION['refresh_token'])) {
echo "refresh token1" . "<br>";
$google_token = json_decode($_SESSION['refresh_token'], true);
$client->refreshToken($google_token['refresh_token']);
$_SESSION['access_token']= $client->getAccessToken();
}
} elseif (!empty($_GET['code']) && empty($_SESSION['access_token'])) {
// if the user is visiting the website for the first time and dont have refresh token:
if (!isset($_SESSION['refresh_token'])) {
echo "access token" . "<br>";
$client->authenticate($_GET['code']);
$_SESSION['access_token'] = $client->getAccessToken();
$_SESSION['refresh_token'] = $_SESSION['access_token'];
// this will never execute, but i put it anyway :) if the user have already visited the site, but the access token have expired use this code (its the same as the above)
} elseif (isset($_SESSION['refresh_token'])) {
echo "refresh token2" . "<br>";
$google_token = json_decode($_SESSION['refresh_token'], true);
$client->refreshToken($google_token['refresh_token']);
$_SESSION['access_token']= $client->getAccessToken();
}
}
// if the access token have expired use the refresh token to gain access instead:
if ($client->isAccessTokenExpired()) {
$google_token = json_decode($_SESSION['refresh_token'], true);
$client->refreshToken($google_token['refresh_token']);
$_SESSION['access_token']= $client->getAccessToken();
}
// unset the sessions for testing:
// unset($_SESSION['access_token']);
// unset($_SESSION['refresh_token']);
// get some info from the user Google API like the file info
if (!empty($_SESSION['access_token'])) {
// create the service in this case Google Drive
$service = buildService($_SESSION['access_token']);
// mark the file ID
$fileid = "*******************";
// print the access token
echo "<pre>";
print_r(getUserInfo($_SESSION['access_token']));
echo "</pre>";
// print file metadata from google drive
// echo "<pre>";
// print_r(printFile($service, $fileid));
// echo "</pre>";
}
// printing the session for testing...
echo "<pre>";
print_r($_SESSION);
echo "</pre>";
// print the refresh token for testing
print_r($_SESSION['refresh_token']);
// print echo to see if the code is executing till the end or there is a fatal error someone in the code :)
echo "string";
?>
I am using Abraham Twitter API SDK and I am facing some problem while executing index.php page.
in my config.php page my code is like this
define('CONSUMER_KEY', 'xxxxxxxxxxxxxxxxxxxxxx');
define('CONSUMER_SECRET', 'xxxxxxxxxxxxxxxxxxxxxxxxxxx');
define('OAUTH_CALLBACK', 'http://example.com/callback.php');
When, I open the index file in the browser, it redirects to connect.php
Here, if I click on Signin with PHP button, the page will redirect to redirect.php
here, my problem comes. In redirect.php page, i am including twitteroauth.php file.
The code in My redirect.php file
/* Start session and load library. */
session_start();
require_once('twitteroauth/twitteroauth.php');
require_once('config.php');
/* Build TwitterOAuth object with client credentials. */
$connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET);
/* Get temporary credentials. */
$request_token = $connection->getRequestToken(OAUTH_CALLBACK);
/* Save temporary credentials to session. */
$_SESSION['oauth_token'] = $token = $request_token['oauth_token'];
$_SESSION['oauth_token_secret'] = $request_token['oauth_token_secret'];
/* If last connection failed don't display authorization link. */
switch ($connection->http_code) {
case 200:
/* Build authorize URL and redirect user to Twitter. */
$url = $connection->getAuthorizeURL($token);
header('Location: ' . $url);
break;
default:
/* Show notification if something went wrong. */
echo 'Could not connect to Twitter. Refresh the page or try again later.';
}
In my twitteroauth.php file, the constructor is looking like this
function __construct($consumer_key, $consumer_secret, $oauth_token = NULL, $oauth_token_secret = NULL) {
$this->sha1_method = new OAuthSignatureMethod_HMAC_SHA1();
$this->consumer = new OAuthConsumer($consumer_key, $consumer_secret);
if (!empty($oauth_token) && !empty($oauth_token_secret)) {
$this->token = new OAuthConsumer($oauth_token, $oauth_token_secret);
} else {
$this->token = NULL;
}
}
My error i am getting in the browser is
Notice: Undefined index: oauth_token in line 80
Could not connect to Twitter. Refresh the page or try again later.
I tried in many ways to solve this problem. But I failed.
Please help me in that.
Thanks in advance.
I had similar error. I solved it by setting a Callback URL in my twitter application settings. http://dev.twitter.com
Login at https://dev.twitter.com
Go to https://dev.twitter.com/apps
Click 'Settings' tab
Set 'Callback URL' as something like http://example.com/twitteroauth/callback.php
Then save the settings
I am trying to implement Login With twitter api using Twitter oauth PHP library. Everything seems to be work fine. I get the Twitter Sign In screen for the user. As per the code I get $twitteroauth->http_code as 200. But it keep redirecting page to the same Twitter Login screen.
Here is my code:
function loginTwitter()
{
// The TwitterOAuth instance
$twitteroauth = new TwitterOAuth('xxx', 'xxxxx');
// Requesting authentication tokens, the parameter is the URL we will be redirected to
$request_token = $twitteroauth->getRequestToken('http://localhost/testsaav/socialAuth/twitterAuth');
// Saving them into the session
$_SESSION['oauth_token'] = $request_token['oauth_token'];
$_SESSION['oauth_token_secret'] = $request_token['oauth_token_secret'];
// If everything goes well..
if($twitteroauth->http_code==200){
// Let's generate the URL and redirect
$url = $twitteroauth->getAuthorizeURL($request_token['oauth_token']);
header('Location: '. $url);
} else {
// It's a bad idea to kill the script, but we've got to know when there's an error.
die('Something wrong happened.');
}
}
I am using Abraham Williams twitter api in order to log in the user. During step one I store the temporary oauth_token and oauth_token _secret in the session. After the user is redirected to my page after the sign in process the session data stored previously are lost. How can I solve this ?
function oauth()
{
//Build TwitterOAuth object with client credentials
$connection = new TwitterOAuth($this->consumer_key, $this->consumer_secret);
//Get temporary credentials
$request_token = $connection->getRequestToken($this->callback);
//Save temporary credentials to session
$session_data = array(
'oauth_token' => $request_token['oauth_token'],
'oauth_token_secret'=> $request_token['oauth_token_secret'],
);
$this->session->set_userdata($session_data);
//If last connection failed don't display authorization link.
switch ($connection->http_code)
{
case 200:
$url = $connection->getAuthorizeURL($request_token['oauth_token'], TRUE);
header('Location: ' . $url);
break;
default:
echo 'Could not connect to Twitter. Refresh the page or try again later.';
}
}
function callback()//callback after user signs in with twitter
{
$connection = new TwitterOAuth($this->consumer_key,
$this->consumer_secret,
$this->session->userdata("oauth_token"),
$this->session->userdata("oauth_token_secret"));
$access_token = $connection->getAccessToken($_REQUEST['oauth_verifier']);
$this->session->set_userdata('access_token', $access_token);
//Remove no longer needed request tokens
$this->session->unset_userdata('oauth_token');
$this->session->unset_userdata('oauth_token_secret');
//If HTTP response is 200 continue otherwise send to connect page to retry
if (200 == $connection->http_code)
{
$this->session->set_userdata('twitter_log_in', TRUE);
redirect('/main/', 'refresh');
}
}
Of course you verified you config file in Session section, but:
Already you tried it in other PC?
Tried DB Sessions or the inverse?
Made you simple tests excluding you case (twitter oauth class)
In somehow, maybe the code are replacing the vars, try log the informations in many parts of the code, to see if it as overwrote in the life of the process
So Im using Abrahams Twitter library like this:
Connect.php
/* Build TwitterOAuth object with client credentials. */
$connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET);
/* Get temporary credentials. */
$request_token = $connection->getRequestToken(OAUTH_CALLBACK);
/* Save temporary credentials to session. */
$_SESSION['oauth_token'] = $token = $request_token['oauth_token'];
$_SESSION['oauth_token_secret'] = $request_token['oauth_token_secret'];
/* If last connection failed don't display authorization link. */
switch ($connection->http_code) {
case 200:
/* Build authorize URL and redirect user to Twitter. */
$url = $connection->getAuthorizeURL($token);
header('Location: ' . $url);
break;
default:
/* Show notification if something went wrong. */
echo 'Could not connect to Twitter. Refresh the page or try again later.';
}
and index.php:
$connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, $_SESSION['oauth_token'], $_SESSION['oauth_token_secret']);
$userInfo = $connection->get('account/verify_credentials');
But I keep getting the error:
"Could not authenticate you"
What am I doing wrong?
Apparently after authentification, I have to replace the temporary authentification token, for a permanent one. Here it is:
Callback.php
/* Create TwitteroAuth object with app key/secret and token key/secret from default phase */
$connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, $_SESSION['oauth_token'], $_SESSION['oauth_token_secret']);
/* Request access tokens from twitter */
$access_token = $connection->getAccessToken($_REQUEST['oauth_verifier']);
/* Save the access tokens. Normally these would be saved in a database for future use. */
$_SESSION['access_token'] = $access_token;
/* Remove no longer needed request tokens */
unset($_SESSION['oauth_token']);
unset($_SESSION['oauth_token_secret']);
/* If HTTP response is 200 continue otherwise send to connect page to retry */
if (200 == $connection->http_code) {
/* The user has been verified and the access tokens can be saved for future use */
$_SESSION['status'] = 'verified';
header('Location: ./index.php');
} else {
die("There was a problem!");
}