• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

PHP GuzzleHttp\Middleware类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了PHP中GuzzleHttp\Middleware的典型用法代码示例。如果您正苦于以下问题:PHP Middleware类的具体用法?PHP Middleware怎么用?PHP Middleware使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



在下文中一共展示了Middleware类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的PHP代码示例。

示例1: getHttpClient

 /**
  * Get the client for making calls
  *
  * @return Client
  */
 public function getHttpClient()
 {
     if ($this->client == null) {
         $handler = HandlerStack::create();
         if ($this->mode == 'record') {
             $history = Middleware::history($this->callList);
             $handler->push($history);
         } elseif ($this->mode == 'playback') {
             $recordings = $this->getRecordings();
             $playList = $recordings;
             $mockedResponses = [];
             foreach ($playList as $item) {
                 $mockedResponses[] = new Response($item['statusCode'], $item['headers'], $item['body']);
             }
             $mockHandler = new MockHandler($mockedResponses);
             $handler = HandlerStack::create($mockHandler);
         }
         $this->client = new Client(['handler' => $handler]);
         if (!$this->shutdownRegistered) {
             register_shutdown_function(array($this, 'endRecord'));
             $this->shutdownRegistered = true;
         }
     }
     return $this->client;
 }
开发者ID:eldiddio,项目名称:php-ews,代码行数:30,代码来源:HttpPlayback.php


示例2: __construct

 /**
  * @param string $id
  * @param string $secret
  * @param string $url
  */
 public function __construct($id, $secret, $url)
 {
     $this->logger = new NullLogger();
     if (!strlen($id) || !strlen($secret)) {
         throw new InvalidArgumentException('api_id and api_secret must both be provided');
     }
     $validatedUrl = filter_var($url, FILTER_VALIDATE_URL);
     if (!$validatedUrl) {
         throw new InvalidArgumentException($url . ' is not a valid URL');
     }
     $this->id = $id;
     $this->secret = $secret;
     $this->baseUrl = $validatedUrl . '/page/api/';
     $handlerStack = HandlerStack::create(GuzzleHttp\choose_handler());
     $handlerStack->push(Middleware::mapRequest(function (RequestInterface $request) {
         $uri = $request->getUri();
         $query = new Query($uri->getQuery());
         /*
          * Add id and version to the query
          */
         $query = $query->merge(Query::createFromArray(['api_id' => $this->id, 'api_ver' => '2']));
         /*
          * Add timestamp to the query
          */
         if (!$query->hasKey('api_ts')) {
             $query = $query->merge(Query::createFromArray(['api_ts', time()]));
         }
         $query = $query->merge(Query::createFromArray(['api_mac' => $this->generateMac($uri->getPath(), $query)]));
         return $request->withUri($uri->withQuery((string) $query));
     }));
     $this->guzzleClient = new GuzzleClient(['handler' => $handlerStack]);
 }
开发者ID:JoelESvensson,项目名称:bsd-api-php-guzzle6,代码行数:37,代码来源:Client.php


示例3: testSSO

 public function testSSO()
 {
     $pid = Helper::getSomeProject();
     $user = Helper::getSomeUser();
     Helper::getClient()->getProjects()->addUser($pid, $user['uid']);
     $targetUrl = "/#s=/gdc/projects/{$pid}|projectDashboardPage";
     $sso = new SSO(null, null, KBGDC_API_URL);
     $ssoLink = $sso->getUrl(KBGDC_USERNAME, KBGDC_SSO_KEY, KBGDC_SSO_PROVIDER, $targetUrl, $user['email'], 3600, KBGDC_SSO_KEY_PASS);
     $stack = \GuzzleHttp\HandlerStack::create();
     $lastRequest = null;
     $stack->push(\GuzzleHttp\Middleware::mapRequest(function (Request $request) use(&$lastRequest) {
         $lastRequest = $request;
         return $request;
     }));
     $client = new Client(['handler' => $stack, \GuzzleHttp\RequestOptions::ALLOW_REDIRECTS => true, 'verify' => false]);
     try {
         $client->request('GET', $ssoLink, ['headers' => ['Accept' => 'application/json']]);
     } catch (RequestException $e) {
         if ($e->hasResponse()) {
             $response = $e->getResponse()->getBody();
             $this->fail("{$response} on link: {$ssoLink}");
         } else {
             $this->fail($e->getMessage() . " on link: {$ssoLink}");
         }
     }
     /** @var Request $lastRequest */
     $result = $lastRequest->getUri()->__toString();
     $this->assertStringEndsWith($targetUrl, urldecode($result));
 }
