Client.php 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. <?php
  2. namespace Culqi;
  3. use Culqi\Error as Errors;
  4. /**
  5. * Class Client
  6. *
  7. * @package Culqi
  8. */
  9. class Client {
  10. public function request($method, $url, $api_key, $data = NULL) {
  11. try {
  12. $url_params = is_array($data) ? '?' . http_build_query($data) : '';
  13. $headers= array("Authorization" => "Bearer ".$api_key, "Content-Type" => "application/json", "Accept" => "application/json");
  14. $options = array(
  15. 'timeout' => 120
  16. );
  17. if($method == "GET") {
  18. $response = \Requests::get(Culqi::BASE_URL. $url . $url_params, $headers, $options);
  19. } else if($method == "POST") {
  20. $response = \Requests::post(Culqi::BASE_URL . $url, $headers, json_encode($data), $options);
  21. } else if($method == "PATCH") {
  22. $response = \Requests::patch(Culqi::BASE_URL . $url, $headers, json_encode($data), $options);
  23. } else if($method == "DELETE") {
  24. $response = \Requests::delete(Culqi::BASE_URL. $url . $url_params, $headers, $options);
  25. }
  26. } catch (\Exception $e) {
  27. throw new Errors\UnableToConnect();
  28. }
  29. if ($response->status_code >= 200 && $response->status_code <= 206) {
  30. return json_decode($response->body);
  31. }
  32. if ($response->status_code == 400) {
  33. throw new Errors\UnhandledError($response->body, $response->status_code);
  34. }
  35. if ($response->status_code == 401) {
  36. throw new Errors\AuthenticationError();
  37. }
  38. if ($response->status_code == 404) {
  39. throw new Errors\NotFound();
  40. }
  41. if ($response->status_code == 403) {
  42. throw new Errors\InvalidApiKey();
  43. }
  44. if ($response->status_code == 405) {
  45. throw new Errors\MethodNotAllowed();
  46. }
  47. throw new Errors\UnhandledError($response->body, $response->status_code);
  48. }
  49. }