cancel
Showing results for 
Show  only  | Search instead for 
Did you mean: 
Announcements
Are you interested in learning how media industry leaders use Dropbox Replay? Register for our webinar here.

Dropbox API Support & Feedback

Find help with the Dropbox API from other developers.

cancel
Showing results for 
Show  only  | Search instead for 
Did you mean: 

Does the Acces token expire?

Does the Acces token expire?

CHBA
Explorer | Level 3

I am using Google Apps script to create a PDF file. This is stored in my Google Drive.

Yesterday I added to the script that I need a copy of new PDF files send to dropbox.
Below is the script I am using.

Yesterday everything worked well, a copy was sent to the dropbox.
Today when I run the script, it get this error:

 

Exception: Request failed for https://content.dropboxapi.com returned code 401. Truncated server response: {"error_summary": "expired_access_token/.", "error": {".tag": "expired_access_token"}} (use muteHttpExceptions option to examine full response)

 

Is it because I am on a free plan that it is expired?
Yesterday when I added the to my script, I found a youtube video where the guy could mark in checkbox 'Never expire' but I dont have that option, so actually I thought it was because dropbox has changed so tokens never would expire.


My Apps Script:

function createPDF(info) {

  // Get the folders in Google Drive where the PDFs should be saved
  var pdfFolder = DriveApp.getFolderById("186bAn5kZu5Mq5FaVkQCD-2I5L3t9RWsO");

  // Access token for Dropbox API
  var accessToken = "MY_ACCES_TOKEN";

  //Dropbox Folder Path to place files in
  var dropboxPath = "/AutoPrintPDF/";
 
  // Get the folder in Google Drive where the temporary files should be saved
  var tempFolder = DriveApp.getFolderById("xxxxxxxxxxxxxxxxxx");
 
  // Get the template document that will be used to create the PDF
  var templateDoc = DriveApp.getFileById("xxxxxxxxxxxxxxxxxxxxxxxxxx");

  // Make a copy of the template document and save it in the tempFolder
  var newTempFile =  templateDoc.makeCopy(tempFolder);

  // Open the copied document
  var openDoc = DocumentApp.openById(newTempFile.getId());
 
  // Get the body of the document
  var body = openDoc.getBody();
 
  // Replace placeholders in the document with the relevant data
  body.replaceText("{truck}", info['Truck'].toUpperCase());
  body.replaceText("{trailer}", info['Trailer'].toUpperCase());
  body.replaceText("{valid}", info['Valid Until']);
  body.replaceText("{pausestart}", info['Pause Start']);
  body.replaceText("{pauseend}", info['Pause End']);
 
  // Save and close the document
  openDoc.saveAndClose();

  // Convert document to PDF
  var blobPDF = newTempFile.getAs(MimeType.PDF);
 
  // Create a new file in pdfFolder with the name of the parking permit
  var pdfFile = pdfFolder.createFile(blobPDF).setName(info['Created at'] + " - Truck: " + info['Truck']);
 
  // Create a new file for Dropbox without special characters in the filename (Sync to windows fails when filename contains special characters)
  var pdfName = info['Created at'] + " - Truck: " + info['Truck'];
  var sanitizedPdfName = pdfName.replace(/[^\w\s]/gi, '');
  var pdfFile = pdfFolder.createFile(blobPDF).setName(pdfName);
  sendToDropbox(sanitizedPdfName, blobPDF);
 
  // Get the URL of the PDF
  var pdfUrl = pdfFile.getUrl();

  // Insert link to PDF in column 8
  var sheet = SpreadsheetApp.getActive().getSheetByName("Filter");
  var lastRow = sheet.getLastRow();
  var linkCell = sheet.getRange(lastRow, 8);
  linkCell.setValue(pdfUrl);


  // Delete the tempFile after PDF is created. Files in trash folder will be deleted after 30 days.
  DriveApp.getFileById(newTempFile.getId()).setTrashed(true)

 
  function sendToDropbox(pdfName, blobPDF) {
    var parameters = {
     "path": dropboxPath + pdfName + ".pdf",
    };

    var headers = {
      'Authorization': 'Bearer ' + accessToken,
      'Content-Type': 'application/octet-stream',
      'Dropbox-API-Arg': JSON.stringify(parameters)
    }

    var options = {
      "method": "POST",
      "headers": headers,
      "payload": blobPDF
    };

    var respons = JSON.parse(UrlFetchApp.fetch(apiurl, options).getContentText());
 


  }
8 Replies 8

Здравко
Legendary | Level 20

Hi @CHBA,

Yes, access token expires (all of them) . Whatever you have read, it's outdated. You need to refresh the access token using refresh token. Take a look here how this can be done without using SDK.

Hope this helps.

CHBA
Explorer | Level 3

Hi Здравко

Thanks for a quick reply.

I may end up with another solution as I dont understand how to fix this with a refresh token.
I followed your instruction in the link.

But already here I am stuck:


"In a terminal window execute following curl command:"

curl https://api.dropbox.com/oauth2/token -d code=<received code> -d grant_type=authorization_code -u <App key>:<App secret>

I replace the 'received code', 'App key', and 'App secret' with my own.

When fired off in Powershell, it throws this error after me:

Invoke-WebRequest : Parameter cannot be processed because the parameter name 'u' is ambiguous. Possible matches include
: -UseBasicParsing -Uri -UseDefaultCredentials -UserAgent.
At line:1 char:128
+ ... AAI0RAl8mTa6112h5d6Exxxxxxx -d grant_type=authorization_code -u yamamxxxx ...
+ ~~
+ CategoryInfo : InvalidArgument: (:) [Invoke-WebRequest], ParameterBindingException
+ FullyQualifiedErrorId : AmbiguousParameter,Microsoft.PowerShell.Commands.InvokeWebRequestCommand

 
If executed in Git Bash or CMD (I run Windows 11), it gives me this:

 % Total % Received % Xferd Average Speed Time Time Time Current
Dload Upload Total Spent Left Speed
100 168 100 90 100 78 372 322 --:--:-- --:--:-- --:--:-- 700{"error": "invalid_grant", "error_description": "code has expired (within the last hour)"}

I have tried generating a new token in the App Console under 'Generated access token' and started from the beginning with your guide again, but it didn't seems to change much. The big idiot is stuck 🙂
Why is it saying 'Code has expired within the last hours'? I just generated a new one? I really dont get it..

Even if I did not get this error, I am actually not sure I understand how this works.

I have an app made from Google Appsheet. It is running on a tablet that stays in a public place for people to fill out the form. Whenever they hit SUBMIT the form starts again ready for the next client to fillout the form.
Each form submission goes into my spreadsheet which then creates a PDF based on the data they submitted, and in the end I autoPrint the PDF.

This is where I tried go with Dropbox because the Synchronization goes super fast. The moment google Apps script has created the PDF and sent a copy to Dropbox, the file shows up in the Dropbox drive on the local pc immediately and prints the PDF file to the local printer.

Please bear with me, if you can help me it is super appreaciated. Otherwise I will see if I can find another solution of how to 'Sync' files fast to the pc from cloud.

All the best

 

CHBA
Explorer | Level 3

Hi Здравко

Thanks for a quick reply.

I may end up with another solution as I dont understand how to fix this with a refresh token.
I followed your instruction in the link.

But already here I am stuck:


"In a terminal window execute following curl command:"

curl https://api.dropbox.com/oauth2/token -d code=<received code> -d grant_type=authorization_code -u <App key>:<App secret>

I replace the 'received code', 'App key', and 'App secret' with my own.

When fired off in Powershell, it throws this error after me:

Invoke-WebRequest : Parameter cannot be processed because the parameter name 'u' is ambiguous. Possible matches include
: -UseBasicParsing -Uri -UseDefaultCredentials -UserAgent.
At line:1 char:128
+ ... AAI0RAl8mTa6112h5d6Exxxxxxx -d grant_type=authorization_code -u yamamxxxx ...
+ ~~
+ CategoryInfo : InvalidArgument: (:) [Invoke-WebRequest], ParameterBindingException
+ FullyQualifiedErrorId : AmbiguousParameter,Microsoft.PowerShell.Commands.InvokeWebRequestCommand

 
If executed in Git Bash or CMD (I run Windows 11), it gives me this:

 % Total % Received % Xferd Average Speed Time Time Time Current
Dload Upload Total Spent Left Speed
100 168 100 90 100 78 372 322 --:--:-- --:--:-- --:--:-- 700{"error": "invalid_grant", "error_description": "code has expired (within the last hour)"}

I have tried generating a new token in the App Console under 'Generated access token' and started from the beginning with your guide again, but it didn't seems to change much. The big idiot is stuck 🙂
Why is it saying 'Code has expired within the last hours'? I just generated a new one? I really dont get it..

Even if I did not get this error, I am actually not sure I understand how this works.

I have an app made from Google Appsheet. It is running on a tablet that stays in a public place for people to fill out the form. Whenever they hit SUBMIT the form starts again ready for the next client to fillout the form.
Each form submission goes into my spreadsheet which then creates a PDF based on the data they submitted, and in the end I autoPrint the PDF.

This is where I tried go with Dropbox because the Synchronization goes super fast. The moment google Apps script has created the PDF and sent a copy to Dropbox, the file shows up in the Dropbox drive on the local pc immediately and prints the PDF file to the local printer.

Please bear with me, if you can help me it is super appreaciated. Otherwise I will see if I can find another solution of how to 'Sync' files fast to the pc from cloud.

All the best

 

CHBA
Explorer | Level 3

Hi @Здравко 

Thanks for a quick reply.

I may end up with another solution as I dont understand how to fix this with a refresh token.
I followed your instruction in the link.

But already here I am stuck:


"In a terminal window execute following curl command:"

curl https://api.dropbox.com/oauth2/token -d code=<received code> -d grant_type=authorization_code -u <App key>:<App secret>

I replace the 'received code', 'App key', and 'App secret' with my own.

When fired off in Powershell, it throws this error after me:

Invoke-WebRequest : Parameter cannot be processed because the parameter name 'u' is ambiguous. Possible matches include
: -UseBasicParsing -Uri -UseDefaultCredentials -UserAgent.
At line:1 char:128
+ ... AAI0RAl8mTa6112h5d6Exxxxxxx -d grant_type=authorization_code -u yamamxxxx ...
+ ~~
+ CategoryInfo : InvalidArgument: (:) [Invoke-WebRequest], ParameterBindingException
+ FullyQualifiedErrorId : AmbiguousParameter,Microsoft.PowerShell.Commands.InvokeWebRequestCommand

 
If executed in Git Bash or CMD (I run Windows 11), it gives me this:

 % Total % Received % Xferd Average Speed Time Time Time Current
Dload Upload Total Spent Left Speed
100 168 100 90 100 78 372 322 --:--:-- --:--:-- --:--:-- 700{"error": "invalid_grant", "error_description": "code has expired (within the last hour)"}

I have tried generating a new token in the App Console under 'Generated access token' and started from the beginning with your guide again, but it didn't seems to change much. The big idiot is stuck 🙂
Why is it saying 'Code has expired within the last hours'? I just generated a new one? I really dont get it..

Even if I did not get this error, I am actually not sure I understand how this works.

I have an app made from Google Appsheet. It is running on a tablet that stays in a public place for people to fill out the form. Whenever they hit SUBMIT the form starts again ready for the next client to fillout the form.
Each form submission goes into my spreadsheet which then creates a PDF based on the data they submitted, and in the end I autoPrint the PDF.

This is where I tried go with Dropbox because the Synchronization goes super fast. The moment google Apps script has created the PDF and sent a copy to Dropbox, the file shows up in the Dropbox drive on the local pc immediately and prints the PDF file to the local printer.

Please bear with me, if you can help me it is super appreaciated. Otherwise I will see if I can find another solution of how to 'Sync' files fast to the pc from cloud.

All the best

 

Здравко
Legendary | Level 20

@CHBA wrote:

...
"In a terminal window execute following curl command:"

curl https://api.dropbox.com/oauth2/token -d code=<received code> -d grant_type=authorization_code -u <App key>:<App secret>

I replace the 'received code', 'App key', and 'App secret' with my own.

When fired off in Powershell, it throws this error after me:

Invoke-WebRequest : Parameter cannot be processed because the parameter name 'u' is ambiguous. Possible matches include
: -UseBasicParsing -Uri -UseDefaultCredentials -UserAgent.
At line:1 char:128
+ ... AAI0RAl8mTa6112h5d6Exxxxxxx -d grant_type=authorization_code -u yamamxxxx ...
+ ~~
+ CategoryInfo : InvalidArgument: (:) [Invoke-WebRequest], ParameterBindingException
+ FullyQualifiedErrorId : AmbiguousParameter,Microsoft.PowerShell.Commands.InvokeWebRequestCommand

 ...


Hi again @CHBA,

In the example I linked above to (and in mot Dropbox examples, that are not part of some SDK), curl is in use. It's powerful tool, multi-platform, and widly available. As seems you're NOT a fen of the tool and since use other tools; alright, but take in mind that different tool usually have different usage syntax (including different options)! Just 'translate' the syntax provided in all examples (including the mine) to the syntax suitable for the tools you're using. If you don't do it, the errors you're receiving would be something normal, of course. Again they are NOT a solution, by self, but just examples; that show in practice the used protocol!

 


@CHBA wrote:

...
If executed in Git Bash or CMD (I run Windows 11), it gives me this:

 % Total % Received % Xferd Average Speed Time Time Time Current
Dload Upload Total Spent Left Speed
100 168 100 90 100 78 372 322 --:--:-- --:--:-- --:--:-- 700{"error": "invalid_grant", "error_description": "code has expired (within the last hour)"}

I have tried generating a new token in the App Console under 'Generated access token' and started from the beginning with your guide again, but it didn't seems to change much. The big idiot is stuck 🙂
Why is it saying 'Code has expired within the last hours'? I just generated a new one? I really dont get it..

...


This code is a middle step for producing some token (either access token or refresh token). Its purpose is only to confirm users choice to confirm grant access for your application to their data (including to you as a user), nothing more. This code is short lived (supposed to be used within ~10-15 mins) and is one shoot code (once used its validity is gone). The code is NOT access token and cannot be used as such! Follow step by step the process described without modifying it by-self, before be sure what's going on. The only step, that need to be repeated, whenever needed (and embedded in your script; of course, after translation to javascript - where you're using fetch), is the last one (as clearly described within the text)!!! You can save the refresh token (in some constant) and manage the access token and it's expiration moment as described. Read more careful!

