1

I am attempting to replicate a CURL POST request in Guzzle, but Guzzle request is failing.

This is the CURL request that works successfully:

$file = new \CURLFile( $document );
$file->setPostFilename( basename( $document ) );

$ch = curl_init();
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1 );
curl_setopt( $ch, CURLOPT_URL, $endpoint );
curl_setopt( $ch, CURLOPT_HTTPHEADER, [
                "Authorization: Bearer " . $accessToken,
                "Content-Type: multipart/form-data",
            ] );
curl_setopt( $ch, CURLOPT_POSTFIELDS, [ 'fileData' => $file ] );

$response = curl_exec( $ch );

And here is what I am currently using for the Guzzle request but it does not work:

$options['multipart'][] = [
    'name'      => 'fileData',
    'contents'  => fopen( $document, 'r' ),
    'filename'  => basename( $document ),
];

$request = $provider->getAuthenticatedRequest( 'POST', $endpoint, $accessToken, $options );

$response = $provider->getParsedResponse( $request );

The response from the Guzzle request is as follows:

{"message":"File cannot be empty","errors":[{"code":"Missing","fields":["document"]}]} 

It's worth noting I am using the thephpleague/oauth2-client library to send the request. I'm looking for any discrepencies between the two request or information on how I can troubleshoot this further myself as I have been spinning my wheels all day on this. Much appreciated

David
  • 2,365
  • 8
  • 34
  • 59

1 Answers1

1

thephpleague/oauth2-client uses different Providers to create the requests and these Providers implement AbstractProvider

The argument $options of AbstractProvider 's getAuthenticatedRequest() is different from GuzzleHttp\Client 's request():

/**
 * Returns an authenticated PSR-7 request instance.
 ...
 * @param  array $options Any of "headers", "body", and "protocolVersion".
 * @return RequestInterface
 */
public function getAuthenticatedRequest($method, $url, $token, array $options = [])

Only keys allowed for $options are "headers", "body", and "protocolVersion".

You should do the extra effort and create the headers and body needed:

$file = new \CURLFile( $document );
$file->setPostFilename( basename( $document ) );
$data = array(
    'uploaded_file' => $file
);
$options = array(
    'headers' => array("Content-Type" => "multipart/form-data"),
    'body' => $data
);
$request = $provider->getAuthenticatedRequest( 'POST', $endpoint, $accessToken, $options );

Reference

Jannes Botis
  • 11,154
  • 3
  • 21
  • 39