how to refresh access token in dropbox api without login in php

1.4k Views Asked by At

I am using https://github.com/kunalvarma05/dropbox-php-sdk for my php project to upload files at dropbox.

Here I do not required any user to use dropbox its just for internal users so i can upload files at my dropbox.

I Generated access token from Dropbox app and everything working but token is getting expired after some time. I did one time Oauth login to regenerate token but new token also expired after some time.

How can i regenerate token or get long-lived token so at backend, so my script can upload files at dropbox after every new upload by user's?

I am using this simple code

include('dropbox/vendor/autoload.php');
        $app = new DropboxApp("client_id", "client_secret", 'access_token');
        $dropbox = new Dropbox($app);
        $data = []; // here getting list of files from database 
        if (!$data->isEmpty()) {
            foreach ($data as $list) {
                $filePath = 'folder_path/'.$list->file_name;
                $fileName = $list->file_name;
                try {
                    // Create Dropbox File from Path
                    $dropboxFile = new DropboxFile($filePath);

                    // Upload the file to Dropbox
                    $uploadedFile = $dropbox->upload($dropboxFile, "/folder_name/" . $fileName, ['autorename' => true]);
                    // File Uploaded
                    echo $uploadedFile->getPathDisplay();
                } catch (DropboxClientException $e) {
                    print_r($e->getMessage());

                }
            }
        } 
3

There are 3 best solutions below

0
Yogesh Saroya On BEST ANSWER

I Found solution

Step 1 : First time do login via Authorization/Login URL and you will get access token and refresh token after Authentication save this refresh token in database or env file. its long lived. (https://github.com/kunalvarma05/dropbox-php-sdk/wiki/Authentication-and-Authorization)

step 2 : using refresh token generate new access token whenever you need using below code

public function refreshToken()
    {
        $arr = [];
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, 'https://api.dropbox.com/oauth2/token');
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, "grant_type=refresh_token&refresh_token=<refresh_token_here>");
        curl_setopt($ch, CURLOPT_USERPWD, '<APP_KEY>'. ':' . '<APP_SECRET>');
        $headers = array();
        $headers[] = 'Content-Type: application/x-www-form-urlencoded';
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        $result = curl_exec($ch);
        $result_arr = json_decode($result,true);
        

        if (curl_errno($ch)) {
            $arr = ['status'=>'error','token'=>null];
        }elseif(isset($result_arr['access_token'])){
            $arr = ['status'=>'okay','token'=>$result_arr['access_token']];
        }
        curl_close($ch);
        return $arr;
    }

Call this function to get new access token

1
Greg On

Dropbox is no longer offering the option to retrieve new long-lived access tokens. It instead is issuing short-lived access tokens and optional refresh tokens instead of long-lived access tokens.

Apps can still get long-term access by requesting "offline" access though, in which case the app receives a "refresh token" that can be used to retrieve new short-lived access tokens as needed, without further manual user intervention. You can find more information in the OAuth Guide and authorization documentation.

It is not possible to fully automate the process of retrieving an access token and optional refresh token. This needs to be done manually by the user at least once. If your app needs to maintain long-term access without the user manually re-authorizing it repeatedly, the app should request "offline" access so that it gets a refresh token. The refresh token doesn't expire and can be stored and used repeatedly to get new short-lived access tokens whenever needed, without the user manually reauthorizing the app.

0
Matt Garrod On

I came across this question when I was searching for a solution to the same problem, but I wanted to make use of the SDK stated in the OP. The solution below uses the SDK functionality to provide an access token using a refresh token.

The refresh token can either be generated using step 1 of the accepted answer (https://github.com/kunalvarma05/dropbox-php-sdk/wiki/Authentication-and-Authorization), which fits with the idea of making use of the SDK or you can generate it manually with a Curl post (original source):

curl --location --request POST 'https://api.dropboxapi.com/oauth2/token' \
-u '<APP_KEY>:<APP_SECRET>' \
-H 'Content-Type: application/x-www-form-urlencoded' \
--data-urlencode 'code=<ACCESS_CODE>' \
--data-urlencode 'grant_type=authorization_code'

Once you have the refresh token, the following code will generate an access token:

$null = null;
$auth = new OAuth2Client(new DropboxApp(<APP_KEY>, <APP_SECRET>), new DropboxClient(DropboxHttpClientFactory::make($null)));
$access_token = $auth->getAccessToken(<REFRESH_TOKEN>, null,'refresh_token')['access_token'];