-
Notifications
You must be signed in to change notification settings - Fork 40
/
Client.php
377 lines (328 loc) · 11.6 KB
/
Client.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
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
<?php
namespace Drip;
use Drip\Exception\DripException;
use Drip\Exception\InvalidArgumentException;
use Drip\Exception\InvalidApiTokenException;
use Drip\Exception\InvalidAccountIdException;
use Drip\Exception\UnexpectedHttpVerbException;
/**
* Drip API
* @author Svetoslav Marinov (SLAVI)
*/
class Client
{
const VERSION = '1.2.0';
/** @var string */
protected $api_token = '';
/** @var string */
protected $account_id = '';
/** @var string */
protected $api_end_point = 'https://api.getdrip.com/v2/';
/** @var integer */
protected $timeout = 30;
/** @var integer */
protected $connect_timeout = 30;
/** @var callable */
protected $guzzle_stack_constructor;
const GET = "GET";
const POST = "POST";
const DELETE = "DELETE";
const PUT = "PUT";
/**
* Accepts the token and saves it internally.
*
* @param string $api_token e.g. qsor48ughrjufyu2dadraasfa1212424
* @param string $account_id e.g. 123456
* @param array $options
* * `api_end_point` (mostly for Drip internal testing)
* * `guzzle_stack_constructor` (for test suite, may break at any time, do not use)
* @throws Exception
*/
public function __construct($api_token, $account_id, $options = [])
{
if (\array_key_exists('api_end_point', $options)) {
$this->api_end_point = $options['api_end_point'];
}
// NOTE: For testing. Could break at any time, please do not depend on this.
if (\array_key_exists('guzzle_stack_constructor', $options)) {
$this->guzzle_stack_constructor = $options['guzzle_stack_constructor'];
}
// TODO: allow setting timeouts
$api_token = trim($api_token);
if (empty($api_token) || !preg_match('#^[\w-]+$#si', $api_token)) {
throw new InvalidApiTokenException("Missing or invalid Drip API token.");
}
$this->api_token = $api_token;
$account_id = trim($account_id);
if (empty($account_id) || !preg_match('#^[\w-]+$#si', $account_id)) {
throw new InvalidAccountIdException("Missing or invalid Drip API token.");
}
$this->account_id = $account_id;
}
/**
* Requests the campaigns for the given account.
* @param array $params Set of arguments
* - status (optional)
* @return \Drip\ResponseInterface
*/
public function get_campaigns($params)
{
if (isset($params['status'])) {
if (!in_array($params['status'], array('active', 'draft', 'paused', 'all'))) {
throw new InvalidArgumentException("Invalid campaign status.");
}
}
return $this->make_request("$this->account_id/campaigns", $params);
}
/**
* Fetch a campaign for the given account based on it's ID.
* @param array $params Set of arguments
* - campaign_id (required)
* @return \Drip\ResponseInterface
*/
public function fetch_campaign($params)
{
if (empty($params['campaign_id'])) {
throw new InvalidArgumentException("campaign_id was not specified");
}
$campaign_id = $params['campaign_id'];
unset($params['campaign_id']); // clear it from the params
return $this->make_request("$this->account_id/campaigns/$campaign_id", $params);
}
/**
* Requests the accounts for the given account.
* Parses the response JSON and returns an array which contains: id, name, created_at etc
* @param void
* @return \Drip\ResponseInterface
*/
public function get_accounts()
{
return $this->make_request('accounts');
}
/**
* Sends a request to add a subscriber and returns its record or false
*
* @param array $params
* @return \Drip\ResponseInterface
*/
public function create_or_update_subscriber($params)
{
// The API wants the params to be JSON encoded
return $this->make_request(
"$this->account_id/subscribers",
array('subscribers' => array($params)),
self::POST
);
}
/**
* Sends a request to add/update a batch (up to 1000) of subscribers
*
* @param array $params
* @return \Drip\ResponseInterface
*/
public function create_or_update_subscribers($params)
{
return $this->make_request(
"$this->account_id/subscribers/batches",
$params,
self::POST
);
}
/**
* Returns info regarding a particular subscriber
*
* @param array $params
* @return \Drip\ResponseInterface
*/
public function fetch_subscriber($params)
{
if (!empty($params['subscriber_id'])) {
$subscriber_id = $params['subscriber_id'];
unset($params['subscriber_id']); // clear it from the params
} else if (!empty($params['email'])) {
$subscriber_id = $params['email'];
unset($params['email']); // clear it from the params
} else {
throw new InvalidArgumentException("Subscriber ID or Email was not specified. You must specify either Subscriber ID or Email.");
}
$subscriber_id = urlencode($subscriber_id);
return $this->make_request("$this->account_id/subscribers/$subscriber_id");
}
/**
* Returns a list of subscribers
*
* @return \Drip\ResponseInterface
*/
public function fetch_subscribers()
{
return $this->make_request("$this->account_id/subscribers");
}
/**
* Subscribes a user to a given campaign for a given account.
*
* @param array $params
*/
public function subscribe_subscriber($params)
{
if (empty($params['campaign_id'])) {
throw new InvalidArgumentException("Campaign ID not specified");
}
$campaign_id = $params['campaign_id'];
unset($params['campaign_id']); // clear it from the params
if (empty($params['email'])) {
throw new InvalidArgumentException("Email not specified");
}
if (!isset($params['double_optin'])) {
$params['double_optin'] = true;
}
// The API wants the params to be JSON encoded
$req_params = array('subscribers' => array($params));
return $this->make_request("$this->account_id/campaigns/$campaign_id/subscribers", $req_params, self::POST);
}
/**
*
* Some keys are removed from the params so they don't get send with the other data to Drip.
*
* @param array $params
*/
public function unsubscribe_subscriber($params)
{
if (!empty($params['subscriber_id'])) {
$subscriber_id = $params['subscriber_id'];
unset($params['subscriber_id']); // clear it from the params
} else if (!empty($params['email'])) {
$subscriber_id = $params['email'];
unset($params['email']); // clear it from the params
} else {
throw new InvalidArgumentException("Subscriber ID or Email was not specified. You must specify either Subscriber ID or Email.");
}
$subscriber_id = urlencode($subscriber_id);
return $this->make_request("$this->account_id/subscribers/$subscriber_id/unsubscribe", $params, self::POST);
}
/**
*
* This calls POST /:account_id/tags to add the tag. It just returns some status code no content
*
* @param array $params
* @param bool $status
*/
public function tag_subscriber($params)
{
if (empty($params['email'])) {
throw new InvalidArgumentException("Email was not specified");
}
if (empty($params['tag'])) {
throw new InvalidArgumentException("Tag was not specified");
}
// The API wants the params to be JSON encoded
$req_params = array('tags' => array($params));
return $this->make_request("$this->account_id/tags", $req_params, self::POST);
}
/**
*
* This calls DELETE /:account_id/tags to remove the tags. It just returns some status code no content
*
* @param array $params
* @param bool $status success or failure
*/
public function untag_subscriber($params)
{
if (empty($params['email'])) {
throw new InvalidArgumentException("Email was not specified");
}
if (empty($params['tag'])) {
throw new InvalidArgumentException("Tag was not specified");
}
// The API wants the params to be JSON encoded
$req_params = array('tags' => array($params));
return $this->make_request("$this->account_id/tags", $req_params, self::DELETE);
}
/**
*
* Posts an event specified by the user.
*
* @param array $params
* @param bool
*/
public function record_event($params)
{
if (empty($params['action'])) {
throw new InvalidArgumentException("Action was not specified");
}
// The API wants the params to be JSON encoded
$req_params = array('events' => array($params));
return $this->make_request("$this->account_id/events", $req_params, self::POST);
}
/**
* @return string
*/
protected function user_agent()
{
return "Drip API PHP Wrapper (getdrip.com). Version " . self::VERSION;
}
/**
* Determines whether the response is a success.
*
* @param int $code
* @return boolean
*/
protected function is_success_response($code)
{
return $code >= 200 && $code <= 299;
}
/**
*
* @param string $url
* @param array $params
* @param int $req_method
* @return \Drip\ResponseInterface
* @throws Exception
*/
protected function make_request($url, $params = array(), $req_method = self::GET)
{
if ($this->guzzle_stack_constructor) {
// This can be replaced with `($this->guzzle_stack_constructor)()` once we drop PHP5 support.
$fn = $this->guzzle_stack_constructor;
$stack = $fn();
} else {
// @codeCoverageIgnoreStart
$stack = \GuzzleHttp\HandlerStack::create();
// @codeCoverageIgnoreEnd
}
$client = new \GuzzleHttp\Client([
'base_uri' => $this->api_end_point,
'handler' => $stack,
]);
$req_params = [
'auth' => [$this->api_token, ''],
'timeout' => $this->timeout,
'connect_timeout' => $this->connect_timeout,
'headers' => [
'User-Agent' => $this->user_agent(),
'Accept' => 'application/json, text/javascript, */*; q=0.01',
'Content-Type' => 'application/vnd.api+json',
],
'http_errors' => false,
];
switch ($req_method) {
case self::GET:
$req_params['query'] = $params;
break;
case self::POST:
case self::DELETE:
// @codeCoverageIgnoreStart
case self::PUT:
// @codeCoverageIgnoreEnd
$req_params['body'] = is_array($params) ? json_encode($params) : $params;
break;
default:
// @codeCoverageIgnoreStart
throw new UnexpectedHttpVerbException("Unexpected HTTP verb $req_method");
break;
// @codeCoverageIgnoreEnd
}
$res = $client->request($req_method, $url, $req_params);
$success_klass = $this->is_success_response($res->getStatusCode()) ? \Drip\SuccessResponse::class : \Drip\ErrorResponse::class;
return new $success_klass($url, $params, $res);
}
}