开发者ID:keboola,项目名称:gooddata-php-client,代码行数:29,代码来源:SSOTest.php


示例4: notifyWhenResponseIsComplete

 public function notifyWhenResponseIsComplete()
 {
     parent::$stack->push(Middleware::mapResponse(function (ResponseInterface $response) {
         print 'Response!' . PHP_EOL;
         return $response;
     }));
 }
开发者ID:rbadillap,项目名称:twitterstreaming,代码行数:7,代码来源:MyGuzzleMiddleware.php


示例5: post

 public function post($full_url, array $multi_parts = [], array $headers = [])
 {
     $options = ['debug' => GUZZLE_DEBUG];
     // Grab the client's handler instance.
     $clientHandler = $this->client->getConfig('handler');
     // Create a middleware that echoes parts of the request.
     $tapMiddleware = Middleware::tap(function ($request) {
         echo $request->getHeader('Content-Type');
         // application/json
         echo $request->getBody();
         // {"foo":"bar"}
     });
     //$options['handler'] = $tapMiddleware($clientHandler);
     $multi_part_vars = array();
     foreach ($multi_parts as $name => $data) {
         if (is_array($data)) {
             $data['name'] = $name;
         } else {
             $data = ['name' => $name, 'contents' => $data];
         }
         $multi_part_vars[] = $data;
     }
     $options['multipart'] = $multi_part_vars;
     //$options['headers'] = ['Referer' =>  $full_url];
     if (!empty($headers)) {
         $options['headers'] = $headers;
     }
     $this->response = $this->client->post($full_url, $options);
     return $this;
 }
开发者ID:vantt,项目名称:vocabulary-crawler,代码行数:30,代码来源:GuzzleHttpRequest.php


示例6: __construct

 public function __construct()
 {
     static::init();
     $Stack = new HandlerStack();
     $Stack->setHandler(new CurlHandler());
     /**
      * Здесь ставим ловушку, чтобы с помощью редиректов
      *   определить адрес сервера, который сможет отсылать сообщения
      */
     $Stack->push(Middleware::mapResponse(function (ResponseInterface $Response) {
         $code = $Response->getStatusCode();
         if ($code >= 301 && $code <= 303 || $code == 307 || $code == 308) {
             $location = $Response->getHeader('Location');
             preg_match('/https?://([^-]*-)client-s/', $location, $matches);
             if (array_key_exists(1, $matches)) {
                 $this->cloud = $matches[1];
             }
         }
         return $Response;
     }));
     /**
      * Ловушка для отлова хедера Set-RegistrationToken
      * Тоже нужен для отправки сообщений
      */
     $Stack->push(Middleware::mapResponse(function (ResponseInterface $Response) {
         $header = $Response->getHeader("Set-RegistrationToken");
         if (count($header) > 0) {
             $this->regToken = trim(explode(';', $header[0])[0]);
         }
         return $Response;
     }));
     //$cookieJar = new FileCookieJar('cookie.txt', true);
     $this->client = new Client(['handler' => $Stack, 'cookies' => true]);
 }
开发者ID:tafint,项目名称:skype,代码行数:34,代码来源:Transport.php


示例7: buildClient

 /**
  * Build the guzzle client instance.
  *
  * @param array $config Additional configuration
  *
  * @return GuzzleClient
  */
 private static function buildClient(array $config = [])
 {
     $handlerStack = new HandlerStack(\GuzzleHttp\choose_handler());
     $handlerStack->push(Middleware::prepareBody(), 'prepare_body');
     $config = array_merge(['handler' => $handlerStack], $config);
     return new GuzzleClient($config);
 }
开发者ID:lhas,项目名称:pep,代码行数:14,代码来源:Client.php


