PHP's lightweight HTTP client

Related tags

HTTP Buzz
Overview

Buzz - Scripted HTTP browser

Build Status BC Check Latest Version Code Coverage Quality Score Total Downloads Monthly Downloads

Buzz is a lightweight (<1000 lines of code) PHP 7.1 library for issuing HTTP requests. The library includes three clients: FileGetContents, Curl and MultiCurl. The MultiCurl supports batch requests and HTTP2 server push.

Installation

Install by running:

composer require kriswallsmith/buzz

You do also need to install a PSR-17 request/response factory. Buzz uses that factory to create PSR-7 requests and responses. Install one from this list.

Example:

composer require nyholm/psr7

Usage

This page will just show you the basics, please read the full documentation.

use Buzz\Browser;
use Buzz\Client\FileGetContents;

$client = new FileGetContents(new Psr17ResponseFactory());
$browser = new Browser($client, new Psr17RequestFactory());
$response = $browser->get('https://www.google.com');

echo $browser->getLastRequest()."\n";
// $response is a PSR-7 object.
echo $response->getStatusCode();

You can also use the low-level HTTP classes directly.

use Buzz\Client\FileGetContents;

$request = new PSR7Request('GET', 'https://google.com/foo');

$client = new FileGetContents(new Psr17ResponseFactory());
$response = $client->sendRequest($request, ['timeout' => 4]);

echo $response->getStatusCode();

Note

The two new Psr17ResponseFactory() and new Psr17RequestFactory() are placeholders for whatever PSR-17 factory you choose. If you use nyholm/psr7 then the example above would start like:

use Buzz\Browser;
use Buzz\Client\FileGetContents;
use Nyholm\Psr7\Factory\Psr17Factory;

$client = new FileGetContents(new Psr17Factory());
$browser = new Browser($client, new Psr17Factory());
$response = $browser->get('https://www.google.com');

HTTP2 server push

Buzz MultiCurl client support HTTP2 server push.

use Buzz\Client\MultiCurl;
use Nyholm\Psr7\Factory\Psr17Factory;
use Nyholm\Psr7\Request;

$client = new MultiCurl(new Psr17Factory());

$start = microtime(true);
$response = $client->sendRequest(new Request('GET', 'https://http2.golang.org/serverpush', [], null, '2.0'));
$timeFirstRequest = microtime(true) - $start;

// Parse response to find asset version. 
$body = $response->getBody()->__toString();
$id = null;
if (preg_match('#/serverpush/static/style.css\?([0-9]+)#sim', $body, $matches)) {
    $id = $matches[1];
}

// Make two new requests
$start = microtime(true);
$client->sendRequest(new Request('GET', 'https://http2.golang.org/serverpush/static/style.css?'.$id));
$client->sendRequest(new Request('GET', 'https://http2.golang.org/serverpush/static/playground.js?'.$id));
$timeOtherRequests = microtime(true) - $start;

echo 'First: '.$timeFirstRequest."\n";
echo 'Other: '.$timeOtherRequests."\n";

Since the two other requests was pushed, we spend no time fetching those.

First: 1.04281
Other: 0.00027

You can configure what request you want to accept as pushed with the push_function_callback option.

The Idea of Buzz

Buzz was created by Kris Wallsmith back in 2010. The project grown very popular over the years with more than 7 million downloads.

Since August 2017 Tobias Nyholm is maintaining this library. The idea of Buzz will still be the same, we should have a simple API and mimic browser behavior for easy testing. We should not reinvent the wheel and we should not be as powerful and flexible as other clients (ie Guzzle). We do, however, take performance very seriously.

We do love PSRs and this is a wish list of what PSR we would like to support:

  • PSR-1 (Code style)
  • PSR-2 (Code style)
  • PSR-4 (Auto loading)
  • PSR-7 (HTTP messages)
  • PSR-17 (HTTP factories)
  • PSR-18 (HTTP client)

The goal

Since the release of 1.0 Buzz has reached its goal of being a lightweight client that covers 90% of all use cases. There are no plans to actively develop new features or change the existing API. There are alternatives for people that wants an more actively maintained HTTP clients. One that is particularly popular and got a big community behind it is the
Symfony HTTP Client.

Contribute

