convert curl to guzzle for spreedly API

698 Views Asked by At

I'm trying to convert this curl call to guzzle:

curl https://core.spreedly.com/v1/gateways/CAL6uXHtGfDsxV2kW6apTP5JhG/purchase.xml \
-u 'Ll6fAtoVY5hTGlJEmtpo5YTS:RKOCG5D8jhgfdDSg524u5iF22XD4Io5VXmyzdCptrvHFTTSy' \
-H 'Content-Type: application/xml' \
-d '<transaction>
      <payment_method_token>ZgPNHes541EMlBN86glRDKRexzq</payment_method_token>
      <amount>100</amount>
      <currency_code>USD</currency_code>
    </transaction>'

I'm know use this so much so any help will be appreciated

This is what I've tried, but I always get this error "Client error response [status code] 422 [reason phrase] Unprocessable Entity"

$xml =  '<transaction>\n';
$xml .=     '<payment_method_token>$payment_method_token</payment_method_token>\n';
$xml .=     '<amount>100</amount>\n';
$xml .=     '<currency_code>USD</currency_code>\n'
$xml .= '<transaction>\n';
$headers = ['Content-Type' => 'application/xml', 'auth' => ['Ll6fAtoVY5hTGlJEmtpo5YTS', 'RKOCG5D8jhgfdDSg524u5iF22XD4Io5VXmyzdCptrvHFTTSy']];
$client = new Client('https://core.spreedly.com/v1/gateways/CAL6uXHtGfDsxV2kW6apTP5JhG/purchase.xml');
$requestCurl = $client->post('', $headers, $xml,[]);
$response = $requestCurl->send()->xml();
dd($response);

Thanks!

2

There are 2 best solutions below

3
On BEST ANSWER

It should look something like this:

$client = new Client('https://core.spreedly.com/v1/gateways/merchant_id');

$xml = '<...>';
$options = [
    'headers'   => [ 'Content-Type' => 'application/xml' ],
    'auth'      => ['username', 'password'],
    'body'      => $xml,
];

$response = $client->post('/purchase.xml', $options);

and you might want to take another look at your code and figure out if you've accidentally posted your API credentials publicly.

0
On

If you reference the Guzzle Docs for working with Clients you will see that you can set the base_url, headers and authentication for all requests that are made with the client.

The difference between my example below and Sammitch's above is that I have added the header and authentication as defaults to the client. This will allow to to make subsequent calls to your api without having to add these as options to each request.

For troubleshooting purposes I simply attach the LogSubscriber so that the http request and response are readily available.

$client = new GuzzleHttp\Client([
    'base_url' => ['https://core.spreedly.com/{version}/gateways/{merchant_id}/', [
        'version' => 'v1',
        'merchant_id' => $merchant_id
    ]],
    'defaults' => [
        'headers'       => ['Content-Type' => 'application/xml'],
        'auth'          => [$username, $pw],
]]);
/**
* Attach a log subscriber is configured to log the full request and response message using echo() calls.
**/
$client->getEmitter()->attach(new GuzzleHttp\Subscriber\Log\LogSubscriber(null, GuzzleHttp\Subscriber\Log\Formatter::DEBUG));

$response = $client->post('purchase.xml', [
    'body' => $xml
]);