Forum Discussion

Fenoma's avatar
Fenoma
Helpful | Level 6
3 years ago
Solved

Upload to Dropbox with Curl and refresh token

Hi, I'm trying to upload files from my website to dropbox and it was working, but i received an error message saying the Access Token Expired. I research a little bit, and read that now dropbox uses "refresh token". I'm trying to find an example or tutorial in order to change the code im using to make it work with refresh token, but I can't find anything. My question is: What do I need to change in this code to make it work with NON EXPIRE TOKEN.

 

Thanks.

 

<?php

  $fp = fopen($path, 'rb');
  $size = filesize($path);
 
  $cheaders = array('Authorization: Bearer <ACCESS TOKEN>',
                    'Content-Type: application/octet-stream',
                    'Dropbox-API-Arg: {"path":"/test/'.$path.'", "mode":"add"}');
 
  curl_setopt($ch, CURLOPT_HTTPHEADER, $cheaders);
  curl_setopt($ch, CURLOPT_PUT, true);
  curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
  curl_setopt($ch, CURLOPT_INFILE, $fp);
  curl_setopt($ch, CURLOPT_INFILESIZE, $size);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  $response = curl_exec($ch);
 
  echo $response;
  curl_close($ch);
  fclose($fp);
 
?>
  • Hi Fenoma,

    As a example you can take a look here. It's not a PHP code, but a command line curl execution. I believe you haven't problem to convert it. The most important is HOW it's gonna work (as idea).

    The code you posted as example should not be changed a lot (it can left almost the same). You have not to assume 'ACCESS TOKEN' has a fixed value anymore (as seems you are doing). This token should be represented as rather variable and definitely not as a literal!!! Good idea is to change your code in a way, every place (no limited to your example) where token is used, the literal to be replaced with a function (you can name it to something like 'getToken' for instance). In this function implementation you can check whether available access token is going to expire and if so, refresh it (as denoted in the post linked to). You can keep refresh token, last received access token (as a cache), and calculated time (moment) of current access token expiration (used for check, in followup calls, whether the access token expires). 😉 That's it.

    Hope this helps.

  • Здравко's avatar
    Здравко
    Legendary | Level 20

    Hi Fenoma,

    As a example you can take a look here. It's not a PHP code, but a command line curl execution. I believe you haven't problem to convert it. The most important is HOW it's gonna work (as idea).

    The code you posted as example should not be changed a lot (it can left almost the same). You have not to assume 'ACCESS TOKEN' has a fixed value anymore (as seems you are doing). This token should be represented as rather variable and definitely not as a literal!!! Good idea is to change your code in a way, every place (no limited to your example) where token is used, the literal to be replaced with a function (you can name it to something like 'getToken' for instance). In this function implementation you can check whether available access token is going to expire and if so, refresh it (as denoted in the post linked to). You can keep refresh token, last received access token (as a cache), and calculated time (moment) of current access token expiration (used for check, in followup calls, whether the access token expires). 😉 That's it.

    Hope this helps.

    • Fenoma's avatar
      Fenoma
      Helpful | Level 6

      Hi Здравко, thank you so much for your reply. I think i'm still committing some mistakes. What I did was this:

       

      1.- went to the link with all the data that the example says:

      https://www.dropbox.com/oauth2/authorize?token_access_type=offline&response_type=code&client_id=<App key>

      Then I got the access code on the browser and I copy it to the next step:

       

      2.- I created a function in order to get the token:

       

              public function getToken(){

                  $url = "https://api.dropbox.com/oauth2/token";

                  $postfields = array(
                      'code' => '<ACCESS_CODE>',
                      'grant_type' => 'authorization_code',
                  );

                  $auth = "<APP_KEY:APP_SECRET>";

                  $curl = curl_init($url);

                  curl_setopt($curl, CURLOPT_POST, true);
                  curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
                  curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, true);
                  curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($postfields));
                  curl_setopt($curl, CURLOPT_USERPWD, $auth);
                  curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);

                  $json_response = curl_exec($curl);
                  $responseObj = json_decode($json_response);

                  return $responseObj->access_token;            
              }
       
      That function gave me an object with the information 
      {"access_token": <TOKEN>, "token_type": "bearer", "expires_in":14400, "refresh_token":<REFRESH_TOKEN>, etc}.
       
      3.- Now that I have the token, I change the code that I post in the first place with the access_token.
       
              public function UpFileToDropbox($path){

                  $fp = fopen($path, 'rb');
                  $size = filesize($path);
                 
                  $cheaders = array('Authorization: Bearer ' . $this->getToken(),
                                      'Content-Type: application/octet-stream',
                                      'Dropbox-API-Arg: {"path":"/test/'.$path.'", "mode":"add"}');
                 
                  $ch = curl_init('https://content.dropboxapi.com/2/files/upload');
                  curl_setopt($ch, CURLOPT_HTTPHEADER, $cheaders);
                  curl_setopt($ch, CURLOPT_PUT, true);
                  curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
                  curl_setopt($ch, CURLOPT_INFILE, $fp);
                  curl_setopt($ch, CURLOPT_INFILESIZE, $size);
                  curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                  $response = curl_exec($ch);
                 
                  echo $response;
                  curl_close($ch);
                  fclose($fp);

              }
       
      It was working for a while, but then I try again and said that the code expired, and then when I try to create a new one (for testing) doing the whole same process, now says "Code Has already been used".
       
      4.- So I assumed that if says the code has been used, mean still valid, so i Tried with the refresh code, but doesn't work:
       
              public function RefreshToken(){

                  $url = "https://api.dropbox.com/oauth2/token";

                  $postfields = array(
                      'refresh_token' => '<REFRESH_TOKEN>',
                      'grant_type' => 'refresh_token',
                  );

                  $auth = ""<APP_KEY:APP_SECRET>";

                  $curl = curl_init($url);

                  curl_setopt($curl, CURLOPT_POST, true);
                  curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
                  curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, true);
                  curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($postfields));
                  curl_setopt($curl, CURLOPT_USERPWD, $auth);
                  curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);

                  $json_response = curl_exec($curl);
                  $responseObj = json_decode($json_response);

                  return $responseObj;              
              }
       
      So I don't understand what am I doing wrong? Thanks!
    • Fenoma's avatar
      Fenoma
      Helpful | Level 6

      Hi Здравко, thank you so much for your reply.

      I follow all the steps and now it is working!!

      • firoj_ali's avatar
        firoj_ali
        Explorer | Level 3

        i am using your code but i am facing this error

        Notice: Array to string conversion in C:\xampp\htdocs\wordpress_forum\wp-content\themes\twentytwentyone-child\functions.php on line 115
        Error in call to API function "files/upload": The given OAuth 2 access token is malformed.

         

About Dropbox API Support & Feedback

Node avatar for Dropbox API Support & Feedback
Find help with the Dropbox API from other developers.5,950 PostsLatest Activity: 9 hours ago
351 Following

If you need more help you can view your support options (expected response time for an email or ticket is 24 hours), or contact us on X or Facebook.

For more info on available support options for your Dropbox plan, see this article.

If you found the answer to your question in this Community thread, please 'like' the post to say thanks and to let us know it was useful!