示例8: testValidateTicket

 /**
  * Test validation of Cas tickets.
  *
  * @covers ::__construct
  * @covers ::validateTicket
  * @covers ::validateVersion1
  * @covers ::validateVersion2
  * @covers ::verifyProxyChain
  * @covers ::parseAllowedProxyChains
  * @covers ::parseServerProxyChain
  *
  * @dataProvider validateTicketDataProvider
  */
 public function testValidateTicket($version, $ticket, $username, $response, $is_proxy, $can_be_proxied, $proxy_chains, $ssl_verification)
 {
     $mock = new MockHandler([new Response(200, array(), $response)]);
     $handler = HandlerStack::create($mock);
     $container = [];
     $history = Middleware::history($container);
     $handler->push($history);
     $httpClient = new Client(['handler' => $handler]);
     $casHelper = $this->getMockBuilder('\\Drupal\\cas\\Service\\CasHelper')->disableOriginalConstructor()->getMock();
     $casValidator = new CasValidator($httpClient, $casHelper);
     $casHelper->expects($this->any())->method('getCasProtocolVersion')->will($this->returnValue($version));
     $casHelper->expects($this->once())->method('getSslVerificationMethod')->willReturn($ssl_verification);
     $casHelper->expects($this->any())->method('getCertificateAuthorityPem')->will($this->returnValue('foo'));
     $casHelper->expects($this->any())->method('isProxy')->will($this->returnValue($is_proxy));
     $casHelper->expects($this->any())->method('canBeProxied')->will($this->returnValue($can_be_proxied));
     $casHelper->expects($this->any())->method('getProxyChains')->will($this->returnValue($proxy_chains));
     $property_bag = $casValidator->validateTicket($version, $ticket, array());
     // Test that we sent the correct ssl option to the http client.
     foreach ($container as $transaction) {
         switch ($ssl_verification) {
             case CasHelper::CA_CUSTOM:
                 $this->assertEquals('foo', $transaction['options']['verify']);
                 break;
             case CasHelper::CA_NONE:
                 $this->assertEquals(FALSE, $transaction['options']['verify']);
                 break;
             default:
                 $this->assertEquals(TRUE, $transaction['options']['verify']);
         }
     }
     $this->assertEquals($username, $property_bag->getUsername());
 }
开发者ID:pulibrary,项目名称:recap,代码行数:45,代码来源:CasValidatorTest.php


示例9: handle

 /**
  * Execute the job.
  *
  * @return void
  */
 public function handle()
 {
     $config = app('Illuminate\\Contracts\\Config\\Repository');
     $client = app(Client::class);
     $logging = $config->get('captain_hook.log.active') && $config->get('queue.driver') != 'sync';
     foreach ($this->webhooks as $webhook) {
         if ($logging) {
             if ($config->get('captain_hook.log.storage_quantity') != -1 && $webhook->logs()->count() >= $config->get('captain_hook.log.storage_quantity')) {
                 $webhook->logs()->orderBy('updated_at', 'desc')->first()->delete();
             }
             $log = new WebhookLog(['webhook_id' => $webhook['id'], 'url' => $webhook['url']]);
             $middleware = Middleware::tap(function (RequestInterface $request, $options) use($log) {
                 $log->payload_format = isset($request->getHeader('Content-Type')[0]) ? $request->getHeader('Content-Type')[0] : null;
                 $log->payload = $request->getBody()->getContents();
             }, function ($request, $options, Promise $response) use($log) {
                 $response->then(function (ResponseInterface $response) use($log) {
                     $log->status = $response->getStatusCode();
                     $log->response = $response->getBody()->getContents();
                     $log->response_format = $log->payload_format = isset($response->getHeader('Content-Type')[0]) ? $response->getHeader('Content-Type')[0] : null;
                     $log->save();
                 });
             });
             $client->post($webhook['url'], ['body' => $this->eventData, 'handler' => $middleware($client->getConfig('handler'))]);
         } else {
             $client->postAsync($webhook['url'], ['body' => $this->eventData, 'verify' => false, 'future' => true]);
         }
     }
 }
开发者ID:phroggyy,项目名称:captainhook,代码行数:33,代码来源:TriggerWebhooksJob.php


