/** * Authenticates a user and returns an authentication token. * * @param string $username * @param string $password * @return TokenInterface * @throws AccountDisabledException * @throws AccountNotConfirmedException * @throws AuthenticationException * @throws AuthorizationLimitReachedException * @throws UserNotFoundException * @throws WrongPasswordException */ public function authenticate($username, $password) { $response = $this->httpClient->post('/auth', ['body' => ['username' => $username, 'password' => $password]])->json(); if (isset($response['error'])) { switch ($response['code']) { case 101: throw new UserNotFoundException(); case 102: throw new AccountNotConfirmedException(); case 103: case 104: case 105: throw new AccountDisabledException(); case 106: throw new AuthorizationLimitReachedException(); case 107: throw new WrongPasswordException(); default: throw new AuthenticationException('An error occurred during the authentication'); } } $token = new Token(); $token->setUid($response['uid']); $token->setToken($response['token']); return $token; }
/** * @param VerifyYubikeyOtpCommand $command * @return YubikeyVerificationResult */ public function verify(VerifyYubikeyOtpCommand $command) { $this->logger->info('Verifying Yubikey OTP'); $body = ['requester' => ['institution' => $command->institution, 'identity' => $command->identity], 'otp' => ['value' => $command->otp]]; $response = $this->guzzleClient->post('api/verify-yubikey', ['json' => $body, 'exceptions' => false]); $statusCode = $response->getStatusCode(); if ($statusCode != 200) { $type = $statusCode >= 400 && $statusCode < 500 ? 'client' : 'server'; $this->logger->info(sprintf('Yubikey OTP verification failed; %s error', $type)); return new YubikeyVerificationResult(true, false); } try { $result = $response->json(); } catch (\RuntimeException $e) { $this->logger->error('Yubikey OTP verification failed; server responded with malformed JSON.'); return new YubikeyVerificationResult(false, true); } if (!isset($result['status'])) { $this->logger->error('Yubikey OTP verification failed; server responded without status report.'); return new YubikeyVerificationResult(false, true); } if ($result['status'] !== 'OK') { $this->logger->error('Yubikey OTP verification failed; server responded with non-OK status report.'); return new YubikeyVerificationResult(false, true); } return new YubikeyVerificationResult(false, false); }
/** * {@inheritdoc} */ public function send(Swift_Mime_Message $message, &$failedRecipients = null) { $this->beforeSendPerformed($message); $options = ['auth' => ['api', $this->key]]; $options['multipart'] = [['name' => 'to', 'contents' => $this->getTo($message)], ['name' => 'message', 'contents' => (string) $message, 'filename' => 'message.mime']]; return $this->client->post($this->url, $options); }
public function sendSms(SendSmsCommand $command) { $this->logger->info('Requesting Gateway to send SMS'); $body = ['requester' => ['institution' => $command->institution, 'identity' => $command->identity], 'message' => ['originator' => $command->originator, 'recipient' => $command->recipient, 'body' => $command->body]]; $response = $this->guzzleClient->post('api/send-sms', ['json' => $body, 'exceptions' => false]); $statusCode = $response->getStatusCode(); if ($statusCode != 200) { $this->logger->error(sprintf('SMS sending failed, error: [%s] %s', $response->getStatusCode(), $response->getReasonPhrase()), ['http-body' => $response->getBody() ? $response->getBody()->getContents() : '']); return false; } try { $result = $response->json(); } catch (\RuntimeException $e) { $this->logger->error('SMS sending failed; server responded with malformed JSON.'); return false; } if (!isset($result['status'])) { $this->logger->error('SMS sending failed; server responded without status report.'); return false; } if ($result['status'] !== 'OK') { $this->logger->error('SMS sending failed; server responded with non-OK status report.'); return false; } return true; }
/** * Notifies the Flowdock channel of a deployment stage being initiated * * @param string $branchName * @param string $applicationName * @param string $connectionName * @param string $eventTitle * @param string $threadTitle * @return ResponseInterface * @throws FlowdockApiException */ public function notify($branchName, $applicationName, $connectionName, $eventTitle, $threadTitle) { if (empty($branchName)) { throw new \InvalidArgumentException('branchName is an Invalid Argument'); } if (empty($applicationName)) { throw new \InvalidArgumentException('applicationName is an Invalid Argument'); } if (empty($connectionName)) { throw new \InvalidArgumentException('connectionName is an Invalid Argument'); } if (empty($eventTitle)) { throw new \InvalidArgumentException('eventTitle is an Invalid Argument'); } if (empty($threadTitle)) { throw new \InvalidArgumentException('threadTitle is an Invalid Argument'); } $title = $this->formatEventTitle($branchName, $applicationName, $connectionName, $eventTitle); $body = json_encode(['flow_token' => $this->flowToken, 'event' => 'activity', 'author' => ['name' => get_current_user()], 'title' => $title, 'external_thread_id' => $this->externalThreadID, 'thread' => ['title' => $threadTitle, 'body' => '']]); $clientOptions = ['headers' => ['Content-Type' => 'application/json'], 'body' => $body]; $response = $this->client->post(self::MESSAGE_API, $clientOptions); if ($response->getStatusCode() != 202) { throw new FlowdockApiException("Error: HTTP " . $response->getStatusCode() . " with message " . $response->getReasonPhrase()); } return $response; }
/** * Execute an operaction * * A successful operation will return result as an array. * An unsuccessful operation will return null. * * @param OperationInterface $op * @return array|null */ public function execute(OperationInterface $op) { try { if ($op instanceof DeleteOperationInterface) { $response = $this->httpClient->delete($op->getEndpoint(), ['headers' => $op->getHeaders()]); } elseif ($op instanceof PostOperationInterface) { $response = $this->httpClient->post($op->getEndpoint(), ['headers' => $op->getHeaders(), 'body' => $op->getData()]); } elseif ($op instanceof PatchOperationInterface) { $response = $this->httpClient->patch($op->getEndpoint(), ['headers' => $op->getHeaders(), 'body' => $op->getData()]); } elseif ($op instanceof PutOperationInterface) { $response = $this->httpClient->put($op->getEndpoint(), ['headers' => $op->getHeaders(), 'body' => $op->getData()]); } else { $response = $this->httpClient->get($op->getEndpoint()); } } catch (GuzzleHttp\Exception\ClientException $e) { throw new Exception\ClientException('ClientException occurred in request to Orchestrate: ' . $e->getMessage(), $e->getCode(), $e); } catch (GuzzleHttp\Exception\ServerException $e) { throw new Exception\ServerException('ServerException occurred in request to Orchestrate: ' . $e->getMessage(), $e->getCode(), $e); } $refLink = null; $location = null; if ($response->hasHeader('ETag')) { $refLink = str_replace('"', '', $response->getHeaderLine('ETag')); } elseif ($response->hasHeader('Link')) { $refLink = str_replace(['<', '>; rel="next"'], ['', ''], $response->getHeaderLine('Link')); } if ($response->hasHeader('Location')) { $location = $response->getHeaderLine('Location'); } $rawValue = $response->getBody(true); $value = json_decode($rawValue, true); return $op->getObjectFromResponse($refLink, $location, $value, $rawValue); }
/** * {@inheritdoc} */ public function post($url, array $headers = array(), $content = '') { $options = array('headers' => $headers, 'body' => $content); $request = $this->client->post($url, $options); $this->response = $request; return $this->response->getBody(); }
/** * {@inheritdoc} */ public function send(Swift_Mime_Message $message, &$failedRecipients = null) { $this->beforeSendPerformed($message); $data = ['key' => $this->key, 'to' => $this->getToAddresses($message), 'raw_message' => $message->toString(), 'async' => false]; $options = ['form_params' => $data]; $this->client->post('https://mandrillapp.com/api/1.0/messages/send-raw.json', $options); return $this->numberOfRecipients($message); }
/** * {@inheritdoc} */ public function send(Swift_Mime_Message $message, &$failedRecipients = null) { $this->beforeSendPerformed($message); $version = phpversion() ?? 'Unknown PHP version'; $os = PHP_OS ?? 'Unknown OS'; $this->client->post('https://api.postmarkapp.com/email', ['headers' => ['X-Postmark-Server-Token' => $this->serverToken, 'Content-Type' => 'application/json', 'User-Agent' => "postmark (PHP Version: {$version}, OS: {$os})"], 'json' => $this->getMessagePayload($message)]); return $this->numberOfRecipients($message); }
/** * {@inheritdoc} */ public function send(Swift_Mime_Message $message, &$failedRecipients = null) { $this->beforeSendPerformed($message); $recipients = $this->getRecipients($message); $message->setBcc([]); $options = ['headers' => ['Authorization' => $this->key], 'json' => ['recipients' => $recipients, 'content' => ['email_rfc822' => $message->toString()]]]; return $this->client->post('https://api.sparkpost.com/api/v1/transmissions', $options); }
/** * {@inheritdoc} */ public function send(Swift_Mime_Message $message, &$failedRecipients = null) { $this->beforeSendPerformed($message); $recipients = $this->getRecipients($message); $message->setBcc([]); $options = ['headers' => ['Authorization' => $this->key], 'json' => ['recipients' => $recipients, 'content' => ['html' => $message->getBody(), 'from' => $this->getFrom($message), 'reply_to' => $this->getReplyTo($message), 'subject' => $message->getSubject()]]]; return $this->client->post('https://api.sparkpost.com/api/v1/transmissions', $options); }
/** * Authentication */ public function auth() { $this->handlerStack->remove('reAuth'); $res = $this->client->post($this->config->get('authUri'), ['form_params' => ['client_id' => $this->config->get('clientId'), 'client_secret' => $this->config->get('clientSecret'), 'grant_type' => 'client_credentials', 'scope' => 'https://graph.microsoft.com/.default']]); $json = \GuzzleHttp\json_decode($res->getBody(), true); $now = new \DateTime('now', new \DateTimeZone('UTC')); $json['expires_in'] = $now->getTimestamp() + $json['expires_in']; $this->tokenStorage->write($json); }
/** * {@inheritdoc} */ public function verifyIpnMessage(Message $message) { $requestBody = array_merge(['cmd' => '_notify-validate'], $message->getAll()); try { $response = $this->httpClient->post($this->serviceEndpoint, array('form_params' => $requestBody)); } catch (\Exception $e) { throw new ServiceException($e->getMessage()); } return new ServiceResponse((string) $response->getBody()); }
public function uuidApi($username) { $response = $this->client->post(static::UUID_API, array('headers' => array('Content-Type' => 'application/json'), 'body' => json_encode(array('agent' => 'minecraft', 'name' => $username))))->json(array('object' => true)); if (!$response) { throw new \RuntimeException('Bad JSON from API: on username ' . $username); } elseif (isset($response->error)) { throw new \RuntimeException('Error from API: ' . $response->error . ' on username ' . $username); } return $response; }
/** * {@inheritdoc} */ public function send(Swift_Mime_Message $message, &$failedRecipients = null) { $options = ['auth' => ['api', $this->key]]; if (version_compare(ClientInterface::VERSION, '6') === 1) { $options['multipart'] = [['name' => 'to', 'contents' => $this->getTo($message)], ['name' => 'message', 'contents' => (string) $message, 'filename' => 'message.mime']]; } else { $options['body'] = ['to' => $this->getTo($message), 'message' => new PostFile('message', (string) $message)]; } return $this->client->post($this->url, $options); }
/** * {@inheritdoc} */ public function send(Swift_Mime_Message $message, &$failedRecipients = null) { $data = ['key' => $this->key, 'to' => $this->getToAddresses($message), 'raw_message' => (string) $message, 'async' => false]; if (version_compare(ClientInterface::VERSION, '6') === 1) { $options = ['form_params' => $data]; } else { $options = ['body' => $data]; } return $this->client->post('https://mandrillapp.com/api/1.0/messages/send-raw.json', $options); }
/** * Send request * * @param array $data * @return Response */ public function request(array $data = array()) { if (count($data)) { $this->setData($data); } $url = $this->buildUrl(); $data = $this->getData(); $response = $this->httpClient->post($url, array("body" => $data)); return new Response($response); }
/** * @param $action * @param array $options * @return mixed * @throws \Exception */ public function post($action, array $options) { $requestOptions = $this->buildRequestOptions($action, $options); try { $response = $this->connection->post($this->api_url, ['headers' => $requestOptions['headers'], 'cookies' => $requestOptions['cookies'], 'query' => $requestOptions['query']]); } catch (RequestException $e) { throw new \Exception($e->getMessage(), $e->getCode(), $e); } return $response->json(); }
/** * sends your notification to the google servers and returns a guzzle repsonse object * containing their answer. * * @param Message $message * * @return \Psr\Http\Message\ResponseInterface * @throws \GuzzleHttp\Exception\RequestException */ public function send(Message $message) { $headers = ['Authorization' => sprintf('key=%s', $this->apiKey), 'Content-Type' => 'application/json']; if (count($message->getEncryptionHeaders()) > 0) { $headers = array_merge($headers, $message->getEncryptionHeaders()); $body = $message->getEncryptedData(); } else { $body = json_encode($message); } return $this->guzzleClient->post($this->getApiUrl(), ['headers' => $headers, 'body' => $body]); }
/** * Create authentication session and store data. * * @return array|bool */ public function create() { $response = $this->client->post('/auth/create', ['body' => ['username' => $this->username, 'password' => $this->password]]); $authData = $response->json(); // authentication failed if (true !== $authData['status']) { return false; } $this->authStorage->store($authData); $this->authData = $authData; return true; }
public function getPaymentStatus(ArrayObject $notificationResponse) { if (!isset($notificationResponse['p24_session_id']) || !isset($notificationResponse['p24_order_id']) || !isset($notificationResponse['p24_amount'])) { throw new \InvalidArgumentException("Missing one of parameter."); } try { $response = $this->httpClient->post($this->getStatusPaymentUrl(), ['form_params' => ['p24_id_sprzedawcy' => $this->gatewayId, 'p24_session_id' => $notificationResponse['p24_session_id'], 'p24_order_id' => $notificationResponse['p24_order_id'], 'p24_kwota' => $notificationResponse['p24_amount'], 'p24_sign' => $this->createHashForPaymentStatus($notificationResponse->toUnsafeArray())]]); return $this->parseResponse($response->getBody()); } catch (RequestException $requestException) { throw new \RuntimeException($requestException->getMessage()); } }
/** * {@inheritdoc} */ public function send(Swift_Mime_Message $message, &$failedRecipients = null) { $this->beforeSendPerformed($message); $options = ['auth' => ['api', $this->key]]; $to = $this->getTo($message); $message->setBcc([]); if (version_compare(ClientInterface::VERSION, '6') === 1) { $options['multipart'] = [['name' => 'to', 'contents' => $to], ['name' => 'message', 'contents' => $message->toString(), 'filename' => 'message.mime']]; } else { $options['body'] = ['to' => $to, 'message' => new PostFile('message', $message->toString())]; } return $this->client->post($this->url, $options); }
/** * {@inheritdoc} */ public function trace(array $spans) { try { $options = ['json' => array_map([$this, 'normalizeSpan'], $spans)]; if (version_compare(ClientInterface::VERSION, '6.0') >= 0) { $this->client->request('POST', $this->baseUrl . '/api/v1/spans', $options); } else { $this->client->post($this->baseUrl . '/api/v1/spans', $options); } } catch (RequestException $e) { throw new TracerException('Unable to publish the traces', $e->getCode(), $e); } }
/** * {@inheritdoc} */ public function send(Swift_Mime_Message $message, &$failedRecipients = null) { $this->beforeSendPerformed($message); $recipients = $this->getRecipients($message); $message->setBcc([]); $options = ['headers' => ['Authorization' => $this->key], 'json' => ['recipients' => $recipients, 'content' => ['html' => $message->getBody(), 'from' => $this->getFrom($message), 'reply_to' => $this->getReplyTo($message), 'subject' => $message->getSubject()]]]; if ($attachments = $message->getChildren()) { $options['json']['content']['attachments'] = array_map(function ($attachment) { return ['type' => $attachment->getContentType(), 'name' => $attachment->getFileName(), 'data' => Swift_Encoding::getBase64Encoding()->encodeString($attachment->getBody())]; }, $attachments); } return $this->client->post('https://api.sparkpost.com/api/v1/transmissions', $options); }
/** * {@inheritdoc} */ public function send(Swift_Mime_Message $message, &$failedRecipients = null) { $this->beforeSendPerformed($message); $from = $this->getFrom($message); $recipients = $this->getRecipients($message); $message->setBcc([]); $options = ['auth' => [$this->publicKey, $this->privateKey], 'headers' => ['Headers' => ['Reply-To' => $this->getReplyTo($message)]], 'json' => ['FromEmail' => $from['email'], 'FromName' => $from['name'], 'Subject' => $message->getSubject(), 'Text-part' => $message->toString(), 'Html-part' => $message->getBody(), 'Recipients' => $recipients]]; if ($attachments = $message->getChildren()) { $options['json']['Attachments'] = array_map(function ($attachment) { return ['Content-type' => $attachment->getContentType(), 'Filename' => $attachment->getFileName(), 'content' => Swift_Encoding::getBase64Encoding()->encodeString($attachment->getBody())]; }, $attachments); } return $this->client->post('https://api.mailjet.com/v3/send', $options); }
/** * Verify the response string. * * @param string $response * * @throws \Vinkla\Recaptcha\RecaptchaException * * @return bool */ public function verify(string $response) : bool { $data = ['secret' => $this->secret, 'response' => $response]; $response = $this->client->post('https://google.com/recaptcha/api/siteverify', ['form_params' => $data]); $data = json_decode((string) $response->getBody(), true); if (!isset($data['success']) || !$data['success']) { if (isset($data['error-codes'])) { $error = reset($data['error-codes']); throw new RecaptchaException("Invalid reCAPTCHA response error [{$error}]."); } throw new RecaptchaException('Invalid reCAPTCHA response.'); } return (bool) $data['success']; }
/** * This is the method that actually makes the call, which can be easily overwritten so that our unit tests can work * * @param TelegramMethods $method * @param array $formData * @return TelegramRawData */ protected function sendRequestToTelegram(TelegramMethods $method, array $formData) : TelegramRawData { $this->logger->debug('About to call HTTP Client'); $response = $this->httpClient->post($this->composeApiMethodUrl($method), $formData); $this->logger->debug('Got response back from Telegram, applying json_decode'); return new TelegramRawData((string) $response->getBody()); }
/** * Notifies the YooChoose API using Guzzle 5 (for PHP 5.4 support). * * @param array $events */ private function notifyGuzzle5(array $events) { $response = $this->guzzle->post($this->getNotificationEndpoint(), array('json' => array('transaction' => null, 'events' => $events), 'auth' => array($this->options['customer-id'], $this->options['license-key']))); if (isset($this->logger)) { $this->logger->debug('Got ' . $response->getStatusCode() . ' from YooChoose notification POST'); } }
/** * @since 0.2 * @param Request $request * @return mixed */ public function postRequest(Request $request) { $resultArray = $this->client->post(null, array('body' => array_merge($request->getParams(), array('format' => 'json')), 'headers' => $request->getHeaders()))->json(); $this->triggerErrors($resultArray); $this->throwUsageExceptions($resultArray); return $resultArray; }
/** * {@inheritDoc} */ public function post(Request $request) { $response = null; try { $response = $this->client->post($request->getPath(), array_merge(['body' => $request->getBody()], $this->getConfiguration($request))); } catch (RequestException $e) { $this->handleRequestException($request, $e); } return $this->createResponse($response); }