JWT API file upload error
AnsweredI am implementing a script for loading an image and creating a link to it.
but I get the error.
what am i missing?
do i need to add the service account as a user to the menu:
https://app.box.com/master/users -> Users & Groups -> New User Account Details
with the service account data?
response object(stdClass)#1 (17) { ["type"]=> string(4) "user" ["id"]=> string(11) "14463115583" ["name"]=> string(13) "RyanDynamics3" ["login"]=> string(51) "AutomationUser_1411644_sKaKcWiknb@boxdevedition.com" ["created_at"]=> string(25) "2020-11-24T00:56:10-08:00" ["modified_at"]=> string(25) "2020-11-24T00:56:29-08:00" ["language"]=> string(2) "en" ["timezone"]=> string(19) "America/Los_Angeles" ["space_amount"]=> int(10737418240) ["space_used"]=> int(0) ["max_upload_size"]=> int(5368709120) ["status"]=> string(6) "active" ["job_title"]=> string(0) "" ["phone"]=> string(0) "" ["address"]=> string(0) "" ["avatar_url"]=> string(48) "https://app.box.com/api/avatar/large/14463115583" ["notification_email"]=> array(0) { } }
the application code I am attaching:
<?php
require 'vendor/autoload.php';
function vd($arr,$name='debug arr '){
echo '<pre>'.$name.' ';
var_dump($arr);
echo '</pre>';
}
function base64_to_jpeg($base64_string, $output_file) {
// open the output file for writing
$ifp = fopen( $output_file, 'wb' );
// split the string on commas
// $data[ 0 ] == "data:image/png;base64"
// $data[ 1 ] == <actual base64 string>
$data = explode( ',', $base64_string );
// we could add validation here with ensuring count( $data ) > 1
fwrite( $ifp, base64_decode( $data[ 1 ] ) );
// clean up the file resource
fclose( $ifp );
return $output_file;
}
function get_current_file_url($Protocol='http://') {
//return $Protocol.$_SERVER['HTTP_HOST'].str_replace($_SERVER['DOCUMENT_ROOT'], '', realpath(__DIR__));
return $Protocol.$_SERVER['HTTP_HOST'] . substr($_SERVER['REQUEST_URI'], 0, strrpos($_SERVER['REQUEST_URI'], "/"));
}
/* /////////////////////// GET TOKEN PART ///////////////////////*/
$json = file_get_contents('config.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
];
use \Firebase\JWT\JWT;
$assertion = JWT::encode($claims, $key, 'RS512');
use GuzzleHttp\Client;
$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();
$access_token = json_decode($data)->access_token;
//vd($access_token,'access_token');die();
//vd(json_decode($data),'data');die();
/* /////////////////////// GET TOKEN PART ///////////////////////*/
/* /////////////////////// UPLOAD PART ///////////////////////*/
$orderId = $_POST['orderId'];
$image_base64 = $_POST['imageBase64'];
//$image_base64 = use this variable to receive base64
require_once 'image.php';
//$orderId = 'https://voltacann.com/wp-json/wc/v3/orders/2463';
$orderId = '2463';
$image['name'] = rand(0,time()).'_'.time().'.jpg';
$image['url'] = base64_to_jpeg($image_base64,"upload_images/".$image['name']);
$image['type'] = pathinfo($image['url'], PATHINFO_EXTENSION);
//vd($image,'image');
//get real path for cUrl
$image_realpath = realpath("upload_images/".$image['name']);
//vd($image_realpath,'image_realpath');
$url = "https://upload.box.com/api/2.0/files/content";
$json_attributes = json_encode(array(
"name" => $image["name"],
"parent" => array("id" => "126219502011")//id folder in box.com
));
//get real path for cUrl
$image_realpath = realpath("upload_images/".$image['name']);
$fields = array(
'attributes' => $json_attributes,
'file' => @new CurlFile($image_realpath, $image['type'], $image['name']),
);
//vd($fields,'fields');
$upload_response = array();
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL, $url);
$headers = array();
$headers[] = 'Authorization: Bearer '.$access_token;
//$headers[] = 'As-User:'. 14434726963;
$headers[] = 'Content-Type:multipart/form-data';
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
$upload_response = json_decode(curl_exec($ch));
curl_close($ch);
if($upload_response->type != 'error') unlink($image_realpath);
vd($upload_response,'upload_response');
die();
/* /////////////////////// UPLOAD PART ///////////////////////*/
/* /////////////////////// SHARE PART ///////////////////////*/
$fileId = 745158812846;
$fileId = $upload_response->entries[0]->id;
$url = "https://api.box.com/2.0/files/$fileId?fields=shared_link";
$json = json_encode(array(
'shared_link' => array(
'access' => 'open',
"permissions"=>array(
"can_preview"=> true,
"can_download"=> true
)
)
));
$share_response = array();
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://api.box.com/2.0/files/'.$fileId.'?fields=shared_link');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
$headers = array();
$headers[] = 'Authorization: Bearer '.$access_token;
$headers[] = 'Content-Type: application/x-www-form-urlencoded';
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$share_response = json_decode(curl_exec($ch));
vd($share_response,'share_response');
if (curl_errno($ch)) {
echo json_encode(array(
'error' => curl_error($ch)
));
}
curl_close($ch);
$result = array(
'imageUrl' => $share_response->shared_link->download_url,
'orderId' => orderId
);
echo json_encode($result);
-
Official comment
You need to validate that the user associated with your token either owns or is collaborating on the folder you're trying to upload the file to. To verify, which user is associated with your token I recommend using the get current user endpoint. I suspect you're probably using JWT authentication, which by default uses a token for the application's service account.
Comment actions -
in the end, the error looks like this:
upload_response object(stdClass)#32 (7) { ["type"]=> string(5) "error" ["status"]=> int(404) ["code"]=> string(9) "not_found" ["context_info"]=> object(stdClass)#29 (1) { ["errors"]=> array(1) { [0]=> object(stdClass)#19 (3) { ["reason"]=> string(17) "invalid_parameter" ["name"]=> string(6) "parent" ["message"]=> string(78) "Invalid value 'd_126219502011'. 'parent' with value 'd_126219502011' not found" } } } ["help_url"]=> string(38) "http://developers.box.com/docs/#errors" ["message"]=> string(9) "Not Found" ["request_id"]=> string(16) "dihebegl0gbm7qt8" }
Please sign in to leave a comment.
Comments
2 comments