示例10: testSend

 /**
  * @covers ::send
  * @covers ::buildRequest
  * @covers ::getGzippedBody
  * @covers ::getAuthorization
  */
 public function testSend()
 {
     $container = array();
     $history = Middleware::history($container);
     $mockHandler = new MockHandler(array(new Response(200, array(), 'Everything OK')));
     $stack = HandlerStack::create($mockHandler);
     $stack->push($history);
     // $stack->push($mockHandler);
     $http = new GuzzleAdapter(new GuzzleClient(array('handler' => $stack)));
     $client = new Client('aaaaa', 'bbbbb', $http);
     $message = new Message('http://www.example.com/', $client);
     $message->set('foo', 'bar');
     // Call send() and ensure the right response was returned (which we set up above)
     $response = $message->send();
     $this->assertEquals(200, $response->getStatusCode());
     $this->assertEquals('Everything OK', $response->getBody());
     // Ensure the request has everything that should be there
     $this->assertCount(1, $container);
     $request = $container[0]['request'];
     $this->assertEquals('POST', $request->getMethod());
     $this->assertEquals('http://www.example.com/', (string) $request->getUri());
     $this->assertEquals('gzip', $request->getHeaderLine('Content-Encoding'));
     $this->assertEquals('application/json', $request->getHeaderLine('Content-Type'));
     $this->assertEquals('2Isi0VhuV8oniANJzAZVBEZ3DSAKmP0hQrVh3jbUNaQ=', $request->getHeaderLine('Authorization'));
     $this->assertEquals('H4sIAAAAAAAAA6tWSsvPV7JSSkosUqoFAO/1K/4NAAAA', base64_encode((string) $request->getBody()));
 }
开发者ID:maartenstaa,项目名称:gameanalytics-php,代码行数:32,代码来源:MessageTest.php


示例11: testSend

 public function testSend()
 {
     $container = [];
     $history = Middleware::history($container);
     $mockResponseData = json_encode(['ok' => true, 'foo' => 'bar']);
     $mock = new MockHandler([new Response(200, [], $mockResponseData)]);
     $stack = HandlerStack::create($mock);
     $stack->push($history);
     $client = new Client(['handler' => $stack]);
     $mockPayload = new MockPayload();
     $foo = 'who:(search+query+OR+other+search+query)';
     $mockPayload->setFoo($foo);
     $apiClient = new ApiClient(self::API_KEY, $client);
     $payloadResponse = $apiClient->send($mockPayload);
     $transaction = array_pop($container);
     // Assert response is of type MockPayloadResponse
     $this->assertInstanceOf('Colada\\Europeana\\Tests\\Test\\Payload\\MockPayloadResponse', $payloadResponse);
     // Assert if the responses match up.
     $transaction['response']->getBody();
     $this->assertEquals($mockResponseData, $transaction['response']->getBody());
     // Assert if the URL is unfuddled.
     $expectedRequestUri = sprintf('http://europeana.eu/api/v2/mock.json?foo=%s&wskey=%s', $foo, self::API_KEY);
     $requestUri = $transaction['request']->getUri();
     $this->assertEquals($expectedRequestUri, $requestUri);
 }
开发者ID:netsensei,项目名称:europeana,代码行数:25,代码来源:ApiClientTest.php


示例12: initClient

 private function initClient()
 {
     $handlerStack = HandlerStack::create();
     $handlerStack->push(MiddlewareBuilder::factoryForPing($this->logger, self::MAX_RETRIES));
     $handlerStack->push(Middleware::log($this->logger, new MessageFormatter('{hostname} {req_header_User-Agent} - [{ts}] \\"{method} {resource} {protocol}/{version}\\" {code} {res_header_Content-Length}')));
     $this->client = new \GuzzleHttp\Client(['base_uri' => $this->storageApi->getApiUrl(), 'handler' => $handlerStack]);
 }
开发者ID:keboola,项目名称:orchestrator-bundle,代码行数:7,代码来源:PingClient.php


