Saturday, July 7, 2012

Dropbox OAuth API Integration on PHP

This post will teach you how to integrate with Dropbox OAuth using PHP platform. Please take note that I'm not using any library to perform this integration nor special coding or whatsoever.

This is basically built from scratch which I want to share with you all, who wish to integrate with Dropbox.

To start with, you need an API credentials which you can get by logging in to your Dropbox account and create an app on this url - https://www.dropbox.com/developers/apps

We need the credentials below to proceed:
  • App key
  • App secret
We also need to understand the 3 url's that we need to access to complete the authentication process as listed below.
The request token url will be use to get a token which will be use to authorize your app to access users information in their behalf.

The authorization url will be the page for users to allow our application to access the users credential.

The access token url will be use to get an access token which will be use to access users credentials in their behalf.

Another thing that we need to understand is how to create signature. We need this in performing oauth request.

For the sake of this post, we will use the PLAINTEXT signature method, which is the simplest signature method.

Once we have the credentials and the api url's, we are now ready to start by just following the simple steps below.

1. Lets request for a token from the request token url - https://api.dropbox.com/1/oauth/request_token. Since we are using plaintext signature method, the signature will be your app secret plus "%26". Please see below.

$key = '<your app key>';
$secret = '<your app secret>';
$timestamp = time();$nonce = md5(time());
$sig = $secret."%26";
$method = "PLAINTEXT";


2. Once we have all the parameters, lets compose the post request.

$url = "https://api.dropbox.com/1/oauth/request_token";
$param = "oauth_consumer_key=$key".
                "&oauth_signature_method=$method".
                "&oauth_signature=$sig".
                "&oauth_timestamp=$timestamp".
                "&oauth_nonce=$nonce".
                "&oauth_version=1.0";


3. Execute post request using curl, which is the basic command in performing post request.

$ch = curl_init();
           
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_VERBOSE, 1);

// disable ssl verification
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);

curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);

// submit post request parameters
curl_setopt($ch, CURLOPT_POSTFIELDS, $param);

// getting response from server
$output = curl_exec($ch);


4. Parse the output and you will get the "oauth_token" and "oauth_token_secret" below which will be use to perform authorization. You can save these information in your session so that you will retrieve it later when performing access token.

// parse the output
parse_str($output, $token);

// save to session
$_SESSION['oauth_token'] = $token['oauth_token'];
$_SESSION['token_secret'] = $token['oauth_token_secret'];


5. From the step #4, we only need the "oauth_token" to request for authorization. For this process, we need to define our callback url in which Dropbox will redirect the users after allowing the access.

$oauth_token = $_SESSION['oauth_token'];
$callback = '<your callback url>';

$url = "https://www.dropbox.com/1/oauth/authorize";
$param = "oauth_token=$oauth_token".
                "&oauth_callback=$callback";

header("Location: $url?$param");


6. After the user allows our application, Dropbox will redirect the user to our callback url we specify on step #5. We need to submit post request to access token url with the parameter "oauth_token" from step #4. This will also require signature, the same way we did on request token process, but this time with extra parameter "oauth_token_secret" from step #4.

$oauth_token = $_SESSION['oauth_token'];
$token_secret = $_SESSION['token_secret'];

$key = '<your app key>';
$secret = '<your app secret>';
$timestamp = time();$nonce = md5(time());
$sig = $secret."%26".$token_secret;
$method = "PLAINTEXT";


7. Lets compose the url and parameter with "oauth_token" as part of the request.

$url = "https://api.dropbox.com/1/oauth/access_token";
$param = "oauth_consumer_key=$key".
                "&oauth_token=$oauth_token".
                "&oauth_signature_method=$method".
                "&oauth_signature=$sig".
                "&oauth_timestamp=$timestamp".
                "&oauth_nonce=$nonce".
                "&oauth_version=1.0";


8. Execute the post request using curl.

$ch = curl_init();
           
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_VERBOSE, 1);

// disable ssl verification
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);

curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);

// submit post request parameters
curl_setopt($ch, CURLOPT_POSTFIELDS, $param);

// getting response from server
$output = curl_exec($ch);


9. Parse the output and we will get an access token which we will use to do the api request. You can save these information in your database so that you won't need to request for authorization when doing api request.

// parse the output
parse_str($output, $token);

// save to session
$_SESSION['oauth_token'] = $token['oauth_token'];
$_SESSION['token_secret'] = $token['oauth_token_secret'];


You can try the full script below I made with a live API account and a basic API request. I optimized the script as well for better coding.

<?php

session_start();

$key = 'vh096l7q9m5m8tv'; // put here your app key
$secret = 'omri1uakcak8zqz'; // put here your app secret

// from callback
$oauth_token = $_GET['oauth_token'];
if ($oauth_token) {
        access_token($key, $secret);
} else {
        request_token($key, $secret);
}

