forked from voucherifyio/voucherify-php-sdk
-
Notifications
You must be signed in to change notification settings - Fork 0
/
VoucherifyRequest.php
114 lines (95 loc) · 2.96 KB
/
VoucherifyRequest.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
<?php
namespace Voucherify;
class VoucherifyRequest {
/**
* @var string
*/
private static $apiURL = "https://api.voucherify.io/v1";
/**
* @var string
*/
private $apiID;
/**
* @var string
*/
private $apiKey;
/**
* @param string $apiID
* @param string $apiKey
*/
public function __construct($apiID, $apiKey) {
$this->setApiID($apiID);
$this->setApiKey($apiKey);
}
private function getHeaders() {
return [
"Content-Type: application/json",
"X-App-Id: " . $this->apiID,
"X-App-Token: " . $this->apiKey,
"X-Voucherify-Channel: PHP-SDK"
];
}
private function encodeParams($params) {
if (!is_array($params) && !is_object($params)) {
return $params;
}
$result = array();
foreach ($params as $key => $value) {
if (is_null($value)) {
continue;
}
$result[] = urlencode($key) . "=" . urlencode($value);
}
return implode("&", $result);
}
/**
* @param string $method
* @param string $endpoint
* @param array|null $params
* @param string|array|object|null $data
*
* @throws Voucherify\ClientException
*/
protected function apiRequest($method, $endpoint, $params, $data) {
$setParams = $params && in_array($method, ["GET", "POST", "DELETE"]);
$setData = $data && in_array($method, ["POST", "PUT", "DELETE"]);
$method = strtoupper($method);
$url = self::$apiURL . $endpoint . ($setParams ? "?" . $this->encodeParams($params) : "");
$options = array();
$options[CURLOPT_URL] = $url;
$options[CURLOPT_HTTPHEADER] = $this->getHeaders();
$options[CURLOPT_RETURNTRANSFER] = true;
$options[CURLOPT_CUSTOMREQUEST] = $method;
$options[CURLOPT_POSTFIELDS] = $setData ? json_encode($data) : NULL;
$curl = curl_init();
curl_setopt_array($curl, $options);
$result = curl_exec($curl);
$statusCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
$error = curl_error($curl);
curl_close($curl);
// Connection errors
if ($result === false) {
throw new ClientException($error);
} // Invalid status code
else if ($statusCode >= 400) {
$resultDecoded = json_decode($result, true);
if($resultDecoded && $resultDecoded['message']) {
throw new ClientException($resultDecoded['message']);
}
throw new ClientException("Unexpected status code: " . $statusCode . " - Details: " . $result);
}
return json_decode($result);
}
/**
* @param string $apiKey
*/
protected function setApiKey($apiKey) {
$this->apiKey = $apiKey;
}
/**
* @param string $apiID
*/
protected function setApiID($apiID) {
$this->apiID = $apiID;
}
}