ApiConnection.php 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. <?php
  2. /**
  3. * Refer to LICENSE.txt distributed with the Temando Shipping module for notice of license
  4. */
  5. namespace Temando\Shipping\Model\Config\Backend\Active;
  6. use Magento\Framework\HTTP\Client\Curl;
  7. use Temando\Shipping\Rest\AuthenticationInterface;
  8. use Temando\Shipping\Rest\Request\AuthRequestInterfaceFactory;
  9. /**
  10. * Simple http client for testing API authentication.
  11. *
  12. * @package Temando\Shipping\Model
  13. * @author Christoph Aßmann <christoph.assmann@netresearch.de>
  14. * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
  15. * @link http://www.temando.com/
  16. */
  17. class ApiConnection
  18. {
  19. /**
  20. * @var Curl
  21. */
  22. private $httpClient;
  23. /**
  24. * @var AuthRequestInterfaceFactory
  25. */
  26. private $requestFactory;
  27. /**
  28. * ApiConnection constructor.
  29. *
  30. * @param Curl $httpClient
  31. * @param AuthRequestInterfaceFactory $requestFactory
  32. */
  33. public function __construct(
  34. Curl $httpClient,
  35. AuthRequestInterfaceFactory $requestFactory
  36. ) {
  37. $this->httpClient = $httpClient;
  38. $this->requestFactory = $requestFactory;
  39. }
  40. /**
  41. * Check if credentials are valid. Dismiss response.
  42. *
  43. * @param string $endpoint
  44. * @param string $accountId
  45. * @param string $bearerToken
  46. *
  47. * @return bool
  48. */
  49. public function test($endpoint, $accountId, $bearerToken)
  50. {
  51. $this->httpClient->setHeaders([
  52. 'Cache-Control' => 'no-cache',
  53. 'Content-Type' => 'application/vnd.api+json',
  54. 'Accept' => 'application/vnd.api+json',
  55. ]);
  56. $request = $this->requestFactory->create([
  57. 'scope' => AuthenticationInterface::AUTH_SCOPE_ADMIN,
  58. 'accountId' => $accountId,
  59. 'bearerToken' => $bearerToken,
  60. ]);
  61. $this->httpClient->post("$endpoint/sessions", $request->getRequestBody());
  62. return ($this->httpClient->getStatus() === 201);
  63. }
  64. }