ApiClient.php 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. <?php
  2. class ApiClient {
  3. const API_URL = 'https://api.notificore.com/v1.0/';
  4. protected $api_url;
  5. protected $api_key;
  6. protected $logger;
  7. public function __construct($api_key, $api_source = null) {
  8. $this->api_key = $api_key;
  9. if (!$api_source) {
  10. $this->api_source = 'Notificore PHP Library';
  11. } else
  12. $this->api_source = $api_source;
  13. }
  14. /**
  15. * @param $resource_url
  16. * @param null|string|array $post_data
  17. * @param null $custom_request
  18. * @return mixed
  19. * @throws \Exception
  20. */
  21. public function sendRequest($resource_url, $post_data = NULL, $custom_request = NULL) {
  22. $client = curl_init();
  23. if ($post_data === NULL || !is_array($post_data))
  24. curl_setopt($client, CURLOPT_HTTPHEADER, array('X-API-KEY: ' . $this->api_key, 'X-API-SOURCE: ' . $this->api_source, 'Content-type: text/json; charset=utf-8'));
  25. else
  26. curl_setopt($client, CURLOPT_HTTPHEADER, array('X-API-KEY: ' . $this->api_key, 'X-API-SOURCE: ' . $this->api_source));
  27. curl_setopt($client, CURLOPT_RETURNTRANSFER, true);
  28. curl_setopt($client, CURLOPT_FOLLOWLOCATION, false);
  29. if ($custom_request !== NULL)
  30. curl_setopt($client, CURLOPT_CUSTOMREQUEST, $custom_request);
  31. curl_setopt($client, CURLOPT_URL, self::API_URL . $resource_url);
  32. if ($post_data !== NULL AND $custom_request === NULL)
  33. curl_setopt($client, CURLOPT_POST, true);
  34. if ($post_data !== NULL)
  35. curl_setopt($client, CURLOPT_POSTFIELDS, $post_data);
  36. $result = curl_exec($client);
  37. if (!$result) {
  38. throw new Exception(curl_error($client), curl_errno($client));
  39. } else
  40. return $result;
  41. }
  42. public function addLog($message) {
  43. }
  44. public function getBalance() {
  45. try {
  46. $resp = $this->sendRequest('common/balance');
  47. } catch (Exception $e) {
  48. $error = 'Request failed (code: ' . $e->getCode() . '): ' . $e->getMessage();
  49. $this->addLog($error);
  50. throw new Exception($error, -1);
  51. }
  52. $result = json_decode($resp, true);
  53. return $result;
  54. }
  55. }