-
Notifications
You must be signed in to change notification settings - Fork 38
Expand file tree
/
Copy pathClient.php
More file actions
576 lines (508 loc) · 18.7 KB
/
Client.php
File metadata and controls
576 lines (508 loc) · 18.7 KB
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
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
<?php
namespace Drip;
use Drip\Exception\DripException;
use Drip\Exception\InvalidArgumentException;
use Drip\Exception\InvalidApiKeyException;
use Drip\Exception\InvalidAccessTokenException;
use Drip\Exception\InvalidAccountIdException;
use Drip\Exception\UnexpectedHttpVerbException;
use Exception;
/**
* Drip API
*
* @author Svetoslav Marinov (SLAVI)
*/
class Client
{
const VERSION = '1.5.0';
/** @var string */
protected $api_key = '';
/** @var string */
protected $access_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|null */
protected $guzzle_stack_constructor;
const GET = "GET";
const POST = "POST";
const DELETE = "DELETE";
const PUT = "PUT";
/**
* Accepts API key or access token and saves it internally.
*
* @param array|string ...$params
* * `api_key` e.g. "qsor48ughrjufyu2dadraasfa1212424"
* * `access_token` e.g. "daar48ughrjufyu2dadraasfa421121"
* * `account_id` e.g. "123456"
* * `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(...$params)
{
// Deprecated constructor call.
if (is_string($params[0])) {
$this->deprecated_constructor(
$params[0], // api_key
$params[1], // account_id
isset($params[2]) ? $params[2] : [] // options
);
return;
}
if (array_key_exists('access_token', $params[0])) {
$this->bearer_auth_setup($params[0]['access_token']);
} else if (array_key_exists('api_key', $params[0])) {
$this->basic_auth_setup($params[0]['api_key']);
} else {
throw new InvalidArgumentException("Missing Drip API key or access token.");
}
$this->set_test_options($params[0]);
$this->set_account_id($params[0]['account_id']);
}
/**
* Accepts API key and stores it internally -- format to be deprecated.
*
* @param string $api_key
* @param string $account_id
* @param array{api_end_point?:string, guzzle_stack_constructor?:callable} $options
* * `api_end_point` (for test suite)
* * `guzzle_stack_constructor` (for test suite)
* @throws Exception
*/
protected function deprecated_constructor($api_key, $account_id, $options = [])
{
$this->basic_auth_setup($api_key);
$this->set_account_id($account_id);
$this->set_test_options($options);
}
/**
* @param string $api_key
* @throws Exception
*/
protected function basic_auth_setup($api_key)
{
$api_key = trim($api_key);
if (empty($api_key) || !preg_match('#^[\w-]+$#si', $api_key)) {
throw new InvalidApiKeyException("Missing or invalid Drip API key.");
}
$this->api_key = $api_key;
}
/**
* @param string $access_token
* @throws Exception
*/
protected function bearer_auth_setup($access_token)
{
$access_token = trim($access_token);
if (empty($access_token) || !preg_match('#^[\w-]+$#si', $access_token)) {
throw new InvalidAccessTokenException("Missing or invalid Drip access token.");
}
$this->access_token = $access_token;
}
/**
* @param string $account_id
* @throws Exception
*/
protected function set_account_id($account_id)
{
$account_id = trim($account_id);
if (empty($account_id) || !preg_match('#^[\w-]+$#si', $account_id)) {
throw new InvalidAccountIdException("Missing or invalid Drip account ID.");
}
$this->account_id = $account_id;
}
/**
* @param array{api_end_point?:string, guzzle_stack_constructor?:callable} $options
* * `api_end_point`
* * `guzzle_stack_constructor`
*/
protected function set_test_options($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
}
/**
* Requests the campaigns for the given account.
*
* @param array{status?:string} $params Set of arguments
* - status (optional)
* @return ResponseInterface
* @throw \Drip\Exception\InvalidArgumentException
*/
public function get_campaigns($params)
{
if (isset($params['status']) && !in_array($params['status'], ['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{campaign_id?:string} $params Set of arguments
* - campaign_id (required)
* @return 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
*
* @return 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<mixed> $params
* @return 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",
['subscribers' => [$params]],
self::POST
);
}
/**
* Sends a request to add/update a batch (up to 1000) of subscribers.
*
* @param array<mixed> $params
* @return 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<mixed> $params
* @return ResponseInterface
* @throw \Drip\Exception\InvalidArgumentException
*/
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 info regarding a particular subscriber subscriptions to campaigns.
*
* @param array<mixed> $params
* @return ResponseInterface
* @throw \Drip\Exception\InvalidArgumentException
*/
public function fetch_subscriber_campaigns($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}/campaign_subscriptions");
}
/**
* Returns a list of subscribers
*
* @return 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<mixed> $params
* @return ResponseInterface
* @throw \Drip\Exception\InvalidArgumentException
*/
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 = ['subscribers' => [$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<mixed> $params
* @return ResponseInterface
* @throw \Drip\Exception\InvalidArgumentException
*/
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 DELETE /:account_id/subscribers/:id_or_email to delete a subscriber.
*
* @param array<mixed> $params
* @return ResponseInterface
* @throw \Drip\Exception\InvalidArgumentException
*/
public function delete_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}", $params, self::DELETE);
}
/**
* This calls POST /:account_id/tags to add the tag. It just returns some status code no content
*
* @param array<mixed> $params
* @return ResponseInterface
* @throw \Drip\Exception\InvalidArgumentException
*/
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 = ['tags' => [$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
* @return ResponseInterface
* @throw \Drip\Exception\InvalidArgumentException
*/
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 = ['tags' => [$params]];
return $this->make_request("{$this->account_id}/tags", $req_params, self::DELETE);
}
/**
* Posts an event specified by the user.
*
* @param array $params
* @return ResponseInterface
* @throw \Drip\Exception\InvalidArgumentException
*/
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 = ['events' => [$params]];
return $this->make_request("{$this->account_id}/events", $req_params, self::POST);
}
/**
* Posts a v3 Shopper Activity event to signal a shopping cart has been created or updated.
* Valid actions: created or updated
* @see https://developer.drip.com/#cart-activity
* @param array $params
* @return ResponseInterface
* @throw \Drip\Exception\InvalidArgumentException
* @throws Exception
*/
public function create_or_update_cart($params)
{
if (strstr($this->api_end_point, '/v3') === false) {
throw new Exception(__CLASS__ . '::' . __METHOD__ . ' only supports the APIv3 endpoint.');
}
return $this->make_request("$this->account_id/shopper_activity/cart", $params, self::POST);
}
/**
* Posts a v3 Shopper Activity event to signal an order has been placed or moddifed.
* Valid actions: placed, updated, paid, fulfilled, refunded, or canceled
* @see https://developer.drip.com/#order-activity
* @param array $params
* @return ResponseInterface
* @throw \Drip\Exception\InvalidArgumentException
* @throws Exception
*/
public function create_or_update_order($params)
{
if (strstr($this->api_end_point, '/v3') === false) {
throw new Exception(__CLASS__ . '::' . __METHOD__ . ' only supports the APIv3 endpoint.');
}
return $this->make_request("$this->account_id/shopper_activity/order", $params, self::POST);
}
/**
* Posts a v3 Shopper Activity event to signal a product has been created, updated or deleted.
* Valid actions: created, updated or deleted
* @see https://developer.drip.com/#product-activity
* @param array $params
* @return ResponseInterface
* @throw \Drip\Exception\InvalidArgumentException
* @throws Exception
*/
public function create_or_update_product($params)
{
if (strstr($this->api_end_point, '/v3') === false) {
throw new Exception(__CLASS__ . '::' . __METHOD__ . ' only supports the APIv3 endpoint.');
}
return $this->make_request("$this->account_id/shopper_activity/product", $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;
}
/**
* Send a request.
*
* @param string $url
* @param array<mixed> $params
* @param string $req_method
* @return ResponseInterface
* @throws Exception
*/
protected function make_request($url, $params = [], $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 = [
'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,
];
if (!empty($this->api_key)) {
$req_params['auth'] = [$this->api_key, ''];
} else if (!empty($this->access_token)) {
$req_params['headers']['Authorization'] = 'Bearer ' . $this->access_token;
}
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");
// @codeCoverageIgnoreEnd
}
$res = $client->request($req_method, $url, $req_params);
return $this->is_success_response($res->getStatusCode()) ? new \Drip\SuccessResponse($url, $params, $res) : new \Drip\ErrorResponse($url, $params, $res);
}
}