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 AutomateWoo;
defined( 'ABSPATH' ) || exit;
/** * @class Integration_ActiveCampaign * * Updated in AutomateWoo version 6.1.0 to work with the ActiveCampaign * REST API instead of relying on the now abandoned SDK. * * @since 6.0.19 */ class Integration_ActiveCampaign extends Integration {
/** @var string */ public $integration_id = 'activecampaign';
/** @var string */ private $api_key;
/** @var string */ private $api_url;
/** @var int */ public $request_count = 1;
/** @var array */ private $active_tags = array();
/** * Constructor. * * @param string $api_url * @param string $api_key */ public function __construct( $api_url, $api_key ) { $this->api_url = trailingslashit( $api_url ) . 'api/3/'; $this->api_key = $api_key; }
/** * Test the current API key to confirm that AutomateWoo can communicate with the ActiveCampaign API * * @return bool */ public function test_integration(): bool { return 200 === $this->request( 'users/me' )->get_response_code(); }
/** * Check if the integration is enabled. * * @return bool */ public function is_enabled(): bool { return (bool) Options::activecampaign_enabled(); }
/** * Create or update a contact on ActiveCampaign * * @see https://developers.activecampaign.com/reference/create-a-new-contact * * @param string $email Email address for the contact * @param string $first_name First name for the contact * @param string $last_name Last name for the contact * @param string $phone Phone number for the contact * @param string $company Company for the contact * * @return bool|array An array containing contact details or false if unsuccessful */ public function sync_contact( $email, $first_name = false, $last_name = false, $phone = false, $company = false ) { $data = array( 'contact' => array( 'email' => $email, ), );
if ( $first_name ) { $data['contact']['firstName'] = $first_name; }
if ( $last_name ) { $data['contact']['lastName'] = $last_name; }
if ( $phone ) { $data['contact']['phone'] = $phone; }
$response = $this->request( 'contact/sync', $data, 'POST' )->get_body();
if ( ! isset( $response['contact']['id'] ) ) { return false; }
$contact = $response['contact'];
if ( $company && ! $this->sync_company( $contact['id'], $contact['orgid'], $company ) ) { return false; }
return $contact; }
/** * Sync a company record for a contact * * @see https://developers.activecampaign.com/reference/create-an-account-1 * * @param string $contact_id ID of the contact to sync company data for * @param string $current_company_id ID of the company currently associated with the contact ("0" = none) * @param string $company_name Name of the company to sync * * @return bool */ public function sync_company( $contact_id, $current_company_id, $company_name ): bool { $account = $this->get_account( $company_name, true );
if ( ! isset( $account['id'] ) ) { return false; }
if ( $current_company_id !== $account['id'] ) { // If an association already exists then it will need to be deleted before creating a new one. if ( $current_company_id !== '0' ) { if ( ! $this->delete_account_association( $contact_id ) ) { $this->log( esc_html__( 'There was an error when attempting to delete an association', 'automatewoo' ) );
return false; } }
$association = array( 'accountContact' => array( 'contact' => $contact_id, 'account' => $account['id'], ), );
$link_account = $this->request( 'accountContacts', $association, 'POST' )->get_body();
if ( ! isset( $link_account['accounts'][0]['id'] ) ) { return false; } }
return true; }
/** * Retreive an account based on the name * * @see https://developers.activecampaign.com/reference/list-all-accounts * * @param string $account_name Name of the account to search for * @param bool $create_missing_account If true then the account will be created if not found * * @return bool|array */ public function get_account( $account_name, $create_missing_account = false ) { $response = $this->request( 'accounts', array( 'search' => $account_name ) )->get_body();
if ( isset( $response['accounts'][0] ) ) { return $response['accounts'][0]; }
if ( $create_missing_account ) { $data = array( 'account' => array( 'name' => $account_name, ), );
$response = $this->request( 'accounts', $data, 'POST' )->get_body();
if ( isset( $response['account']['id'] ) ) { return $response['account']; } }
return false; }
/** * Delete a Contact/ Account association based on the Contact ID * * @see https://developers.activecampaign.com/reference/delete-an-association-1 * * @param string $contact_id ID of the contact to delete an account association for * * @return bool */ public function delete_account_association( $contact_id ): bool { $data = array( 'filters[contact]' => $contact_id, );
$response = $this->request( 'accountContacts', $data )->get_body();
if ( isset( $response['accountContacts'][0]['id'] ) ) { $response = $this->request( 'accountContacts/' . $response['accountContacts'][0]['id'], array(), 'DELETE' );
if ( $response->is_successful() ) { return true; } }
return false; }
/** * Get all lists from the ActiveCampaign API * * @see https://developers.activecampaign.com/reference/retrieve-all-lists * * @return array */ public function get_lists(): array { $cache = Cache::get_transient( 'ac_lists' ); if ( $cache ) { return $cache; }
$response = $this->request( 'lists' )->get_body();
if ( ! isset( $response['lists'] ) ) { $this->log( __( 'Unexpected response when trying to retrieve all lists', 'automatewoo' ) );
return []; }
$clean_lists = []; foreach ( $response['lists'] as $list ) { $clean_lists[ $list['id'] ] = $list['name']; }
Cache::set_transient( 'ac_lists', $clean_lists, 0.15 );
return $clean_lists; }
/** * Add a contact to a list * * @see https://developers.activecampaign.com/reference/update-list-status-for-contact * * @param string $contact ID of the contact to add to a list * @param string $list ID of the list to add the contact to * * @return bool */ public function add_contact_to_list( $contact, $list ) { $data = array( 'contactList' => array( 'list' => $list, 'contact' => $contact, 'status' => '1', ), );
return $this->request( 'contactLists', $data, 'POST' )->is_successful(); }
/** * Check is the contact exists in ActiveCampaign. * Result from API is cached for 5 minutes. * * @see https://developers.activecampaign.com/reference/list-all-contacts * * @param string $email The email address to look up * * @return bool|array False if contact is not found or the contact data if successful */ public function is_contact( $email ) { $cache_key = 'aw_ac_is_contact_' . md5( $email );
$cache = get_transient( $cache_key ); if ( $cache ) { return $cache === 'yes'; }
$contact = $this->get_contact( $email );
set_transient( $cache_key, false !== $contact ? 'yes' : 'no', MINUTE_IN_SECONDS * 5 );
return $contact; }
/** * Retreive data for an existing contact * * @param string $email The email address to retreive contact data for * * @return bool|array */ public function get_contact( $email ) { if ( ! is_email( $email ) ) { $this->log( __( 'Invalid email was supplied when checking if contact exists in ActiveCampaign', 'automatewoo' ) );
return false; }
$response = $this->request( 'contacts', array( 'email' => $email ) )->get_body();
return isset( $response['contacts'][0] ) ? $response['contacts'][0] : false; }
/** * Delete the transient for a given email address * * @param string $email The email address to clear the contact transient for * * @return void */ public function clear_contact_transients( $email ) { delete_transient( 'aw_ac_is_contact_' . md5( $email ) ); }
/** * Retreive all custom fields * * @see https://developers.activecampaign.com/reference/retrieve-fields * * @return array */ public function get_contact_custom_fields(): array { $cache = Cache::get_transient( 'ac_contact_fields' ); if ( $cache ) { return $cache; }
$response = $this->request( 'fields' )->get_body();
if ( ! isset( $response['fields'] ) ) { $this->log( __( 'Unexpected response when trying to retrieve all custom fields', 'automatewoo' ) );
return []; }
$fields = [];
foreach ( $response['fields'] as $item ) { $fields[ $item['id'] ] = $item; }
Cache::set_transient( 'ac_contact_fields', $fields, 0.15 );
return $fields; }
/** * Get a tag ID by its name * * @param string $tag Name of the tag to get the ID for * @param bool $create_missing_tag If true then the tag will be created if not found * @param bool $retry_on_error Whether to retry if an error occurs when creating a tag. It will clear the cache and try again. * * @return string|bool */ public function get_tag_id( $tag, $create_missing_tag = false, $retry_on_error = true ) { $transient = 'ac_tags';
if ( empty( $this->active_tags ) ) { $cache = Cache::get_transient( $transient ); if ( $cache ) { $this->active_tags = $cache; } else { $response = $this->paginated_request( 'tags' ); $this->active_tags = $response['tags'];
Cache::set_transient( $transient, $this->active_tags, 0.15 ); } }
$match = array_search( strtolower( $tag ), array_map( 'strtolower', array_column( $this->active_tags, 'tag' ) ), true );
if ( false !== $match ) { return $this->active_tags[ $match ]['id']; }
if ( $create_missing_tag ) { // Tag not found so we need to create it. $data = array( 'tag' => array( 'tag' => $tag, 'tagType' => 'contact', ), );
$response = $this->request( 'tags', $data, 'POST' )->get_body();
if ( ! isset( $response['tag']['id'] ) ) {
if ( isset( $response['error'] ) && strpos( $response['error'], 'Duplicate entry' ) !== false && $retry_on_error ) { // Somehow the tag was created by another process in the meantime or externally so we clear the cache and try again. Cache::delete_transient( $transient ); $this->active_tags = [];
return $this->get_tag_id( $tag, $create_missing_tag, false ); } // phpcs:disable WordPress.PHP.DevelopmentFunctions $this->log( 'Unexpected response when attempting to create a tag. Response: ' . print_r( $response, true ) . 'Tags: ' . print_r( $this->active_tags, true ) );
// phpcs:enable return false; }
$this->active_tags[] = $response['tag']; // Refresh cache to include new tag Cache::set_transient( $transient, $this->active_tags, 0.15 );
return $response['tag']['id']; }
return false; }
/** * Add tags to an existing contact * * @param string $contact ID of the contact to add tags to * @param array $tags An array of tags to add * * @return bool */ public function add_tags( $contact, $tags ) { if ( empty( $tags ) ) { return false; }
$successful = true;
foreach ( $tags as $tag ) { $tag_id = $this->get_tag_id( $tag, true );
if ( $tag_id ) { $data = [ 'contactTag' => array( 'contact' => $contact, 'tag' => $tag_id, ), ];
if ( ! $this->request( 'contactTags', $data, 'POST' )->is_successful() ) { $successful = false; } } }
return $successful; }
/** * Send a request to the ActiveCampaign API * * @see https://developers.activecampaign.com/reference/overview * * @param string $path Path to the API endpoint * @param array $data Data to include with the request * @param string $method The HTTP method for this request * * @return \ActiveCampaign|false */ public function request( $path, $data = [], $method = 'GET' ) { $url = $this->api_url . $path; $request_args = [ 'timeout' => 10, 'method' => $method, 'sslverify' => false, 'headers' => [ 'Api-Token' => $this->api_key, ], ];
++$this->request_count;
// avoid overloading the api if ( $this->request_count % 4 === 0 ) { sleep( 2 ); }
switch ( $method ) { case 'GET': // SEMGREP WARNING EXPLANATION // This is escaped with esc_url_raw, but semgrep only takes into consideration esc_url. $url = esc_url_raw( add_query_arg( array_map( 'urlencode', $data ), $url ) ); break; case 'DELETE': $request_args['method'] = 'DELETE'; break; default: $request_args['body'] = wp_json_encode( $data ); break; }
$response = new Remote_Request( $url, $request_args ); $this->maybe_log_request_errors( $response );
return $response; }
/** * Send a request to the ActiveCampaign API with pagination * * @see https://developers.activecampaign.com/reference/pagination * * @param string $path Path to the API endpoint * @param array $data Data to include with the request * @param string $method The HTTP method for this request * @param int $page The page to fetch. * @param array $results Accumulated results for all the pages. * * @return array */ public function paginated_request( $path, $data = [], $method = 'GET', $page = 0, $results = [] ) {
// Set offset based on the $page and the api_pagination_limit $data['limit'] = $this->get_api_pagination_limit(); $data['offset'] = $page * $this->get_api_pagination_limit();
// Get elements for the current page and add them to the results. $request = $this->request( $path, $data, $method )->get_body(); $results = array_merge( $results, $request[ $path ] );
// If there are more elements left. Fetch again with the next page. if ( $request['meta']['total'] > count( $results ) ) { return $this->paginated_request( $path, $data, $method, ++$page, $results ); }
return [ $path => $results, 'meta' => [ 'total' => $request['meta']['total'] ], ]; }
/** * @return void * @deprecated */ protected function get_sdk() { wc_deprecated_function( __METHOD__, '6.1.0', 'request' ); }
/** * Clear all cached data * * @return void */ public function clear_cache_data() { Cache::delete_transient( 'ac_lists' ); Cache::delete_transient( 'ac_tags' ); Cache::delete_transient( 'ac_contact_fields' ); }
/** * Get the pagination limit. * * @return int */ public function get_api_pagination_limit() {
/** * Filter the pagination limit for Active Campaign REST API. * * @since 6.0.31 * @filter automatewoo/integrations/active_campaign/pagination */ return apply_filters( 'automatewoo/integrations/active_campaign/pagination', 100 ); } }
|