json_encode error: Type is not supported on multipart/form-data

65 views Asked by At

I'm configuring FedEx trade documents upload API. I tried to follow the documentation but I got error

json_encode error: Type is not supported

This is my payload example.

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;
    }
  }

What is wrong with this code?

1

There are 1 answers

0
Bipu Shrestha On

After some research, I found the issue, this $this->uploader was my headers function.

private function buildUploader($access_token)
{
  return Http::withOptions([
    'base_uri' => $this->base,
    'headers' => [
      'Authorization' => "Bearer {$access_token}",
      'content-type' => 'multipart/form-data',
    ],
  ]);
}

But it seems I don't need to use content type here so I did change a little, and this works for me well.

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;
  }