How to refresh Dropbox API's access token in PHP without logging in
P粉239164234
2023-08-26 11:28:49
<p>I am using https://github.com/kunalvarma05/dropbox-php-sdk to upload files to my dropbox. </p>
<p>Here I don't need any users to use dropbox, just for internal users so I can upload files to my dropbox. </p>
<p>I generated the access token from the Dropbox app and everything works fine, but the token expires after some time. I did an Oauth login to regenerate the token, but the new token also expires after a while. </p>
<p>How do I regenerate the token or get a long-lived token so that my script can upload the file to dropbox after every time the user uploads a new file? </p>
<p>I'm using this simple code</p>
<pre class="brush:php;toolbar:false;">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());
}
}
}</pre></p>
Dropbox no longer offers the option to retrieve a new long-term access token. Instead, it issues short-term access tokens and optional refresh tokens instead of long-term access tokens.
Applications can still gain long-term access by requesting "offline" access, at which point the application receives a "refresh token" and can retrieve new short-term access tokens as needed without further manual user intervention . You can find more information in the OAuth Guide and Authorization Documentation.
The process of retrieving access tokens and optional refresh tokens cannot be fully automated. This requires the user to do it manually at least once. If your application needs to maintain long-term access without requiring the user to repeatedly manually reauthorize, it should request "offline" access in order to obtain a refresh token. Refresh tokens do not expire and can be stored and reused to obtain new short-lived access tokens when needed without requiring the user to manually reauthorize the application.
I found the solution
Step 1: Log in for the first time through the authorization/login URL. After completing the authentication, you will get an access token and a refresh token. Save the refresh token in the database or environment file. It has a long lifespan. (https://github.com/kunalvarma05/dropbox-php-sdk/wiki/Authentication-and-Authorization)
Step 2: Using the refresh token, generate a new access token using the following code
Call this function to obtain a new access token