We are aware of the issue with the badge emails resending to everyone, we apologise for the inconvenience - learn more here.

Forum Discussion

rdyar's avatar
rdyar
Helpful | Level 5
11 months ago

Simple Node script not working with clientId /secret

I'm trying to do the worlds simplest node dropbox script but getting an error, clearly I am missing something.   I set up an App - and gave it all the read permissions.   Then I have this script ...
  • rdyar's avatar
    rdyar
    11 months ago

    I was able to get this all to work as a script. So far it has worked great, running every 15 minutes for the last week. I only do the dropbox auth part if the thing I want to share has actually changed which happens several times per day during working hours.

     

    In order get the refresh token chatGPT give me a script to run in powershell:

    I pasted this in all at once:

     

    $clientId = "yourAppIDHere"
    $clientSecret = "YourAppSecret"
    $authorizationCode = "ACCESSCodeFromPreviousStep"
    $base64Auth = [Convert]::ToBase64String([Text.Encoding]::UTF8.GetBytes("${clientId}:${clientSecret}"))
    $headers = @{ Authorization = "Basic $base64Auth"}
    $body = @{ code = $authorizationCode  grant_type = "authorization_code"}
    $response = Invoke-RestMethod -Uri "https://api.dropbox.com/oauth2/token" -Method Post -Headers $headers -Body $body
    # Output the access token
    $response.refresh_token
     
    That gave me refresh token that I can then use to get a current access token - so that is hard coded in the script.
     
    I then have a db auth function which uses that refresh token and returns a new access token:
     
    import fetch from "node-fetch";
    const clientId = "yourAppID";
    const clientSecret = "YourAppSecret";
    const refreshToken =
      "RefreshTokenFromPowershell";

    // Function to refresh the access token
    export default async function refreshAccessToken() {
      const response = await fetch("https://api.dropboxapi.com/oauth2/token", {
        method: "POST",
        headers: {
          "Content-Type": "application/x-www-form-urlencoded",
          Authorization: `Basic ${Buffer.from(
            `${clientId}:${clientSecret}`
          ).toString("base64")}`,
        },
        body: `grant_type=refresh_token&refresh_token=${refreshToken}`,
      });

      const data = await response.json();
      console.log("data in refresh :>> ", data);
      if (data.access_token) {
        return data.access_token;
      } else {
        throw new Error("Failed to refresh access token");
      }
    }
     
    Then I use that access token like you normally would.
     
    import fetch from "node-fetch";
     const config = {
        fetch,
        accessToken,
        clientId,
        clientSecret,
      };

      const dbx = new Dropbox(config);
     
    const data = await dbx.filesListFolder({ path: "" });