PluginProbe
MailerLite – WooCommerce integration / 1.8.8
MailerLite – WooCommerce integration v1.8.8
3.1.27 3.1.25 3.1.26 3.1.24 3.1.23 3.1.22 3.1.21 3.1.20 3.1.19 3.1.18 3.1.17 3.1.16 3.1.15 1.8.7 1.8.8 2.0 2.0.1 2.0.2 2.0.3 2.0.4 2.0.5 2.0.6 2.0.7 2.0.8 2.0.9 All 148 releases
woo-mailerlite / includes / classes / process / OrderProcess.php

OrderProcess.php in MailerLite – WooCommerce integration 1.8.8, at includes/classes/process/OrderProcess.php

752 lines 23.6 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2
3 namespace MailerLite\Includes\Classes\Process;
4
5 use MailerLite\Includes\Classes\Settings\ApiSettings;
6 use MailerLite\Includes\Classes\Settings\MailerLiteSettings;
7 use MailerLite\Includes\Classes\Singleton;
8 use MailerLite\Includes\Shared\Api\ApiType;
9 use MailerLite\Includes\Shared\Api\PlatformAPI;
10
11 class OrderProcess extends Singleton
12 {
13
14 /**
15 * Process order tracking
16 * 1.) Get current data from WooCommerce
17 * 2.) Update subscriber data with updated values
18 * woo_ml_process_order_tracking
19 *
20 * @param $order_id
21 */
22 public function processOrderTracking($order_id)
23 {
24
25 $order = wc_get_order($order_id);
26
27 $order_tracked = $order->get_meta('_woo_ml_order_tracking');
28
29 if ($order_tracked) // Prevent tracking orders multiple times
30 {
31 return;
32 }
33
34 // Step 1: Get order tracking data from order
35 $tracking_data = $this->getOrderTrackingData($order_id);
36
37 if (!empty($tracking_data)) {
38
39 $mailerliteClient = new PlatformAPI(MAILERLITE_WP_API_KEY);
40
41 if ($mailerliteClient->getApiType() == ApiType::CLASSIC) {
42 $ml_subscriber_obj = mailerlite_wp_get_subscriber_by_email($tracking_data['email']);
43
44 // Customer exists on MailerLite
45 if ($ml_subscriber_obj) {
46
47 // Step 2: Update subscriber data via API
48 $subscriber_data = [
49 'fields' => [
50 'woo_orders_count' => $tracking_data['orders_count'],
51 'woo_total_spent' => $tracking_data['total_spent'],
52 'woo_last_order' => $tracking_data['last_order'],
53 'woo_last_order_id' => $order_id
54 ]
55 ];
56
57 $subscriber_updated = mailerlite_wp_update_subscriber($tracking_data['email'], $subscriber_data);
58
59 if ($subscriber_updated) {
60
61 $this->completeOrderDataSubmitted($order_id);
62 }
63 }
64 }
65 }
66
67 // Mark order data as tracked
68 $this->completeOrderTracking($order_id);
69 }
70
71 /**
72 * Get order tracking data from order
73 * woo_ml_get_order_tracking_data
74 *
75 * @param int $order_id
76 *
77 * @return array
78 * @throws Exception
79 */
80 public function getOrderTrackingData($order_id)
81 {
82
83 if (!is_numeric($order_id)) {
84 return [];
85 }
86
87 $customer_email = '';
88 $order_count = 0;
89 $total_spent = 0;
90 $last_order_date = '';
91
92 $order = wc_get_order($order_id);
93
94 $customer = \WC_Data_Store::load('report-customers')->get_data([
95 'order_before' => null,
96 'order_after' => null,
97 'searchby' => 'email',
98 'search' => $order->get_billing_email(),
99 ])->data;
100
101 $customer_email = $order->get_billing_email();
102
103 if (count($customer)) {
104 foreach ($customer as $value) {
105 if ( ! isset($customer['last_order_date'])) {
106 $customer['last_order_date'] = $value['date_last_order'];
107 }
108
109 if ($customer['last_order_date'] < $value['date_last_order']) {
110 $customer['last_order_date'] = $value['date_last_order'];
111 }
112
113 $order_count += $value['orders_count'] ?? 0;
114 $total_spent += $value['total_spend'] ?? 0;
115 }
116
117 $last_order_date = $customer['last_order_date'];
118 } else {
119 $last_order_date = $order->get_date_created()->date_i18n('Y-m-d H:i:s');
120 }
121
122 $order_count++;
123 $total_spent += $order->get_total();
124
125 return [
126 'email' => $customer_email,
127 'customer_id' => $customer[0]['id'] ?? 0,
128 'orders_count' => $order_count,
129 'total_spent' => $total_spent,
130 'last_order' => $last_order_date,
131 'last_order_id' => $order_id
132 ];
133 }
134
135 /**
136 * Process order create and subscription to newsletter
137 * woo_ml_process_order_subscription
138 *
139 * @param $order_id
140 *
141 * @return void
142 */
143 public function processOrderSubscription($order_id)
144 {
145 $order = wc_get_order($order_id);
146 $customer_data = $this->getCustomerDataFromOrder($order_id);
147
148 $subscribe = $order->get_meta('_woo_ml_subscribe');
149
150 if ($subscribe === "") {
151 $subscribe = MailerLiteSettings::getInstance()->getMlOption('checkout_preselect') === 'yes' && MailerLiteSettings::getInstance()->getMlOption('checkout_hide') === 'yes';
152
153 if ($subscribe) {
154 $this->setOrderCustomerSubscribe($order_id);
155 }
156 }
157
158
159 $data = [];
160 $data['email'] = $customer_data['email'];
161 $data['checked_sub_to_mailist'] = $subscribe;
162 $checkout_id = isset($_COOKIE['mailerlite_checkout_token']) ? $_COOKIE['mailerlite_checkout_token'] : CheckoutProcess::getInstance()->getSavedCheckoutIdByEmail($customer_data['email']);
163
164 $data['checkout_id'] = $checkout_id;
165 $data['order_id'] = $order_id;
166 $data['payment_method'] = $order->get_payment_method();
167
168 if ($data['payment_method'] == 'bacs' || $data['payment_method'] == 'cheque') {
169 @setcookie('mailerlite_checkout_email', null, -1, '/');
170 @setcookie('mailerlite_checkout_token', null, -1, '/');
171 } else {
172 $data['checkout_data'] = CheckoutProcess::getInstance()->getCheckoutData();
173 }
174 $subscriber_fields = MailerLiteSettings::getInstance()->getSubscriberFieldsFromCustomerData($customer_data);
175 if (sizeof($subscriber_fields) > 0) {
176 $data['fields'] = $subscriber_fields;
177 }
178
179 $mailerliteClient = new PlatformAPI(MAILERLITE_WP_API_KEY);
180
181 if ($mailerliteClient->getApiType() === ApiType::CLASSIC) {
182
183 $subscriber_result = $this->addSubscriberSaveOrder($data, 'order_created');
184
185 if (isset($subscriber_result->added_to_group)) {
186 if ($subscriber_result->added_to_group) {
187 $this->markOrderSubscribedViaApi($order_id);
188 } else {
189 $this->completeOrderCustomerAlreadySubscribed($order_id);
190 }
191 }
192
193 if (isset($subscriber_result->updated_fields) && $subscriber_result->updated_fields) {
194 $this->markOrderSubscriberUpdated($order_id);
195 }
196 }
197
198 if ($mailerliteClient->getApiType() === ApiType::CURRENT) {
199
200 $shop = get_option('woo_ml_shop_id', false);
201
202 if ($shop === false) {
203
204 return;
205 }
206
207 $subscribe = $this->orderCustomerSubscribe($order_id);
208
209 $cart_details = CartProcess::getInstance()->getCartDetails($order_id);
210
211 //rename zip key for API
212 $zip = $subscriber_fields['zip'] ?? '';
213 unset($subscriber_fields['zip']);
214 $subscriber_fields['z_i_p'] = $zip;
215
216 $order_customer = [
217 'email' => $data['email'],
218 'create_subscriber' => $subscribe,
219 'accepts_marketing' => $subscribe,
220 'subscriber_fields' => $subscriber_fields
221 ];
222
223 if (strval($cart_details['customer_id']) !== "0") {
224
225 $order_customer['resource_id'] = (string)$cart_details['customer_id'];
226 }
227
228 $order_cart = [
229 'items' => $cart_details['items']
230 ];
231
232 // Delete existing cart (abandoned checkout)
233 $checkout_id = $_COOKIE['mailerlite_checkout_token'] ?? CheckoutProcess::getInstance()->getSavedCheckoutIdByEmail($data['email']);
234
235 if ($checkout_id !== null) {
236
237 $mailerliteClient->deleteOrder($shop, $checkout_id);
238
239 @setcookie('mailerlite_checkout_email', null, -1, '/');
240 @setcookie('mailerlite_checkout_token', null, -1, '/');
241
242 CheckoutProcess::getInstance()->removeCheckout($data['email']);
243 }
244
245 // set order status completed (when processing and paid)
246 if ($cart_details['status'] == 'processing') {
247 $cart_details['status'] = 'completed';
248 }
249
250 // Create order
251 $order_create = $mailerliteClient->syncOrder($shop, $order_id, $order_customer, $order_cart,
252 $cart_details['status'], $cart_details['total_price'], $cart_details['created_at']);
253
254 if ($order_create) {
255
256 $this->completeOrderDataSubmitted($order_id);
257 }
258 }
259 }
260
261 /**
262 * Get customer data from order
263 * woo_ml_get_customer_data_from_order
264 *
265 * @param $order_id
266 *
267 * @return array|bool
268 */
269 public function getCustomerDataFromOrder($order_id)
270 {
271
272 if (empty($order_id)) {
273 return false;
274 }
275
276 $order = wc_get_order($order_id);
277
278 if (method_exists($order, 'get_billing_email')) {
279 $data = array(
280 'email' => $order->get_billing_email(),
281 'name' => "{$order->get_billing_first_name()} {$order->get_billing_last_name()}",
282 'first_name' => $order->get_billing_first_name(),
283 'last_name' => $order->get_billing_last_name(),
284 'company' => $order->get_billing_company(),
285 'city' => $order->get_billing_city(),
286 'postcode' => $order->get_billing_postcode(),
287 'state' => $order->get_billing_state(),
288 'country' => $order->get_billing_country(),
289 'phone' => $order->get_billing_phone()
290 );
291 } else {
292 // NOTE: Only for compatibility with WooCommerce < 3.0
293 $data = array(
294 'email' => $order->billing_email,
295 'name' => "{$order->billing_first_name} {$order->billing_last_name}",
296 'first_name' => $order->billing_first_name,
297 'last_name' => $order->billing_last_name,
298 'company' => $order->billing_company,
299 'city' => $order->billing_city,
300 'postcode' => $order->billing_postcode,
301 'state' => $order->billing_state,
302 'country' => $order->billing_country,
303 'phone' => $order->billing_phone
304 );
305 }
306
307 return $data;
308 }
309
310 /**
311 * Check whether a customer wants to be subscribed to our mailing list or not
312 * woo_ml_order_customer_subscribe
313 *
314 * @param $order_id
315 *
316 * @return bool
317 */
318 public function orderCustomerSubscribe($order_id)
319 {
320
321 $order = wc_get_order($order_id);
322
323 $subscribe = $order->get_meta('_woo_ml_subscribe');
324
325 return ('1' == $subscribe) ? true : false;
326 }
327
328 /**
329 * Mark order as "wants to be subscribed to mailing our list"
330 * woo_ml_set_order_customer_subscribe
331 *
332 * @param $order_id
333 */
334 public function setOrderCustomerSubscribe($order_id)
335 {
336 $order = wc_get_order($order_id);
337
338 $order->add_meta_data('_woo_ml_subscribe', true);
339 $order->save_meta_data();
340 }
341
342 /**
343 * Check whether order data was submitted via API or not
344 * woo_ml_order_data_submitted
345 *
346 * @param $order_id
347 *
348 * @return bool
349 */
350 public function orderDataSubmitted($order_id)
351 {
352
353 $order = wc_get_order($order_id);
354
355 $data_submitted = $order->get_meta('_woo_ml_order_data_submitted');
356
357 return ('1' == $data_submitted) ? true : false;
358 }
359
360 /**
361 * Mark order as "order data submitted"
362 * woo_ml_complete_order_data_submitted
363 *
364 * @param $order_id
365 */
366 public function completeOrderDataSubmitted($order_id)
367 {
368 $order = wc_get_order($order_id);
369
370 $order->add_meta_data('_woo_ml_order_data_submitted', true);
371 $order->save_meta_data();
372 }
373
374 /**
375 * Gets triggered on completed order event. Fetches order data
376 * and passes it along to api
377 * woo_ml_send_completed_order
378 *
379 * @param Integer $order_id
380 *
381 * @return void
382 */
383 public function sendCompletedOrder($order_id)
384 {
385 $order = wc_get_order($order_id);
386 $order_data['order'] = $order->get_data();
387 $order_items = $order->get_items();
388 $customer_email = $order->get_billing_email();
389
390 $saved_checkout = CheckoutProcess::getInstance()->getSavedCheckoutByEmail($customer_email);
391 $order_data['checkout_id'] = !empty($saved_checkout) ? $saved_checkout->checkout_id : null;
392
393 $ignored_products = MailerLiteSettings::getInstance()->remapList(ProductProcess::getInstance()->getIgnoredProductList());
394
395 foreach ($order_items as $key => $value) {
396 $item_data = $value->get_data();
397 $order_data['order']['line_items'][$key] = $item_data;
398 $order_data['order']['line_items'][$key]['ignored_product'] = in_array($item_data['product_id'],
399 $ignored_products) ? 1 : 0;
400 }
401 @setcookie('mailerlite_checkout_email', null, -1, '/');
402 @setcookie('mailerlite_checkout_token', null, -1, '/');
403
404 if ($order_data['order']['status'] == 'processing') {
405 $order_data['order']['status'] = 'completed';
406 }
407
408 $this->wpSendOrder($order_data);
409
410 if (!empty($saved_checkout)) {
411
412 CheckoutProcess::getInstance()->removeCheckout($customer_email);
413 }
414
415 }
416
417 /**
418 * Check whether order was already tracked or not
419 * woo_ml_order_tracking_completed
420 *
421 * @param $order_id
422 *
423 * @return bool
424 */
425 public function checkOrderTracking($order_id)
426 {
427 $order = wc_get_order($order_id);
428
429 $order_tracked = $order->get_meta('_woo_ml_order_tracked');
430
431 return ('1' == $order_tracked) ? true : false;
432 }
433
434 /**
435 * Mark order as being tracked
436 * woo_ml_complete_order_tracking
437 *
438 * @param $order_id
439 */
440 public function completeOrderTracking($order_id)
441 {
442 $order = wc_get_order($order_id);
443
444 $order->add_meta_data('_woo_ml_order_tracked', true);
445 $order->save_meta_data();
446 }
447
448 /**
449 * On change of order status to processing send order data
450 * woo_ml_payment_status_processing
451 *
452 * @param Integer $order_id
453 *
454 * @return void
455 */
456 public function paymentStatusProcessing($order_id)
457 {
458 $order = wc_get_order($order_id);
459
460 if ($order->get_status() === 'processing') {
461 $data = [];
462 $customer_email = $order->get_billing_email();
463
464 // load the checkout id from the cookie first
465 // if that fails, then check the mailerlite checkouts table
466 $checkoutId = null;
467 if (isset($_COOKIE['mailerlite_checkout_token'])) {
468
469 $checkoutId = $_COOKIE['mailerlite_checkout_token'];
470 } else {
471
472 $saved_checkout = CheckoutProcess::getInstance()->getSavedCheckoutByEmail($customer_email);
473 $checkoutId = !empty($saved_checkout) ? $saved_checkout->checkout_id : null;
474 }
475
476 $data['checkout_id'] = $checkoutId;
477 $data['order_id'] = $order_id;
478 $data['payment_method'] = $order->get_payment_method();
479
480 @setcookie('mailerlite_checkout_email', null, -1, '/');
481 @setcookie('mailerlite_checkout_token', null, -1, '/');
482
483 $this->addSubscriberSaveOrder($data, 'order_processing');
484 CheckoutProcess::getInstance()->removeCheckout($customer_email);
485
486 if ((int)get_option('woo_mailerlite_platform', 1) === ApiType::CURRENT) {
487
488 $this->processOrderSubscription($order_id);
489 }
490 }
491 }
492
493 /**
494 * Mark order as "subscriber was updated"
495 * woo_ml_complete_order_subscriber_updated
496 *
497 * @param $order_id
498 */
499 public function markOrderSubscriberUpdated($order_id)
500 {
501 $order = wc_get_order($order_id);
502
503 $order->add_meta_data('_woo_ml_subscriber_updated', true);
504 $order->save_meta_data();
505 }
506
507 /**
508 * Check whether a subscriber was updated from order or not
509 * woo_ml_order_subscriber_updated
510 *
511 * @param $order_id
512 *
513 * @return bool
514 */
515 public function checkOrderSubscriberUpdated($order_id)
516 {
517 $order = wc_get_order($order_id);
518
519 $subscriber_updated_from_order = $order->get_meta('_woo_ml_subscriber_updated');
520
521 return ('1' == $subscriber_updated_from_order) ? true : false;
522 }
523
524 /**
525 *
526 * woo_ml_complete_order_customer_already_subscribed
527 *
528 * @param $order_id
529 *
530 * @return void
531 */
532 public function completeOrderCustomerAlreadySubscribed($order_id)
533 {
534 $order = wc_get_order($order_id);
535
536 $order->add_meta_data('_woo_ml_already_subscribed', true);
537 $order->save_meta_data();
538 }
539
540 /**
541 * Mark order as "customer subscribed via API"
542 * woo_ml_complete_order_customer_subscribed
543 *
544 * @param $order_id
545 */
546 public function markOrderSubscribedViaApi($order_id)
547 {
548 $order = wc_get_order($order_id);
549
550 $order->add_meta_data('_woo_ml_subscribed', true);
551 $order->save_meta_data();
552 }
553
554 /**
555 *
556 * woo_ml_order_customer_already_subscribed
557 *
558 * @param $order_id
559 *
560 * @return bool
561 */
562 public function orderCustomerAlreadySubscribed($order_id)
563 {
564
565 $order = wc_get_order($order_id);
566
567 $already_subscribed = $order->get_meta('_woo_ml_already_subscribed');
568
569 return ('1' == $already_subscribed) ? true : false;
570 }
571
572 /**
573 * Check whether a customer was subscribed via API or not
574 *subscribe
575 * woo_ml_order_customer_subscribed
576 *
577 * @param $order_id
578 *
579 * @return bool
580 */
581 public function checkCustomerSubscribed($order_id)
582 {
583
584 $order = wc_get_order($order_id);
585
586 $subscribed = $order->get_meta('_woo_ml_subscribed');
587
588 return ('1' == $subscribed) ? true : false;
589 }
590
591 /**
592 * Sending order data on creation of order and/or order status change to processing
593 * mailerlite_wp_add_subscriber_and_save_order
594 *
595 * @param array $data
596 * @param string $event
597 *
598 * @return bool
599 */
600 public function addSubscriberSaveOrder($data, $event)
601 {
602 if (!ApiSettings::getInstance()->wpApiKeyExists()) {
603 return false;
604 }
605
606 try {
607 $mailerliteClient = new PlatformAPI(MAILERLITE_WP_API_KEY);
608
609 $shop_id = '';
610
611 $shop_url = site_url();
612 $data['shop_url'] = home_url();
613 $data['order_url'] = $shop_url . "/wp-admin/post.php?post=" . $data['order_id'] . "&action=edit";
614 //order_created case also takes care of processing sub if they have ticked the box to
615 //receive newsletters
616
617 if ($mailerliteClient->getApiType() === ApiType::CLASSIC) {
618 if ($event === 'order_created') {
619 $result = $mailerliteClient->sendSubscriberData($shop_id, $data);
620
621 if (isset($result->added_to_group) && isset($result->updated_fields)) {
622 return $result;
623 } elseif (isset($result->deactivate) && $result->deactivate) {
624 woo_ml_deactivate_woo_ml_plugin(true);
625
626 return false;
627 } else {
628 return false;
629 }
630 } else {
631
632 $result = $mailerliteClient->sendOrderProcessing($shop_id, $data);
633 if (isset($result->deactivate) && $result->deactivate) {
634 woo_ml_deactivate_woo_ml_plugin(true);
635 }
636
637 if ($event === 'order_processing') {
638 $this->sendCompletedOrder($data['order_id']);
639 $this->processOrderTracking($data['order_id']);
640 }
641
642 return true;
643 }
644 }
645
646 } catch (\Exception $e) {
647 return false;
648 }
649 }
650
651 /**
652 * Sends completed order data to api to be evaluated and saved and/if trigger automations
653 * mailerlite_wp_send_order
654 *
655 * @param array $order_data
656 *
657 * @return bool|void
658 */
659 public function wpSendOrder($order_data)
660 {
661 if (!ApiSettings::getInstance()->wpApiKeyExists()) {
662 return false;
663 }
664
665 try {
666 $mailerliteClient = new PlatformAPI(MAILERLITE_WP_API_KEY);
667
668 if ($mailerliteClient->getApiType() == ApiType::CLASSIC) {
669
670 $store = home_url();
671
672 $shop_url = site_url();
673 $order_data['order_url'] = $shop_url . "/wp-admin/post.php?post=" . $order_data['order']['id'] . "&action=edit";
674
675 $result = $mailerliteClient->saveOrder($store, $order_data);
676
677 if (isset($result->deactivate) && $result->deactivate) {
678 woo_ml_deactivate_woo_ml_plugin(true);
679 }
680 }
681
682 if ($mailerliteClient->getApiType() == ApiType::CURRENT) {
683
684 $shop = get_option('woo_ml_shop_id', false);
685
686 if ($shop === false) {
687
688 return false;
689 }
690
691 $subscribe = $this->orderCustomerSubscribe($order_data['order']['id']);
692
693 $cart_details = CartProcess::getInstance()->getCartDetails($order_data['order']['id']);
694
695 $customer_data = $this->getCustomerDataFromOrder($order_data['order']['id']);
696 $subscriber_fields = MailerLiteSettings::getInstance()->getSubscriberFieldsFromCustomerData($customer_data);
697
698 //rename zip key for API
699 $zip = $subscriber_fields['zip'] ?? '';
700 unset($subscriber_fields['zip']);
701 $subscriber_fields['z_i_p'] = $zip;
702
703 $order_customer = [
704 'email' => $order_data['order']['billing']['email'],
705 'create_subscriber' => $subscribe,
706 'accepts_marketing' => $subscribe,
707 'subscriber_fields' => $subscriber_fields
708 ];
709
710 if (strval($cart_details['customer_id']) !== "0") {
711
712 $order_customer['resource_id'] = (string)$cart_details['customer_id'];
713
714 // check customer fields
715 $wc_customer = new \WC_Customer($cart_details['customer_id']);
716
717 if (!empty($wc_customer->get_email())) {
718
719 $order_customer['orders_count'] = $wc_customer->get_order_count();
720 $order_customer['total_spent'] = $wc_customer->get_total_spent();
721 }
722 }
723
724 $order_cart = [
725 'items' => $cart_details['items']
726 ];
727
728 if (is_numeric($order_data['order']['id'])) {
729 $order_data['order']['status'] = 'completed';
730 }
731
732 $mailerliteClient->syncOrder($shop, $order_data['order']['id'], $order_customer, $order_cart,
733 $order_data['order']['status'], $cart_details['total_price'], $cart_details['created_at']);
734
735 if ($mailerliteClient->responseCode() === 201 || $mailerliteClient->responseCode() === 200) {
736
737 $this->orderDataSubmitted($order_data['order']['id']);
738
739 // Delete existing cart (abandoned checkout)
740 if ($order_data['checkout_id'] !== null) {
741
742 $mailerliteClient->deleteOrder($shop, $order_data['checkout_id']);
743 }
744 }
745
746 return true;
747 }
748 } catch (\Exception $e) {
749 return false;
750 }
751 }
752 }