Sunday, April 6, 2014

PHP: Get Token From Dropbox

Just use Dropbox for serving the files/pictures of your personal site or startup site, for free use, there is up to 16 GB maximum capacity, far enough to carry out your idea.

First off, we will sign up for Dropbox, start a application that uses Core API. This will give you the key and secret. Prepare it in a file named config.json.

  "key": "your-dropbox-api-key",
  "secret": "your-dropbox-api-secret"

Download you PHP sdks from here: Unzip and put in your project directory.

Prepare you getdbxtoken.php as following, this will load dropbox php library along with you config in the previous json file.

require_once "dropbox-php-sdk-1.1.3/lib/Dropbox/autoload.php";
use \Dropbox as dbx;

        $appInfo = dbx\AppInfo::loadFromJsonFile("config.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();


Run the script from command line:

chmod a+x getdbxtoken.php
php -q getdbxtoken.php

You will need to input auth code in order to get the token, which is obtained by following the link and give the allow permission (go to the brower and [login in] and grant that). While you get that auth code, copy it to your command line, press enter. It will throw you the access token. In consequence, we tried to open a new client and fetch the account info, which is returned as an array, printed to your screen later.

1. Go to:
2. Click "Allow" (you might have to log in first).
3. Copy the authorization code.
Enter the authorization code here: 

To note once obtained the token, you might want to save it to a secure place since you don't need to log in (auth) again. Next time you can just build client by the token, and connect directly to dropbox.

No comments:

Post a Comment