Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get the body of SENT data with Guzzle PHP?

Tags:

I am using Guzzle (v6.1.1) in PHP to make a POST request to a server. It works fine. I am adding some logging functions to log what was sent and received and I can't figure out how to get the data that Guzzle sent to the server. I can get the response just fine, but how do I get the sent data? (Which would be the JSON string.)

Here is the relevant portion of my code:

$client = new GuzzleHttp\Client(['base_uri' => $serviceUrlPayments ]);     try {        $response = $client->request('POST', 'Charge', [             'auth' => [$securenetId, $secureKey],             'json' => [     "amount" => $amount,                             "paymentVaultToken" => array(                                     "customerId" => $customerId,                                     "paymentMethodId" => $token,                                     "publicKey" => $publicKey                                     ),                             "extendedInformation" => array(                                     "typeOfGoods" => $typeOfGoods,                                     "userDefinedFields" => $udfs,                                     "notes" => $Notes                                     ),                             'developerApplication'=> $developerApplication              ]     ]);      } catch (ServerErrorResponseException $e) {         echo (string) $e->getResponse()->getBody();     }       echo $response->getBody(); // THIS CORRECTLY SHOWS THE SERVER RESPONSE     echo $client->getBody();           // This doesn't work     echo $client->request->getBody();  // nor does this 

Any help would be appreciated. I did try to look in Guzzle sourcecode for a function similar to getBody() that would work with the request, but I'm not a PHP expert so I didn't come up with anything helpful. I also searched Google a lot but found only people talking about getting the response back from the server, which I have no trouble with.

like image 639
ruhnet Avatar asked Jan 20 '16 20:01

ruhnet


People also ask

How do I get data from guzzle response?

As described earlier, you can get the body of a response using the getBody() method. Guzzle uses the json_decode() method of PHP and uses arrays rather than stdClass objects for objects. You can use the xml() method when working with XML data.

How do I get past the header in guzzle?

// Set various headers on a request $client->request('GET', '/get', [ 'headers' => [ 'User-Agent' => 'testing/1.0', 'Accept' => 'application/json', 'X-Foo' => ['Bar', 'Baz'] ] ]); Headers may be added as default options when creating a client.

Is guzzle better than cURL?

It provides easy user interface. Guzzle can use various kinds of HTTP clients .


2 Answers

You can do this work by creating a Middleware.

use GuzzleHttp\Client; use GuzzleHttp\HandlerStack; use GuzzleHttp\Middleware; use Psr\Http\Message\RequestInterface;  $stack = HandlerStack::create(); // my middleware $stack->push(Middleware::mapRequest(function (RequestInterface $request) {     $contentsRequest = (string) $request->getBody();     //var_dump($contentsRequest);      return $request; }));  $client = new Client([     'base_uri' => 'http://www.example.com/api/',     'handler' => $stack ]);  $response = $client->request('POST', 'itemupdate', [     'auth' => [$username, $password],     'json' => [         "key" => "value",         "key2" => "value",     ] ]); 

This, however, is triggered before to receive the response. You may want to do something like this:

$stack->push(function (callable $handler) {     return function (RequestInterface $request, array $options) use ($handler) {         return $handler($request, $options)->then(             function ($response) use ($request) {                 // work here                 $contentsRequest = (string) $request->getBody();                 //var_dump($contentsRequest);                 return $response;             }         );     }; }); 
like image 53
Federkun Avatar answered Oct 01 '22 02:10

Federkun


Using Guzzle 6.2.

I've been struggling with this for the last couple days too, while trying to build a method for auditing HTTP interactions with different APIs. The solution in my case was to simply rewind the request body.

The the request's body is actually implemented as a stream. So when the request is sent, Guzzle reads from the stream. Reading the complete stream moves the stream's internal pointer to the end. So when you call getContents() after the request has been made, the internal pointer is already at the end of the stream and returns nothing.

The solution? Rewind the pointer to the beginning and read the stream again.

<?php // ... $body = $request->getBody(); echo $body->getContents(); // -->nothing  // Rewind the stream $body->rewind(); echo $body->getContents(); // -->The request body :) 
like image 30
DJ Sipe Avatar answered Oct 01 '22 00:10

DJ Sipe