/** * @param \Buzz\Message\Request $request * @param object $tracking */ public function bind(Request $request, $tracking) { $number = $tracking->getNumber(); $trackingData = []; $trackingData = ['tracking_number' => $number]; if ($courier = $tracking->getCourier()) { $trackingData['slug'] = $courier; } if ($orderId = $tracking->getOrderId()) { $trackingData['order_id'] = $orderId; } if ($orderUrl = $tracking->getOrderUrl()) { $trackingData['order_id_path'] = $orderUrl; } if ($meta = $tracking->getMeta()) { $customFields = []; foreach ($meta as $key => $value) { $customFields[$key] = $value; } $trackingData['custom_fields'] = $customFields; } $content = ['tracking' => $trackingData]; $content = $this->encodeContent($content); $request->setContent($content); }
/** * @param Buzz\Message\Request $request * @param Doctrine\Common\Collections\Collection $collection * @throws AntiMattr\Sears\Exception\IntegrationException */ public function bindCollection(Request $request, Collection $collection) { $createdAt = $this->getCreatedAt(); if (null === $createdAt) { throw new IntegrationException('CreatedAt is required'); } $element = $this->xmlBuilder->setRoot('dss-order-adjustment-feed')->setNamespace('http://seller.marketplace.sears.com/oms/v1')->setSchemaLocation('http://seller.marketplace.sears.com/oms/v1 dss-order-return-v1.xsd ')->create(); $element->addChild('date-time-stamp', $this->getCreatedAt()->format('Y-m-d\\TH:i:s')); // Hold all IntegrationExceptions until the end $exceptions = array(); foreach ($collection as $orderReturn) { try { $this->xmlBuilder->addChild($element, 'dss-order-adjustment', $orderReturn->toArray()); } catch (IntegrationException $e) { $orderId = $orderReturn->getPurchaseOrderId(); $message = $e->getMessage(); $exceptions[] = $this->exceptionMessageForOrder($orderId, $message); } } $xml = $element->asXML(); $request->setContent($xml); if (count($exceptions) > 0) { throw new IntegrationException(json_encode($exceptions)); } }
/** * Create request instance * * @param string $method Request method * @param string $path Request path * @param array $body Request body array */ protected function createRequest($method, $path, array $body) { $request = new Request($method, $path, $this->createHost()); $request->setHeaders(['Accept' => 'application/json; charset=UTF-8', 'Content-Type' => 'application/json', 'X-Stream' => 'true']); $request->addHeader('Authorization: Basic ' . base64_encode($this->options['username'] . ':' . $this->options['password'])); $request->setContent(json_encode($body)); return $request; }
/** * @param array $paymentDetails * * @return \LedjIn\Bridge\Buzz\Response */ public function createOffsitePurchase(array $paymentDetails) { $paymentDetails['TxType'] = static::OPERATION_PAYMENT; $query = http_build_query($paymentDetails); $request = new Request('post', $this->getOffsiteResource(), $this->getGatewayHost()); $request->setContent($query); return $this->doRequest($request); }
/** * @param Request $request * @return BuzzRequest */ protected function prepareRequest(Request $request) { $buzzRequest = new BuzzRequest($request->getMethod(), $request->getUrl()->getResource(), $request->getUrl()->getHost()); $buzzRequest->setProtocolVersion($request->getProtocolVersion()); $buzzRequest->setHeaders(HeaderConverter::convertAssociativeToRaw($this->prepareHeaders($request))); $buzzRequest->setContent($request->getContent()); return $buzzRequest; }
/** * Converts a PSR request into a BuzzRequest request. * * @param RequestInterface $request * * @return BuzzRequest */ private function createRequest(RequestInterface $request) { $buzzRequest = new BuzzRequest(); $buzzRequest->setMethod($request->getMethod()); $buzzRequest->fromUrl($request->getUri()->__toString()); $buzzRequest->setProtocolVersion($request->getProtocolVersion()); $buzzRequest->setContent((string) $request->getBody()); $this->addPsrHeadersToBuzzRequest($request, $buzzRequest); return $buzzRequest; }
/** * Plumbery method to request webdriver server. * * @param string $verb HTTP method to use (GET, POST, DELETE) * @param string $path Relative URL to server, without prefix "/" * @param string $content Content of request * @param array $headers Additional HTTP headers */ public function request($verb, $path, $content = null, array $headers = array()) { $url = $this->url . $path; $request = new Request($verb, $url); $request->setContent($content); $response = new Response(); $this->client->send($request, $response); $response->setContent(str_replace("", "", $response->getContent())); $this->verifyResponse($response); return $response; }
/** * @param ConfigurationInterface $configuration * @param PayURequestInterface $request * * @return Request */ public function build(ConfigurationInterface $configuration, PayURequestInterface $request) { $curlRequest = new Request(); if (PayURequestInterface::METHOD_POST === $request->getMethod()) { $curlRequest->setContent($this->serializer->toJson($request->getDataObject())); } $curlRequest->setHost(sprintf('%s://%s/', $configuration->getProtocol(), $configuration->getDomain())); $curlRequest->setResource(sprintf('%s/%s/%s', $configuration->getPath(), $configuration->getVersion(), $request->getPath())); $curlRequest->setMethod($request->getMethod()); $this->addHeaders($curlRequest, $configuration); return $curlRequest; }
/** * Tells if the data looks like spam * * @param array $data * @return boolean */ public function isSpam(array $data) { $data['blog'] = $this->blogUrl; $request = new Message\Request('POST', '/1.1/comment-check', $this->getHost()); $request->setContent(http_build_query($data)); $request->addHeader('Content-Type: application/x-www-form-urlencoded'); $request->addHeader(sprintf('Content-Length: %d', strlen($request->getContent()))); $response = new Message\Response(); $client = new Client\Curl(); $client->send($request, $response); return 'true' == $response->getContent(); }
public function testToStringFormatsTheRequest() { $request = new Request('POST', '/resource/123', 'http://example.com'); $request->setProtocolVersion(1.1); $request->addHeader('Content-Type: application/x-www-form-urlencoded'); $request->setContent('foo=bar&bar=baz'); $expected = "POST /resource/123 HTTP/1.1\r\n"; $expected .= "Host: http://example.com\r\n"; $expected .= "Content-Type: application/x-www-form-urlencoded\r\n"; $expected .= "\r\n"; $expected .= "foo=bar&bar=baz\r\n"; $this->assertEquals($expected, (string) $request); }
public function testConvertsARequestToAContextArray() { $request = new Message\Request('POST', '/resource/123', 'http://example.com'); $request->addHeader('Content-Type: application/x-www-form-urlencoded'); $request->addHeader('Content-Length: 15'); $request->setContent('foo=bar&bar=baz'); $client = new StreamClient(); $client->setMaxRedirects(5); $client->setIgnoreErrors(false); $client->setTimeout(10); $expected = array('http' => array('method' => 'POST', 'header' => "Content-Type: application/x-www-form-urlencoded\r\nContent-Length: 15", 'content' => 'foo=bar&bar=baz', 'protocol_version' => 1.0, 'ignore_errors' => false, 'max_redirects' => 5, 'timeout' => 10)); $this->assertEquals($expected, $client->getStreamContextArray($request)); }
public function sendRequest() { // new Request $request = new Request($this->requestType, $this->resource, $this->host); // add headers $request->addHeaders($this->headers); // add body $request->setContent($this->body); // prepare client $response = new Response(); $curl = new Curl(); $curl->send($request, $response); $this->request = $request; $this->response = $response; }
/** * {@inheritDoc} */ public function createTokenResponse($clientId, $secret, $code, $redirectUrl = "") { $url = 'https://www.google.com/accounts/o8/oauth2/token'; $request = new Request(Request::METHOD_POST, $url); $request->setContent(http_build_query(array('code' => $code, 'client_id' => $clientId, 'client_secret' => $secret, 'grant_type' => 'authorization_code', 'redirect_uri' => urldecode($redirectUrl)))); $response = new Response(); $this->client->send($request, $response); $data = json_decode($response->getContent()); if (isset($data->error)) { return; } $expiresAt = time() + $data->expires_in; $people = 'https://www.googleapis.com/plus/v1/people/me' . '?key=' . $clientId . '&access_token=' . $data->access_token; $me = json_decode($this->request($people)); return new GoogleToken($me, $data->access_token, $expiresAt); }
/** * Helper to send requests to Metrics API. * * @param string $path Path after metrics api version. * @param string $method HTTP Mthod, 'GET' or 'POST'. * @param array<string,array> $data Metrics data. * * @return stdClass */ protected function request($path, $method, array $data = array()) { $request = new Request(); $response = new Response(); $transport = $this->getTransport(); $request->setMethod($method); $request->setResource($this->buildPath($path)); $request->setHost(self::URI); $request->addHeader('Authorization: Basic ' . base64_encode($this->getAuthCredentials())); $request->addHeader('User-Agent: ' . $this->getUserAgent()); if (count($data)) { $request->addHeader('Content-Type: application/json'); $request->setContent(json_encode($data)); } $transport->send($request, $response); return json_decode($response->getContent()); }
/** * @param Buzz\Message\Request $request * @param Doctrine\Common\Collections\Collection $collection * @throws AntiMattr\Sears\Exception\IntegrationException */ public function bindCollection(Request $request, Collection $collection) { $element = $this->xmlBuilder->setRoot('shipment-feed')->setNamespace('http://seller.marketplace.sears.com/oms/v5')->setSchemaLocation('http://seller.marketplace.sears.com/oms/v5 asn.xsd ')->create(); // Hold all IntegrationExceptions until the end $exceptions = array(); foreach ($collection as $shipment) { try { $this->xmlBuilder->addChild($element, 'shipment', $shipment->toArray()); } catch (IntegrationException $e) { $orderId = $shipment->getPurchaseOrderId(); $message = $e->getMessage(); $exceptions[] = $this->exceptionMessageForOrder($orderId, $message); } } $xml = $element->asXML(); $request->setContent($xml); if (count($exceptions) > 0) { throw new IntegrationException(json_encode($exceptions)); } }
public function testConvertsARequestToAContextArray() { $request = new Request('POST', '/resource/123', 'http://example.com'); $request->addHeader('Content-Type: application/x-www-form-urlencoded'); $request->addHeader('Content-Length: 15'); $request->setContent('foo=bar&bar=baz'); $client = new StreamClient(); $client->setMaxRedirects(5); $client->setIgnoreErrors(false); $client->setTimeout(10); $expected = array('http' => array('method' => 'POST', 'header' => "Content-Type: application/x-www-form-urlencoded\r\nContent-Length: 15", 'content' => 'foo=bar&bar=baz', 'protocol_version' => 1.1, 'ignore_errors' => false, 'follow_location' => true, 'max_redirects' => 6, 'timeout' => 10), 'ssl' => array('verify_peer' => true, 'verify_host' => 2)); $this->assertEquals($expected, $client->getStreamContextArray($request)); $client->setVerifyPeer(true); $expected['ssl']['verify_peer'] = true; $this->assertEquals($expected, $client->getStreamContextArray($request)); $client->setMaxRedirects(0); $expected['http']['follow_location'] = false; $expected['http']['max_redirects'] = 1; $this->assertEquals($expected, $client->getStreamContextArray($request)); }
/** * @param Buzz\Message\Request $request * @param Doctrine\Common\Collections\Collection $collection * @throws AntiMattr\Sears\Exception\IntegrationException */ public function bindCollection(Request $request, Collection $collection) { $element = $this->xmlBuilder->setRoot('dss-inventory-feed')->setNamespace('http://seller.marketplace.sears.com/inventory/v1')->setSchemaLocation('http://seller.marketplace.sears.com/inventory/v1 dss-inventory.xsd ')->create(); $parent = $element->addChild('dss-inventory'); // Hold all IntegrationExceptions until the end $exceptions = array(); foreach ($collection as $inventory) { try { $this->xmlBuilder->addChild($parent, 'item', $inventory->toArray()); } catch (IntegrationException $e) { $productId = $inventory->getProductId(); $message = $e->getMessage(); $exceptions[] = $this->exceptionMessageForProduct($productId, $message); } } $xml = $element->asXML(); $request->setContent($xml); if (count($exceptions) > 0) { throw new IntegrationException(json_encode($exceptions)); } }
/** * Make an API request. * * @param \Tev\Bs\Contracts\EndpointInterface $endpoint Requesting endpoint * @return \Tev\Bs\Contracts\ResponseInterface Response * * @throws \Exception * @throws \Tev\Bs\Exception\ErrorResponseException */ public function request(EndpointInterface $endpoint) { if ($this->customerId !== null) { $endpoint->setParam('customer_id', $this->customerId); } // Request $request = new Request($endpoint->getMethod(), $endpoint->getUrl(), $this->host); $request->setContent($endpoint->getContent()); // Response $response = new Response(); // Authorisation $listener = new BasicAuthListener($this->clientId, $this->clientSecret); $listener->preSend($request); // Send $client = new Curl(); $client->setTimeout(30); $client->send($request, $response); // Parse $parser = new Parser($response, $endpoint); return $parser->getResponse(); }
/** * @param $method * @param $relativeUrl * @param array|\stdClass $content * @return mixed */ protected function doHttpRequest($method, $relativeUrl, $content = null) { $relativeUrl = ltrim($relativeUrl, '/'); $response = new Response(); $request = new Request($method); $request->fromUrl($this->baseUrl . '/' . $relativeUrl); $request->addHeader("Content-Type: application/json"); $request->addHeader('Accept: application/json'); if ($content) { $request->setContent(json_encode(array_filter((array) $content))); } $timezone = new \DateTimeZone("UTC"); $datetime = new \DateTime(null, $timezone); $timestamp = str_replace('-', '', $datetime->format('c')); $nonce = uniqid(); $authToken = $this->makeAuthHeader($request, $timestamp, $nonce); $request->addHeader("Authorization: " . $authToken); // $listener = new BasicAuthListener($this->username, $this->password); // $listener->preSend($request); $this->httpClient->send($request, $response); return $this->getResult($response); }
/** * @dataProvider provideClient */ public function testConsecutiveRequests($client) { // request 1 $request = new Request(Request::METHOD_PUT); $request->fromUrl($_SERVER['TEST_SERVER']); $request->addHeader('Content-Type: application/json'); $request->setContent(json_encode(array('foo' => 'bar'))); $response = new Response(); $client->send($request, $response); $data = json_decode($response->getContent(), true); $this->assertEquals('PUT', $data['SERVER']['REQUEST_METHOD']); $this->assertEquals('application/json', $data['SERVER']['CONTENT_TYPE']); $this->assertEquals('{"foo":"bar"}', $data['INPUT']); // request 2 $request = new Request(Request::METHOD_GET); $request->fromUrl($_SERVER['TEST_SERVER']); $response = new Response(); $client->send($request, $response); $data = json_decode($response->getContent(), true); $this->assertEquals('GET', $data['SERVER']['REQUEST_METHOD']); $this->assertEmpty($data['INPUT']); }
/** * @param array $parameters * * @return array */ protected function doHttpRequest($parameters) { $request = new Request(RequestInterface::METHOD_POST, self::OAUTH2_ACCESS_TOKEN_URL); $response = new Response(); $contentParameters = ['client_id' => $this->configManager->get('oro_google_integration.client_id'), 'client_secret' => $this->configManager->get('oro_google_integration.client_secret')]; $parameters = array_merge($contentParameters, $parameters); $content = http_build_query($parameters, '', '&'); $headers = ['Content-length: ' . strlen($content), 'content-type: application/x-www-form-urlencoded', 'user-agent: oro-oauth']; $request->setHeaders($headers); $request->setContent($content); $this->httpClient->send($request, $response); return $this->getResponseContent($response); }
/** * {@inheritDoc} */ public function setContent($content) { parent::setContent(json_encode($content)); }
/** * Performs an HTTP request * * @param string $url The url to fetch * @param string $content The content of the request * @param string $method The HTTP method to use * * @return string The response content */ protected function httpRequest($url, $content = null, $method = null) { if (null === $method) { $method = null === $content ? HttpRequest::METHOD_GET : HttpRequest::METHOD_POST; } $request = new HttpRequest($method, $url); $response = new HttpResponse(); $request->setContent($content); $this->httpClient->send($request, $response); return $response; }
/** * @param int $paymentOrderId * @param float $amount * @param string $currency * * @return array */ public function PaymentOrderRefund($paymentOrderId, $amount, $currency) { $request = new Request(); $request->setMethod('POST'); foreach (array('paymentOrderId', 'amount', 'currency') as $param) { if (null == ${$param}) { throw new InvalidArgumentException($param); } } $params = array('PaymentOrderId' => $paymentOrderId, 'RefundAmount' => $amount, 'Currency' => $currency); $request->setContent(json_encode($params)); return $this->doRequest('PaymentOrder/Refund', $request)->getContentJson(); }
/** * Performs an HTTP request * * @param string $url The url to fetch * @param string $content The content of the request * @param array $headers The headers of the request * @param string $method The HTTP method to use * * @return HttpResponse The response content */ protected function httpRequest($url, $content = null, $headers = array(), $method = null) { if (null === $method) { $method = null === $content ? HttpRequestInterface::METHOD_GET : HttpRequestInterface::METHOD_POST; } $request = new HttpRequest($method, $url); $response = new HttpResponse(); $headers = array_merge(array('User-Agent: HWIOAuthBundle (https://github.com/hwi/HWIOAuthBundle)'), $headers); $request->setHeaders($headers); $request->setContent($content); $this->httpClient->send($request, $response); return $response; }
/** * Performs an HTTP request * * @param string $url The url to fetch * @param string|array $content The content of the request * @param array $headers The headers of the request * @param string $method The HTTP method to use * * @return HttpResponse The response content */ protected function httpRequest($url, $content = null, $headers = array(), $method = null) { if (null === $method) { $method = null === $content || '' === $content ? HttpRequestInterface::METHOD_GET : HttpRequestInterface::METHOD_POST; } $request = new HttpRequest($method, $url); $response = new HttpResponse(); $contentLength = 0; if (is_string($content)) { $contentLength = strlen($content); } elseif (is_array($content)) { $contentLength = strlen(implode('', $content)); } $headers = array_merge(array('User-Agent: HWIOAuthBundle (https://github.com/hwi/HWIOAuthBundle)', 'Content-Length: ' . $contentLength), $headers); $request->setHeaders($headers); $request->setContent($content); try { $this->httpClient->send($request, $response); } catch (ClientException $e) { throw new HttpTransportException('Error while sending HTTP request', $this->getName(), $e->getCode(), $e); } return $response; }
/** * Make HTTP Request. * * @return mixed[] */ public function request($method, $resource, $params = [], $timeout = 10) { $headers = ['User-Agent: ' . $this->getAccountData()['appName'], 'Content-Type: application/json']; $storage = Storage::get(); $hash = $storage->createHash($method, $resource, $params); $etag = $storage->get($hash); if ($etag) { $headers[] = 'If-None-Match: ' . $etag; } $message = new Request($method, $resource, self::BASE_URL . $this->getAccountData()['accountId'] . self::API_VERSION); $message->setHeaders($headers); if (!empty($params)) { // When attaching files set content as is if (array_key_exists('binary', $params)) { $message->setContent($params['binary']); } else { $message->setContent(json_encode($params)); } } $response = new Response(); $bc = $this->createCurl(); $bc->setTimeout($timeout); if (!empty($this->getAccountData()['login']) && !empty($this->getAccountData()['password'])) { $bc->setOption(CURLOPT_USERPWD, $this->getAccountData()['login'] . ':' . $this->getAccountData()['password']); } elseif (!empty($this->getAccountData()['token'])) { $message->addHeader('Authorization: Bearer ' . $this->getAccountData()['token']); } $bc->send($message, $response); $storage->put($hash, trim($response->getHeader('ETag'), '"')); $data = new \stdClass(); switch ($response->getStatusCode()) { case 201: $data = json_decode($response->getContent()); $data->message = 'Created'; break; case 204: $data->message = 'Resource succesfully deleted'; break; case 304: $data->message = '304 Not Modified'; break; case 400: $data->message = '400 Bad Request'; break; case 403: $data->message = '403 Forbidden'; break; case 404: $data->message = '404 Not Found'; break; case 415: $data->message = '415 Unsupported Media Type'; break; case 429: $data->message = '429 Too Many Requests. ' . $response->getHeader('Retry-After'); break; case 500: $data->message = '500 Hmm, that isn�t right'; break; case 502: $data->message = '502 Bad Gateway'; break; case 503: $data->message = '503 Service Unavailable'; break; case 504: $data->message = '504 Gateway Timeout'; break; default: $data = json_decode($response->getContent()); break; } return $data; }
/** * Performs an HTTP request * * @param string $url The url to fetch * @param string|array $content The content of the request * @param array $headers The headers of the request * @param string $method The HTTP method to use * * @return HttpResponse The response content */ protected function httpRequest($url, $content = null, $headers = array(), $method = null) { if (null === $method) { $method = null === $content ? HttpRequestInterface::METHOD_GET : HttpRequestInterface::METHOD_POST; } $request = new HttpRequest($method, $url); $response = new HttpResponse(); $contentLength = 0; if (is_string($content)) { $contentLength = strlen($content); } elseif (is_array($content)) { $contentLength = strlen(implode('', $content)); } $headers = array_merge(array('User-Agent: HWIOAuthBundle (https://github.com/hwi/HWIOAuthBundle)', 'Content-Length: ' . $contentLength), $headers); $request->setHeaders($headers); $request->setContent($content); $this->httpClient->send($request, $response); return $response; }
/** * @param string $method * @param array $arguments * @return array|Request[]|Response[] */ protected function compose($method, $arguments) { $request = new Request('POST', $this->getPath(), $this->getUrl()); $request->addHeader(sprintf('%s: %s', self::TOKEN_HEADER, $this->getToken())); $request->setContent(json_encode(array('method' => $method, 'arguments' => $arguments))); if (is_string($this->auth)) { $request->addHeader(sprintf('Authorization: Basic %s', $this->auth)); } return array($request, new Response()); }
/** * Sets the request's content to a JSON session creation payload. * * @param HttpRequest $request * @param string $password The password to use in the input. Will use the default one if not set. * * @return string */ protected function setSessionInput(HttpRequest $request, $password = null) { $request->setContent(sprintf('{"SessionInput": {"login": "******", "password": "******"}}', $password ?: $this->loginPassword)); }