Buzz is great because it is small, simple and yet flexible. We are always happy to receive bug reports and bug fixes. We are also looking forward to review a pull request with a new middleware, especially if the middleware covers a common use case.

We will probably not accept any configuration option or feature to any of the clients or the Browser.

Backwards Compatibility Promise

We take backwards compatibility very seriously as you should do with any open source project. We strictly follow Semver. Please note that Semver works a bit different prior version 1.0.0. Minor versions prior 1.0.0 are allow to break backwards compatibility.

Being greatly inspired by Symfony's bc promise, we have adopted their method of deprecating classes, interfaces and functions.

Running the tests

There are 2 kinds of tests for this library; unit tests and integration tests. They can be run separably by:

./vendor/bin/phpunit --testsuite Unit
./vendor/bin/phpunit --testsuite Integration

The integration tests makes real HTTP requests to a webserver. There are two different webservers used by our integration tests. A real Nginx server and PHP's built in webserver. The tests that runs with PHP's webserver are provided by php-http/client-integration-tests.

To start the server, open terminal A and run:

./vendor/bin/http_test_server

The other type of integration tests are using Nginx. We use Docker to start the Nginx server.

docker build -t buzz/tests .
docker run -d -p 127.0.0.1:8022:80 buzz/tests

You are now ready to run the integration tests

./vendor/bin/phpunit --testsuite Integration

Test Server Push

To use HTTP/2 server push you need to run the very latest PHP version. PHP also need to use cUrl > 7.61.1 and be compiled with libnghttp2. You can use docker:

composer update
docker run -it --rm --name php-latest -v  "$PWD":/usr/src/myapp -w /usr/src/myapp tommymuehle/docker-alpine-php-nightly \
  php vendor/bin/phpunit tests/Integration/MultiCurlServerPushTest.php
