-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlemonsqueezy-api.php
More file actions
3313 lines (2898 loc) · 160 KB
/
lemonsqueezy-api.php
File metadata and controls
3313 lines (2898 loc) · 160 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
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
/**
* Plugin Name: LemonSqueezy API WordPress
* Plugin URI: https://github.com/sinanisler/lemonsqueezy-api
* Description: Connect your WordPress site with LemonSqueezy API to automatically create user accounts when customers make a purchase. Uses scheduled API polling to monitor sales. NOW WITH IMPROVED RELIABILITY: Full pagination support, transaction verification, automatic retry mechanism, and bulletproof user creation!
* Version: 0.4
* Author: sinanisler
* Author URI: https://github.com/sinanisler
* License: GPL v2 or later
* License URI: https://www.gnu.org/licenses/gpl-2.0.html
* Text Domain: snn
*/
if (!defined('ABSPATH')) {
exit;
}
// Include GitHub auto-update functionality
require_once plugin_dir_path(__FILE__) . 'github-update.php';
class LemonSqueezy_API_WordPress {
private $option_name = 'lemonsqueezy_api_settings';
private $log_option_name = 'lemonsqueezy_api_logs';
public function __construct() {
// Admin menu
add_action('admin_menu', array($this, 'add_admin_menu'));
add_action('admin_init', array($this, 'register_settings'));
// Cron job for API-based sales fetching
add_action('lemonsqueezy_api_check_sales', array($this, 'check_recent_sales'));
add_filter('cron_schedules', array($this, 'add_custom_cron_interval'));
// Activation/Deactivation
register_activation_hook(__FILE__, array($this, 'activate'));
register_deactivation_hook(__FILE__, array($this, 'deactivate'));
// AJAX handlers
add_action('wp_ajax_lemonsqueezy_test_api', array($this, 'test_api_connection'));
add_action('wp_ajax_lemonsqueezy_clear_logs', array($this, 'clear_logs'));
add_action('wp_ajax_lemonsqueezy_fetch_products', array($this, 'fetch_products'));
add_action('wp_ajax_lemonsqueezy_uninstall_plugin', array($this, 'uninstall_plugin_data'));
// Add admin styles
add_action('admin_head', array($this, 'admin_styles'));
// Add plugin row meta for uninstall link
add_filter('plugin_row_meta', array($this, 'add_plugin_row_meta'), 10, 2);
// Subscription renewal redirect
add_action('template_redirect', array($this, 'check_subscription_renewal_redirect'));
}
/**
* Add admin styles
*/
public function admin_styles() {
$screen = get_current_screen();
if (strpos($screen->id, 'lemonsqueezy-api') === false) {
return;
}
?>
<style>
.snn-lemonsqueezy-stats-grid { display: grid; grid-template-columns: 1fr 1fr 1fr 1fr; gap: 20px; margin-bottom: 30px; }
.snn-lemonsqueezy-stat-card { background: #fff; color: #333; padding: 25px; border-radius: 8px; border: 1px solid #ddd; box-shadow: 0 2px 8px rgba(0,0,0,0.1); }
.snn-lemonsqueezy-stat-card-header { font-size: 14px; margin-bottom: 10px; color: #666; }
.snn-lemonsqueezy-stat-card-value { font-size: 22px; font-weight: bold; color: #000; }
.snn-lemonsqueezy-stat-card-footer { font-size: 12px; margin-top: 10px; color: #666; }
.snn-lemonsqueezy-section { padding: 20px; background: white; border: 1px solid #ccd0d4; margin-bottom: 20px; border-radius: 4px; }
.snn-lemonsqueezy-section h2 { margin-top: 0; padding-bottom: 10px; border-bottom: 2px solid #000; }
.snn-lemonsqueezy-recent-logs-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px; }
.snn-lemonsqueezy-recent-logs-header h2 { margin: 0; border-bottom: none; }
.snn-lemonsqueezy-products-notice { background: #f9f9f9; border-left: 4px solid #000; padding: 15px; margin: 20px 0; }
.snn-lemonsqueezy-products-loading { display: none; text-align: center; padding: 20px; }
.snn-lemonsqueezy-products-list { display: none; }
.snn-lemonsqueezy-products-list table { margin-top: 20px; }
.snn-lemonsqueezy-products-list th { padding: 10px; background: #f5f5f5; font-weight: 600; }
.snn-lemonsqueezy-products-list td { padding: 10px; vertical-align: top; }
.snn-lemonsqueezy-product-roles-checkboxes { }
.snn-lemonsqueezy-product-roles-checkboxes label { display: block; margin: 3px 0; font-weight: normal; }
.snn-lemonsqueezy-api-info { background: #f0f8ff; padding: 15px; border-left: 4px solid #000; }
.snn-lemonsqueezy-email-tags { margin-top: 15px; padding: 15px; background: #f0f0f1; border-left: 4px solid #000; }
.snn-lemonsqueezy-email-tags h4 { margin-top: 0; }
.snn-lemonsqueezy-email-tags ul { margin: 10px 0; padding-left: 20px; }
.snn-lemonsqueezy-search-filters { display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 15px; margin-bottom: 15px; }
.snn-lemonsqueezy-search-filters input { width: 100%; }
.snn-lemonsqueezy-search-actions { display: flex; gap: 10px; }
.snn-lemonsqueezy-search-total { margin-left: auto; align-self: center; color: #666; }
.snn-lemonsqueezy-log-entry { background: white; padding: 15px; margin-bottom: 10px; border: 1px solid #ccd0d4; border-radius: 4px; }
.snn-lemonsqueezy-log-header { cursor: pointer; display: flex; justify-content: space-between; align-items: center; }
.snn-lemonsqueezy-log-timestamp { margin-left: 15px; color: #666; font-size: 12px; }
.snn-lemonsqueezy-log-details { display: none; margin-top: 10px; padding-top: 10px; border-top: 1px solid #eee; }
.snn-lemonsqueezy-log-details pre { background: #f5f5f5; padding: 10px; overflow-x: auto; font-size: 12px; }
.snn-lemonsqueezy-user-entry { background: white; padding: 15px; margin-bottom: 10px; border: 1px solid #ccd0d4; border-radius: 4px; }
.snn-lemonsqueezy-user-entry:hover { box-shadow: 0 2px 4px rgba(0,0,0,0.1); transition: box-shadow 0.2s; }
.snn-lemonsqueezy-user-header { cursor: pointer; display: flex; justify-content: space-between; align-items: center; gap: 15px; }
.snn-lemonsqueezy-user-header:hover { background: #f9f9f9; }
.snn-lemonsqueezy-user-main-info { flex: 1; display: flex; align-items: center; gap: 15px; }
.snn-lemonsqueezy-user-meta-info { display: flex; gap: 15px; align-items: center; font-size: 12px; color: #666; }
.snn-lemonsqueezy-user-details { display: none; margin-top: 15px; padding-top: 15px; border-top: 1px solid #eee; }
.snn-lemonsqueezy-user-details-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 20px; }
.snn-lemonsqueezy-user-actions { margin-top: 20px; padding-top: 15px; border-top: 1px solid #eee; display: flex; gap: 10px; }
.snn-lemonsqueezy-user-details h3 { margin-top: 0; font-size: 14px; color: #000; }
.snn-lemonsqueezy-user-details table { font-size: 13px; }
.snn-lemonsqueezy-user-details th { width: 40%; padding: 8px; background: #f9f9f9; }
.snn-lemonsqueezy-user-details td { padding: 8px; }
.snn-lemonsqueezy-purchase-history { max-height: 200px; overflow-y: auto; border: 1px solid #ddd; border-radius: 4px; }
.snn-lemonsqueezy-purchase-history table { font-size: 12px; }
.snn-lemonsqueezy-purchase-history th { padding: 6px; background: #f5f5f5; }
.snn-lemonsqueezy-purchase-history td { padding: 6px; }
.snn-lemonsqueezy-raw-data { background: #f5f5f5; padding: 10px; border-radius: 4px; max-height: 300px; overflow-y: auto; }
.snn-lemonsqueezy-raw-data pre { margin: 0; font-size: 11px; white-space: pre-wrap; word-wrap: break-word; }
.snn-lemonsqueezy-pagination { padding: 15px; background: white; border: 1px solid #ccd0d4; border-radius: 4px; margin-top: 10px; }
.snn-lemonsqueezy-pagination .tablenav-pages { text-align: center; }
.snn-lemonsqueezy-pagination .page-numbers { padding: 5px 10px; margin: 0 2px; border: 1px solid #ccd0d4; background: white; text-decoration: none; display: inline-block; color: #000; }
.snn-lemonsqueezy-pagination .page-numbers.current { background: #000; color: white; border-color: #000; }
.snn-lemonsqueezy-pagination .page-numbers:hover:not(.current) { background: #f0f0f1; }
.snn-lemonsqueezy-settings-form { display: flex; align-items: center; gap: 15px; }
.snn-lemonsqueezy-no-results { background: white; padding: 20px; border: 1px solid #ccd0d4; border-radius: 4px; text-align: center; }
.snn-lemonsqueezy-email-status-yes { color: green; }
.snn-lemonsqueezy-email-status-no { color: #999; }
.snn-lemonsqueezy-user-email-preview { color: #666; margin-left: 10px; font-size: 13px; }
.snn-lemonsqueezy-user-username { font-size: 14px; }
.snn-lemonsqueezy-save-reminder { background: #f9f9f9; border-left: 4px solid #000; padding: 15px; margin: 15px 0; }
.snn-lemonsqueezy-spinner-container { text-align: center; padding: 20px; }
.snn-lemonsqueezy-wide-layout { width: 100%; max-width: none; }
</style>
<?php
}
/**
* Plugin activation
*/
public function activate() {
global $wpdb;
// Set default options
$default_options = array(
'access_token' => '',
'default_roles' => array('subscriber'),
'product_roles' => array(),
'product_auto_create' => array(), // Per-product auto create users setting
'products' => array(),
'cron_interval' => 120,
'sales_limit' => 50,
'send_welcome_email' => true,
'email_subject' => 'Welcome to {{site_name}}!',
'email_template' => $this->get_default_email_template(),
'log_limit' => 500,
'user_list_per_page' => 20,
'handle_refunds' => true,
'refund_action' => 'remove_roles',
'handle_subscriptions' => true,
'subscription_cancellation_action' => 'remove_roles',
'subscription_renewal_page' => '', // Page ID for subscription renewal redirect
'log_rotation_days' => 30
);
if (!get_option($this->option_name)) {
add_option($this->option_name, $default_options);
}
// Add database indexes for frequently queried meta keys
$this->add_meta_key_indexes();
// Schedule cron
$this->schedule_cron();
}
/**
* Add database indexes for frequently queried meta keys
*/
private function add_meta_key_indexes() {
global $wpdb;
// List of meta keys that are frequently queried
$meta_keys = array(
'lemonsqueezy_sale_id',
'lemonsqueezy_product_name',
'lemonsqueezy_created_date',
'lemonsqueezy_email_sent',
'lemonsqueezy_subscription_status',
'lemonsqueezy_sale_data'
);
// Check if indexes already exist and create them if needed
foreach ($meta_keys as $meta_key) {
$index_name = 'ls_' . md5($meta_key);
// Check if index exists
$index_exists = $wpdb->get_var($wpdb->prepare(
"SELECT COUNT(1)
FROM INFORMATION_SCHEMA.STATISTICS
WHERE table_schema = DATABASE()
AND table_name = %s
AND index_name = %s",
$wpdb->usermeta,
$index_name
));
// Create index if it doesn't exist
if (!$index_exists) {
// Direct query since index names can't be prepared
$wpdb->query(
"ALTER TABLE {$wpdb->usermeta}
ADD INDEX {$index_name} (meta_key(191), meta_value(100))"
);
}
}
}
/**
* Plugin deactivation
*/
public function deactivate() {
$timestamp = wp_next_scheduled('lemonsqueezy_api_check_sales');
if ($timestamp) {
wp_unschedule_event($timestamp, 'lemonsqueezy_api_check_sales');
}
}
/**
* Add custom cron interval
*/
public function add_custom_cron_interval($schedules) {
$settings = get_option($this->option_name);
$interval = isset($settings['cron_interval']) ? intval($settings['cron_interval']) : 120;
$schedules['lemonsqueezy_custom'] = array(
'interval' => $interval,
'display' => sprintf(__('Every %d seconds', 'snn'), $interval)
);
return $schedules;
}
/**
* Schedule cron job
*/
private function schedule_cron() {
$timestamp = wp_next_scheduled('lemonsqueezy_api_check_sales');
if ($timestamp) {
wp_unschedule_event($timestamp, 'lemonsqueezy_api_check_sales');
}
wp_schedule_event(time(), 'lemonsqueezy_custom', 'lemonsqueezy_api_check_sales');
}
/**
* Add admin menu
*/
public function add_admin_menu() {
add_menu_page(
__('LemonSqueezy API', 'snn'),
__('LemonSqueezy API', 'snn'),
'manage_options',
'lemonsqueezy-api-dashboard',
array($this, 'dashboard_page'),
'dashicons-cart',
120
);
add_submenu_page(
'lemonsqueezy-api-dashboard',
__('Dashboard', 'snn'),
__('Dashboard', 'snn'),
'manage_options',
'lemonsqueezy-api-dashboard',
array($this, 'dashboard_page')
);
add_submenu_page(
'lemonsqueezy-api-dashboard',
__('Settings', 'snn'),
__('Settings', 'snn'),
'manage_options',
'lemonsqueezy-api-settings',
array($this, 'settings_page')
);
add_submenu_page(
'lemonsqueezy-api-dashboard',
__('API Logs', 'snn'),
__('API Logs', 'snn'),
'manage_options',
'lemonsqueezy-api-logs',
array($this, 'logs_page')
);
add_submenu_page(
'lemonsqueezy-api-dashboard',
__('User List', 'snn'),
__('User List', 'snn'),
'manage_options',
'lemonsqueezy-api-users',
array($this, 'users_page')
);
add_submenu_page(
'lemonsqueezy-api-dashboard',
__('Uninstall Plugin', 'snn'),
__('Uninstall Plugin', 'snn'),
'manage_options',
'lemonsqueezy-api-uninstall',
array($this, 'uninstall_page')
);
}
/**
* Register settings
*/
public function register_settings() {
register_setting('lemonsqueezy_api_settings_group', $this->option_name);
}
/**
* Create HTTP headers for LemonSqueezy API requests
*/
private function get_api_headers($access_token) {
return array(
'Authorization' => 'Bearer ' . $access_token,
'Accept' => 'application/vnd.api+json',
'Content-Type' => 'application/vnd.api+json'
);
}
/**
* Parse LemonSqueezy JSON:API orders response
* Just returns raw data, no parsing bullshit
*/
private function parse_lemonsqueezy_orders($json_data) {
$orders = array();
if (!isset($json_data['data']) || !is_array($json_data['data'])) {
return $orders;
}
foreach ($json_data['data'] as $item) {
// Just return the entire raw item, fuck parsing
$orders[] = $item;
}
return $orders;
}
/**
* Extract subscription ID from order relationships
* Fetches subscriptions from the relationship link
*/
private function extract_subscription_id($order_item, $access_token = '') {
// Method 1: Try direct data field (some API responses include this)
if (isset($order_item['relationships']['subscription']['data']['id'])) {
return $order_item['relationships']['subscription']['data']['id'];
}
// Method 2: Fetch from subscriptions relationship link
if (isset($order_item['relationships']['subscriptions']['links']['related']) && !empty($access_token)) {
$subscriptions_url = $order_item['relationships']['subscriptions']['links']['related'];
$this->log_activity('FETCHING SUBSCRIPTIONS FROM RELATIONSHIP', array(
'url' => $subscriptions_url,
'order_id' => isset($order_item['id']) ? $order_item['id'] : 'unknown'
));
$response = wp_remote_get($subscriptions_url, array(
'headers' => $this->get_api_headers($access_token)
));
if (is_wp_error($response)) {
$this->log_activity('Subscription relationship fetch error', array(
'url' => $subscriptions_url,
'error' => $response->get_error_message()
));
return '';
}
$body = wp_remote_retrieve_body($response);
$data = json_decode($body, true);
// Log raw response for debugging
$this->log_activity('RAW SUBSCRIPTIONS RELATIONSHIP RESPONSE', array(
'url' => $subscriptions_url,
'raw_response' => $data
));
// Extract first subscription ID from the response
if (isset($data['data']) && is_array($data['data']) && !empty($data['data'])) {
$first_subscription = $data['data'][0];
if (isset($first_subscription['id'])) {
return $first_subscription['id'];
}
}
}
return '';
}
/**
* Fetch subscription data from LemonSqueezy API
*/
private function fetch_subscription($access_token, $subscription_id) {
if (empty($subscription_id) || empty($access_token)) {
return new WP_Error('invalid_params', 'Access token and subscription ID are required');
}
$url = "https://api.lemonsqueezy.com/v1/subscriptions/{$subscription_id}";
$this->log_activity('FETCHING SUBSCRIPTION', array(
'url' => $url,
'subscription_id' => $subscription_id
));
$response = wp_remote_get($url, array(
'headers' => $this->get_api_headers($access_token)
));
if (is_wp_error($response)) {
$this->log_activity('Subscription fetch error', array(
'subscription_id' => $subscription_id,
'url' => $url,
'error' => $response->get_error_message()
));
return $response;
}
$body = wp_remote_retrieve_body($response);
$data = json_decode($body, true);
// Log raw subscription data for debugging
$this->log_activity('RAW SUBSCRIPTION RESPONSE', array(
'subscription_id' => $subscription_id,
'url' => $url,
'raw_response' => $data
));
if (!isset($data['data'])) {
$error_msg = $this->get_api_error_message($data);
$this->log_activity('Subscription API error', array(
'subscription_id' => $subscription_id,
'error' => $error_msg,
'response' => $data
));
return new WP_Error('api_error', $error_msg);
}
return $data['data'];
}
/**
* Parse LemonSqueezy JSON:API user response
*/
private function parse_lemonsqueezy_user($json_data) {
if (!isset($json_data['data']['attributes'])) {
return null;
}
return array(
'id' => isset($json_data['data']['id']) ? $json_data['data']['id'] : '',
'name' => isset($json_data['data']['attributes']['name']) ? $json_data['data']['attributes']['name'] : '',
'email' => isset($json_data['data']['attributes']['email']) ? $json_data['data']['attributes']['email'] : ''
);
}
/**
* Parse LemonSqueezy JSON:API products response
*/
private function parse_lemonsqueezy_products($json_data) {
$products = array();
if (!isset($json_data['data'])) {
return $products;
}
foreach ($json_data['data'] as $item) {
if (!isset($item['type']) || $item['type'] !== 'products') {
continue;
}
$attrs = isset($item['attributes']) ? $item['attributes'] : array();
$products[] = array(
'id' => isset($item['id']) ? $item['id'] : '',
'name' => isset($attrs['name']) ? $attrs['name'] : '',
'published' => isset($attrs['status']) && $attrs['status'] === 'published'
);
}
return $products;
}
/**
* Get error message from LemonSqueezy JSON:API response
*/
private function get_api_error_message($json_data) {
if (isset($json_data['errors']) && is_array($json_data['errors'])) {
if (!empty($json_data['errors'][0]['detail'])) {
return $json_data['errors'][0]['detail'];
}
if (!empty($json_data['errors'][0]['title'])) {
return $json_data['errors'][0]['title'];
}
}
return 'Unknown API error';
}
/**
* Check recent sales via API (cron job) - IMPROVED WITH PAGINATION
*/
public function check_recent_sales() {
$settings = get_option($this->option_name);
$access_token = isset($settings['access_token']) ? $settings['access_token'] : '';
if (empty($access_token)) {
$this->log_activity('Cron error', array('error' => 'Access token not set'));
return;
}
// Fetch ALL orders with pagination support
$all_orders = $this->fetch_all_orders_with_pagination($access_token);
if (is_wp_error($all_orders)) {
$this->log_activity('Orders fetch error', array(
'error' => $all_orders->get_error_message()
));
return;
}
// Log first order completely raw
if (!empty($all_orders)) {
$this->log_activity('ORDERS FETCHED WITH PAGINATION', array(
'total_orders_fetched' => count($all_orders),
'first_order_sample' => $all_orders[0]
));
}
if (!empty($all_orders)) {
$new_sales_count = 0;
$failed_sales_count = 0;
$refunds_processed = 0;
$subscriptions_updated = 0;
$skipped_count = 0;
foreach ($all_orders as $sale) {
$sale_id = isset($sale['id']) ? $sale['id'] : '';
if (empty($sale_id)) {
continue;
}
// Extract attributes from JSON:API structure
$attrs = isset($sale['attributes']) ? $sale['attributes'] : array();
$email = isset($attrs['user_email']) ? sanitize_email($attrs['user_email']) : '';
// Handle refunds - check the 'refunded' boolean in attributes
if (isset($settings['handle_refunds']) && $settings['handle_refunds']) {
if (isset($attrs['refunded']) && $attrs['refunded'] === true) {
$refund_result = $this->handle_refund($sale);
if (!is_wp_error($refund_result)) {
$refunds_processed++;
}
continue;
}
}
// Handle subscription status changes - fetch actual subscription data
if (isset($settings['handle_subscriptions']) && $settings['handle_subscriptions']) {
// Extract subscription ID from relationships (pass access_token to fetch from links)
$subscription_id = $this->extract_subscription_id($sale, $access_token);
if (!empty($subscription_id)) {
// Fetch the actual subscription to check its status
$subscription = $this->fetch_subscription($access_token, $subscription_id);
if ($subscription && !is_wp_error($subscription)) {
$sub_attrs = isset($subscription['attributes']) ? $subscription['attributes'] : array();
$sub_status = isset($sub_attrs['status']) ? $sub_attrs['status'] : '';
// Check for subscription states that require action
if (in_array($sub_status, array('expired', 'unpaid'))) {
$sub_result = $this->handle_subscription_change($sale, $subscription);
if (!is_wp_error($sub_result)) {
$subscriptions_updated++;
}
continue;
} else if ($sub_status === 'cancelled') {
// Cancelled but check if grace period has ended
$ends_at = isset($sub_attrs['ends_at']) ? $sub_attrs['ends_at'] : '';
if (!empty($ends_at) && strtotime($ends_at) <= time()) {
// Grace period ended, treat as expired
$sub_result = $this->handle_subscription_change($sale, $subscription);
if (!is_wp_error($sub_result)) {
$subscriptions_updated++;
}
continue;
}
}
}
}
}
// Check processing status using improved tracking
$processing_status = $this->get_sale_processing_status($sale_id);
if ($processing_status === 'completed') {
// Verify user still exists
if (!empty($email)) {
$user = get_user_by('email', $email);
if ($user) {
$stored_sale_id = get_user_meta($user->ID, 'lemonsqueezy_sale_id', true);
if ($stored_sale_id === $sale_id) {
// User exists and matches - all good
$skipped_count++;
continue;
}
} else {
// User was deleted, mark for reprocessing
$this->update_sale_processing_status($sale_id, 'pending', 'User was deleted');
}
} else {
$skipped_count++;
continue;
}
}
// Process new or failed sales
if ($processing_status === 'pending' || $processing_status === 'failed') {
// Mark as processing to prevent duplicate processing
$this->update_sale_processing_status($sale_id, 'processing', 'Starting user creation');
// Add small delay between requests to avoid rate limiting
usleep(100000); // 0.1 seconds
$result = $this->process_sale($sale);
if (!is_wp_error($result)) {
// VERIFY user was actually created before marking as completed
if (!empty($email)) {
$user = get_user_by('email', $email);
if ($user) {
$stored_sale_id = get_user_meta($user->ID, 'lemonsqueezy_sale_id', true);
if ($stored_sale_id === $sale_id) {
// Success! User exists and matches
$this->update_sale_processing_status($sale_id, 'completed', 'User verified and created successfully');
$new_sales_count++;
} else {
// User exists but sale ID doesn't match - may be duplicate
$this->update_sale_processing_status($sale_id, 'failed', 'User exists but sale_id mismatch');
$failed_sales_count++;
}
} else {
// User creation returned success but user not found!
$this->update_sale_processing_status($sale_id, 'failed', 'User creation succeeded but user not found in database');
$failed_sales_count++;
$this->log_activity('CRITICAL: User creation verification failed', array(
'sale_id' => $sale_id,
'email' => $email,
'result' => $result
));
}
}
} else {
// Error during processing
$retry_count = $this->get_sale_retry_count($sale_id);
if ($retry_count < 3) {
$this->update_sale_processing_status($sale_id, 'failed', $result->get_error_message(), $retry_count + 1);
$this->log_activity('Sale processing failed - will retry', array(
'sale_id' => $sale_id,
'error' => $result->get_error_message(),
'retry_count' => $retry_count + 1
));
} else {
$this->update_sale_processing_status($sale_id, 'permanent_failure', $result->get_error_message(), $retry_count + 1);
$this->log_activity('Sale processing failed permanently', array(
'sale_id' => $sale_id,
'error' => $result->get_error_message(),
'retry_count' => $retry_count + 1
));
}
$failed_sales_count++;
}
}
}
// Cleanup old tracking entries (older than 90 days)
$this->cleanup_old_sale_tracking();
$this->log_activity('Cron completed', array(
'total_sales_fetched' => count($all_orders),
'new_sales_processed' => $new_sales_count,
'failed_sales' => $failed_sales_count,
'skipped_already_processed' => $skipped_count,
'refunds_processed' => $refunds_processed,
'subscriptions_updated' => $subscriptions_updated
));
}
// Also check existing users' subscriptions for status changes
if (isset($settings['handle_subscriptions']) && $settings['handle_subscriptions']) {
$subscriptions_checked = $this->check_existing_subscriptions($access_token);
if ($subscriptions_checked > 0) {
$this->log_activity('Existing subscriptions checked', array(
'total_checked' => $subscriptions_checked
));
}
}
}
/**
* Fetch all orders with pagination support
* LemonSqueezy API returns paginated results - we need to fetch ALL pages
*/
private function fetch_all_orders_with_pagination($access_token, $max_pages = 10) {
$all_orders = array();
$current_page = 1;
$has_more_pages = true;
while ($has_more_pages && $current_page <= $max_pages) {
$orders_url = 'https://api.lemonsqueezy.com/v1/orders?page[number]=' . $current_page . '&page[size]=100';
$this->log_activity('FETCHING ORDERS PAGE', array(
'url' => $orders_url,
'page' => $current_page
));
$response = wp_remote_get($orders_url, array(
'headers' => $this->get_api_headers($access_token),
'timeout' => 30
));
if (is_wp_error($response)) {
$this->log_activity('Orders page fetch error', array(
'page' => $current_page,
'error' => $response->get_error_message()
));
return $response;
}
$body = wp_remote_retrieve_body($response);
$data = json_decode($body, true);
// Check for JSON:API structure
if (!isset($data['data'])) {
$error_msg = $this->get_api_error_message($data);
$this->log_activity('Orders API error', array(
'page' => $current_page,
'error' => $error_msg,
'response' => $data
));
return new WP_Error('api_error', $error_msg);
}
// Parse and add orders from this page
$page_orders = $this->parse_lemonsqueezy_orders($data);
$all_orders = array_merge($all_orders, $page_orders);
// Check for pagination metadata
$meta = isset($data['meta']) ? $data['meta'] : array();
$page_info = isset($meta['page']) ? $meta['page'] : array();
$current_page_num = isset($page_info['currentPage']) ? intval($page_info['currentPage']) : $current_page;
$last_page = isset($page_info['lastPage']) ? intval($page_info['lastPage']) : 1;
$this->log_activity('Orders page fetched', array(
'current_page' => $current_page_num,
'last_page' => $last_page,
'orders_this_page' => count($page_orders),
'total_orders_so_far' => count($all_orders)
));
// Check if there are more pages
if ($current_page_num >= $last_page || empty($page_orders)) {
$has_more_pages = false;
} else {
$current_page++;
// Small delay to avoid rate limiting
usleep(200000); // 0.2 seconds between pages
}
}
if ($current_page > $max_pages) {
$this->log_activity('WARNING: Max pages limit reached', array(
'max_pages' => $max_pages,
'total_orders_fetched' => count($all_orders),
'note' => 'Some orders may have been missed. Increase max_pages if needed.'
));
}
return $all_orders;
}
/**
* Get sale processing status from database
* Returns: 'pending', 'processing', 'completed', 'failed', 'permanent_failure'
*/
private function get_sale_processing_status($sale_id) {
global $wpdb;
$status = $wpdb->get_var($wpdb->prepare(
"SELECT meta_value FROM {$wpdb->options} WHERE option_name = %s",
'lemonsqueezy_sale_status_' . $sale_id
));
if ($status === null) {
return 'pending'; // Not processed yet
}
$status_data = maybe_unserialize($status);
return isset($status_data['status']) ? $status_data['status'] : 'pending';
}
/**
* Update sale processing status in database
*/
private function update_sale_processing_status($sale_id, $status, $message = '', $retry_count = 0) {
$status_data = array(
'status' => $status,
'message' => $message,
'retry_count' => $retry_count,
'last_attempt' => current_time('mysql'),
'updated_at' => time()
);
update_option('lemonsqueezy_sale_status_' . $sale_id, $status_data, false);
}
/**
* Get retry count for a sale
*/
private function get_sale_retry_count($sale_id) {
global $wpdb;
$status = $wpdb->get_var($wpdb->prepare(
"SELECT meta_value FROM {$wpdb->options} WHERE option_name = %s",
'lemonsqueezy_sale_status_' . $sale_id
));
if ($status === null) {
return 0;
}
$status_data = maybe_unserialize($status);
return isset($status_data['retry_count']) ? intval($status_data['retry_count']) : 0;
}
/**
* Cleanup old sale tracking entries (older than 90 days)
*/
private function cleanup_old_sale_tracking() {
global $wpdb;
$cutoff_time = time() - (90 * DAY_IN_SECONDS);
// Get all sale status options
$options = $wpdb->get_results(
"SELECT option_name, option_value FROM {$wpdb->options}
WHERE option_name LIKE 'lemonsqueezy_sale_status_%'",
ARRAY_A
);
$deleted_count = 0;
foreach ($options as $option) {
$status_data = maybe_unserialize($option['option_value']);
$updated_at = isset($status_data['updated_at']) ? intval($status_data['updated_at']) : 0;
// Delete if older than 90 days and completed/permanent_failure
if ($updated_at < $cutoff_time) {
$status = isset($status_data['status']) ? $status_data['status'] : '';
if (in_array($status, array('completed', 'permanent_failure'))) {
delete_option($option['option_name']);
$deleted_count++;
}
}
}
if ($deleted_count > 0) {
$this->log_activity('Cleanup old sale tracking', array(
'deleted_count' => $deleted_count
));
}
}
/**
* Check existing users' subscriptions for status changes
* This catches subscription changes that may not appear in recent orders
*/
private function check_existing_subscriptions($access_token) {
if (empty($access_token)) {
return 0;
}
$settings = get_option($this->option_name);
// Get users with LemonSqueezy subscriptions who are still active (not marked as expired/unpaid)
$args = array(
'meta_query' => array(
'relation' => 'AND',
array(
'key' => 'lemonsqueezy_sale_data',
'compare' => 'EXISTS'
),
array(
'relation' => 'OR',
array(
'key' => 'lemonsqueezy_subscription_status',
'compare' => 'NOT EXISTS'
),
array(
'key' => 'lemonsqueezy_subscription_status',
'value' => array('expired', 'unpaid'),
'compare' => 'NOT IN'
)
)
),
'number' => 50, // Check 50 users per cron run to avoid timeouts
'fields' => 'ids' // Only fetch user IDs for better performance
);
$user_query = new WP_User_Query($args);
$user_ids = $user_query->get_results();
$checked_count = 0;
foreach ($user_ids as $user_id) {
// Get stored sale data
$sale_data_json = get_user_meta($user_id, 'lemonsqueezy_sale_data', true);
if (empty($sale_data_json)) {
continue;
}
$sale_data = json_decode($sale_data_json, true);
if (!$sale_data) {
continue;
}
// Extract subscription ID (pass access_token to fetch from links if needed)
$subscription_id = $this->extract_subscription_id($sale_data, $access_token);
if (empty($subscription_id)) {
continue; // Not a subscription purchase
}
// Fetch current subscription status
$subscription = $this->fetch_subscription($access_token, $subscription_id);
if (!$subscription || is_wp_error($subscription)) {
continue;
}
$sub_attrs = isset($subscription['attributes']) ? $subscription['attributes'] : array();
$sub_status = isset($sub_attrs['status']) ? $sub_attrs['status'] : '';
$ends_at = isset($sub_attrs['ends_at']) ? $sub_attrs['ends_at'] : '';
$checked_count++;
// Check if subscription needs action
if (in_array($sub_status, array('expired', 'unpaid'))) {
// Subscription has ended, remove roles
$result = $this->handle_subscription_change($sale_data, $subscription);
if (!is_wp_error($result)) {
$user = get_userdata($user_id);
$this->log_activity('Subscription auto-detected as ended', array(
'user_id' => $user_id,
'email' => $user ? $user->user_email : 'unknown',
'subscription_id' => $subscription_id,
'status' => $sub_status
));
}
} else if ($sub_status === 'cancelled' && !empty($ends_at) && strtotime($ends_at) <= time()) {
// Cancelled subscription, grace period ended
$result = $this->handle_subscription_change($sale_data, $subscription);
if (!is_wp_error($result)) {
$this->log_activity('Cancelled subscription grace period ended', array(
'user_id' => $user->ID,
'email' => $user->user_email,
'subscription_id' => $subscription_id,
'ends_at' => $ends_at
));
}
}
}
return $checked_count;
}
/**
* Process a sale and create/update user - IMPROVED WITH TRANSACTION SAFETY
*/
private function process_sale($sale_data) {
// Extract from attributes if exists
$attrs = isset($sale_data['attributes']) ? $sale_data['attributes'] : $sale_data;
$email = isset($attrs['user_email']) ? sanitize_email($attrs['user_email']) : '';
$product_name = isset($attrs['first_order_item']['product_name']) ? sanitize_text_field($attrs['first_order_item']['product_name']) : '';
$product_id = isset($attrs['first_order_item']['product_id']) ? strval($attrs['first_order_item']['product_id']) : '';
$sale_id = isset($sale_data['id']) ? $sale_data['id'] : '';
if (empty($email)) {
return new WP_Error('invalid_email', 'Email address is required');
}
if (empty($sale_id)) {
return new WP_Error('invalid_sale_id', 'Sale ID is required');
}
if (empty($product_id)) {
$this->log_activity('MISSING PRODUCT ID', array(
'email' => $email,
'raw_sale' => $sale_data
));