function request_token($key='', $secret='') {
        $timestamp = time();
        $nonce = md5(time());
        $sig = $secret."%26";
        $method = "PLAINTEXT";

        $url = "https://api.dropbox.com/1/oauth/request_token";
        $param = "oauth_consumer_key=$key".
                 "&oauth_signature_method=$method".
                 "&oauth_signature=$sig".
                 "&oauth_timestamp=$timestamp".
                 "&oauth_nonce=$nonce".
                 "&oauth_version=1.0";

        $output = post_request($url, $param);

        // parse the output
        parse_str($output, $token);

        // save to session
        $_SESSION['oauth_token'] = $token['oauth_token'];
        $_SESSION['token_secret'] = $token['oauth_token_secret'];

        authorize();
}

function authorize() {
        $oauth_token = $_SESSION['oauth_token'];
        $callback = "http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']; // put your callback url

        $url = "https://www.dropbox.com/1/oauth/authorize";
        $param = "oauth_token=$oauth_token".
                 "&oauth_callback=$callback";

        header("Location: $url?$param");
}

function access_token($key='', $secret='') {
        $oauth_token = $_SESSION['oauth_token'];
        $token_secret = $_SESSION['token_secret'];

        $timestamp = time();
        $nonce = md5(time());
        $sig = $secret."%26".$token_secret;
        $method = "PLAINTEXT";

        $url = "https://api.dropbox.com/1/oauth/access_token";
        $param = "oauth_consumer_key=$key".
                 "&oauth_token=$oauth_token".
                 "&oauth_signature_method=$method".
                 "&oauth_signature=$sig".
                 "&oauth_timestamp=$timestamp".
                 "&oauth_nonce=$nonce".
                 "&oauth_version=1.0";

        $output = post_request($url, $param);

        // parse the output
        parse_str($output, $token);

        // save to session
        $_SESSION['oauth_token'] = $token['oauth_token'];
        $_SESSION['token_secret'] = $token['oauth_token_secret'];

        folders($key, $secret);
}

function folders($key='', $secret='') {
        $oauth_token = $_SESSION['oauth_token'];
        $token_secret = $_SESSION['token_secret'];

        $timestamp = time();
        $nonce = md5(time());
        $sig = $secret."%26".$token_secret;
        $method = "PLAINTEXT";

        $url = "https://api.dropbox.com/1/metadata/dropbox";
        $param = "oauth_consumer_key=$key".
                 "&oauth_token=$oauth_token".
                 "&oauth_signature_method=$method".
                 "&oauth_signature=$sig".
                 "&oauth_timestamp=$timestamp".
                 "&oauth_nonce=$nonce".
                 "&oauth_version=1.0";

        $output = file_get_contents($url."?".$param);
        $jsondata = json_decode($output);

        foreach ($jsondata->contents as $contents) {
                echo $contents->path."<br/>";
        }
}

function post_request($url='', $param='') {
        $ch = curl_init();

        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_VERBOSE, 1);

        // disable ssl verification
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);

        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);

        // submit post request parameters
        curl_setopt($ch, CURLOPT_POSTFIELDS, $param);

        // getting response from server
        $output = curl_exec($ch);

        return $output;
}

?>


