-
Notifications
You must be signed in to change notification settings - Fork 0
/
eacSoftwareRegistry_Subscription_Webhooks.php
executable file
·764 lines (690 loc) · 26.2 KB
/
eacSoftwareRegistry_Subscription_Webhooks.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
<?php
/**
* EarthAsylum Consulting {eac} Software Registration Server - {eac}SoftwareRegistry Subscriptions for WooCommerce
*
* Adds a custom WebHook to WooCommerce > Settings > Advanced > Webhooks for subscription updates.
* Extends the WooCommerce 'order.*' WebHooks by adding subscription data to orders with subscriptions.
* Adds product meta-data to subscriptions and/or orders.
*
* Uses subscriptions in WooCommerce Payments and assumed to work with WooCommerce Subscriptions
*
* @category WordPress Plugin
* @package {eac}SoftwareRegistry\Webhook
* @author Kevin Burkholder <KBurkholder@EarthAsylum.com>
* @copyright Copyright (c) 2024 EarthAsylum Consulting <www.earthasylum.com>
* @version 2.x
*
* @wordpress-plugin
* Plugin Name: {eac}SoftwareRegistry Subscription WebHooks
* Description: Software Registration Server Subscription Webhooks for WooCommerce - adds a custom Webhook topic for subscription updates to WooCommerce Webhooks.
* Version: 2.1.0
* Requires at least: 5.8.0
* Tested up to: 6.6
* Requires PHP: 7.4
* WC requires at least: 7.0
* WC tested up to: 9.1
* Plugin URI: https://swregistry.earthasylum.com/subscriptions-for-woocommerce/
* Author: EarthAsylum Consulting
* Author URI: http://www.earthasylum.com
* License: GPLv3 or later
* License URI: https://www.gnu.org/licenses/gpl.html
* Text Domain: eacsoftwareregistry-subscription-webhooks
* Domain Path: /languages
*/
namespace EarthAsylumConsulting;
class eacSoftwareRegistry_Subscription_Webhooks
{
/**
* constructor method
*
* Add filters and actions for our custom webhook
*
* @return void
*/
public function __construct()
{
// declare compatibility with WooCommerce 9.0/HPOS
add_action('before_woocommerce_init', function()
{
if ( class_exists( \Automattic\WooCommerce\Utilities\FeaturesUtil::class ) ) {
\Automattic\WooCommerce\Utilities\FeaturesUtil::declare_compatibility( 'custom_order_tables', __FILE__, true );
}
});
if (is_admin())
{
// on plugin_action_links_ filter, add 'Settings' link
add_filter( 'plugin_action_links_' . plugin_basename( __FILE__ ),
array( $this, 'plugin_action_links' ), 20, 3 );
// add our order webhook options
add_action( 'woocommerce_webhook_options', array( $this, 'add_webhook_options' ));
// save our order webhook options
add_action( 'woocommerce_webhook_options_save', array( $this, 'save_webhook_options' ));
}
add_action( 'plugins_loaded', array( $this, 'set_actions_and_filters' ) );
// add our custom webhook topic
add_filter( 'woocommerce_webhook_topics', array( $this, 'add_webhook_topic' ));
}
/**
* add actions/filters for subscriptions
*
* Add filters and actions for our custom webhook
*
* @return void
*/
public function set_actions_and_filters()
{
// trigger our webhook from wc subscription hook
if ( function_exists('\wcs_get_subscription') )
{
add_action( 'woocommerce_subscription_status_updated', array( $this, 'subscription_updated_wc' ), 10, 3 );
}
// trigger our webhooks from sumo subscription hook(s)
if ( class_exists('\SUMOSubscriptions',false) )
{
add_action( 'sumosubscriptions_subscription_created', function($sub_id)
{
remove_action( 'sumosubscriptions_active_subscription', array($this,'subscription_updated_sumo'), 20,1 );
$this->subscription_updated_sumo($sub_id);
}, 20, 1 );
add_action( 'sumosubscriptions_subscription_resumed', function($sub_id)
{
remove_action( 'sumosubscriptions_active_subscription', array($this,'subscription_updated_sumo'), 20,1 );
$this->subscription_updated_sumo($sub_id);
}, 20, 1 );
// add_action( 'sumosubscriptions_subscription_paused', array( $this, 'subscription_updated_sumo' ), 20, 1 );
// add_action( 'sumosubscriptions_subscription_cancelled', array( $this, 'subscription_updated_sumo' ), 20, 1 );
add_action( 'sumosubscriptions_subscription_expired', array( $this, 'subscription_updated_sumo' ), 20, 1 );
add_action( 'sumosubscriptions_active_subscription', array( $this, 'subscription_updated_sumo' ), 20, 1 );
add_action( 'sumosubscriptions_pause_subscription', array( $this, 'subscription_updated_sumo' ), 20, 1 );
add_action( 'sumosubscriptions_cancel_subscription', array( $this, 'subscription_updated_sumo' ), 20, 1 );
}
// filter the webhook payload for our's and for order webhooks
add_filter( 'woocommerce_webhook_payload', array( $this, 'get_webhook_payload' ), 10, 4 );
// get webhook delivery response - $http_args, $response, $duration, $arg, $this->get_id() );
add_action( 'woocommerce_webhook_delivery', array( $this, 'get_webhook_response' ), 10, 5 );
}
/**
* on plugin_action_links_ filter, add 'Settings' & 'Support' link
*
* @param array $pluginLinks Default links
* @return array with added link
*/
public function plugin_action_links( $pluginLinks, $pluginFile, $pluginData )
{
if (empty($pluginData)) return $pluginLinks;
$query = array(
'page' => 'wc-settings',
'tab' => 'advanced',
'section' => 'webhooks',
);
$settings_url = sprintf(
'<a href="%s" title="%s">%s</a>',
esc_url( add_query_arg( $query,self_admin_url( 'admin.php' ) ) ),
/* translators: %s: WooCommerce */
esc_attr( sprintf( __( "%s Webhooks", 'eacsoftwareregistry-subscription-webhooks' ),'WooCommerce' ) ),
__( 'Settings', 'eacsoftwareregistry-subscription-webhooks' )
);
$website_url = sprintf(
'<a href="%s" title="%s">%s</a>',
esc_url( "https://swregistry.earthasylum.com/{$pluginData['slug']}" ),
/* translators: %s: this Plugin name */
esc_attr( sprintf( __( "%s Documentation", 'eacsoftwareregistry-subscription-webhooks' ), $pluginData['Name'] ) ),
__( 'Docs', 'eacsoftwareregistry-subscription-webhooks' )
);
$support_url = sprintf(
/* translators: %s: support url, %s: title, %s: link display */
'<a href="%s" title="%s">%s</a>',
esc_url( "https://wordpress.org/support/plugin/{$pluginData['slug']}" ),
/* translators: %s: this Plugin name */
esc_attr( sprintf( __( "%s Support", 'eacsoftwareregistry-subscription-webhooks' ), $pluginData['Name'] ) ),
__( 'Support', 'eacsoftwareregistry-subscription-webhooks' )
);
return array_merge( [$settings_url, $website_url, $support_url], $pluginLinks );
}
/**
* Add webhook options to admin page
*
* @return void
*/
public function add_webhook_options( $topics )
{
$webhook_id = absint( $_GET['edit-webhook'] );
$sub_options = \get_option('eacSoftwareRegistry_subscription_options_'.$webhook_id,[]);
$options = [
[
'NEWORDER',
__('Append related subscriptions to orders','eacsoftwareregistry-subscription-webhooks'),
in_array('NEWORDER',$sub_options) ? ' checked=checked' : '',
],
[
'RENEWAL',
__('Append related subscriptions to renewals','eacsoftwareregistry-subscription-webhooks'),
in_array('RENEWAL',$sub_options) ? ' checked=checked' : '',
],
[
'METADATA',
__('Append product meta data to all orders','eacsoftwareregistry-subscription-webhooks'),
in_array('METADATA',$sub_options) ? ' checked=checked' : '',
],
]
?>
<div id="webhook-subscription-options" style="display: none;"">
<h4><?php esc_html_e( '{eac}SoftwareRegistry Subscription WebHooks', 'woocommerce' ); ?></h4>
<table class="form-table">
<tbody>
<tr valign="top">
<th scope="row" class="titledesc">
<label for="eacSoftwareRegistry_subscription_options">
<?php esc_html_e( 'Order Options', 'eacsoftwareregistry-subscription-webhooks' ); ?>
<?php echo wc_help_tip( __( 'Append subscription record(s) to orders with related subscriptions. Append custom fields and attributes from products ordered to order records;', 'eacsoftwareregistry-subscription-webhooks' ) ); ?>
</label>
</th>
<td class="forminp">
<?php
foreach ($options as $x => $option) {
echo "<span style='display: block;'><input type='checkbox' name='eacSoftwareRegistry_subscription_options[]' id='eacSoftwareRegistry_subscription_options_{$x}' value='{$option[0]}'{$option[2]}><label for='eacSoftwareRegistry_subscription_options_{$x}'>{$option[1]}</label></span>\n";
}
?>
</td>
</tr>
</tbody>
</table>
<script type="text/javascript">
jQuery( function ( $ ) {
$( '#webhook-options' ).find( '#webhook_topic' ).on( 'change', function() {
var current = $( this ).val(),
subscriptions_field = $( '#webhook-options' ).find( '#webhook-subscription-options' );
subscriptions_field.hide();
if ( current.match(/^order\.(created|updated|restored)$/) ) {
subscriptions_field.show();
}
}).trigger( 'change' );
});
</script>
</div>
<?php
}
/**
* save webhook options to admin page
*
* @param int $webhook_id
* @return void
*/
public function save_webhook_options( $webhook_id )
{
$webhook = wc_get_webhook( $webhook_id );
$topic = $webhook->get_topic();
if (preg_match('/^order\.(created|updated|restored)$/',$topic))
{
$options = $_POST['eacSoftwareRegistry_subscription_options'] ?? null;
if ( !empty($options) && is_array($options) )
{
$options = array_filter($options, function($value)
{
return (in_array($value,['NEWORDER','RENEWAL','METADATA']));
}
);
\update_option('eacSoftwareRegistry_subscription_options_'.$webhook_id,$options);
}
else
{
\delete_option('eacSoftwareRegistry_subscription_options_'.$webhook_id);
}
}
}
/**
* Add webhook topic to drop-down list.
* Custom topics are prefixed with woocommerce_ or wc_ are valid.
*
* @param array $topics array of current topics
* @return array $topics
*/
public function add_webhook_topic( $topics )
{
// using WooCommerce Subscriptions
if ( function_exists('\wcs_get_subscription') )
{
$topics['action.wc_eacswregistry_subscription'] = __('{eac}SoftwareRegistry WC Subscription','eacsoftwareregistry-subscription-webhooks');
}
// Using SUMO Subscriptions
if ( class_exists('\SUMOSubscriptions',false) )
{
$topics['action.wc_eacswregistry_sumosub'] = __('{eac}SoftwareRegistry Sumo Subscription','eacsoftwareregistry-subscription-webhooks');
}
return $topics;
}
/**
* subscription updated (wc)
*
* triggered by woocommerce_subscription_status_updated
* triggers custom webhook wc_eacswregistry_subscription
*
* @param object $subscription WC_Subscription
* @param string $newStatus new status
* @param string $oldStatus old status
* @return void
*/
public function subscription_updated_wc( $subscription, $newStatus=null, $oldStatus=null )
{
$this->logDebug($subscription,__METHOD__.' '.current_action());
do_action('wc_eacswregistry_subscription', [$subscription->get_id(),current_action()] );
}
/**
* subscription updated (sumo)
*
* triggered by ***
* triggers custom webhook wc_eacswregistry_sumosub
*
* @param string $sub_id subscription post id
* @return void
*/
public function subscription_updated_sumo( $sub_id )
{
$this->logDebug($sub_id,__METHOD__.' '.current_action());
do_action('wc_eacswregistry_sumosub', [$sub_id,current_action()] );
}
/**
* Get the webhook response
*
* @param array $http_args
* @param array $response
* @param float $duration
* @param string $post_id
* @param int $webhook_id
*/
public function get_webhook_response( $http_args, $response, $duration, $post_id, $webhook_id )
{
$this->logDebug([$response['response'],json_decode($response['body'])],__METHOD__.' '.current_action());
}
/**
* Get the payload data for our webhook
*
* WebHook topic header = 'X-Wc-Webhook-Topic: action.wc_eacswregistry_subscription',
* WebHook topic header = 'X-Wc-Webhook-Topic: action.wc_eacswregistry_sumosub',
*
* @param array $payload ['action'=>,'arg'=>]
* @param string $resource 'action', 'order'
* @param int $resource_id subscription or order id
* @param int $webhook_id
* @return array $payload
*/
public function get_webhook_payload( $payload, $resource, $resource_id, $webhook_id )
{
$webhook = wc_get_webhook( $webhook_id );
// switch to the user who created the webhook
$current_user = get_current_user_id();
wp_set_current_user( $webhook->get_user_id() );
$version = str_replace( 'wp_api_', '', $webhook->get_api_version() );
/*
* custom subscription actions: wc_eacswregistry_subscription, wc_eacswregistry_sumosub
*/
if ( $resource == 'action' && is_array($resource_id) )
{
list ($resource_id,$current_action) = $resource_id;
if ( $payload['action'] == 'wc_eacswregistry_subscription' )
// wc subscription update - get subscription order and overlay additional subscription data
{
$subscription = new \WC_Subscription($resource_id);
$payload = array_merge(
$this->get_endpoint_data( $version, 'order', $resource_id ),
$this->get_subscription_data_wc($subscription)
);
$payload['current_action'] = $current_action;
$payload['related_orders'] = $this->get_related_orders_wc($subscription);
}
else if ( $payload['action'] == 'wc_eacswregistry_sumosub' )
// sumo subscription update - get subscription order and overlay additional subscription data
{
$subscription = get_post($resource_id); //new \sumo_get_subscription($resource_id);
// initial order (created subscription)
$parent = get_post_meta( $subscription->ID, 'sumo_get_parent_order_id', true );
// last renewal order (or parent)
$renewal = get_post_meta( $subscription->ID, 'sumo_get_renewal_id', true ) ?: $parent;
// endpoint renewal order
$order = $this->get_endpoint_data( $version, 'order', $renewal );
if (empty($order['parent_id'])) $order['parent_id'] = $order['id'];
$payload = array_merge(
$order,
$this->get_subscription_data_sumo($subscription,$renewal)
);
// trigger update (renew/revise) by setting post_id
if (!strpos($current_action,'_created')) {
$payload['post_id'] = $order['id'];
}
$payload['current_action'] = $current_action;
$payload['related_orders'] = $this->get_related_orders_sumo($subscription);
}
}
/*
* Woo order hook(s): order.created, order.updated, order.deleted, order.restored
*/
else if ( $resource == 'order' && is_numeric($resource_id) )
{
$sub_options = \get_option('eacSoftwareRegistry_subscription_options_'.$webhook_id,[]);
if (in_array('RENEWAL',$sub_options)) // append subscription to renewal order
{
if (function_exists('\wcs_order_contains_renewal') && \wcs_order_contains_renewal($resource_id))
{
$payload['subscriptions'] = $this->get_wc_subscriptions( $resource_id, 'RENEWAL' );
}
else if (function_exists('\sumosubs_is_renewal_order') && \sumosubs_is_renewal_order($resource_id))
{
$payload['post_id'] = $payload['id'];
$payload['created_via'] = 'subscription';
$payload['subscriptions'] = $this->get_sumo_subscriptions( $resource_id, 'RENEWAL');
}
}
else if (in_array('NEWORDER',$sub_options)) // append subscription to new order
{
if (function_exists('\wcs_order_contains_subscription') && \wcs_order_contains_subscription($resource_id))
{
$payload['subscriptions'] = $this->get_wc_subscriptions( $resource_id, 'NEWORDER' );
}
else if (function_exists('\sumo_order_contains_subscription') && \sumo_order_contains_subscription($resource_id))
{
unset($payload['post_id']);
$payload['subscriptions'] = $this->get_sumo_subscriptions( $resource_id, 'NEWORDER');
}
}
if (in_array('METADATA',$sub_options)) // append order productt(s) meta-data
{
$payload['product_meta'] = $this->get_product_meta(wc_get_order($resource_id));
}
}
// Restore the current user.
wp_set_current_user( $current_user );
$this->logDebug($payload,__METHOD__.' '.$resource.' '.current_action());
return $payload;
}
/**
* Get payload data (support legacy api)
*
* @param string $version API version
* @param string $resource 'order'
* @param string $resource_id order id
* @return array endpoint version of order record
*/
private function get_endpoint_data( $version, $resource, $resource_id )
{
if ( ! is_null( wc()->api ) ) // legacy api
{
try {
return wc()->api->get_endpoint_data( "/wc/{$version}/{$resource}s/{$resource_id}" );
} catch (\Throwable $e) {$this->logDebug($e);}
}
try {
$RestApiUtil = new \Automattic\WooCommerce\Utilities\RestApiUtil();
return $RestApiUtil->get_endpoint_data("/wc/{$version}/{$resource}s/{$resource_id}" );
} catch (\Throwable $e) {$this->logDebug($e);}
}
/**
* Get subscription records (wc)
*
* @param array $resource_id order id
* @param string $type NEWORDER | RENEWAL
* @return array subscription records array
*/
private function get_wc_subscriptions( $resource_id, $type )
{
$subs = ($type == 'NEWORDER')
? \wcs_get_subscriptions_for_order($resource_id)
: \wcs_get_subscriptions_for_renewal_order($resource_id);
$payload = array();
foreach ($subs as $sub)
{
$payload[ $sub->get_id() ] = array_merge(
$this->get_endpoint_data( $version, 'order', $sub->get_id() ),
$this->get_subscription_data_wc($sub)
);
}
return $payload;
}
/**
* Get subscription records (sumo)
*
* @param array $resource_id order id
* @param string $type NEWORDER | RENEWAL
* @return array subscription records array
*/
private function get_sumo_subscriptions( $resource_id, $type )
{
$order = wc_get_order($resource_id);
$parent = $order->get_parent_id();
$parent = ($parent) ? wc_get_order($parent) : $order;
$payload = array();
$related = $parent->get_meta('sumo_subsc_get_available_postids_from_parent_order');
if (!empty($related))
{
foreach ($related as $id) {
$sub = get_post($id);
$payload[$id] = array_merge(
(array)$sub,
$this->get_subscription_data_sumo($sub,$order)
);
}
}
return $payload;
}
/**
* Get subscription data to add to the payload (wc)
*
* @param array $subscription WC_Subscription
* @return array subscription data array
*/
private function get_subscription_data_wc( $subscription )
{
return [ // dates are UTC/GMT
'status' => strtolower($subscription->get_status()),
'date_created' => $this->dateFormat( $subscription->get_date('date_created') ),
'date_modified' => $this->dateFormat( $subscription->get_date('date_modified') ),
'date_paid' => $this->dateFormat( $subscription->get_date('date_paid') ),
'date_completed' => $this->dateFormat( $subscription->get_date('date_completed') ),
'last_order_id' => $subscription->get_last_order(),
'last_order_date_created' => $this->dateFormat( $subscription->get_date('last_order_date_created') ),
'last_order_date_paid' => $this->dateFormat( $subscription->get_date('last_order_date_paid') ),
'last_order_date_completed' => $this->dateFormat( $subscription->get_date('last_order_date_completed') ),
'schedule_trial_end' => $this->dateFormat( $subscription->get_date('schedule_trial_end') ),
'schedule_start' => $this->dateFormat( $subscription->get_date('schedule_start') ),
'schedule_end' => $this->dateFormat( $subscription->get_date('schedule_end') ),
'schedule_cancelled' => $this->dateFormat( $subscription->get_date('schedule_cancelled') ),
'schedule_next_payment' => $this->dateFormat( $subscription->get_date('schedule_next_payment') ),
'schedule_payment_retry' => $this->dateFormat( $subscription->get_date('schedule_payment_retry') ),
'billing_period' => $subscription->get_billing_period(),
'billing_interval' => $subscription->get_billing_interval(),
'sign_up_fee' => $subscription->get_sign_up_fee(),
'product_meta' => $this->get_product_meta($subscription),
];
}
/**
* Get subscription data to add to the payload (sumo)
*
* @param array $subscription SUMO subscription
* @param array $order WC order
* @return array subscription data array
*/
private function get_subscription_data_sumo( $subscription, $order )
{
$order = wc_get_order($order);
$parent = $order->get_parent_id();
$parent = ($parent) ? wc_get_order($parent) : $order;
$plan = \sumo_get_subscription_plan($subscription->ID);
$period = $plan['subscription_duration'];
switch ($period) {
case 'D':
$period = 'day';
break;
case 'W':
$period = 'week';
break;
case 'M':
$period = 'month';
break;
case 'Y':
$period = 'year';
break;
}
$interval = $plan['subscription_duration_value'];
$next = get_post_meta( $subscription->ID,'sumo_get_next_payment_date',true);
$end = get_post_meta( $subscription->ID,'sumo_get_sub_end_date',true) ?: $next;
$start = get_post_meta( $subscription->ID,'sumo_get_sub_start_date',true);
if (empty($start)) {
try {
$start = new \DateTimeImmutable($end);
$start = $start->modify("-{$interval} {$period}")->format('Y-m-d\TH:i:s');
} catch (\Throwable $e) {$end = $start = '';} // when paused
}
$status = strtolower(get_post_meta( $subscription->ID,'sumo_get_status',true));
$cancelled = ($status == 'cancelled') ? $end : '';
return [ // dates are UTC/GMT
'id' => $subscription->ID, // override order id
'status' => $status,
'date_created' => $this->dateFormat( $parent->get_date_created() ),
'date_modified' => $this->dateFormat( $order->get_date_modified() ),
'date_paid' => $this->dateFormat( get_post_meta( $subscription->ID,'sumo_get_last_payment_date',true) ),
'date_completed' => $this->dateFormat( $order->get_date_completed() ),
'last_order_id' => $order->get_id(),
'last_order_date_created' => $this->dateFormat( $order->get_date_created() ),
'last_order_date_paid' => $this->dateFormat( $order->get_date_paid() ),
'last_order_date_completed' => $this->dateFormat( $order->get_date_completed() ),
'schedule_trial_end' => $this->dateFormat( get_post_meta( $subscription->ID,'sumo_get_trial_end_date',true) ),
'schedule_start' => $this->dateFormat( $start ),
'schedule_end' => $this->dateFormat( $end ),
'schedule_cancelled' => $this->dateFormat( $cancelled ),
'schedule_next_payment' => $this->dateFormat( $next ),
// 'schedule_payment_retry' => $this->dateFormat( get_post_meta( $subscription->ID,'schedule_payment_retry') ),
'billing_period' => $period,
'billing_interval' => $interval,
'sign_up_fee' => $plan['signup_fee'],
'product_meta' => $this->get_product_meta($order,[ $plan['subscription_product_id'] ]),
];
}
/**
* Get product meta data
*
* @param object $order WC_Subscription or WC_Order
* @param object $includeonly these item(s)
* @return array [id => type]
*/
private function get_product_meta( $order, $include=null )
{
$result = array();
$items = $order->get_items();
foreach ($items as $item)
{
if (is_array($include))
{
if (!in_array($item->get_product_id(),$include) && !in_array($item->get_variation_id(),$include)) continue;
}
$meta_data = $attributes = $categories = array();
$product = wc_get_product( $item->get_product_id() );
$product_id = $product->get_id();
foreach ($product->get_meta_data() as $meta) {
$meta_data[ $meta->key ] = $meta->value;
}
$attributes = $product->get_attributes();
if ($categories = get_the_terms( $product_id, 'product_cat' )) {
$categories = array_combine(wp_list_pluck( $categories, 'slug' ),wp_list_pluck( $categories, 'name' ));
}
if ($variation_id = $item->get_variation_id())
{
$product = wc_get_product( $variation_id );
foreach ($product->get_meta_data() as $meta) {
if (!empty($meta->value)) {
$meta_data[ $meta->key ] = $meta->value;
}
}
$attributes = array_merge($attributes,$product->get_attributes());
if ($varcat = get_the_terms( $variation_id, 'product_cat' )) {
$varcat = array_combine(wp_list_pluck( $varcat, 'slug' ),wp_list_pluck( $varcat, 'name' ));
$categories = array_merge($categories,$varcat);
}
}
// strip "pa_" prefix (product attribute)
$_attributes = [];
foreach ($attributes as $key => $value) {
if (is_a($value,'WC_Product_Attribute')) {
$value = $value->get_options()[0] ?? null;
}
$_attributes[ preg_replace('/^pa_(.+)/','$1',$key) ] = $value;
}
$result[ $product_id ] = array(
'id' => $product_id,
'name' => $product->get_name(),
'slug' => $product->get_slug(),
'sku' => $product->get_sku(),
'attributes'=> $_attributes,
'meta_data' => array_filter($meta_data, function($key){return ($key[0] != '_');}, ARRAY_FILTER_USE_KEY),
'categories'=> $categories,
);
}
return $result;
}
/**
* Get related orders and order type (wc)
*
* @param array $subscription WC_Subscription
* @return array [id => type]
*/
private function get_related_orders_wc( $subscription )
{
$relatedOrders = [];
foreach ( ['parent','renewal','resubscribe','switch'] as $type )
{
foreach ($subscription->get_related_orders('ids',$type) as $id)
{
$relatedOrders[$id] = $type;
}
}
krsort($relatedOrders,SORT_NUMERIC);
return $relatedOrders;
}
/**
* Get related orders and order type (sumo)
*
* @param array $subscription sumo subscription
* @return array [id => type]
*/
private function get_related_orders_sumo( $subscription )
{
$relatedOrders = get_post_meta( $subscription->ID, 'sumo_get_every_renewal_ids', true );
$relatedOrders = (empty($relatedOrders)) ? [] : array_fill_keys(maybe_unserialize($relatedOrders), 'renewal');
$relatedOrders[ get_post_meta( $subscription->ID, 'sumo_get_parent_order_id', true ) ] = 'parent';
krsort($relatedOrders,SORT_NUMERIC);
return $relatedOrders;
}
/**
* Format date to ISO 8601 'Y-m-d\TH:i:s'
*
* @param string $date
* @return string 'Y-m-d\TH:i:s'
*/
private function dateFormat( $date )
{
if (empty($date)) return $date;
if (is_a($date,'WC_DateTime'))
{
$date->setTimezone(new \DateTimeZone('UTC'));
return $date->date('Y-m-d\TH:i:s');
}
try {
$date = new \DateTimeImmutable($date);
$date = $date->format('Y-m-d\TH:i:s');
} catch (\Throwable $e) {$date = '';}
return $date;
}
/**
* logging via eacDoojigger
*
* @param mixed $data
* @param string $label
*/
private function logDebug( $data, $label=null )
{
if (function_exists('\eacDoojigger'))
{
\eacDoojigger()->logDebug($data,$label);
}
}
}
new \EarthAsylumConsulting\eacSoftwareRegistry_Subscription_Webhooks();
?>