Hi everyone i am new in dropbox api (php version).
i am getting authCode using authorizeUrl, its working good for only one time if i reload page error message shows on
'HTTP status 400 {"error_description": "code has expired (within the last hour)", "error": "invalid_grant"}
how to get permanent authCode from dropbox.
$appInfo = dbx\AppInfo::loadFromJsonFile("api-key.json");
$webAuth = new dbx\WebAuthNoRedirect($appInfo, "PHP-Example/1.0");
$authorizeUrl = $webAuth->start();
echo "1. Go to: " . $authorizeUrl . "\n";
echo "2. Click \"Allow\" (you might have to log in first).\n";
echo "3. Copy the authorization code.\n";
$authCode = "****************************************";
list($accessToken, $dropboxUserId) = $webAuth->finish($authCode);
print "Access Token: " . $accessToken . "\n";
$dbxClient = new dbx\Client($accessToken, "PHP-Example/1.0");
$accountInfo = $dbxClient->getAccountInfo();
print_r($accountInfo);
Found the solution in this error
some steps to solve this problem
go to Apps page Dropbox apps
add your site or localhost link to OAuth 2 Redirect URIs
next to generate access token, then copy the access token and use it .
finally remove this lines
list($accessToken, $dropboxUserId) = $webAuth->finish($authCode);
print "Access Token: " . $accessToken . "\n";
and paste directly in your access token into
$accessToken =
"VTEp2cvkQ8************************************";
it's working perfectly
Related
I am having this weird issue here in which the instant I get a token via Dropbox and try to test it, an exception is thrown with this message:
HTTP status 401 {"error": "The given OAuth 2 access token doesn't
exist or has expired."}
Why would a Dropbox token expire as soon as I generate it?
Let me show you the flow of my app:
User sees this screen:
Which has the following relevant PHP code:
require "../../includes/dropbox-sdk/Dropbox/autoload.php";
require "../../includes/config.php";
session_start();
session_regenerate_id();
$appInfo = Dropbox\AppInfo::loadFromJsonFile("../../includes/dropbox-sdk/Dropbox/app-info.json");
$webAuth = new Dropbox\WebAuthNoRedirect($appInfo, "Mignori-Box/1.0");
$authorizeUrl = $webAuth->start();
So okay, we generate a Dropbox authorization URL with the official SDK, which seems to be working fine, the user sees this screen:
They click allow, Dropbox gives them an Authorization token, then they paste it into my site, and submit it. This is the code that processes the form:
try
{
$accessToken = $_POST['authorization_code'];
$dbxClient = new Dropbox\Client($accessToken, "Mignori-Box/1.0");
$accountInfo = $dbxClient->getAccountInfo();
}catch(Exception $e)
{
echo "<div class=\"alert alert-danger\">";
echo "<strong>An error has occurred.</strong><br>" . $e -> getMessage();
echo "</div>";
}
But no matter how recent the token is, when the user submits the token the catch is called and the warning displayed. Even if the token was generated literally seconds ago, this happens.
Can someone please enlighten me as to what's wrong?
I was forgetting the step to convert the authorization code into an access token.
list($accessToken, $dropboxUserId) = $webAuth->finish($authCode);
In other words, I was indeed using the wrong token. Haha. Last snippet of code should be:
try
{
list($accessToken, $dropboxUserId) = $webAuth->finish($_POST['authorization_code']);
$dbxClient = new Dropbox\Client($accessToken, "Mignori-Box/1.0");
$accountInfo = $dbxClient->getAccountInfo();
}catch(Exception $e)
{
echo "<div class=\"alert alert-danger\">";
echo "<strong>An error has occurred.</strong><br>" . $e -> getMessage();
echo "</div>";
}
I have the following code
<?php
// Include DropBox API
require_once "dropbox-sdk/Dropbox/autoload.php";
use \Dropbox as dbx;
// Settings for DropBox
$appInfo = dbx\AppInfo::loadFromJsonFile("config.json");
$webAuth = new dbx\WebAuthNoRedirect($appInfo, "PHP-Example/1.0");
$authCode = \trim(\readline("A-WALID-KEY-HERE"));
list($accessToken, $dropboxUserId) = $webAuth->finish($authCode);
print "Access Token: " . $accessToken . "\n";
?>
Bud i get this error when i run the code.
Call to undefined function readline()
What am I doing wrong?
It sounds from your comment like you're trying to run this as a web app. If so, you're going to run into trouble. This looks like the command-line app example code, which is why it uses readline (which reads input from the command-line).
You might want to start from the web-file-browser example that ships with the SDK. This is meant to be run as a web app and should show you to how to do (among other things) authentication in the browser.
I had the same problem with the same code. You have forgotten to add this:
$authorizeUrl = $webAuth->start();
just right after this line:
$webAuth = new dbx\WebAuthNoRedirect($appInfo, "PHP-Example/1.0");
What you have to do is to use the created link stored in the variable $authorizeUrl to get the authorization code.
After doing this you need to use the authorization code to generate a token. For this comment the part of your code like that:
<?php
// Include DropBox API
require_once "dropbox-sdk/Dropbox/autoload.php";
use \Dropbox as dbx;
// Settings for DropBox
//$appInfo = dbx\AppInfo::loadFromJsonFile("config.json");
//$webAuth = new dbx\WebAuthNoRedirect($appInfo, "PHP-Example/1.0");
//**$authorizeUrl = $webAuth->start();**
$authCode = \trim(\readline("**A-WALID-KEY-HERE**"));
list($accessToken, $dropboxUserId) = $webAuth->finish($authCode);
print "Access Token: " . $accessToken . "\n";
?>
Once you get the token save it somewhere safe and comment also the rest of the lines. Then you can access dropbox with no problem. For example:
$dbxClient = new dbx\Client($accessToken, "PHP-Example/1.0");
$accountInfo = $dbxClient->getAccountInfo();
How can I solve the problem with this error? I am using xampp and php 5.5.6 for my application. My code is as follow:
<?php
`enter code here`# Include the Dropbox SDK libraries
require_once "dropbox-php-sdk-1.1.2/lib/Dropbox/autoload.php";
use \Dropbox as dbx;
$appInfo = dbx\AppInfo::loadFromJsonFile("app-info.json");
$webAuth = new dbx\WebAuthNoRedirect($appInfo, "PHP-Example/1.0");
$authorizeUrl = $webAuth->start();
echo "1. Go to: " . $authorizeUrl . "\n";
echo "2. Click \"Allow\" (you might have to log in first).\n";
echo "3. Copy the authorization code.\n";
$authCode = \trim(\readline("Enter the authorization code here: "));
list($accessToken, $dropboxUserId) = $webAuth->finish($authCode);
print "Access Token: " . $accessToken . "\n";
$dbxClient = new dbx\Client($accessToken, "PHP-Example/1.0");
$accountInfo = $dbxClient->getAccountInfo();
print_r($accountInfo);
// uploading files
$f = fopen($_FILES["file"]["name"], "rb");
$result = $dbxClient->uploadFile($_FILES["file"]["name"], dbx\WriteMode::add(), $f);
fclose($f);
print_r($result);`enter code here`
?>
When I run the script on my browser, I get this error.
From the README:
Requirements:
PHP 5.3+, with 64-bit integers.
I'm accessing dropbox using OAuth 2.0 where it will gain an access token after succesfully authenticating a user. When I have successfully authenticating a user, I'm stuck at the success page where I have the authorization code. How do I redirect to my localhost and convert it to access token? I'm developing using php.
$appInfo = dbx\AppInfo::loadFromJsonFile("config.json");
$webAuth = new dbx\WebAuthNoRedirect($appInfo, "PHP-Example/1.0");
$authorizeUrl = $webAuth->start();
//echo $authorizeUrl;
header("Location:$authorizeUrl");
//$authCode = \trim(\readline("Enter the authorization code here: "));
$authCode = $_GET;
list($accessToken, $dropboxUserId) = $webAuth->finish($authcode);
print "Access Token: " . $accessToken . "\n";
$dbxClient = new dbx\Client($accessToken, "PHP-Example/1.0");
$accountInfo = $dbxClient->getAccountInfo();
print_r($accountInfo);
You're using WebAuthNoRedirect, which doesn't do redirection back to your app. You need to use WebAuth (which does do the redirection). If you look at the web-file-browser.php example in the PHP SDK download, you'll see an example that looks like this:
function getWebAuth()
{
list($appInfo, $clientIdentifier, $userLocale) = getAppConfig();
$redirectUri = getBaseUrl()."/dropbox-auth-finish";
$csrfTokenStore = new dbx\ArrayEntryStore($_SESSION, 'dropbox-auth-csrf-token');
return new dbx\WebAuth($appInfo, $clientIdentifier, $redirectUri, $csrfTokenStore, $userLocale);
}
I would start from that sample, as it's a complete end-to-end web app.
I followed again THIS TUTORIAL to upload a file on Google Drive with php, directly from my REMOTE SERVER: so I have created new API Project from Google API Console, enabled Drive API service, requested OAuth Client ID and Client Secret, wrote them in a script, then upload it together with Google APIs Client Library for PHP folder to this http://www.MYSERVER.com/script1.php, to retrieve Auth code:
<?php
require_once 'google-api-php-client/src/Google_Client.php';
require_once 'google-api-php-client/src/contrib/Google_DriveService.php';
$drive = new Google_Client();
$drive->setClientId('XXX'); // HERE I WRITE MY Client ID
$drive->setClientSecret('XXX'); // HERE I WRITE MY Client Secret
$drive->setRedirectUri('urn:ietf:wg:oauth:2.0:oob');
$drive->setScopes(array('https://www.googleapis.com/auth/drive'));
$gdrive = new Google_DriveService($drive);
$url = $drive->createAuthUrl();
$authorizationCode = trim(fgets(STDIN));
$token = $drive->authenticate($authorizationCode);
?>
When I visit http://www.MYSERVER.com/script1.php I allow authorization and get the Auth code that I can write in a second script. Then I upload it to http://www.MYSERVER.com/script2.php, who looks like:
<?php
require_once 'google-api-php-client/src/Google_Client.php';
require_once 'google-api-php-client/src/contrib/Google_DriveService.php';
$drive = new Google_Client();
$drive->setClientId('X'); // HERE I WRITE MY Client ID
$drive->setClientSecret('X'); // HERE I WRITE MY Client Secret
$drive->setRedirectUri('urn:ietf:wg:oauth:2.0:oob');
$drive->setScopes(array('https://www.googleapis.com/auth/drive'));
$gdrive = new Google_DriveService($drive);
$_GET['code']= 'X/XXX'; // HERE I WRITE AUTH CODE RETRIEVED AFTER RUNNING REMOTE script.php
file_put_contents('token.json', $drive->authenticate());
$drive->setAccessToken(file_get_contents('token.json'));
$doc = new Google_DriveFile();
$doc->setTitle('Test Drive');
$doc->setDescription('Document');
$doc->setMimeType('text/plain');
$content = file_get_contents('drive.txt');
$output = $gdrive->files->insert($doc, array(
'data' => $content,
'mimeType' => 'text/plain',
));
print_r($output);
?>
Well, now the file drive.txt is uploaded on my Google Drive and structure of token.json file is a sort of:
{"access_token":"XXX","token_type":"Bearer","expires_in":3600,"refresh_token":"YYY","created":1365505148}
Now, as you can imagine I can call script2.php and upload file until a certain time. Finally, the point is: I don't want the token to expire, I don't want to allow authorization each time it expire (recalling script1.php): I need to call the script2.php periodically during the day, to upload my file automatically, without user interaction. So, what's the best way to automatically refresh the token forever in this context? Do I need another script? Can I add some code to script2.php? or modify the token.json file? And where can I read the time remaining before the token expire? Thanks!
You don't have to periodically ask for an access token. If you have a refresh_token, PHP client will automatically acquire a new access token for you.
In order to retrieve an refresh_token, you need to set access_type to "offline" and ask for offline access permissions:
$drive->setAccessType('offline');
Once you get a code,
$_GET['code']= 'X/XXX';
$drive->authenticate();
// persist refresh token encrypted
$refreshToken = $drive->getAccessToken()["refreshToken"];
For future requests, make sure that refreshed token is always set:
$tokens = $drive->getAccessToken();
$tokens["refreshToken"] = $refreshToken;
$drive->setAccessToken(tokens);
If you want a force access token refresh, you can do it by calling refreshToken:
$drive->refreshToken($refreshToken);
Beware, refresh_token will be returned only on the first $drive->authenticate(), you need to permanently store it. In order to get a new refresh_token, you need to revoke your existing token and start auth process again.
Offline access is explained in detail on Google's OAuth 2.0 documentation.
After messing a lot I got this to work. I am using one file/script to get the offline token and then a class to do stuff with the api:
require_once 'src/Google/autoload.php'; // load library
session_start();
$client = new Google_Client();
// Get your credentials from the console
$client->setApplicationName("Get Token");
$client->setClientId('...');
$client->setClientSecret('...');
$client->setRedirectUri('...'); // self redirect
$client->setScopes(array('https://www.googleapis.com/auth/drive.file'));
$client->setAccessType("offline");
$client->setApprovalPrompt('force');
if (isset($_GET['code'])) {
$client->authenticate($_GET['code']);
$_SESSION['token'] = $client->getAccessToken();
$client->getAccessToken(["refreshToken"]);
$redirect = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
header('Location: ' . filter_var($redirect, FILTER_SANITIZE_URL));
return;
}
if (isset($_SESSION['token'])) {
$client->setAccessToken($_SESSION['token']);
}
if (isset($_REQUEST['logout'])) {
unset($_SESSION['token']);
$client->revokeToken();
}
?>
<!doctype html>
<html>
<head><meta charset="utf-8"></head>
<body>
<header><h1>Get Token</h1></header>
<?php
if ($client->getAccessToken()) {
$_SESSION['token'] = $client->getAccessToken();
$token = json_decode($_SESSION['token']);
echo "Access Token = " . $token->access_token . '<br/>';
echo "Refresh Token = " . $token->refresh_token . '<br/>';
echo "Token type = " . $token->token_type . '<br/>';
echo "Expires in = " . $token->expires_in . '<br/>';
echo "Created = " . $token->created . '<br/>';
echo "<a class='logout' href='?logout'>Logout</a>";
file_put_contents("token.txt",$token->refresh_token); // saving access token to file for future use
} else {
$authUrl = $client->createAuthUrl();
print "<a class='login' href='$authUrl'>Connect Me!</a>";
}
?>
</body>
</html>
You can load refresh token from file and use it as necessary for offline access:
class gdrive{
function __construct(){
require_once 'src/Google/autoload.php';
$this->client = new Google_Client();
}
function initialize(){
echo "initializing class\n";
$client = $this->client;
// credentials from google console
$client->setClientId('...');
$client->setClientSecret('...');
$client->setRedirectUri('...');
$refreshToken = file_get_contents(__DIR__ . "/token.txt"); // load previously saved token
$client->refreshToken($refreshToken);
$tokens = $client->getAccessToken();
$client->setAccessToken($tokens);
$this->doSomething(); // go do something with the api
}
}
More here: https://github.com/yannisg/Google-Drive-Uploader-PHP