-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclass-convertkit-api-v4.php
1839 lines (1521 loc) · 52.9 KB
/
class-convertkit-api-v4.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
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
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/**
* ConvertKit API class.
*
* @package ConvertKit
* @author ConvertKit
*/
/**
* ConvertKit API class
*
* @package ConvertKit
* @author ConvertKit
*/
class ConvertKit_API_V4 {
use ConvertKit_API_Traits;
/**
* The SDK version.
*
* @var string
*/
public const VERSION = '2.0.0';
/**
* Redirect URI.
*
* @var bool|string
*/
protected $redirect_uri = false;
/**
* Refresh token.
*
* @var bool|string
*/
protected $refresh_token = false;
/**
* Optional context of the request.
*
* @var bool|string
*/
protected $context = false;
/**
* Save debug data to log
*
* @var bool
*/
protected $debug = false;
/**
* The plugin name.
*
* @var bool|string
*/
protected $plugin_name;
/**
* The plugin path.
*
* @var bool|string
*/
protected $plugin_path;
/**
* The plugin URL.
*
* @var bool|string
*/
protected $plugin_url;
/**
* The plugin version.
*
* @var bool|string
*/
protected $plugin_version;
/**
* ConvertKit API endpoints that use the /oauth/ namespace
* i.e. https://api.kit.com/oauth/endpoint
*
* @since 2.0.0
*
* @var array
*/
protected $api_endpoints_oauth = array(
'token',
);
/**
* ConvertKit API endpoints that use the /wordpress/ namespace
* i.e. https://api.kit.com/wordpress/endpoint
*
* @since 1.3.0
*
* @var array
*/
protected $api_endpoints_wordpress = array(
'posts',
'products',
'profile/',
'recommendations_script',
'subscriber_authentication/send_code',
'subscriber_authentication/verify',
'accounts/oauth_access_token',
);
/**
* Holds the log class for writing to the log file
*
* @var bool|ConvertKit_Log|WC_Logger
*/
public $log = false;
/**
* Holds an array of error messages, localized to the plugin
* using this API class.
*
* @var bool|array
*/
public $error_messages = false;
/**
* Sets up the API with the required credentials.
*
* @since 1.0.0
*
* @param string $client_id OAuth Client ID.
* @param string $redirect_uri OAuth Redirect URI.
* @param bool|string $access_token ConvertKit OAuth Access Token.
* @param bool|string $refresh_token ConvertKit OAuth Refresh Token.
* @param bool|object $debug Save data to log.
* @param bool|string $context Context of originating request.
*/
public function __construct( $client_id, $redirect_uri, $access_token = false, $refresh_token = false, $debug = false, $context = false ) {
// Set API credentials, debugging and logging class.
$this->client_id = $client_id;
$this->redirect_uri = $redirect_uri;
$this->access_token = $access_token;
$this->refresh_token = $refresh_token;
$this->debug = $debug;
$this->context = $context;
$this->plugin_name = ( defined( 'CONVERTKIT_PLUGIN_NAME' ) ? CONVERTKIT_PLUGIN_NAME : false );
$this->plugin_path = ( defined( 'CONVERTKIT_PLUGIN_PATH' ) ? CONVERTKIT_PLUGIN_PATH : false );
$this->plugin_url = ( defined( 'CONVERTKIT_PLUGIN_URL' ) ? CONVERTKIT_PLUGIN_URL : false );
$this->plugin_version = ( defined( 'CONVERTKIT_PLUGIN_VERSION' ) ? CONVERTKIT_PLUGIN_VERSION : false );
// Setup logging class if the required parameters exist.
if ( $this->debug && $this->plugin_path !== false ) {
$this->log = new ConvertKit_Log( $this->plugin_path );
}
// Define translatable / localized error strings.
// WordPress requires that the text domain be a string (e.g. 'woocommerce-convertkit') and not a variable,
// otherwise localization won't work.
// phpcs:disable
$this->error_messages = array(
// form_subscribe().
'form_subscribe_form_id_empty' => __( 'form_subscribe(): the form_id parameter is empty.', 'convertkit' ),
'form_subscribe_email_empty' => __( 'form_subscribe(): the email parameter is empty.', 'convertkit' ),
// sequence_subscribe().
'sequence_subscribe_sequence_id_empty' => __( 'sequence_subscribe(): the sequence_id parameter is empty.', 'convertkit' ),
'sequence_subscribe_email_empty' => __( 'sequence_subscribe(): the email parameter is empty.', 'convertkit' ),
// tag_subscribe().
'tag_subscribe_tag_id_empty' => __( 'tag_subscribe(): the tag_id parameter is empty.', 'convertkit' ),
'tag_subscribe_email_empty' => __( 'tag_subscribe(): the email parameter is empty.', 'convertkit' ),
// tag_unsubscribe().
'tag_unsubscribe_tag_id_empty' => __( 'tag_unsubscribe(): the tag_id parameter is empty.', 'convertkit' ),
'tag_unsubscribe_email_empty' => __( 'tag_unsubscribe(): the email parameter is empty.', 'convertkit' ),
'tag_unsubscribe_email_invalid' => __( 'tag_unsubscribe(): the email parameter is not a valid email address.', 'convertkit' ),
// get_subscriber_by_email().
'get_subscriber_by_email_email_empty' => __( 'get_subscriber_by_email(): the email parameter is empty.', 'convertkit' ),
/* translators: Email Address */
'get_subscriber_by_email_none' => __( 'No subscriber(s) exist in ConvertKit matching the email address %s.', 'convertkit' ),
// get_subscriber_by_id().
'get_subscriber_by_id_subscriber_id_empty' => __( 'get_subscriber_by_id(): the subscriber_id parameter is empty.', 'convertkit' ),
// get_subscriber_tags().
'get_subscriber_tags_subscriber_id_empty' => __( 'get_subscriber_tags(): the subscriber_id parameter is empty.', 'convertkit' ),
// unsubscribe_email().
'unsubscribe_email_empty' => __( 'unsubscribe(): the email parameter is empty.', 'convertkit' ),
// broadcast_delete().
'broadcast_delete_broadcast_id_empty' => __( 'broadcast_delete(): the broadcast_id parameter is empty.', 'convertkit' ),
// get_all_posts().
'get_all_posts_posts_per_request_bound_too_low' => __( 'get_all_posts(): the posts_per_request parameter must be equal to or greater than 1.', 'convertkit' ),
'get_all_posts_posts_per_request_bound_too_high' => __( 'get_all_posts(): the posts_per_request parameter must be equal to or less than 50.', 'convertkit' ),
// get_posts().
'get_posts_page_parameter_bound_too_low' => __( 'get_posts(): the page parameter must be equal to or greater than 1.', 'convertkit' ),
'get_posts_per_page_parameter_bound_too_low' => __( 'get_posts(): the per_page parameter must be equal to or greater than 1.', 'convertkit' ),
'get_posts_per_page_parameter_bound_too_high' => __( 'get_posts(): the per_page parameter must be equal to or less than 50.', 'convertkit' ),
// subscriber_authentication_send_code().
'subscriber_authentication_send_code_email_empty' => __( 'subscriber_authentication_send_code(): the email parameter is empty.', 'convertkit' ),
'subscriber_authentication_send_code_redirect_url_empty' => __( 'subscriber_authentication_send_code(): the redirect_url parameter is empty.', 'convertkit' ),
'subscriber_authentication_send_code_redirect_url_invalid' => __( 'subscriber_authentication_send_code(): the redirect_url parameter is not a valid URL.', 'convertkit' ),
'subscriber_authentication_send_code_response_token_missing'=> __( 'subscriber_authentication_send_code(): the token parameter is missing from the API response.', 'convertkit' ),
// subscriber_authentication_verify().
'subscriber_authentication_verify_token_empty' => __( 'subscriber_authentication_verify(): the token parameter is empty.', 'convertkit' ),
'subscriber_authentication_verify_subscriber_code_empty' => __( 'subscriber_authentication_verify(): the subscriber_code parameter is empty.', 'convertkit' ),
'subscriber_authentication_verify_response_error' => __( 'The entered code is invalid. Please try again, or click the link sent in the email.', 'convertkit' ),
// profile().
'profiles_signed_subscriber_id_empty' => __( 'profiles(): the signed_subscriber_id parameter is empty.', 'convertkit' ),
// request().
/* translators: HTTP method */
'request_method_unsupported' => __( 'API request method %s is not supported in ConvertKit_API class.', 'convertkit' ),
'request_rate_limit_exceeded' => __( 'ConvertKit API Error: Rate limit hit.', 'convertkit' ),
'request_internal_server_error' => __( 'ConvertKit API Error: Internal server error.', 'convertkit' ),
'request_bad_gateway' => __( 'ConvertKit API Error: Bad gateway.', 'convertkit' ),
'response_type_unexpected' => __( 'ConvertKit API Error: The response is not of the expected type array.', 'convertkit' ),
);
// phpcs:enable
}
/**
* Generates and stores a code verifier for PKCE authentication flow.
*
* @since 2.0.0
*
* @return string
*/
private function generate_and_store_code_verifier() {
// If a code verifier already exists, use it.
$code_verifier = $this->get_code_verifier();
if ( $code_verifier ) {
return $code_verifier;
}
// Generate a random string.
$code_verifier = random_bytes( 64 );
// Encode to Base64 string.
$code_verifier = $this->base64_urlencode( $code_verifier );
// Store in database for later use.
update_option( 'ck_code_verifier', $code_verifier );
// Return.
return $code_verifier;
}
/**
* Base64URL the given code verifier, as PHP has no built in function for this.
*
* @since 2.0.0
*
* @param string $code_verifier Code Verifier.
* @return string Code Challenge.
*/
public function generate_code_challenge( $code_verifier ) {
// Hash using S256.
$code_challenge = hash( 'sha256', $code_verifier, true );
// Encode to Base64 string.
$code_challenge = base64_encode( $code_challenge ); // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions
// Convert Base64 to Base64URL by replacing “+” with “-” and “/” with “_”.
$code_challenge = strtr( $code_challenge, '+/', '-_' );
// Remove padding character from the end of line.
$code_challenge = rtrim( $code_challenge, '=' );
// Return.
return $code_challenge;
}
/**
* Returns the stored code verifier generated by generate_and_store_code_verifier().
*
* @since 2.0.0
*
* @return bool|string
*/
public function get_code_verifier() {
return get_option( 'ck_code_verifier' );
}
/**
* Deletes the stored code verifier generated by generate_code_verifier().
*
* @since 2.0.0
*
* @return bool
*/
private function delete_code_verifier() {
return delete_option( 'ck_code_verifier' );
}
/**
* Base64URL encode the given string.
*
* @since 2.0.0
*
* @param string $str String to encode.
* @return string Encoded string.
*/
public function base64_urlencode( $str ) {
// Encode to Base64 string.
$str = base64_encode( $str ); // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions
// Convert Base64 to Base64URL by replacing “+” with “-” and “/” with “_”.
$str = strtr( $str, '+/', '-_' );
// Remove padding character from the end of line.
$str = rtrim( $str, '=' );
return $str;
}
/**
* Returns the URL used to begin the OAuth process
*
* @since 2.0.0
*
* @param bool|string $return_url Return URL.
* @param bool|string $tenant_name Tenant Name (if specified, issues tokens specific to that name. Useful for using the same account on multiple sites).
* @return string OAuth URL
*/
public function get_oauth_url( $return_url = false, $tenant_name = false ) {
// Generate and store code verifier and challenge.
$code_verifier = $this->generate_and_store_code_verifier();
$code_challenge = $this->generate_code_challenge( $code_verifier );
// Build args.
$args = array(
'client_id' => $this->client_id,
'response_type' => 'code',
'redirect_uri' => rawurlencode( $this->redirect_uri ),
'code_challenge' => $code_challenge,
'code_challenge_method' => 'S256',
);
if ( $return_url ) {
$args['state'] = $this->base64_urlencode(
wp_json_encode(
array(
'return_to' => $return_url,
'client_id' => $this->client_id,
)
)
);
}
if ( $tenant_name ) {
$args['tenant_name'] = rawurlencode( $tenant_name );
}
// Return OAuth URL.
return add_query_arg(
$args,
$this->oauth_authorize_url
);
}
/**
* Exchanges the given code for an access token, refresh token and other data.
*
* @since 2.0.0
*
* @param string $authorization_code Authorization Code, returned from get_oauth_url() flow.
* @return WP_Error|array
*/
public function get_access_token( $authorization_code ) {
$result = $this->post(
'token',
array(
'client_id' => $this->client_id,
'grant_type' => 'authorization_code',
'code' => $authorization_code,
'redirect_uri' => $this->redirect_uri,
'code_verifier' => $this->get_code_verifier(),
)
);
// Delete code verifier, as it's no longer needed.
// If the access token request fails, the user
// will begin the process again, which generates a
// new code verifier.
$this->delete_code_verifier();
// If an error occured, log and return it now.
if ( is_wp_error( $result ) ) {
$this->log( 'API: Error: ' . $result->get_error_message() );
return $result;
}
/**
* Perform any actions with the new access token, such as saving it.
*
* @since 2.0.0
*
* @param array $result Access Token, Refresh Token, Expiry, Bearer and Scope.
* @param string $client_id OAuth Client ID.
*/
do_action( 'convertkit_api_get_access_token', $result, $this->client_id );
// Return.
return $result;
}
/**
* Fetches a new access token using the supplied refresh token.
*
* @since 2.0.0
*/
public function refresh_token() {
$result = $this->post(
'token',
array(
'client_id' => $this->client_id,
'grant_type' => 'refresh_token',
'refresh_token' => $this->refresh_token,
)
);
// If an error occured, log and return it now.
if ( is_wp_error( $result ) ) {
$this->log( 'API: Error: ' . $result->get_error_message() );
return $result;
}
// Store existing access and refresh tokens.
$previous_access_token = $this->access_token;
$previous_refresh_token = $this->refresh_token;
// Update the access and refresh tokens in this class.
$this->access_token = $result['access_token'];
$this->refresh_token = $result['refresh_token'];
/**
* Perform any actions with the new access token, such as saving it.
*
* @since 2.0.0
*
* @param array $result New Access Token, Refresh Token, Expiry, Bearer and Scope.
* @param string $client_id OAuth Client ID.
* @param string $previous_access_token Existing Access Token.
* @param string $previous_refresh_token Existing Refresh Token.
*/
do_action( 'convertkit_api_refresh_token', $result, $this->client_id, $previous_access_token, $previous_refresh_token );
// Return.
return $result;
}
/**
* Exchanges the given API Key for an Access Token.
*
* @since 2.0.0
*
* @param string $api_key API Key.
* @param string $api_secret API Secret.
* @return WP_Error|array
*/
public function get_access_token_by_api_key_and_secret( $api_key, $api_secret ) {
return $this->post(
'accounts/oauth_access_token',
array(
'api_key' => $api_key,
'api_secret' => $api_secret,
'client_id' => $this->client_id,
)
);
}
/**
* Creates the given subscriber, assiging them to the given ConvertKit Form.
*
* @since 1.0.0
*
* @param int $form_id Form ID.
* @param string $email Email Address.
* @param string $first_name First Name.
* @param array $custom_fields Custom Fields.
* @return WP_Error|array
*/
public function form_subscribe( $form_id, $email, $first_name = '', $custom_fields = array() ) {
// Create subscriber.
$subscriber = $this->create_subscriber( $email, $first_name, 'active', $custom_fields );
// Bail if an error occured.
if ( is_wp_error( $subscriber ) ) {
return $subscriber;
}
// Add subscriber to form.
return $this->add_subscriber_to_form( $form_id, $subscriber['subscriber']['id'] );
}
/**
* Creates the given subscriber, assiging them to the given ConvertKit Legacy Form.
*
* @since 2.0.0
*
* @param int $form_id Form ID.
* @param string $email Email Address.
* @param string $first_name First Name.
* @param array $custom_fields Custom Fields.
* @return WP_Error|array
*/
public function legacy_form_subscribe( $form_id, $email, $first_name = '', $custom_fields = array() ) {
// Create subscriber.
$subscriber = $this->create_subscriber( $email, $first_name, 'active', $custom_fields );
// Bail if an error occured.
if ( is_wp_error( $subscriber ) ) {
return $subscriber;
}
// Add subscriber to legacy form.
return $this->add_subscriber_to_legacy_form( $form_id, $subscriber['subscriber']['id'] );
}
/**
* Creates the given subscriber, assiging them to the given ConvertKit Tag.
*
* @since 1.0.0
*
* @param int $tag_id Tag ID.
* @param string $email Email Address.
* @param string $first_name First Name.
* @param array $custom_fields Custom Fields.
* @return WP_Error|array
*/
public function tag_subscribe( $tag_id, $email, $first_name = '', $custom_fields = array() ) {
// Create subscriber.
$subscriber = $this->create_subscriber( $email, $first_name, 'active', $custom_fields );
// Bail if an error occured.
if ( is_wp_error( $subscriber ) ) {
return $subscriber;
}
// Add subscriber to tag.
return $this->tag_subscriber( $tag_id, $subscriber['subscriber']['id'] );
}
/**
* Creates the given subscriber, assiging them to the given ConvertKit Sequence.
*
* @since 1.0.0
*
* @param int $sequence_id Sequence ID.
* @param string $email Email Address.
* @param string $first_name First Name.
* @param array $custom_fields Custom Fields.
* @return WP_Error|array
*/
public function sequence_subscribe( $sequence_id, $email, $first_name = '', $custom_fields = array() ) {
// Create subscriber.
$subscriber = $this->create_subscriber( $email, $first_name, 'active', $custom_fields );
// Bail if an error occured.
if ( is_wp_error( $subscriber ) ) {
return $subscriber;
}
// Add subscriber to sequence.
return $this->add_subscriber_to_sequence( $sequence_id, $subscriber['subscriber']['id'] );
}
/**
* Get the ConvertKit subscriber ID associated with email address if it exists.
* Return false if subscriber not found.
*
* @param string $email_address Email Address.
*
* @see https://developers.kit.com/v4.html#get-a-subscriber
*
* @return WP_Error|false|integer
*/
public function get_subscriber_id( string $email_address ) {
$subscribers = $this->get(
'subscribers',
array( 'email_address' => $email_address )
);
if ( is_wp_error( $subscribers ) ) {
return $subscribers;
}
if ( ! count( $subscribers['subscribers'] ) ) {
return false;
}
// Return the subscriber's ID.
return $subscribers['subscribers'][0]['id'];
}
/**
* Unsubscribe an email address.
*
* @param string $email_address Email Address.
*
* @see https://developers.kit.com/v4.html#unsubscribe-subscriber
*
* @return WP_Error|false|object
*/
public function unsubscribe_by_email( string $email_address ) {
// Get subscriber ID.
$subscriber_id = $this->get_subscriber_id( $email_address );
if ( is_wp_error( $subscriber_id ) ) {
return $subscriber_id;
}
return $this->post(
sprintf(
'subscribers/%s/unsubscribe',
(int) $subscriber_id
)
);
}
/**
* Gets all posts from the API.
*
* @since 1.0.0
*
* @param int $posts_per_request Number of Posts to fetch in each request.
* @return WP_Error|array
*/
public function get_all_posts( $posts_per_request = 50 ) {
// Sanitize some parameters.
$posts_per_request = absint( $posts_per_request );
// Sanity check that parameters aren't outside of the bounds as defined by the API.
if ( $posts_per_request < 1 ) {
return new WP_Error( 'convertkit_api_error', $this->get_error_message( 'get_all_posts_posts_per_request_bound_too_low' ) );
}
if ( $posts_per_request > 50 ) {
return new WP_Error( 'convertkit_api_error', $this->get_error_message( 'get_all_posts_posts_per_request_bound_too_high' ) );
}
// Define an array to store the posts in.
$posts = array();
// Mock the response to start the while loop.
$response = array(
'page' => 0, // Start on page zero, as the below loop will add 1 to this.
'total_pages' => 1, // We always know there will be one page of posts.
);
// Iterate through each page of posts.
while ( absint( $response['total_pages'] ) >= absint( $response['page'] ) + 1 ) {
// Fetch posts.
$response = $this->get_posts( absint( $response['page'] ) + 1, $posts_per_request );
// Bail if an error occured.
if ( is_wp_error( $response ) ) {
return $response;
}
// Exit loop if no posts exist.
if ( ! count( $response ) ) {
break;
}
// Append posts to array.
foreach ( $response['posts'] as $post ) {
$posts[ $post['id'] ] = $post;
}
}
// If no posts exist, log an error.
if ( ! count( $posts ) ) {
$this->log( 'API: get_posts(): Error: No broadcasts exist in ConvertKit.' );
}
// Return posts.
return $posts;
}
/**
* Get legacy forms.
*
* @param boolean $include_total_count To include the total count of records in the response, use true.
* @param string $after_cursor Return results after the given pagination cursor.
* @param string $before_cursor Return results before the given pagination cursor.
* @param integer $per_page Number of results to return.
*
* @since 2.0.0
*
* @return WP_Error|array
*/
public function get_legacy_forms(
bool $include_total_count = false,
string $after_cursor = '',
string $before_cursor = '',
int $per_page = 100
) {
return $this->get(
'landing_pages',
$this->build_total_count_and_pagination_params(
array(
'type' => 'embed',
),
$include_total_count,
$after_cursor,
$before_cursor,
$per_page
)
);
}
/**
* Get legacy landing pages.
*
* @param boolean $include_total_count To include the total count of records in the response, use true.
* @param string $after_cursor Return results after the given pagination cursor.
* @param string $before_cursor Return results before the given pagination cursor.
* @param integer $per_page Number of results to return.
*
* @since 2.0.0
*
* @return WP_Error|array
*/
public function get_legacy_landing_pages(
bool $include_total_count = false,
string $after_cursor = '',
string $before_cursor = '',
int $per_page = 100
) {
return $this->get(
'landing_pages',
$this->build_total_count_and_pagination_params(
array(
'type' => 'hosted',
),
$include_total_count,
$after_cursor,
$before_cursor,
$per_page
)
);
}
/**
* Gets posts from the API.
*
* @since 1.0.0
*
* @param int $page Page number.
* @param int $per_page Number of Posts to return.
* @return WP_Error|array
*/
public function get_posts( $page = 1, $per_page = 10 ) {
// Sanitize some parameters.
$page = absint( $page );
$per_page = absint( $per_page );
// Sanity check that parameters aren't outside of the bounds as defined by the API.
if ( $page < 1 ) {
return new WP_Error( 'convertkit_api_error', $this->get_error_message( 'get_posts_page_parameter_bound_too_low' ) );
}
if ( $per_page < 1 ) {
return new WP_Error( 'convertkit_api_error', $this->get_error_message( 'get_posts_per_page_parameter_bound_too_low' ) );
}
if ( $per_page > 50 ) {
return new WP_Error( 'convertkit_api_error', $this->get_error_message( 'get_posts_per_page_parameter_bound_too_high' ) );
}
$posts = array();
// Send request.
$response = $this->get(
'posts',
array(
'page' => $page,
'per_page' => $per_page,
)
);
// If an error occured, return WP_Error.
if ( is_wp_error( $response ) ) {
$this->log( 'API: get_posts(): Error: ' . $response->get_error_message() );
return $response;
}
// If the response isn't an array as we expect, log that no posts exist and return a blank array.
if ( ! is_array( $response['posts'] ) ) {
$this->log( 'API: get_posts(): Error: No broadcasts exist in ConvertKit.' );
return new WP_Error( 'convertkit_api_error', $this->get_error_message( 'response_type_unexpected' ) );
}
// If no posts exist, log that no posts exist and return a blank array.
if ( ! count( $response['posts'] ) ) {
$this->log( 'API: get_posts(): Error: No broadcasts exist in ConvertKit.' );
return $posts;
}
return $response;
}
/**
* Gets a specific post.
*
* @since 1.3.8
*
* @param int $post_id Post ID.
* @return WP_Error|array
*/
public function get_post( $post_id ) {
// Send request.
$response = $this->get(
sprintf( 'posts/%s', $post_id )
);
// If an error occured, return WP_Error.
if ( is_wp_error( $response ) ) {
$this->log( 'API: get_posts(): Error: ' . $response->get_error_message() );
return $response;
}
// If the response contains a message, an error occured.
// Log and return it now.
if ( array_key_exists( 'message', $response ) ) {
$error = new WP_Error(
'convertkit_api_error',
$response['message']
);
$this->log( 'API: get_post(): Error: ' . $error->get_error_message() );
return $error;
}
return $response['post'];
}
/**
* Fetches all products from the API.
*
* @since 1.1.0
*
* @return WP_Error|array
*/
public function get_products() {
$this->log( 'API: get_products()' );
$products = array();
$response = $this->get( 'products' );
// If an error occured, log and return it now.
if ( is_wp_error( $response ) ) {
$this->log( 'API: get_products(): Error: ' . $response->get_error_message() );
return $response;
}
// If the response isn't an array as we expect, log that no products exist and return a blank array.
if ( ! is_array( $response['products'] ) ) {
$this->log( 'API: get_products(): Error: No products exist in ConvertKit.' );
return new WP_Error( 'convertkit_api_error', $this->get_error_message( 'response_type_unexpected' ) );
}
// If no products exist, log that no products exist and return a blank array.
if ( ! count( $response['products'] ) ) {
$this->log( 'API: get_products(): Error: No products exist in ConvertKit.' );
return $products;
}
foreach ( $response['products'] as $product ) {
$products[ $product['id'] ] = $product;
}
return $products;
}
/**
* Sends an email to the given email address, which will contain a ConvertKit link
* which the subscriber can click to authenticate themselves.
*
* Upon successful authentication, the subscriber will be redirected from the ConvertKit
* link to the given redirect URL.
*
* @since 1.3.0
*
* @param string $email Email Address.
* @param string $redirect_url Redirect URL.
* @return WP_Error|string
*/
public function subscriber_authentication_send_code( $email, $redirect_url ) {
// Sanitize some parameters.
$email = trim( $email );
$redirect_url = trim( $redirect_url );
// Return error if no email address or redirect URL is specified.
if ( empty( $email ) ) {
return new WP_Error( 'convertkit_api_error', $this->get_error_message( 'subscriber_authentication_send_code_email_empty' ) );
}
if ( empty( $redirect_url ) ) {
return new WP_Error( 'convertkit_api_error', $this->get_error_message( 'subscriber_authentication_send_code_redirect_url_empty' ) );
}
// Return error if an invalid redirect URL is specified.
if ( ! filter_var( $redirect_url, FILTER_VALIDATE_URL ) ) {
return new WP_Error( 'convertkit_api_error', $this->get_error_message( 'subscriber_authentication_send_code_redirect_url_invalid' ) );
}
// Send request.
$response = $this->post(
'subscriber_authentication/send_code',
array(
'email_address' => $email,
'redirect_url' => $redirect_url,
)
);
// If an error occured, log and return it now.
if ( is_wp_error( $response ) ) {
$this->log( 'API: subscriber_authentication_send_code(): Error: ' . $response->get_error_message() );
return $response;
}
// Confirm that a token was supplied in the response.
if ( ! isset( $response['token'] ) ) {
$this->log( 'API: ' . $this->get_error_message( 'subscriber_authentication_send_code_response_token_missing' ) );
return new WP_Error( 'convertkit_api_error', $this->get_error_message( 'subscriber_authentication_send_code_response_token_missing' ) );
}
// Return token, which is used with the subscriber code (sent by email) when subsequently calling subscriber_authentication_verify().
return $response['token'];
}
/**
* Verifies the given token and subscriber code, which are included in the link
* sent by email in the subscriber_authentication_send_code() step.
*
* @since 1.3.0
*
* @param string $token Token.
* @param string $subscriber_code Subscriber Code.
* @return WP_Error|string
*/
public function subscriber_authentication_verify( $token, $subscriber_code ) {
// Sanitize some parameters.
$token = trim( $token );
$subscriber_code = trim( $subscriber_code );
// Return error if no email address or redirect URL is specified.
if ( empty( $token ) ) {
return new WP_Error( 'convertkit_api_error', $this->get_error_message( 'subscriber_authentication_verify_token_empty' ) );