18 comments:

  1. Can you tell me how to get folder files in this code

    ReplyDelete
  2. You can call the folders() function here then if you need a specific path of your dropbox folder then just change the url by adding the path after the dropbox. $url = "https://api.dropbox.com/1/metadata/dropbox/path/to/files";

    Hope this helps.

    ReplyDelete
  3. thnx for replay can you solve my another query ..
    actually i want to copy the dropbox files to my own server....currenlty we access only ..can tell how can i copy the file to my server

    ReplyDelete
  4. how can i this can apply $url = "https://api.dropbox.com/1/metadata/dropbox/path/to/files";

    can you explain a littel bit please.

    ReplyDelete
  5. which part of function we get access token ....i don't get it access token.

    ReplyDelete
  6. actually i want to copy the dropbox files to my own server....currenlty we access only ..can tell how can i copy the file to my server
    - I believe each file has a share url returned to you when you get the information when you call function folders($key='', $secret='')

    how can i this can apply $url = "https://api.dropbox.com/1/metadata/dropbox/path/to/files";
    - you can call function folders($key='', $secret='') I have here then just change the url to go to your folders on dropbox. ex. if you have a folder "products" on your dropbox account setting the url on folders() function to "https://api.dropbox.com/1/metadata/dropbox/products" will display all files under that folder.

    which part of function we get access token ....i don't get it access token.
    - function access_token($key='', $secret='') pass your app key and secret and you will get an access token when you parse the output parse_str($output, $token); and an array will be set to $token.

    ReplyDelete
  7. Thnx buddy ...you are savior. but one problem still i have when i run this function folders($key='', $secret='') i do not get share url or i got this Array ....................................
    {
    "hash": "334fa54fce7ea5df02b5ac2e11f7523d",
    "thumb_exists": false,
    "bytes": 0,
    "path": "/",
    "is_dir": true,
    "icon": "folder",
    "root": "dropbox",

    "contents": [

    {"rev": "213232a24f88",
    "thumb_exists": true,
    "path": "/dell.png",
    "is_dir": false,
    "client_mtime": "Tue, 24 Mar 2015 05:43:57 +0000",
    "icon": "page_white_picture",
    "read_only": false,
    "modifier": null,
    "bytes": 5238,
    "modified": "Mon, 06 Apr 2015 04:09:45 +0000",
    "size": "5.1 KB",
    "root": "dropbox",
    "mime_type": "image/png",
    "revision": 8498},
    ],
    "size": "0 bytes"
    }
    .........................................................
    and after that you use Foreach loop. and get $contents->path....
    acullty i want to be when i get the list of file of dropbox account ...when i click the any file those file will save to our server or downloads...

    ReplyDelete
  8. To download the file, please try this url = "https://api-content.dropbox.com/1/files/auto/". Let me know if it works!

    ReplyDelete
  9. Also, the method you need to use there is GET.

    ReplyDelete
  10. Sorry, the url should be "https://api-content.dropbox.com/1/files/auto/path/to/file".. where in path/to/file is the path of the file which on your case it should be /dell.png.. then call file_get_contents($url."?".$param);

    ReplyDelete
  11. This comment has been removed by the author.

    ReplyDelete
  12. Hi It's not working .i send you code folder function. please correct where i m wrong. i m not understand. :(

    function folders($key='', $secret='')
    {
    $oauth_token = $_SESSION['oauth_token'];
    $token_secret = $_SESSION['token_secret'];

    $timestamp = time();
    $nonce = md5(time());
    $sig = $secret."%26".$token_secret;
    $method = "PLAINTEXT";
    $url = "https://api-content.dropbox.com/1/files/auto";

    $param = "oauth_consumer_key=$key".
    "&oauth_token=$oauth_token".
    "&oauth_signature_method=$method".
    "&oauth_signature=$sig".
    "&oauth_timestamp=$timestamp".
    "&oauth_nonce=$nonce".
    "&oauth_version=1.0";

    $output = file_get_contents($url."?".$param);
    print_r($output);
    echo '';
    $jsondata = json_decode($output);
    echo '';



    foreach ($jsondata->contents as $contents)
    {

    }
    }

    ReplyDelete
  13. OKAY I GOT IT ALL CREDIT GOES TO YOU...:):):)

    but a small one how do i copy a image from dropbox to own dev server.?

    Please suggest something for this one.

    ReplyDelete
  14. I just created a new post to do this, please check it out and let me know if it works - http://paulgonzaga.blogspot.com/2015/04/download-files-from-url-and-save-it-to.html

    ReplyDelete
  15. Hi Paul,
    After login show dropbox page than what's the next process.?

    ReplyDelete
  16. file_get_contents(https://api.dropbox.com/1/metadata/dropbox?oauth_consumer_key=wtsj3li9dm6lj81&oauth_token=9joc2mkz7j9lhiqp&oauth_signature_method=PLAINTEXT&oauth_signature=29fzk77pefen7lz%26cb969o1f050sx3t&oauth_timestamp=1490002891&oauth_nonce=3e741ade66c4a4c533c1a7d6d0c290dd&oauth_version=1.0): failed to open stream: HTTP request failed!

    ReplyDelete
  17. El Yucateco - Mapyro
    El Yucateco, Hot Sauce, Green 동해 출장샵 Chile Habanero, $3.90. 이천 출장마사지 El Yucateco, 진주 출장샵 Salsa Picante de 서산 출장안마 Chile 광주광역 출장안마 Habanero, $8.90.

    ReplyDelete

Leadership 101


  • Leadership demands sacrifices for the near-term to receive lasting benefits. the longer we wait to make sacrifices, the harder they become. Successful people make important decisions early in their life, then manage those decisions the rest of their lives.
  • Growth does not happen by chance. If you want to be sure to grow, you need a plan something strategic, specific, and scheduled. it's a discipline that would need incredible determination from us.
  • Success comes by going the extra mile, working the extra hours, and investing the extra time. The same is true for us. If we want to get to excel in any segment of life, a little extra effort can help. Our efforts can go a long way if we only work a little smarter, listen a little better, push a little harder, and persevere a little longer.
  • Making a difference in your work is not about productivity; it's about people. When you focus on others and connect with them, you can work together to accomplish great things.
  • Envision a goal you'd like to reach. Make it big enough to scare you a little. Now write down a plan for moving toward it. Create mini-goals within the big goal, to set yourself up for continual progress. And include some risks, too. Set yourself up for success.
  • Leaders build margins, not image. A leader may be forced to take unpopular stands for the good of the company. Popularity isn't bad, but decisions made solely on the basis of popular opinion can be devastating. So take courage and make the right though sometimes painful choices.