示例13: testBasicClient

 public function testBasicClient()
 {
     $mock = new MockHandler([new Response(200, ['X-Foo' => 'Bar'], "{\"foo\":\"bar\"}")]);
     $container = [];
     $history = Middleware::history($container);
     $stack = HandlerStack::create($mock);
     $stack->push($history);
     $http_client = new Client(['handler' => $stack]);
     $client = new BuuyersClient('u', 'p');
     $client->setClient($http_client);
     $client->companies->getCompany(1);
     foreach ($container as $transaction) {
         $basic = $transaction['request']->getHeaders()['Authorization'][0];
         $this->assertTrue($basic == "Basic dTpw");
         $method = $transaction['request']->getMethod();
         $this->assertEquals($method, 'GET');
         //> GET
         if ($transaction['response']) {
             $statusCode = $transaction['response']->getStatusCode();
             $this->assertEquals(200, $statusCode);
             //> 200, 200
         } elseif ($transaction['error']) {
             echo $transaction['error'];
             //> exception
         }
     }
 }
开发者ID:buuyers,项目名称:buuyers-api-php,代码行数:27,代码来源:BuuyersClientTest.php


示例14: register

 /**
  * Register method.
  */
 public function register()
 {
     // Configuring all guzzle clients.
     $this->app->bind(ClientInterface::class, function () {
         // Guzzle client
         return new Client(['handler' => $this->app->make(HandlerStack::class)]);
     });
     $this->app->alias(ClientInterface::class, Client::class);
     // Bind if needed.
     $this->app->bindIf(HandlerStack::class, function () {
         return HandlerStack::create();
     });
     // If resolved, by this SP or another, add some layers.
     $this->app->resolving(HandlerStack::class, function (HandlerStack $stack) {
         /** @var \DebugBar\DebugBar $debugBar */
         $debugBar = $this->app->make('debugbar');
         $stack->push(new Middleware(new Profiler($timeline = $debugBar->getCollector('time'))));
         $stack->unshift(new ExceptionMiddleware($debugBar->getCollector('exceptions')));
         /** @var \GuzzleHttp\MessageFormatter $formatter */
         $formatter = $this->app->make(MessageFormatter::class);
         $stack->unshift(GuzzleMiddleware::log($debugBar->getCollector('messages'), $formatter));
         // Also log to the default PSR logger.
         if ($this->app->bound(LoggerInterface::class)) {
             $logger = $this->app->make(LoggerInterface::class);
             // Don't log to the same logger twice.
             if ($logger === $debugBar->getCollector('messages')) {
                 return;
             }
             // Push the middleware on the stack.
             $stack->unshift(GuzzleMiddleware::log($logger, $formatter));
         }
     });
 }
开发者ID:hannesvdvreken,项目名称:guzzle-debugbar,代码行数:36,代码来源:ServiceProvider.php


示例15: getClient

 /**
  * Constructs a Solr client from input params.
  *
  * @return Client
  */
 protected function getClient(InputInterface $input, OutputInterface $output)
 {
     if (isset($this->client)) {
         return $this->client;
     }
     $baseURL = $input->getOption('url');
     $username = $input->getOption('username');
     $password = $input->getOption('password');
     // Add trailing slash if one doesn't exist
     if ($baseURL[strlen($baseURL) - 1] !== '/') {
         $baseURL .= '/';
     }
     $output->writeln("Solr URL: <info>{$baseURL}</info>");
     if (!empty($username)) {
         $output->writeln("Basic auth: <info>{$username}</info>");
     }
     // Middleware which logs requests
     $before = function (Request $request, $options) use($output) {
         $url = $request->getUri();
         $method = $request->getMethod();
         $output->writeln(sprintf("<info>%s</info> %s ", $method, $url));
     };
     // Setup the default handler stack and add the logging middleware
     $stack = HandlerStack::create();
     $stack->push(Middleware::tap($before));
     // Guzzle options
     $options = ['base_uri' => $baseURL, 'handler' => $stack];
     if (isset($username)) {
         $options['auth'] = [$username, $password];
     }
     $guzzle = new GuzzleClient($options);
     return new Client($guzzle);
 }
开发者ID:opendi,项目名称:solrclient,代码行数:38,代码来源:AbstractCommand.php


示例16: getStackFunction

 public function getStackFunction()
 {
     return Middleware::mapRequest(function (RequestInterface $request) {
         // Notice that we have to return a request object
         return $request->withHeader('X-Vault-Token', $this->_token);
     });
 }