Hope this clarifies matter.

CHBA
Explorer | Level 3

Hi @Здравко 

I am sorry if you think I dont read carefully. I have read your thread, googled and a hell lot more to figure out, but sorry that I dont get it.

I have installed Curl on windows, thats why I wrote I tried in Git bash as well and showed here the message I get there.
Also yes, I do understand that 'This code is a middle step for producing some token' but I never come any further.

Thanks for your time.
I need to go with another solution, this is way too complicated for me. But thanks again.

Здравко
Legendary | Level 20

@CHBA wrote:

...
Also yes, I do understand that 'This code is a middle step for producing some token' but I never come any further.
...


Hmm...🤔 What's going wrong actually? Your issue description isn't very clear (to me at least). Post exact commands and results that passed together with the error you're receiving (to be clear what's on step by step and reproducible). Mask all access/refresh tokens, of course.

 


@CHBA wrote:

...
I need to go with another solution, this is way too complicated for me. But thanks again.


You can always use the javascript SDK, since you use javascript. There are examples too.

Good luck.

Greg-DB
Dropbox Staff

@CHBA Здравко is correct; Dropbox is no longer offering the option for creating new long-lived access tokens. Dropbox is now issuing short-lived access tokens (and optional refresh tokens) instead of long-lived access tokens. You can find more information on this migration here. This is not related to the plan (i.e., free or not) on your account.

 

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. There's a basic outline of processing this flow in this blog post which may serve as a useful example. Note that it is not possible to use the "Generate" button to get a refresh token. That button will only create short-lived access tokens. You would need to use the OAuth app authorization flow to get a refresh token.

 

When using the OAuth app authorization flow, note that the "authorization code" (sometimes called "access code") is different than access tokens and refresh tokens. Authorization codes can each only be used once, and are only valid for a short period of time, to complete the authorization flow.

 

We do recommend using one of the official Dropbox SDKs whenever possible. For examples of implementing this with the Dropbox JavaScript SDK, for instance, please refer to the examples included in the "examples" folder in the SDK. As long as you set the app key (a.k.a. client ID) and refresh token, like shown in this example for the JavaScript SDK, the SDK will actually handle refresh process for you automatically. The SDK will automatically catch expired access token errors and call the API to get a new short-lived access token when needed. Refresh tokens don't expire (though they can be revoked on demand), so if this is only for your own account, you would only need to get a refresh token for your own account once and could re-use that.

 

If something isn't working as expected, please share the steps/code to reproduce the issue, and the error or unexpected output you get.

Need more support?
Who's talking

Top contributors to this post

  • User avatar
    Greg-DB Dropbox Staff
  • User avatar
    Здравко Legendary | Level 20
  • User avatar
    CHBA Explorer | Level 3
What do Dropbox user levels mean?