SiteProApiClient.php 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. <?php
  2. use ErrorException;
  3. class SiteProApiClient {
  4. /** @var string */
  5. protected $apiUrl;
  6. protected $apiUser;
  7. protected $apiPass;
  8. public function __construct($apiUrl, $apiUsername, $apiPassword) {
  9. $this->apiUrl = $apiUrl;
  10. $this->apiUser = $apiUsername;
  11. $this->apiPass = $apiPassword;
  12. }
  13. public function remoteCall($method, $params) {
  14. $url = $this->apiUrl.$method;
  15. $ch = curl_init();
  16. curl_setopt($ch, CURLOPT_URL, $url);
  17. curl_setopt($ch, CURLOPT_USERAGENT, 'Site.pro API Client/1.0.1 (PHP '.phpversion().')');
  18. curl_setopt($ch, CURLOPT_POST, true);
  19. curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($params));
  20. curl_setopt($ch, CURLOPT_HTTPHEADER, array(
  21. 'Connection: Close',
  22. 'Content-Type: application/json',
  23. ));
  24. curl_setopt($ch, CURLOPT_TIMEOUT, 300);
  25. curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
  26. curl_setopt($ch, CURLOPT_USERPWD, $this->apiUser.':'.$this->apiPass);
  27. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  28. $r = curl_exec($ch);
  29. $errNo = curl_errno($ch);
  30. $errMsg = curl_error($ch);
  31. $status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
  32. curl_close($ch);
  33. if ($errNo) {
  34. $res = null;
  35. throw new ErrorException('Curl Error ('.$errNo.'): '.$errMsg);
  36. }
  37. if ($status != 200) {
  38. $res = json_decode($r);
  39. if (!$res) {
  40. $res = null;
  41. throw new ErrorException('Response Code ('.$status.')');
  42. }
  43. } else {
  44. $res = json_decode($r);
  45. }
  46. return $res;
  47. }
  48. }