Comments
  • Rewrote MultiCurl to be concurrent and async

    Rewrote MultiCurl to be concurrent and async

    Hi,

    The MultiCurl client had a bug where it would hang for ever on new versions. See this comment for an explanation (I think): http://www.php.net/manual/en/function.curl-multi-select.php#110869

    In any case, I wanted to be able to process responses as they come back, rather than block for the entire batch to complete. I have therefore rewritten the client completely. It is still fully BC, but you can now pass a callback option that will get invoked as the response becomes available. This changes the interface a bit, since the user land code will then have to call proceed to delegate control back to multi-curl, concurrent style.

    Sorry for the missing tests, but then there weren't any on the original code either.

    opened by troelskn 18
  • Timeout detection?

    Timeout detection?

    Hi

    I am having timeouts in some requests and I would like to control them. Right now, I am checking emptyness in Response Content to detect timeouts, is there a cleaner way to check timeout inside Buzz Library?

    I am using Curl as Client.

    Best regards

    opened by ricardclau 15
  • Hotfix for try..catch in Buzz\Client\Curl.php for Buzz Version 0.16.1

    Hotfix for try..catch in Buzz\Client\Curl.php for Buzz Version 0.16.1

    Hi Kris,

    in our production code, we are using the version 0.16.1 of your Buzz Browser with the Curl client. Since the timeout handling from version 0.17.0 isn't released yet, we are not able to handle timeouts in our health-check component gently.

    Do you have enough capacity to release the try..catch for curl_exec as a hotfix in version 0.16.2.

    This would be great.

    Otherwise, can you approximate the date of release for version 0.17.0?

    opened by LegendOfGIT 12
  • Problems sending character '+' in POST Requests

    Problems sending character '+' in POST Requests

    Hi

    I am trying to get rid of Zend_HTTP_Client in order to use Buzz but I am having this problem. If one of my POST Parameters contains character '+' it gets converted to ' ' instead of passing it correctly.

    '+' character is always a dirty bitch on HTTP Requests, if you use it on GET you must pass it urlencoded and in POST it leads to problems most of the times.

    I have tried Client\Curl and Client\FileGetContents, both having same problems

    Have you got any solution for that? If it is impossible to fix it I will have to switch back to Zend_HTTP_Client as we need the '+' character to be sent.

    Thanks for your time

    Best regards

    opened by ricardclau 11
  • 0.14 *much* slower than 0.13 when used with behat

    0.14 *much* slower than 0.13 when used with behat

    We use buzz as part of our BDD process with behat, and we recently noticed a vast slowdown in the time taken to run behat tests of an API implemented in symfony.

    We've isolated the cause to the change from buzz 0.13 to 0.14. Our composer.json rule for behat was set to @stable, which has started pulling in 0.14.

    When we revert to 0.13, the problem went away. We demonstrated this on a couple of different machines.

    I wasn't able to determine the issue. The behat test in question has 158 steps and usually rattles through in roughly a minute, bounded by IO/CPU. With buzz 0.14, then everything still works, but it takes an order of magnitude or more longer to complete the test. Our entire suite of tests usually takes an hour or so, but this change renders the process unworkable.

    While running, I can't see very much happening. It's as if it's waiting - cpu is at just about zero, and there's plenty of memory, and the machine is using an SSD (though there's not much io happening anyway). I couldn't see any other signs of something being wrong. Simply reverting to buzz 0.13, and making no other change to the configuration fixed things.

    We're running centos 6.6.

    Is there anything else we need to tune or setup to make the new version run as quickly as the old?

    opened by haylingsailor 10
  • connection timed out after 5000 milliseconds

    connection timed out after 5000 milliseconds

    I'm getting this when I log in with Facebook using HWIAuthBundle

    request.CRITICAL: Uncaught PHP Exception Buzz\Exception\ClientException: "Connection timed out after 5000 milliseconds" at /home/website/public_html/vendor/kriswallsmith/buzz/lib/Buzz/Client/Curl.php line 29 {"exception":"[object] (Buzz\\Exception\\ClientException: Connection timed out after 5000 milliseconds at /home/website/public_html/vendor/kriswallsmith/buzz/lib/Buzz/Client/Curl.php:29)"} [] [2014-09-23 15:13:18] security.DEBUG: Write SecurityContext in the session [] []

    opened by JonnyD 10
  • Added support for CURLOPT_SSL_VERIFYHOST

    Added support for CURLOPT_SSL_VERIFYHOST

    This PR adds support for CURLOPT_SSL_VERIFYHOST option. Default value is set to 2 according to documentation (http://php.net//manual/pl/function.curl-setopt.php). There should not be any BC issues.

    opened by adampiotrowski 10
  • Get http status of response?

    Get http status of response?

    Am making a request. Everything works fine, until there is an other HTTP status than 200, for example 404. This then just returns an empty string. Any chance how to catch the http status?

    opened by rapsli 9
  • SSL url throws a runtime exception

    SSL url throws a runtime exception

    Here is a code snippet to reproduce:

    error_reporting(E_ALL); 
    ini_set('display_errors', true); 
    $browser = new Buzz\Browser();
    $response = $browser->get("https://www.google.com");
    

    Setting the scheme to https instead of http throws the following exception in the browser:

    Fatal error: Uncaught exception 'RuntimeException' with message 'file_get_contents(https://www.google.com/): failed to open stream: operation failed' in /www/api/Buzz/lib/Buzz/Client/FileGetContents.php on line 49 RuntimeException: file_get_contents(https://www.google.com/): failed to open stream: operation failed in /www/api/Buzz/lib/Buzz/Client/FileGetContents.php on line 49 Call Stack: 0.0004 662440 1. {main}() /www/api/new_document_test_buzz.php:0 0.0020 748224 2. Buzz\Browser->get() /www/api/new_document_test_buzz.php:30 0.0024 776160 3. Buzz\Browser->call() /www/api/Buzz/lib/Buzz/Browser.php:25 0.0027 788520 4. Buzz\Browser->send() /www/api/Buzz/lib/Buzz/Browser.php:71 0.0028 803168 5. Buzz\Client\FileGetContents->send() /www/api/Buzz/lib/Buzz/Browser.php:114

    Do you need to use the CURL client or something different? I wonder if the error message could be more clear about how to remedy the situation.

    opened by duanegran 9
  • Added new client: Samson\Protocol\Protocol\HTTP

    Added new client: Samson\Protocol\Protocol\HTTP

    This PR adds an optional dependency: samson/protocol.

    The problem with Curl is that it isn't available on all installations and file_get_contents refuses to actually fetch contents if the return status is any other dan 2xx, meaning you can't get the actual error message for, for example, a 404 or 500 response.

    This adds a third client, named Protocol. This one tries to do an HTTP request using bare sockets. The socket classes appear to be more common in PHP installations than CURL, so it should almost always work.

    I ran the tests using the server.php script and they work as expected.

    opened by Burgov 9
  • MultiCurl::proceed is now blocking

    MultiCurl::proceed is now blocking

    Before version 1 (beta) MultiCurl::proceed() was non-blocking, and now it's a blocking call. It waits until all requests finish.

    <?php
    
    use Buzz\Client\MultiCurl;
    use Nyholm\Psr7\Factory\MessageFactory;
    use Nyholm\Psr7\Factory\Psr17Factory;
    use Nyholm\Psr7\Request;
    
    require __DIR__.'/vendor/autoload.php';
    
    
    $client = new MultiCurl(new Psr17Factory());
    
     $client->sendAsyncRequest($a = new Request('GET', 'http://httpbin.org/delay/1'), ['callback' => function($request, $response, $exception) {
        dump('A');
        dump(time() - $_SERVER['REQUEST_TIME_FLOAT']);
        // echo $response->getBody()->getContents();
    }]);
    
     $client->sendAsyncRequest($a = new Request('GET', 'http://httpbin.org/delay/2'), ['callback' => function($request, $response, $exception) {
        dump('B');
        dump(time() - $_SERVER['REQUEST_TIME_FLOAT']);
        // echo $response->getBody()->getContents();
    }]);
     $client->sendAsyncRequest($a = new Request('GET', 'http://httpbin.org/delay/3'), ['callback' => function($request, $response, $exception) {
        dump('C');
        dump(time() - $_SERVER['REQUEST_TIME_FLOAT']);
        // echo $response->getBody()->getContents();
    }]);
    
    while (true) {
        $client->proceed();
        echo '.';
        usleep(100000);
    }
    
    opened by lyrixx 8
  • SSL certificate problem: unable to get local issuer certificate

    SSL certificate problem: unable to get local issuer certificate

    Hello,

    I am using "kriswallsmith/Buzz" package with Amazon SP API SDK. I am getting the following error:

    Note: See #2 in log. This line generates the error. This is 5th line in my function financialEvents(Request $request) in code given below the log.

    Buzz\Exception\RequestException: SSL certificate problem: unable to get local issuer certificate in file \\amazon-spapi\vendor\kriswallsmith\buzz\lib\Client\AbstractCurl.php on line 228
    
    #0 \\amazon-spapi\vendor\kriswallsmith\buzz\lib\Client\Curl.php(24): Buzz\Client\AbstractCurl-&gt;parseError(Object(Nyholm\Psr7\Request), 60, Resource id #45)
    #1 \\amazon-spapi\vendor\amazon-php\sp-api-sdk\src\AmazonPHP\SellingPartner\OAuth.php(69): Buzz\Client\Curl-&gt;sendRequest(Object(Nyholm\Psr7\Request))
    #2 \\amazon-spapi\app\Http\Controllers\API\DataController.php(68): AmazonPHP\SellingPartner\OAuth-&gt;exchangeRefreshToken('Atzr|IwEBIIiZuC...')
    #3 \\amazon-spapi\vendor\laravel\framework\src\Illuminate\Routing\Controller.php(54): App\Http\Controllers\API\DataController-&gt;financialEvents(Object(Illuminate\Http\Request))
    #4 \\amazon-spapi\vendor\laravel\framework\src\Illuminate\Routing\ControllerDispatcher.php(45): Illuminate\Routing\Controller-&gt;callAction('financialEvents', Array)
    #5 \\amazon-spapi\vendor\laravel\framework\src\Illuminate\Routing\Route.php(262): Illuminate\Routing\ControllerDispatcher-&gt;dispatch(Object(Illuminate\Routing\Route), Object(App\Http\Controllers\API\DataController), 'financialEvents')
    #6 \\amazon-spapi\vendor\laravel\framework\src\Illuminate\Routing\Route.php(205): Illuminate\Routing\Route-&gt;runController()
    #7 \\amazon-spapi\vendor\laravel\framework\src\Illuminate\Routing\Router.php(695): Illuminate\Routing\Route-&gt;run()
    #8 \\amazon-spapi\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php(128): Illuminate\Routing\Router-&gt;Illuminate\Routing\{closure}(Object(Illuminate\Http\Request))
    #9 \\amazon-spapi\vendor\laravel\framework\src\Illuminate\Routing\Middleware\SubstituteBindings.php(50): Illuminate\Pipeline\Pipeline-&gt;Illuminate\Pipeline\{closure}(Object(Illuminate\Http\Request))
    #10 \\amazon-spapi\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php(167): Illuminate\Routing\Middleware\SubstituteBindings-&gt;handle(Object(Illuminate\Http\Request), Object(Closure))
    #11 \\amazon-spapi\vendor\laravel\framework\src\Illuminate\Routing\Middleware\ThrottleRequests.php(127): Illuminate\Pipeline\Pipeline-&gt;Illuminate\Pipeline\{closure}(Object(Illuminate\Http\Request))
    #12 \\amazon-spapi\vendor\laravel\framework\src\Illuminate\Routing\Middleware\ThrottleRequests.php(103): Illuminate\Routing\Middleware\ThrottleRequests-&gt;handleRequest(Object(Illuminate\Http\Request), Object(Closure), Array)
    #13 \\amazon-spapi\vendor\laravel\framework\src\Illuminate\Routing\Middleware\ThrottleRequests.php(55): Illuminate\Routing\Middleware\ThrottleRequests-&gt;handleRequestUsingNamedLimiter(Object(Illuminate\Http\Request), Object(Closure), 'api', Object(Closure))
    #14 \\amazon-spapi\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php(167): Illuminate\Routing\Middleware\ThrottleRequests-&gt;handle(Object(Illuminate\Http\Request), Object(Closure), 'api')
    #15 \\amazon-spapi\vendor\laravel\framework\src\Illuminate\Auth\Middleware\Authenticate.php(44): Illuminate\Pipeline\Pipeline-&gt;Illuminate\Pipeline\{closure}(Object(Illuminate\Http\Request))
    #16 \\amazon-spapi\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php(167): Illuminate\Auth\Middleware\Authenticate-&gt;handle(Object(Illuminate\Http\Request), Object(Closure), 'sanctum')
    #17 \\amazon-spapi\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php(103): Illuminate\Pipeline\Pipeline-&gt;Illuminate\Pipeline\{closure}(Object(Illuminate\Http\Request))
    #18 \\amazon-spapi\vendor\laravel\framework\src\Illuminate\Routing\Router.php(697): Illuminate\Pipeline\Pipeline-&gt;then(Object(Closure))
    #19 \\amazon-spapi\vendor\laravel\framework\src\Illuminate\Routing\Router.php(672): Illuminate\Routing\Router-&gt;runRouteWithinStack(Object(Illuminate\Routing\Route), Object(Illuminate\Http\Request))
    #20 \\amazon-spapi\vendor\laravel\framework\src\Illuminate\Routing\Router.php(636): Illuminate\Routing\Router-&gt;runRoute(Object(Illuminate\Http\Request), Object(Illuminate\Routing\Route))
    #21 \\amazon-spapi\vendor\laravel\framework\src\Illuminate\Routing\Router.php(625): Illuminate\Routing\Router-&gt;dispatchToRoute(Object(Illuminate\Http\Request))
    #22 \\amazon-spapi\vendor\laravel\framework\src\Illuminate\Foundation\Http\Kernel.php(167): Illuminate\Routing\Router-&gt;dispatch(Object(Illuminate\Http\Request))
    #23 \\amazon-spapi\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php(128): Illuminate\Foundation\Http\Kernel-&gt;Illuminate\Foundation\Http\{closure}(Object(Illuminate\Http\Request))
    #24 \\amazon-spapi\vendor\laravel\framework\src\Illuminate\Foundation\Http\Middleware\TransformsRequest.php(21): Illuminate\Pipeline\Pipeline-&gt;Illuminate\Pipeline\{closure}(Object(Illuminate\Http\Request))
    #25 \\amazon-spapi\vendor\laravel\framework\src\Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull.php(31): Illuminate\Foundation\Http\Middleware\TransformsRequest-&gt;handle(Object(Illuminate\Http\Request), Object(Closure))
    #26 \\amazon-spapi\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php(167): Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull-&gt;handle(Object(Illuminate\Http\Request), Object(Closure))
    #27 \\amazon-spapi\vendor\laravel\framework\src\Illuminate\Foundation\Http\Middleware\TransformsRequest.php(21): Illuminate\Pipeline\Pipeline-&gt;Illuminate\Pipeline\{closure}(Object(Illuminate\Http\Request))
    #28 \\amazon-spapi\vendor\laravel\framework\src\Illuminate\Foundation\Http\Middleware\TrimStrings.php(40): Illuminate\Foundation\Http\Middleware\TransformsRequest-&gt;handle(Object(Illuminate\Http\Request), Object(Closure))
    #29 \\amazon-spapi\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php(167): Illuminate\Foundation\Http\Middleware\TrimStrings-&gt;handle(Object(Illuminate\Http\Request), Object(Closure))
    #30 \\amazon-spapi\vendor\laravel\framework\src\Illuminate\Foundation\Http\Middleware\ValidatePostSize.php(27): Illuminate\Pipeline\Pipeline-&gt;Illuminate\Pipeline\{closure}(Object(Illuminate\Http\Request))
    #31 \\amazon-spapi\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php(167): Illuminate\Foundation\Http\Middleware\ValidatePostSize-&gt;handle(Object(Illuminate\Http\Request), Object(Closure))
    #32 \\amazon-spapi\vendor\laravel\framework\src\Illuminate\Foundation\Http\Middleware\PreventRequestsDuringMaintenance.php(86): Illuminate\Pipeline\Pipeline-&gt;Illuminate\Pipeline\{closure}(Object(Illuminate\Http\Request))
    #33 \\amazon-spapi\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php(167): Illuminate\Foundation\Http\Middleware\PreventRequestsDuringMaintenance-&gt;handle(Object(Illuminate\Http\Request), Object(Closure))
    #34 \\amazon-spapi\vendor\fruitcake\laravel-cors\src\HandleCors.php(52): Illuminate\Pipeline\Pipeline-&gt;Illuminate\Pipeline\{closure}(Object(Illuminate\Http\Request))
    #35 \\amazon-spapi\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php(167): Fruitcake\Cors\HandleCors-&gt;handle(Object(Illuminate\Http\Request), Object(Closure))
    #36 \\amazon-spapi\vendor\laravel\framework\src\Illuminate\Http\Middleware\TrustProxies.php(39): Illuminate\Pipeline\Pipeline-&gt;Illuminate\Pipeline\{closure}(Object(Illuminate\Http\Request))
    #37 \\amazon-spapi\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php(167): Illuminate\Http\Middleware\TrustProxies-&gt;handle(Object(Illuminate\Http\Request), Object(Closure))
    #38 \\amazon-spapi\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php(103): Illuminate\Pipeline\Pipeline-&gt;Illuminate\Pipeline\{closure}(Object(Illuminate\Http\Request))
    #39 \\amazon-spapi\vendor\laravel\framework\src\Illuminate\Foundation\Http\Kernel.php(142): Illuminate\Pipeline\Pipeline-&gt;then(Object(Closure))
    #40 \\amazon-spapi\vendor\laravel\framework\src\Illuminate\Foundation\Http\Kernel.php(111): Illuminate\Foundation\Http\Kernel-&gt;sendRequestThroughRouter(Object(Illuminate\Http\Request))
    #41 \\amazon-spapi\public\index.php(52): Illuminate\Foundation\Http\Kernel-&gt;handle(Object(Illuminate\Http\Request))
    #42 {main}
    

    My code is as follows:

    
    <?php
    
    namespace App\Http\Controllers\API;
    
    use Illuminate\Http\Request;
    use Illuminate\Support\Facades\Auth;
    use Symfony\Component\HttpFoundation\Response;
    
    use App\Http\Controllers\API\BaseController as BaseController;
    use Validator;
    //use App\Models\User;
    use App\Models\SpApiAdHocData;
    
    use AmazonPHP\SellingPartner\Marketplace;
    use AmazonPHP\SellingPartner\Regions;
    use AmazonPHP\SellingPartner\SellingPartnerSDK;
    use Buzz\Client\Curl;
    use AmazonPHP\SellingPartner\Exception\ApiException;
    use AmazonPHP\SellingPartner\Configuration;
    use App\Http\Controllers\AmazonAuthController;
    use Monolog\Handler\StreamHandler;
    use Monolog\Logger;
    use Nyholm\Psr7\Factory\Psr17Factory;
    
    //require_once __DIR__ . '/vendor/autoload.php';
    
    class DataController extends BaseController
    {
        private $factory;
        private $client;
        private $configuration;
        private $logger;
        private $sdk;
    
        /**
         * DataController constructor.
         */
        public function __construct()
        {
            $this->factory = new Psr17Factory();
            $this->client = new Curl($this->factory);
            
            $this->configuration = Configuration::forIAMUser(
                AmazonAuthController::CLIENT_ID,
                AmazonAuthController::CLIENT_SECRET,
                AmazonAuthController::AWS_ACCESS_KEY,
                AmazonAuthController::AWS_SECRET_KEY
            );
            
            $this->logger = new Logger('name');
            $this->logger->pushHandler(new StreamHandler(__DIR__ . '/sp-api-php.log', Logger::DEBUG));
            
            $this->sdk = SellingPartnerSDK::create(
                $this->client,
                $this->factory,
                $this->factory,
                $this->configuration,
                $this->logger
            );
        }
    
        public function financialEvents(Request $request)
        {
            $authUser = Auth::user();
            //return $this->sendResponse([ 'email' => $authUser->email], 'You are OK!', Response::HTTP_OK);
            $row = SpApiAdHocData::where('email', $authUser->email)->get()->first();
            $refreshToken = $row['refresh_token'];
            $accessToken = $this->sdk->oAuth()->exchangeRefreshToken($refreshToken);
    
            try {
                $item = $this->sdk->finances()->listFinancialEvents(
                    $accessToken,
                    Regions::EUROPE,
                    100,
                    new \DateTimeImmutable('2022-01-01T00:00:00.00+0530'),
                    new \DateTimeImmutable('2022-03-01T00:00:00.00+0530')
                );
                dump($item);
            } catch (ApiException $exception) {
                dump($exception->getMessage());
            }
    
            return $this->sendResponse([ 'row' => $row], 'You are OK!', Response::HTTP_OK);
        }
    }
    

    Kindly guide.

    Thank you.

    Rupesh

    opened by rupeshbhurke 1
  • Test broken

    Test broken

    https://github.com/kriswallsmith/Buzz/pull/421 PHP Fatal error: Array and string offset access syntax with curly braces is no longer supported in /home/scrutinizer/.analysis/phpcs/vendor/squizlabs/php_codesniffer/src/Config.php on line 399

    opened by toxbyte 0
  • Library should uppercase HTTP method name

    Library should uppercase HTTP method name

    I was experimenting with using this library as http client for stripe-php, via psr18-adapter/stripe-php that I'm working on now, but had to go back to Guzzle, as Buzz is broken there. You see, stripe library defines lowercased HTTP methods names everywhere, but their servers do not accept those:

    ❯ curl -XGET "https://api.stripe.com/v1/customers"
    
    {
      "error": {
        "message": "You did not provide an API key. You need to provide your API key in the Authorization header, using Bearer auth (e.g. 'Authorization: Bearer YOUR_SECRET_KEY'). See https://stripe.com/docs/api#authentication for details, or we can help at https://support.stripe.com/.",
        "type": "invalid_request_error"
      }
    }
    ❯ curl -Xget "https://api.stripe.com/v1/customers"
    <html>
    <head><title>400 Bad Request</title></head>
    <body>
    <center><h1>400 Bad Request</h1></center>
    <hr><center>nginx</center>
    </body>
    </html>
    

    I think you might want to make this library uppercase method names as well, like other libraries do. After all, you do that in some places already

    opened by ostrolucky 4
Releases(1.2.1)
Owner
Kris Wallsmith
Kris Wallsmith
Unirest - a set of lightweight HTTP libraries available in multiple languages

Unirest is a set of lightweight HTTP libraries available in multiple languages, built and maintained by Mashape, who also maintain the open-source API Gateway Kong.

Kong 1.3k Dec 30, 2022
Unirest is a set of lightweight HTTP libraries available in multiple languages.

Unirest for PHP Unirest is a set of lightweight HTTP libraries available in multiple languages. This fork is maintained by APIMatic for its Code Gener

APIMatic 14 Oct 26, 2022
Declarative HTTP Clients using Guzzle HTTP Library and PHP 8 Attributes

Waffler How to install? $ composer require waffler/waffler This package requires PHP 8 or above. How to test? $ composer phpunit Quick start For our e

Waffler 3 Aug 26, 2022
Guzzle, an extensible PHP HTTP client

Guzzle, PHP HTTP client Guzzle is a PHP HTTP client that makes it easy to send HTTP requests and trivial to integrate with web services. Simple interf

Guzzle 22.3k Jan 2, 2023
A Chainable, REST Friendly, PHP HTTP Client. A sane alternative to cURL.

Httpful Httpful is a simple Http Client library for PHP 7.2+. There is an emphasis of readability, simplicity, and flexibility – basically provide the

Nate Good 1.7k Dec 21, 2022
HTTPlug, the HTTP client abstraction for PHP

HTTPlug HTTPlug, the HTTP client abstraction for PHP. Intro HTTP client standard built on PSR-7 HTTP messages. The HTTPlug client interface is compati

The PHP HTTP group 2.4k Dec 30, 2022
↪️ Bypass for PHP creates a custom HTTP Server to return predefined responses to client requests

Bypass for PHP provides a quick way to create a custom HTTP Server to return predefined responses to client requests.Useful for tests with Pest PHP or PHPUnit.

CiaReis 101 Dec 1, 2022
A PHP proxy to solve client browser HTTP CORS(cross-origin) restrictions.

cors-bypass-proxy A PHP proxy to solve client browser HTTP CORS(cross-origin) restrictions. A simple way to solve CORS issue when you have no access t

Gracious Emmanuel 15 Nov 17, 2022
Zenscrape package is a simple PHP HTTP client-provider that makes it easy to parsing site-pages

Zenscrape package is a simple PHP HTTP client-provider that makes it easy to parsing site-pages

Andrei 3 Jan 17, 2022
Async HTTP/1.1+2 client for PHP based on Amp.

This package provides an asynchronous HTTP client for PHP based on Amp. Its API simplifies standards-compliant HTTP resource traversal and RESTful web

AMPHP 641 Dec 19, 2022
Event-driven, streaming HTTP client and server implementation for ReactPHP

HTTP Event-driven, streaming HTTP client and server implementation for ReactPHP. This HTTP library provides re-usable implementations for an HTTP clie

ReactPHP 640 Dec 29, 2022
Simple HTTP cURL client for PHP 7.1+ based on PSR-18

Simple HTTP cURL client for PHP 7.1+ based on PSR-18 Installation composer require sunrise/http-client-curl QuickStart composer require sunrise/http-f

Sunrise // PHP 15 Sep 5, 2022
A super lightweight PSR-7 implementation

PSR-7 implementation A super lightweight PSR-7 implementation. Very strict and very fast. Description Guzzle Laminas Slim Nyholm Lines of code 3.300 3

Tobias Nyholm 972 Jan 5, 2023
Requests for PHP is a humble HTTP request library. It simplifies how you interact with other sites and takes away all your worries.

Requests for PHP Requests is a HTTP library written in PHP, for human beings. It is roughly based on the API from the excellent Requests Python librar

null 3.5k Dec 31, 2022
PSR-7 HTTP Message implementation

zend-diactoros Repository abandoned 2019-12-31 This repository has moved to laminas/laminas-diactoros. Master: Develop: Diactoros (pronunciation: /dɪʌ

Zend Framework 1.6k Dec 9, 2022
Record your test suite's HTTP interactions and replay them during future test runs for fast, deterministic, accurate tests.

This is a port of the VCR Ruby library to PHP. Record your test suite's HTTP interactions and replay them during future test runs for fast, determinis

php-vcr 1.1k Dec 23, 2022
Requests for PHP is a humble HTTP request library. It simplifies how you interact with other sites and takes away all your worries.

Requests for PHP Requests is a HTTP library written in PHP, for human beings. It is roughly based on the API from the excellent Requests Python librar

null 3.5k Dec 31, 2022
The HttpClient component provides powerful methods to fetch HTTP resources synchronously or asynchronously.

HttpClient component The HttpClient component provides powerful methods to fetch HTTP resources synchronously or asynchronously. Resources Documentati

Symfony 1.7k Jan 6, 2023
PSR HTTP Message implementations

laminas-diactoros Diactoros (pronunciation: /dɪʌktɒrɒs/): an epithet for Hermes, meaning literally, "the messenger." This package supercedes and repla

Laminas Project 343 Dec 25, 2022