public function upload($file, $remote_path, $chunk_size) { if (!file_exists($file) || !is_readable($file) || !($fp = fopen($file, 'rb'))) { throw new \Exception(sprintf(__('The file %s does not seem to exist or is not readable.', 'my-wp-backup'), $file)); } $upload_id = null; while (!feof($fp)) { try { $res = $this->client->put('chunked_upload', null, array('upload_id' => $upload_id, 'offset' => ftell($fp)))->setBody(wpb_get_file_chunk($fp, $chunk_size))->send()->json(); if (null === $upload_id) { $upload_id = $res['upload_id']; } } catch (BadResponseException $e) { $body = $e->getResponse()->getBody(true); error_log($e->getRequest()->getRawHeaders()); error_log($body); throw new \Exception($body); } } $req = $this->client->post('commit_chunked_upload/auto/' . ltrim($remote_path, '/'), null, array('upload_id' => $upload_id, 'overwrite' => 'true')); try { return $req->send()->json(); } catch (BadResponseException $e) { $body = $e->getResponse()->getBody(true); error_log($e->getRequest()->getRawHeaders()); error_log($body); throw new \Exception($body); } }
/** * @inheritdoc */ public function post($url, $params) { $request = $this->client->post($url, null, json_encode($params)); $this->setHeaders($request); $response = $request->send(); return json_decode($response->getBody(true)); }
/** * @dataProvider cbProvider */ public function testResponse($expectedStatusCode, $expectedResponseContent, $request, $testCase, $testHeaders) { $process = new Process('php -S [::1]:8999', __DIR__ . '/../../resources'); $process->start(); sleep(1); $signature = sha1($request . ServerMock::PROJECT_SECRET_KEY); $headers = null; if ($testHeaders) { $headers = $testHeaders; } else { $headers = array('Authorization' => 'Signature ' . $signature); } $request = $this->guzzleClient->post('/webhook_server.php?test_case=' . $testCase, $headers, $request); try { $response = $request->send(); } catch (BadResponseException $e) { $process->stop(); $response = $e->getResponse(); } static::assertSame($expectedResponseContent, $response->getBody(true)); static::assertSame($expectedStatusCode, $response->getStatusCode()); static::assertArrayHasKey('x-xsolla-sdk', $response->getHeaders()); static::assertSame(Version::getVersion(), (string) $response->getHeader('x-xsolla-sdk')); static::assertArrayHasKey('content-type', $response->getHeaders()); if (204 === $response->getStatusCode()) { static::assertStringStartsWith('text/plain', (string) $response->getHeader('content-type')); } else { static::assertStringStartsWith('application/json', (string) $response->getHeader('content-type')); } }
/** * @inheritdoc */ public function getAccessToken() { if ($this->accessToken) { return $this->accessToken; } $postFields = array('grant_type' => 'password', 'client_id' => $this->clientId, 'client_secret' => $this->clientSecret, 'username' => $this->username, 'password' => $this->password . $this->securityToken); $request = $this->guzzle->post('oauth2/token', null, $postFields); $request->setAuth('user', 'pass'); $response = $request->send(); $responseBody = $response->getBody(); $jsonResponse = json_decode($responseBody, true); if ($response->getStatusCode() !== 200) { $message = $responseBody; if (isset($jsonResponse['error_description'])) { $message = $jsonResponse['error_description']; } $this->log->error($message, array('response' => $responseBody)); throw new Exception\SalesforceAuthentication($message); } if (!isset($jsonResponse['access_token']) || empty($jsonResponse['access_token'])) { $message = 'Access token not found'; $this->log->error($message, array('response' => $responseBody)); throw new Exception\SalesforceAuthentication($message); } $this->accessToken = $jsonResponse['access_token']; return $this->accessToken; }
/** * @dataProvider cbProvider */ public function testResponse($expectedStatusCode, $expectedResponseContent, $request, $testCase, $testHeaders) { $signature = sha1($request . self::PROJECT_SECRET_KEY); if ($testHeaders) { $headers = $testHeaders; } else { $headers = array('Authorization' => 'Signature ' . $signature); } $request = self::$httpClient->post('/webhook_server.php?test_case=' . $testCase, $headers, $request); try { $response = $request->send(); } catch (BadResponseException $e) { $response = $e->getResponse(); } static::assertSame($expectedResponseContent, $response->getBody(true)); static::assertSame($expectedStatusCode, $response->getStatusCode()); static::assertArrayHasKey('x-xsolla-sdk', $response->getHeaders()); static::assertSame(Version::getVersion(), (string) $response->getHeader('x-xsolla-sdk')); static::assertArrayHasKey('content-type', $response->getHeaders()); if (Response::HTTP_NO_CONTENT === $response->getStatusCode()) { static::assertStringStartsWith('text/plain', (string) $response->getHeader('content-type')); } else { static::assertStringStartsWith('application/json', (string) $response->getHeader('content-type')); } }
public function post($url) { $request = $this->client->post($url); $request->addPostFields($this->postFields); foreach ($this->headers as $k => $v) { $request->addHeader($k, $v); } return $request->send()->json(); }
public function __call($method, array $parameters) { // Derive the request body $requestBody = $this->encoder->encodeRequest($this->createNamespace($method), $parameters, $this->requestId++); // Initialise the POST request from the HTTP client $request = $this->client->post(null, $this->getRequiredHeaders(), $requestBody); // Return the decoded response from an invocation of the HTTP request return $this->encoder->decodeResponse($request->send()); }
/** * Send and Event to Customer.io * @param $id * @param $name * @param $data * @return Response */ public function event($id, $name, $data) { $body = array_merge(array('name' => $name), $this->parseData($data)); try { $response = $this->client->post('/api/v1/customers/' . $id . '/events', null, $body, array('auth' => $this->auth))->send(); } catch (RequestException $e) { $response = $e->getResponse(); } return new Response($response->getStatusCode(), $response->getReasonPhrase()); }
/** * @param string $action add|update|delete * @param integer $id * @param string|null $data * * @return Response|null */ public function sendAction($action, $id, $data = null) { try { $request = $this->client->post(sprintf('animelist/%s/%s.xml', $action, $id), null, $data ? ['data' => $data] : []); $request->setAuth($this->user_name, $this->user_password); $request->setHeader('User-Agent', 'api-team-' . $this->api_key); return $request->send(); } catch (BadResponseException $e) { // is not a critical error return null; } }
/** * Writes the record down to the log of the implementing handler * * @param array $record * * @return void */ protected function write(array $record) { $data = $this->generateDataStream($record); // extract url and content out of http data stream to send it via guzzle list($header, $body) = explode("\r\n\r\n", $data, 2); list($postLine, $hostLine) = explode("\r\n", $header); $host = substr($hostLine, strlen('HOST: ')); $url = substr($postLine, strlen('POST '), -strlen(' HTTP/1.1')); parse_str($body, $dataArray); $uri = $this->protocol . $host . $url; $this->client->post($uri, ['Content-Type' => 'application/json'], json_encode($dataArray))->send(); }
/** * Post a new case to the signifyd api via http. * * Using an array of data provided, post a request to the API to create a * new signifyd fraud case. * * @param array $data * * @return array */ public function post(array $data) { try { $response = self::$client->post('cases', null, json_encode($data))->send(); if (!$response->isSuccessful()) { return $this->error($repsonse->getStatusCode(), 'case_id'); } return $this->success($response->json()['investigationId'], 'case_id'); } catch (Exception $e) { return $this->error($e->getMessage(), 'case_id'); } }
/** * @param string $username * @param string $password * * @throws ClientErrorResponseException * * @return bool */ public function isAuthenticationValid($username, $password) { $request = $this->httpClient->post('authentication?username=' . urlencode($username), null, $this->createAuthenticationRequestBody($password)); try { $request->send(); } catch (ClientErrorResponseException $exception) { if (400 === $exception->getResponse()->getStatusCode()) { return false; } throw $exception; } return true; }
private function authorize() { if (!$this->client instanceof Client) { throw new \Exception('Authorization process called prematurely.'); } if (!$this->token) { throw new \Exception('Token not informed.'); } $authorization = $this->client->post('Login/Autenticar?token=' . $this->token)->send(); if (false === (bool) $authorization->getBody()) { throw new \Exception('Authorization did not succeed.'); } preg_match('/^apiCredentials=(\\w+)/', $authorization->getSetCookie(), $match); $this->apiCredentials = $match[1]; }
/** * returns a collection of issue by key * * @param array $keyList * @return array[] */ public function getIssuesByKeys($keyList = array()) { // if no keys given if (empty($keyList)) { return array(); } // build request for given issue keys $req = $this->client->post($this->buildUrl("search"), array(), json_encode(array('jql' => 'key IN (' . implode(",", $keyList) . ')', 'startAt' => 0, 'maxResults' => count($keyList), 'fields' => static::$attributeList))); $req->setHeader('Content-Type', 'application/json'); // request the jira issue data try { $res = $req->send($req); $resJson = $res->json(); } catch (ClientErrorResponseException $e) { // if there are errors most likely the issue do not exists, so remove them from search list $errors = $e->getResponse()->json(); foreach ($errors['errorMessages'] as $error) { if (preg_match("/An issue with key '([^']+)' does not exist for field 'key'\\./mi", $error, $match) || preg_match("/The issue key '([^']+)' for field 'key' is invalid\\./mi", $error, $match)) { unset($keyList[array_search($match[1], $keyList)]); } } // request again return $this->getIssuesByKeys($keyList); } // loop through all results and parse them into a clean data set $issues = array(); foreach ($resJson['issues'] as $issueData) { $cleanData = $this->parser->parseJiraIssue($issueData); $issues[$cleanData['key']] = $cleanData; } return $issues; }
public function getPayload($entry, $accessToken, $message, $picture, &$chosenProvider) { try { $provider = craft()->oauth->getProvider('twitter'); $token = craft()->socialPoster_accounts->getToken('twitter'); $client = new Client('https://api.twitter.com/1.1'); $subscriber = $provider->getSubscriber($token); $client->addSubscriber($subscriber); $request = $client->post('statuses/update.json', null, array('status' => $message)); $response = $request->send(); $data = $response->json(); SocialPosterPlugin::log('Twitter post: ' . print_r($data, true), LogLevel::Info); $responseReturn = $this->_returnResponse($response); if (isset($data['id'])) { return array('success' => true, 'response' => $responseReturn, 'data' => $data); } else { return array('success' => false, 'response' => $responseReturn, 'data' => $data); } } catch (ClientErrorResponseException $e) { return array('success' => false, 'response' => $this->_returnResponse($e->getResponse(), $e)); } catch (ServerErrorResponseException $e) { return array('success' => false, 'response' => $this->_returnResponse($e->getResponse(), $e)); } catch (RequestErrorResponseException $e) { return array('success' => false, 'response' => $this->_returnResponse($e->getResponse(), $e)); } catch (CurlException $e) { return array('success' => false, 'response' => $this->_returnResponse($e->getMessage(), $e)); } }
/** * @param string $uri * @param array $parameters * @return \Guzzle\Http\Message\Response */ public function post($uri, array $parameters = array()) { $request = $this->httpClient->post($uri, null, $parameters); /* @var $request \Guzzle\Http\Message\Request */ $this->configureRequest($request); return $request->send(); }
protected function post($url = '', $params = array(), $headers = array(), $output = 'json') { $user_token = $this->session->userdata('token'); if (!empty($user_token)) { $headers['X-authorization'] = $user_token; } // var_dump($url , $params , $headers);exit(); $client = new Client(); $client->setUserAgent($this->input->user_agent()); $params['source_ip'] = $this->input->ip_address(); $request = $client->post($url, $headers, $params, array('timeout' => self::GUZZLE_TIMEOUT)); try { $response = $request->send(); return GuzzleWrapper::response($response); } catch (Guzzle\Http\Exception\BadResponseException $e) { // superclass of ClientErrorResponseException (4xx), ServerErrorResponseException (5xx) and TooManyRedirectsException $response = $e->getResponse(); return GuzzleWrapper::response($response); } catch (Guzzle\Http\Exception\CurlException $e) { return GuzzleWrapper::exception($e); } catch (\Exception $e) { return GuzzleWrapper::exception($e); } return $request; }
/** * doRequest * * @param $content - Content to be sent * * @return Response * @throws Exception - When content length is 0 */ public function doRequest($content) { $request = $this->httpClient->post(null, array('MMProvision-Access-Token' => $this->getToken(), 'Content-Type' => 'text/xml'), $content, array()); $request->getQuery()->set('Function', 'Module')->set('Module_Code', 'remoteprovisioning')->set('Module_Function', 'XML'); $response = $request->send(); return new Response($response); }
/** * Sends the client, product and appointment details to the API * * @param ClientContract $client * @param ProductContract|null $product * @param AppointmentContract|null $appointment * @return \Guzzle\Http\Message\Response */ public function send(ClientContract $client, ProductContract $product = null, AppointmentContract $appointment = null) { $contentBody = []; if (empty($client)) { throw new \UnexpectedValueException('Client Details must be specified'); } $contentBody['client'] = $client->toArray(); if (!empty($product)) { $contentBody[$product->getKey()] = $product->toArray(); } if (!empty($appointment)) { $contentBody['appointment'] = $appointment->toArray(); } $result = $this->guzzleClient->post($this->url . "/" . $this->urn, null, empty($this->encryptor) ? $contentBody : $this->encryptor->encryptData(json_encode($contentBody))); return $result->send(); }
public function onRenderShoppingComplete() { $app = $this->app; $orderId = $app['session']->get('eccube.front.shopping.order.id'); if (!$orderId) { $app->log('onRenderShoppingComplete event orderId not found', array(), Logger::ERROR); return; } $Order = $app['eccube.repository.order']->find($orderId); if (!$Order) { $app->log('onRenderShoppingComplete event Order not found', array(), Logger::ERROR); return; } $FreeeLight = $app['eccube.plugin.repository.freeelight']->find(1); if (!$FreeeLight && !$FreeeLight->getCompanyId()) { $app->log('onRenderShoppingComplete event Freee not setup', array(), Logger::ERROR); return; } $OAuth2 = $app['eccube.plugin.repository.freee_oauth2']->find(FreeeOAuth2::DEFAULT_ID); if (!$OAuth2) { $app->log('onRenderShoppingComplete event Freee OAuth2 unauthorization', array(), Logger::ERROR); return; } $client = new Client('https://api.freee.co.jp'); if ($OAuth2->isExpire()) { $params = array('grant_type' => 'refresh_token', 'client_id' => $FreeeLight->getClientId(), 'client_secret' => $FreeeLight->getClientSecret(), 'refresh_token' => $OAuth2->getRefreshToken()); $data = $client->post('/oauth/token?grant_type=refresh_token', array(), $params)->send()->json(); $OAuth2->setPropertiesFromArray($data); $app['orm.em']->flush(); } else { $app['session']->set('access_token', 'not expire'); } $AccountItem = $app['eccube.plugin.repository.freee_account_item']->findOneBy(array('name' => '売掛金')); $Tax = $app['eccube.plugin.repository.freee_tax']->findOneBy(array('name' => 'sales_with_tax_8')); $Wallet = $app['eccube.plugin.repository.freee_wallet']->findOneBy(array('name' => '現金')); $client = new Client('https://api.freee.co.jp'); $detail = new \StdClass(); $detail->account_item_id = $AccountItem->getId(); $detail->tax_code = $Tax->getCode(); $detail->amount = $Order->getPaymentTotal(); $detail->item_id = null; $detail->section_id = null; $detail->tag_ids = array(); $detail->description = ""; $payment = new \StdClass(); $payment->date = date('Y-m-d'); $payment->from_walletable_type = $Wallet->getType(); $payment->from_walletable_id = $Wallet->getId(); $payment->amount = $Order->getPaymentTotal(); $params = array("company_id" => $FreeeLight->getCompanyId(), "issue_date" => date('Y-m-d'), "due_date" => null, "type" => "income", "partner_id" => null, "ref_number" => $Order->getId(), "details" => array($detail), "payments" => array()); $app['session']->set('complete_params', json_encode($params)); try { $request = $client->post('/api/1/deals.json', array('Authorization' => 'Bearer ' . $OAuth2->getAccessToken(), 'content-type' => 'application/json'), array()); $request->setBody(json_encode($params)); $result = $request->send()->json(); $app['session']->set('complete', $result); } catch (\Exception $e) { $app->log($e->getMessage(), array(), Logger::ERROR); } }
private function request($method, $path, $params = array()) { $url = $this->api . rtrim($path, '/') . '/'; // Using Guzzle library --------------------------------- $client = new Client($url, array('ssl.certificate_authority' => false, 'curl.options' => array('CURLOPT_CONNECTTIMEOUT' => 30))); // headers $headers = array('Connection' => 'close', 'User-Agent' => 'PHPPlivo'); if (!strcmp($method, "POST")) { $request = $client->post('', $headers, json_encode($params)); $request->setHeader('Content-type', 'application/json'); } else { if (!strcmp($method, "GET")) { $request = $client->get('', $headers, $params); $request->getQuery()->merge($params); } else { if (!strcmp($method, "DELETE")) { $request = $client->delete('', $headers, $params); $request->getQuery()->merge($params); } } } $request->setAuth($this->auth_id, $this->auth_token); $response = $request->send(); $responseData = $response->json(); $status = $response->getStatusCode(); return array("status" => $status, "response" => $responseData); }
/** * @param int $facilityId * @param int $doctorId * @param DoctorService $doctorService * * @return DoctorService */ public function addDoctorService($facilityId, $doctorId, $doctorService) { $request = $this->client->post(['facilities/{facilityId}/doctors/{doctorId}/services', ['facilityId' => $facilityId, 'doctorId' => $doctorId]], null, $this->serializer->serialize($doctorService, 'json', SerializationContext::create()->setGroups(['post']))); /** @var DoctorService $newDoctorService */ $newDoctorService = $this->authorizedRequest($request, DoctorService::class, DeserializationContext::create()->setGroups(['get'])); return $newDoctorService; }
public function store(Request $request) { // validate indata /* * - ClientId * - ShipToCompany (semi required) * - ShipToFirstname (semi required) * - ShipToLastname (semi required) * - ShipToAddress (required) * - ShipToAddress2 * - ShipToPostalCode (required) * - ShipToCity (required) * - ShipToCountry [Lista på svenska] * - ShipToEmail * - ShipToPhone * - ShipToFax * - Text1 [Eget fält] * - QuantityARTIKELNR1 [ARTIKELNR1 byts ut mot artikelnr?] numeric * - ItemIdentifier [Skicka artikelnr som värde] */ $this->validate($request, ['ClientId' => 'required', 'ShipToCompany' => 'required_without:ShipToFirstname,ShipToLastname', 'ShipToFirstname' => 'required_without:ShipToCompany', 'ShipToLastname' => 'required_without:ShipToCompany', 'ShipToAddress' => 'required', 'ShipToAddress2' => '', 'ShipToPostalCode' => 'required', 'ShipToCity' => 'required', 'ShipToCountry' => 'required', 'ShipToEmail' => '', 'ShipToPhone' => '', 'ShipToFax' => '', 'Text1' => '', 'Quantity[*]' => '', 'ItemIdentifier' => '']); // posta till http://linabews.lxir.se/order13.asp $client = new Client(getenv('NORDICGATEWAY_ENDPOINT')); $request = $client->post('order13.asp', null, $request->all())->send(); return $request->getStatusCode(); }
/** * @param \Tufesa\Service\Type\BuyRequest $buyRequest * @return \Tufesa\Service\Type\BuyResponse * @throws \Tufesa\Service\Exceptions\ResponseException */ public function buyTickets(BuyRequest $buyRequest) { $customersXML = ""; foreach ($buyRequest->getCustomers() as $customer) { $customersXML .= self::createCustomerXML($customer) . PHP_EOL; } $requestFormat = <<<REQUEST <?xml version="1.0" encoding="UTF-8"?> <BUSDoc version="1.0"> <request> <from>%s</from> <to>%s</to> <date>%s</date> <schedule>%s</schedule> <folio>%s</folio> <customers>%s</customers> </request> </BUSDoc> REQUEST; $body = sprintf($requestFormat, $buyRequest->getFrom(), $buyRequest->getTo(), $buyRequest->getDate()->format("Ymd"), $buyRequest->getSchedule(), $buyRequest->getFolio(), $customersXML); $headers = ["Content-Type" => "text/xml", "Accept" => "text/json"]; $request = $this->guzzleClient->post("buy", $headers, $body); $this->setLastRequest($request); $response = $request->send(); $this->setLastResponse($response); $resource = $response->json(); if ($resource["_Response"]["resultField"]["_id"] != "00") { throw new ResponseException($resource["_Response"]["resultField"]["_message"]); } $tickets = $resource["_Response"]["dataField"][0]; return BuyResponseFactory::create($tickets); }
/** * Get RealFaviconGenerator response * * @param QueryData $queryData RealFaviconGenerator query * @return mixed RealFaviconGenerator response */ protected function getResponse(QueryData $queryData) { $client = new Client($this->generator->getBaseurl()); $request = $client->post($this->generator->getUri(), null, $queryData->__toString()); $response = $client->send($request); return $response; }
/** * * @param array $p * @return bool|TokenResponse */ protected function accessTokenRequest(array $p) { $this->c->setConfig(array(\Guzzle\Http\Client::REQUEST_OPTIONS => array('allow_redirects' => false, 'exceptions' => false, 'verify' => false))); if ($this->clientConfig->getCredentialsInRequestBody()) { // provide credentials in the POST body $p['client_id'] = $this->clientConfig->getClientId(); $p['client_secret'] = $this->clientConfig->getClientSecret(); } else { // use basic authentication $curlAuth = new \Guzzle\Plugin\CurlAuth\CurlAuthPlugin($this->clientConfig->getClientId(), $this->clientConfig->getClientSecret()); $this->c->addSubscriber($curlAuth); } try { $request = $this->c->post($this->clientConfig->getTokenEndpoint()); $request->addPostFields($p); $request->addHeader('Accept', 'application/json'); $responseData = $request->send()->json(); // some servers do not provide token_type, so we allow for setting // a default // issue: https://github.com/fkooman/php-oauth-client/issues/13 if (null !== $this->clientConfig->getDefaultTokenType()) { if (is_array($responseData) && !isset($responseData['token_type'])) { $responseData['token_type'] = $this->clientConfig->getDefaultTokenType(); } } // if the field "expires_in" has the value null, remove it // issue: https://github.com/fkooman/php-oauth-client/issues/17 if ($this->clientConfig->getAllowNullExpiresIn()) { if (is_array($responseData) && array_key_exists("expires_in", $responseData)) { if (null === $responseData['expires_in']) { unset($responseData['expires_in']); } } } // if the field "scope" is empty string a default can be set // through the client configuration // issue: https://github.com/fkooman/php-oauth-client/issues/20 if (null !== $this->clientConfig->getDefaultServerScope()) { if (is_array($responseData) && isset($responseData['scope']) && '' === $responseData['scope']) { $responseData['scope'] = $this->clientConfig->getDefaultServerScope(); } } return new TokenResponse($responseData); } catch (\Guzzle\Common\Exception\RuntimeException $e) { return false; } }
/** * @When /^I make an authenticated request to "([^"]*)"$/ */ public function iMakeAnAuthenticatedRequestTo($url) { $client = new Client('', array('request.options' => array('exceptions' => false))); $request = $client->post($this->locatePath($url)); $request->addHeader('Authorization', 'Bearer ' . $this->accessToken); $response = $request->send(); $this->currentResponse = $response; }
/** * {@inheritdoc} */ public function send($uri, $payload) { try { $response = $this->client->post($uri, $this->getHeaders(true), $payload)->send(); } catch (CurlException $e) { throw TcpException::transportError($e); } catch (CompatCurlException $e) { throw TcpException::transportError($e); } catch (BadResponseException $e) { throw HttpException::httpError($e->getMessage(), $e->getResponse()->getStatusCode(), $e); } catch (ServerErrorResponseException $e) { throw HttpException::httpError($e->getMessage(), $e->getResponse()->getStatusCode(), $e); } catch (ClientErrorResponseException $e) { throw HttpException::httpError($e->getMessage(), $e->getResponse()->getStatusCode(), $e); } return $response->getBody(true); }
public function getLoginSession($redirectUrl) { $code = Yii::$app->request->get('code'); $guzzle = new Client(); $request = $guzzle->post('https://foursquare.com/oauth2/access_token', [], ['client_id' => $this->clientId, 'client_secret' => $this->secret, 'grant_type' => 'authorization_code', 'redirect_uri' => $redirectUrl, 'code' => $code]); $response = $request->send()->json(); $this->setAccessToken($response['access_token']); }
public static function post($url, $data) { $client = new Client(); $request = $client->post($url); $request->setBody(json_encode($data), 'application/json'); $response = $request->send(); return $response->json(); }