Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- namespace App\Utils;
- use GuzzleHttp\Client;
- use Psr\Http\Message\ResponseInterface;
- /**
- * Class HttpClient
- *
- * @package App\Utils
- */
- class HttpClient
- {
- const CONNECTION_TIMEOUT = 30;
- /**
- * @var array|false|string
- */
- private $apiSecret;
- /**
- * @var Client
- */
- protected $client;
- /**
- * @var ResponseInterface
- */
- protected $lastResponse;
- /**
- * HttpClient constructor.
- * @param Client $client
- */
- public function __construct(Client $client)
- {
- $this->apiSecret = getenv('API_SECRET');
- $this->client = $client;
- }
- /**
- * @param string $uri
- * @param array $data
- *
- * @return mixed|\Psr\Http\Message\ResponseInterface
- * @throws \GuzzleHttp\Exception\GuzzleException
- */
- public function makeGetRequest(string $uri, array $data = [], $hostHeader = false, $debug = false)
- {
- $attributes = $this->getBasicAttributes($data, $debug, $hostHeader);
- $attributes['query'] = $data;
- try {
- $lastResponse = $this->client->request('GET', $uri, $attributes);
- return $this->getLastResponseContent($lastResponse);
- } catch (\Throwable $e) {
- return false;
- }
- }
- /**
- * @param string $uri
- * @param array $data
- *
- * @return mixed|\Psr\Http\Message\ResponseInterface
- * @throws \GuzzleHttp\Exception\GuzzleException
- */
- public function makePostRequest(string $uri, array $data = [], $hostHeader = false, $debug = false)
- {
- $attributes = $this->getBasicAttributes($data, $debug, $hostHeader);
- $attributes['form_params'] = $data;
- try {
- $lastResponse = $this->client->request('POST', $uri, $attributes);
- return $this->getLastResponseContent($lastResponse);
- } catch (\Throwable $e) {
- return false;
- }
- }
- /**
- * @param $lastResponse
- * @param bool $decodeJson
- * @return mixed|null
- */
- protected function getLastResponseContent($lastResponse, bool $decodeJson = true)
- {
- $responseContent = $lastResponse ? $lastResponse->getBody()->getContents() : null;
- return ($decodeJson && $responseContent) ? json_decode($responseContent) : $responseContent;
- }
- /**
- * @param array $content
- *
- * @return string
- */
- protected function generateSign(array $content)
- {
- $serializedContent = serialize($content);
- return hash_hmac('sha512', $serializedContent, $this->apiSecret);
- }
- /**
- * @param array $data
- * @param bool $debug
- * @param bool $hostHeader
- * @return array
- */
- private function getBasicAttributes(array $data, bool $debug, bool $hostHeader): array
- {
- $attributes = [
- 'headers' => [
- 'sign' => $this->generateSign($data)
- ],
- 'connect_timeout' => self::CONNECTION_TIMEOUT,
- 'debug' => $debug
- ];
- if ($hostHeader) {
- $attributes['headers']['host'] = $hostHeader;
- }
- return $attributes;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement