/** * Execute a http request. If payload == null no body will be sent. Empty body ('{}') is supported by sending a * empty stdClass. * * @param string $path * @param string $method * @param mixed|null $payload * * @throws Exceptions\ValidationException if the API returns a 4xx http status code. Usually means invalid data was sent. * @throws Exceptions\UnautorizedException if the API returns a 401 http status code. Check API token and key. * @throws Exceptions\UnexpectedException if the API returns a 500 http status code or something unexpected happens (ie.: Network error). * * @return stdClass */ protected function httpRequest($path, $method, $payload = null) { $http_sess = $this->moip->getSession(); $headers = []; $body = null; if ($payload !== null) { $body = json_encode($payload, JSON_UNESCAPED_SLASHES); if ($body) { // if it's json serializable $headers['Content-Type'] = 'application/json'; } else { $body = null; } } try { $http_response = $http_sess->request($path, $headers, $body, $method); } catch (Requests_Exception $e) { throw new Exceptions\UnexpectedException($e); } $code = $http_response->status_code; $response_body = $http_response->body; if ($code >= 200 && $code < 300) { return json_decode($response_body); } elseif ($code == 401) { throw new Exceptions\UnautorizedException(); } elseif ($code >= 400 && $code <= 499) { $errors = Exceptions\Error::parseErrors($response_body); throw new Exceptions\ValidationException($code, $errors); } throw new Exceptions\UnexpectedException(); }