我正在配置 FedEx 贸易文件上传 API。我尝试遵循文档,但出现错误
json_encode 错误:不支持类型
这是我的有效负载示例。
try{
$document = [
"workflowName"=> "ETDPostshipment",
"carrierCode"=> "FDXE",
"name"=> 'invoiceFileName',
"contentType"=> 'application/pdf',
"meta"=> [
"shipDocumentType"=> "COMMERCIAL_INVOICE",
"trackingNumber"=> "794988380825",
"shipmentDate"=> "2024-02-26",
"originCountryCode"=> "JP",
"destinationCountryCode"=> $country_code
]
];
$body = [
[
'name' => 'document',
'contents' => json_encode($document)
],
[
'name' => 'attachment',
'contents' => fopen(public_path('storage/invoice/invoiceFileName'), 'r'),
'filename' => $shipping['invoiceFileName']
]
];
$response = $this->uploader->post($path, ['multipart' => $body]);
$data = json_decode($response->getBody(), true);
Log::info('Document uploaded successfully.', ['response' => $data]);
return $data;
}
catch(RequestException $e){
Log::error('Request Exception: ' . $e->getMessage(), ['code' => $e->getCode()]);
}
catch (Throwable $e){
Log::error('Unexpected Exception: ' . $e->getMessage());
return;
}
}
这段代码有什么问题?
经过一番研究,我发现了问题,这个
$this->uploader
是我的标题函数。
private function buildUploader($access_token)
{
return Http::withOptions([
'base_uri' => $this->base,
'headers' => [
'Authorization' => "Bearer {$access_token}",
'content-type' => 'multipart/form-data',
],
]);
}
但似乎我不需要在这里使用内容类型,所以我做了一点改变,这对我来说很有效。
try{
$document = [
"workflowName"=> "ETDPreshipment",
"carrierCode"=> "FDXE",
"name"=> 'invoiceFileName',
"contentType"=> 'application/pdf',
"meta"=> [
"shipDocumentType"=> "COMMERCIAL_INVOICE",
"trackingNumber"=> "794988380825",
"originCountryCode"=> "JP",
"destinationCountryCode"=> $country_code
]
];
$body = [
'document' => json_encode($document)
];
$file = fopen(public_path('storage/invoice/invoiceFileName'), 'r');
$uploader = Http::withOptions([
'headers' => [
'Authorization' => "Bearer {$this->access_token}",
],
]);
$response = $uploader->attach('attachment', $file, $shipping['invoiceFileName'])->post($path, $body);
$data = json_decode($response->getBody(), true);
return $data;
}