开发者ID:koshatul,项目名称:vault,代码行数:7,代码来源:VaultAuthToken.php


示例17: testSend

 public function testSend()
 {
     $self = $this;
     $mockRequestData = ['foo' => 'bar', 'token' => self::TOKEN];
     $mockResponseData = ['ok' => true, 'foo' => 'bar'];
     $handler = HandlerStack::create(new MockHandler([new Response(200, [], json_encode($mockResponseData))]));
     $historyContainer = [];
     $history = Middleware::history($historyContainer);
     $handler->push($history);
     $apiClient = new ApiClient(self::TOKEN, new Client(['handler' => $handler]));
     $apiClient->addRequestListener(function (RequestEvent $event) use(&$eventsDispatched, $mockRequestData, $self) {
         $eventsDispatched[ApiClient::EVENT_REQUEST] = true;
         $self->assertEquals($mockRequestData, $event->getRawPayload());
     });
     $apiClient->addResponseListener(function (ResponseEvent $event) use(&$eventsDispatched, $mockResponseData, $self) {
         $eventsDispatched[ApiClient::EVENT_RESPONSE] = true;
         $self->assertEquals($mockResponseData, $event->getRawPayloadResponse());
     });
     $mockPayload = new MockPayload();
     $mockPayload->setFoo('bar');
     $apiClient->send($mockPayload);
     $transaction = $historyContainer[0];
     $requestUrl = (string) $transaction['request']->getUri();
     $requestContentType = $transaction['request']->getHeader('content-type')[0];
     parse_str($transaction['request']->getBody(), $requestBody);
     $responseBody = json_decode($transaction['response']->getBody(), true);
     $this->assertEquals(ApiClient::API_BASE_URL . 'mock', $requestUrl);
     $this->assertEquals('application/x-www-form-urlencoded', $requestContentType);
     $this->assertEquals($mockRequestData, $requestBody);
     $this->assertEquals($mockResponseData, $responseBody);
     $this->assertArrayHasKey(ApiClient::EVENT_REQUEST, $eventsDispatched);
     $this->assertArrayHasKey(ApiClient::EVENT_RESPONSE, $eventsDispatched);
 }
开发者ID:billhance,项目名称:slack,代码行数:33,代码来源:ApiClientTest.php


示例18: __construct

 public function __construct($email, $password, SessionStorageInterface $sessionStorage = null, $env = 'prod', $debug = false)
 {
     if (!in_array($env, ['test', 'prod'], true)) {
         throw new InvalidArgumentException("Environment must be one of: prod, test");
     }
     if (null === $sessionStorage) {
         if (php_sapi_name() == "cli") {
             $sessionStorage = new MemorySessionStorage();
         } else {
             $sessionStorage = new NativeSessionStorage();
         }
     }
     $this->sessionStorage = $sessionStorage;
     $this->email = $email;
     $this->password = $password;
     $params = ['base_uri' => $this->{$env . 'Url'}];
     if ($debug) {
         $this->transactionHistory = [];
         $history = Middleware::history($this->transactionHistory);
         $stack = HandlerStack::create();
         $stack->push($history);
         $params['handler'] = $stack;
     }
     $this->client = new Client($params);
 }
开发者ID:CodeNet-pl,项目名称:kk-client,代码行数:25,代码来源:KKClient.php


