Magento 2 Documentation  2.3
Documentation for Magento 2 CMS v2.3 (December 2018)
EntityRESTApiHelper.php
Go to the documentation of this file.
1 <?php
8 
9 use GuzzleHttp\Client;
10 
16 {
20  const INTEGRATION_ADMIN_TOKEN_URI = '/rest/V1/integration/admin/token';
21 
25  const APPLICATION_JSON_HEADER = ['Content-Type' => 'application/json'];
26 
32  private $guzzle_client;
33 
39  public function __construct($host, $port)
40  {
41  $this->guzzle_client = new Client([
42  'base_uri' => "http://{$host}:{$port}",
43  'timeout' => 5.0,
44  ]);
45  }
46 
56  public function submitAuthAPIRequest($apiMethod, $requestURI, $jsonBody, $headers)
57  {
58  $allHeaders = $headers;
59  $authTokenVal = $this->getAuthToken();
60  $authToken = ['Authorization' => 'Bearer ' . $authTokenVal];
61  $allHeaders = array_merge($allHeaders, $authToken);
62 
63  return $this->submitAPIRequest($apiMethod, $requestURI, $jsonBody, $allHeaders);
64  }
65 
71  private function getAuthToken()
72  {
73  $jsonArray = json_encode(['username' => 'admin', 'password' => 'admin123']);
74 
75  $response = $this->submitAPIRequest(
76  'POST',
77  self::INTEGRATION_ADMIN_TOKEN_URI,
78  $jsonArray,
79  self::APPLICATION_JSON_HEADER
80  );
81 
82  if ($response->getStatusCode() != 200) {
83  throwException($response->getReasonPhrase() .' Could not get admin token from service, please check logs.');
84  }
85 
86  $authToken = str_replace('"', "", $response->getBody()->getContents());
87  return $authToken;
88  }
89 
99  private function submitAPIRequest($apiMethod, $requestURI, $jsonBody, $headers)
100  {
101  $response = $this->guzzle_client->request(
102  $apiMethod,
103  $requestURI,
104  [
105  'headers' => $headers,
106  'body' => $jsonBody
107  ]
108  );
109 
110  return $response;
111  }
112 }
$response
Definition: 404.php:11
submitAuthAPIRequest($apiMethod, $requestURI, $jsonBody, $headers)