Skip to main content
Question

Uploading files using API and JWT token

  • May 22, 2025
  • 2 replies
  • 31 views

Forum|alt.badge.img

Hi!
I have problem with uploading files using API and JWT token, public and private key.

I have used it a long time and everything was okay, but now I don't receive a response from boxcom, there are an empty body.

2 replies

Forum|alt.badge.img

Hello, 

Can you send me the code you are running to upload files? 

Thanks, 

Alex, Box Developer Advocate


Forum|alt.badge.img

Hello, this is my second account.

This is my code:

$json = file_get_contents(ROOT_SITE_DIR.'/data/boxComConfigs/new_box.json');
$config = json_decode($json);

$private_key = $config->boxAppSettings->appAuth->privateKey;
$passphrase = $config->boxAppSettings->appAuth->passphrase;
$key = openssl_pkey_get_private($private_key, $passphrase);


$authenticationUrl = 'https://api.box.com/oauth2/token';

$claims = [
   
'iss' => $config->boxAppSettings->clientID,
   
'sub' => $config->enterpriseID,
   
'box_sub_type' => 'enterprise',
   
'aud' => $authenticationUrl,
   
'jti' => base64_encode(random_bytes(64)),
   
'exp' => time() + 45,
   
'kid' => $config->boxAppSettings->appAuth->publicKeyID
];


$assertion = JWT::encode($claims, $key, 'RS512');


$params = [
   
'grant_type' => 'urn:ietf:params:oauth:grant-type:jwt-bearer',
   
'assertion' => $assertion,
   
'client_id' => $config->boxAppSettings->clientID,
   
'client_secret' => $config->boxAppSettings->clientSecret
];
$client = new Client();



$response = $client->request('POST', $authenticationUrl, [
   
'form_params' => $params
]);



$data = $response->getBody()->getContents();
$token = json_decode($data)->access_token;


//update file
//$url = "https://upload.box.com/api/2.0/files/807022067600/content";

// upload file
$url = "https://upload.box.com/api/2.0/files/content";

if
(isset($_POST['btnUpload'])) {


   
$file_upload = $_FILES['file']['tmp_name'];



   
$json = json_encode(array(
       
'name' => $_FILES['file']['name'],
       
'parent' => array('id' => 0),
       
"shared_link" => array(
                
"access" => "open"
       
)
    ))
;

   
$filePath = $_FILES['file']['tmp_name'];
   
$fileName = $_FILES['file']['name'];
   
$fileType = $_FILES['file']['type'];

   
$fields = array(
       
'attributes' => $json,
   
);



    try
{
       
$ch = curl_init();


       
curl_setopt($ch,CURLOPT_URL, $url);




       
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
           
'Authorization: Bearer '.$token,
           
'Content-Type: multipart/form-data'
       
));

       
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
       
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);

       
$response = curl_exec($ch);
       
curl_close($ch);


   
} catch (Exception $e) {
       
$response = $e->getMessage();
       
print_r($response);

   
}