示例19: testDetailArray

 public function testDetailArray()
 {
     $mock = new MockHandler([new Response(200, ['Content-Type' => 'application/json'], '{
                 "id": "main",
                 "authorizedFor": "Myself",
                 "creator": {
                     "id": "1234",
                     "description": "[email protected]"
                 },
                 "created": "2016-01-31 00:13:30",
                 "#data": "KBC::ComponentProjectEncrypted==F2LdyHQB45lJHtf",
                 "oauthVersion": "2.0",
                 "appKey": "1234",
                 "#appSecret": "KBC::ComponentEncrypted==/5fEM59+3+59+5+"
             }')]);
     // Add the history middleware to the handler stack.
     $container = [];
     $history = Middleware::history($container);
     $stack = HandlerStack::create($mock);
     $stack->push($history);
     $cred = new Credentials('some-token', ['handler' => $stack, 'url' => 'https://syrup.keboola.com/oauth-v2/']);
     $cred->enableReturnArrays(true);
     $result = $cred->getDetail('wr-dropbox', 'credentials-id');
     $this->assertInternalType('array', $result);
     $this->assertCount(8, $result);
     $this->assertArrayHasKey('#data', $result);
     $this->assertArrayHasKey('#appSecret', $result);
     /** @var Request $request */
     $request = $container[0]['request'];
     $this->assertEquals("https://syrup.keboola.com/oauth-v2/credentials/wr-dropbox/credentials-id", $request->getUri()->__toString());
     $this->assertEquals("GET", $request->getMethod());
     $this->assertEquals("some-token", $request->getHeader("x-storageapi-token")[0]);
 }
开发者ID:keboola,项目名称:oauth-v2-php-client,代码行数:33,代码来源:CredentialsTest.php


示例20: toApi

 public function toApi(Request $request)
 {
     $client = new \GuzzleHttp\Client();
     $input = $request::all();
     $command = 'request';
     $api_key = 'MjuhMtfAAfvJqzbnWFLA';
     // $api_key = 'mysendykey';
     $api_username = 'chris-stop';
     // $api_username = 'mysendyusername';
     $from_name = 'Chris Munialo';
     $from_lat = $input['lat'];
     $from_long = $input['lng'];
     $from_description = '';
     $to_name = 'TRM';
     $to_lat = $input['lat1'];
     $to_long = $input['lng1'];
     $to_description = '';
     $recepient_name = 'John';
     $recepient_phone = '0710000000';
     $recepient_email = '[email protected]';
     $pick_up_date = '2016-04-20 12:12:12';
     $status = false;
     $pay_method = 0;
     $amount = 10;
     $return = true;
     $note = 'Sample note';
     $note_status = true;
     $request_type = 'quote';
     $info = ['command' => $command, 'data' => ['api_key' => $api_key, 'api_username' => $api_username, 'from' => ['from_name' => $from_name, 'from_lat' => floatval($from_lat), 'from_long' => floatval($from_long), 'from_description' => $from_description], 'to' => ['to_name' => $to_name, 'to_lat' => floatval($to_lat), 'to_long' => floatval($to_long), 'to_description' => $to_description], 'recepient' => ['recepient_name' => $recepient_name, 'recepient_phone' => $recepient_phone, 'recepient_email' => $recepient_email], 'delivery_details' => ['pick_up_date' => $pick_up_date, 'collect_payment' => ['status' => $status, 'pay_method' => $pay_method, 'amount' => $amount], 'return' => $return, 'note' => $note, 'note_status' => $note_status, 'request_type' => $request_type]]];
     $clientHandler = $client->getConfig('handler');
     // Create a middleware that echoes parts of the request.
     $tapMiddleware = Middleware::tap(function ($request) {
         $request->getHeader('Content-Type');
         // application/json
         $request->getBody();
         // {"foo":"bar"}
     });
     $endpoint = 'https://developer.sendyit.com/v1/api/#request';
     // $info = json_encode($info);
     $client = new \GuzzleHttp\Client();
     $res = $client->request('POST', $endpoint, ['json' => $info, 'handler' => $tapMiddleware($clientHandler), 'headers' => ['Accept' => 'application/json']]);
     // $res->getStatusCode();
     // "200"
     // $res->getHeader('content-type');
     // 'application/json; charset=utf8'
     $pns = json_decode($res->getBody(), true);
     // var_dump($pns);
     // echo $pns;
     // echo $pns;
     // $pns= $res->getBody();
     // {"type":"User"...
     // Send an asynchronous request.
     // $request = new \GuzzleHttp\Psr7\Request('POST', $endpoint );
     // $promise = $client->sendAsync($request)->then(function ($response) {
     // $response->getBody();
     // });
     // $promise->wait();
     return view('orders.new', ['pns' => $pns]);
 }
开发者ID:krysmunialo,项目名称:sendy---request_delivery,代码行数:59,代码来源:OrdersController.php



注:本文中的GuzzleHttp\Middleware类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
PHP GuzzleHttp\Url类代码示例发布时间:2022-05-23
下一篇:
PHP GuzzleHttp\HandlerStack类代码示例发布时间:2022-05-23
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap