PHP: Dropbox API OAuth Setup, PHP scripts

May 30, 2022

On the previous post we started the integration with the Dropbox API.


Now we are going to create three php script files for the setup of the Dropbox authentication:

  1. oauth-step1.php
    This page will start the process. It will contain a link that will take us to the Dropbox site.
  2. oauth-step2.php
    This page will receive a code from Dropbox, and then request a "access_token" that we will use for the Dropbox API calls.
  3. oauth-step3.php
    This page will display a "success" message.

The oauth-step1.php file defines a link to the Dropbox site that will start the authorization process.
We will submit our App key, obtained when we registered our App. We will also specify the url, Dropbox will redirect us if the authorization was successful.

Note that we are using the token_access=offline parameter, since we will be using the API from a website, which means that the "access_token" will expire after certain amount of time. Also, we will receive a "refresh_token" which will be used to get a new "access_token" everytime the previous one has expired.

On the sample code shown below we are using a local web server, and we have our files placed in a "dropbox-api" folder.
Our first file will be invoked on a browser with the following url:

http://localhost/dropbox-api/oauth-step1.php

oauth-step1.php


<html>
<head></head>
<body>
    <?php
    $client_id = 'abcdefghijklmno';

    $redirect_url = 'http://localhost/dropbox-api/oauth-step2.php';

    $authorization_url = 'https://www.dropbox.com/oauth2/authorize?client_id=' . $client_id
        . '&token_access_type=offline'
        . '&response_type=code'
        . '&redirect_uri=' . $redirect_url
    ?>
    <div style="text-align:center">
        <p>My Dropbox App</p>
        <a href="<?php echo $authorization_url; ?>">Authorize Dropbox</a>
    </div>
</body>
</html>


The oauth-step2.php file will be the file were Dropbox redirect us when we sign in and authorize the App.

The first part of this file reads the "code" parameter, and checks for any error on this phase.


oauth-step2.php


<?php
// This page is called by Dropbox OAuth process after the user has authorized the app

// If the user authorizes the app, Dropbox returns a "code" in a url parameter
$code = $_GET['code'];

// If the user does not authorizes the app, Dropbox return an error, 
// which we will display to the user, and then we terminate the script
if (empty($code)) {
    $error = $_GET['error'];
    $error_description = $_GET['error_description'];

    if (!empty($error)) {
        echo $error . ': ' . $error_description;
    }
    exit;
}


Once we have the "code" from Dropbox, we have to submit it to them to get the actual tokens that would be used on our API calls: an "access token" and a "refresh token"

For this we are using the php curl functions.

We also check that the response from Dropbox is valid, otherwise we display the returned error message.


oauth-step2.php (cont)



// If we get the "code" we submit it to a Dropbox url, which in return will give us 
// an "access token" and a "refresh token"

$client_id = 'abcdefghijklmno';
$secret = 'onmlkjihgfedcba';

$redirect_url = 'http://localhost/dropbox-api/oauth-step2.php';
$url = 'https://api.dropbox.com/oauth2/token';

$data = array(
    'code' => $code,
    'grant_type' => 'authorization_code',
    'redirect_uri' => $redirect_url
);

$query_string = http_build_query($data);

$ch = curl_init($url);

curl_setopt($ch, CURLOPT_USERPWD, $client_id . ":" . $secret);  
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $query_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

$response = curl_exec($ch);

curl_close($ch);

// The response is in json format
$json = json_decode($response);


// If the response could not be decoded as json
if (is_null($json)) {
    echo $response;
    exit;
}

// If the response contains an error message ... with an "error_summary" field
if (!empty($json->error->{".tag"})) {
    echo $json->error->{".tag"} . (!empty($json->error_summary) ? ': ' . $json->error_summary : '');
    exit;
}

// If the response contains an error message ... with an "error_message" field
if (!empty($json->error)) {
    echo $json->error . (!empty($json->error_description) ? ': ' . $json->error_description : '');
    exit;
}

// If the response doesn't contain the "access token"
if (empty($json->access_token)) {
    echo 'Unknown error: ' . $response;
    exit;
}


The next part on the processing of the response implies to store it safely. In our case we are going to store the response in a MySQL database.

On our database we will create a table named "dropbox_settings" with the following definition:


CREATE TABLE `dropbox_settings` (
  `id` int(11) NOT NULL,    
  `access_token` varchar(255) NOT NULL,
  `expires_in` int(11) NOT NULL,
  `token_type` varchar(25) NOT NULL,
  `scope` text NOT NULL,
  `refresh_token` varchar(255) NOT NULL,
  `account_id` varchar(255) NOT NULL,
  `uid` varchar(15) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

ALTER TABLE `dropbox_settings`
  ADD PRIMARY KEY (`id`);

ALTER TABLE `dropbox_settings`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;

Then the next snippet of code, at the end of our oauth-step2.php file, will store the response from Dropbox into our database for later use.

After the response is stored in the database we will be redirected to our last page oauth-step3.php.


oauth-step2.php (cont)


// Then we save the response data (access token, refresh token) in a database

$host = 'localhost'; 
$user = 'YOUR USER';  
$pass = 'YOUR PASSWORD'; 
$db = 'YOUR DATABASE';

$mysqli = new mysqli($host, $user, $pass, $db);

$sql = 'insert into dropbox_settings (access_token, expires_in, token_type, scope, refresh_token, account_id, uid)
values ( 
    "' . $mysqli->real_escape_string($json->access_token) . '",
    "' . intval($json->expires_in) . '",
    "' . $mysqli->real_escape_string($json->token_type) . '",
    "' . $mysqli->real_escape_string($json->scope) . '",
    "' . $mysqli->real_escape_string($json->refresh_token) . '",
    "' . $mysqli->real_escape_string($json->account_id) . '",
    "' . intval($json->uid) . '" 
)';

$mysqli->query($sql) or die($mysqli->error);

$mysqli->close();

header('Location: oauth-step3.php');

Note that you would have to enter your database user, password, and name before running this file.


The last file on our process displays an Authorization Successful message.


oauth-step3.php


<html>
<head></head>
<body>
    <div style="text-align:center">
        <p>My Dropbox App</p>
        <strong>Authorization Successful</strong>
    </div>
</body>
</html>



One additional step to complete before running the above files is to enter the Redirect URL on the Settings page of our Dropbox App page as shown below:

http://localhost/dropbox-api/oauth-step2.php


Set Redirect Url in Dropbox



On the next post we will show these script files in action.