PluginProbe
MailerLite – WooCommerce integration / 2.0
MailerLite – WooCommerce integration v2.0
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 2.1.0 All 147 releases
woo-mailerlite / includes / classes / process / OrderProcess.php

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

756 lines 23.9 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 @setcookie('mailerlite_accepts_marketing', null, -1, '/');
172 } else {
173 $data['checkout_data'] = CheckoutProcess::getInstance()->getCheckoutData();
174 }
175 $subscriber_fields = MailerLiteSettings::getInstance()->getSubscriberFieldsFromCustomerData($customer_data);
176 if (sizeof($subscriber_fields) > 0) {
177 $data['fields'] = $subscriber_fields;
178 }
179
180 $mailerliteClient = new PlatformAPI(MAILERLITE_WP_API_KEY);
181
182 if ($mailerliteClient->getApiType() === ApiType::CLASSIC) {
183
184 $subscriber_result = $this->addSubscriberSaveOrder($data, 'order_created');
185
186 if (isset($subscriber_result->added_to_group)) {
187 if ($subscriber_result->added_to_group) {
188 $this->markOrderSubscribedViaApi($order_id);
189 } else {
190 $this->completeOrderCustomerAlreadySubscribed($order_id);
191 }
192 }
193
194 if (isset($subscriber_result->updated_fields) && $subscriber_result->updated_fields) {
195 $this->markOrderSubscriberUpdated($order_id);
196 }
197 }
198
199 if ($mailerliteClient->getApiType() === ApiType::CURRENT) {
200
201 $shop = get_option('woo_ml_shop_id', false);
202
203 if ($shop === false) {
204
205 return;
206 }
207
208 $subscribe = $this->orderCustomerSubscribe($order_id);
209
210 $cart_details = CartProcess::getInstance()->getCartDetails($order_id);
211
212 //rename zip key for API
213 $zip = $subscriber_fields['zip'] ?? '';
214 unset($subscriber_fields['zip']);
215 $subscriber_fields['z_i_p'] = $zip;
216
217 $order_customer = [
218 'email' => $data['email'],
219 'create_subscriber' => $subscribe,
220 'accepts_marketing' => $subscribe,
221 'subscriber_fields' => $subscriber_fields
222 ];
223
224 if (strval($cart_details['customer_id']) !== "0") {
225
226 $order_customer['resource_id'] = (string)$cart_details['customer_id'];
227 }
228
229 $order_cart = [
230 'items' => $cart_details['items']
231 ];
232
233 // Delete existing cart (abandoned checkout)
234 $checkout_id = $_COOKIE['mailerlite_checkout_token'] ?? CheckoutProcess::getInstance()->getSavedCheckoutIdByEmail($data['email']);
235
236 if ($checkout_id !== null) {
237
238 $mailerliteClient->deleteOrder($shop, $checkout_id);
239
240 @setcookie('mailerlite_checkout_email', null, -1, '/');
241 @setcookie('mailerlite_checkout_token', null, -1, '/');
242 @setcookie('mailerlite_accepts_marketing', null, -1, '/');
243
244 CheckoutProcess::getInstance()->removeCheckout($data['email']);
245 }
246
247 // set order status completed (when processing and paid)
248 if ($cart_details['status'] == 'processing') {
249 $cart_details['status'] = 'completed';
250 }
251
252 // Create order
253 $order_create = $mailerliteClient->syncOrder($shop, $order_id, $order_customer, $order_cart,
254 $cart_details['status'], $cart_details['total_price'], $cart_details['created_at']);
255
256 if ($order_create) {
257
258 $this->completeOrderDataSubmitted($order_id);
259 }
260 }
261 }
262
263 /**
264 * Get customer data from order
265 * woo_ml_get_customer_data_from_order
266 *
267 * @param $order_id
268 *
269 * @return array|bool
270 */
271 public function getCustomerDataFromOrder($order_id)
272 {
273
274 if (empty($order_id)) {
275 return false;
276 }
277
278 $order = wc_get_order($order_id);
279
280 if (method_exists($order, 'get_billing_email')) {
281 $data = array(
282 'email' => $order->get_billing_email(),
283 'name' => "{$order->get_billing_first_name()} {$order->get_billing_last_name()}",
284 'first_name' => $order->get_billing_first_name(),
285 'last_name' => $order->get_billing_last_name(),
286 'company' => $order->get_billing_company(),
287 'city' => $order->get_billing_city(),
288 'postcode' => $order->get_billing_postcode(),
289 'state' => $order->get_billing_state(),
290 'country' => $order->get_billing_country(),
291 'phone' => $order->get_billing_phone()
292 );
293 } else {
294 // NOTE: Only for compatibility with WooCommerce < 3.0
295 $data = array(
296 'email' => $order->billing_email,
297 'name' => "{$order->billing_first_name} {$order->billing_last_name}",
298 'first_name' => $order->billing_first_name,
299 'last_name' => $order->billing_last_name,
300 'company' => $order->billing_company,
301 'city' => $order->billing_city,
302 'postcode' => $order->billing_postcode,
303 'state' => $order->billing_state,
304 'country' => $order->billing_country,
305 'phone' => $order->billing_phone
306 );
307 }
308
309 return $data;
310 }
311
312 /**
313 * Check whether a customer wants to be subscribed to our mailing list or not
314 * woo_ml_order_customer_subscribe
315 *
316 * @param $order_id
317 *
318 * @return bool
319 */
320 public function orderCustomerSubscribe($order_id)
321 {
322
323 $order = wc_get_order($order_id);
324
325 $subscribe = $order->get_meta('_woo_ml_subscribe');
326
327 return ('1' == $subscribe) ? true : false;
328 }
329
330 /**
331 * Mark order as "wants to be subscribed to mailing our list"
332 * woo_ml_set_order_customer_subscribe
333 *
334 * @param $order_id
335 */
336 public function setOrderCustomerSubscribe($order_id)
337 {
338 $order = wc_get_order($order_id);
339
340 $order->add_meta_data('_woo_ml_subscribe', true);
341 $order->save_meta_data();
342 }
343
344 /**
345 * Check whether order data was submitted via API or not
346 * woo_ml_order_data_submitted
347 *
348 * @param $order_id
349 *
350 * @return bool
351 */
352 public function orderDataSubmitted($order_id)
353 {
354
355 $order = wc_get_order($order_id);
356
357 $data_submitted = $order->get_meta('_woo_ml_order_data_submitted');
358
359 return ('1' == $data_submitted) ? true : false;
360 }
361
362 /**
363 * Mark order as "order data submitted"
364 * woo_ml_complete_order_data_submitted
365 *
366 * @param $order_id
367 */
368 public function completeOrderDataSubmitted($order_id)
369 {
370 $order = wc_get_order($order_id);
371
372 $order->add_meta_data('_woo_ml_order_data_submitted', true);
373 $order->save_meta_data();
374 }
375
376 /**
377 * Gets triggered on completed order event. Fetches order data
378 * and passes it along to api
379 * woo_ml_send_completed_order
380 *
381 * @param Integer $order_id
382 *
383 * @return void
384 */
385 public function sendCompletedOrder($order_id)
386 {
387 $order = wc_get_order($order_id);
388 $order_data['order'] = $order->get_data();
389 $order_items = $order->get_items();
390 $customer_email = $order->get_billing_email();
391
392 $saved_checkout = CheckoutProcess::getInstance()->getSavedCheckoutByEmail($customer_email);
393 $order_data['checkout_id'] = !empty($saved_checkout) ? $saved_checkout->checkout_id : null;
394
395 $ignored_products = MailerLiteSettings::getInstance()->remapList(ProductProcess::getInstance()->getIgnoredProductList());
396
397 foreach ($order_items as $key => $value) {
398 $item_data = $value->get_data();
399 $order_data['order']['line_items'][$key] = $item_data;
400 $order_data['order']['line_items'][$key]['ignored_product'] = in_array($item_data['product_id'],
401 $ignored_products) ? 1 : 0;
402 }
403 @setcookie('mailerlite_checkout_email', null, -1, '/');
404 @setcookie('mailerlite_checkout_token', null, -1, '/');
405 @setcookie('mailerlite_accepts_marketing', null, -1, '/');
406
407 if ($order_data['order']['status'] == 'processing') {
408 $order_data['order']['status'] = 'completed';
409 }
410
411 $this->wpSendOrder($order_data);
412
413 if (!empty($saved_checkout)) {
414
415 CheckoutProcess::getInstance()->removeCheckout($customer_email);
416 }
417
418 }
419
420 /**
421 * Check whether order was already tracked or not
422 * woo_ml_order_tracking_completed
423 *
424 * @param $order_id
425 *
426 * @return bool
427 */
428 public function checkOrderTracking($order_id)
429 {
430 $order = wc_get_order($order_id);
431
432 $order_tracked = $order->get_meta('_woo_ml_order_tracked');
433
434 return ('1' == $order_tracked) ? true : false;
435 }
436
437 /**
438 * Mark order as being tracked
439 * woo_ml_complete_order_tracking
440 *
441 * @param $order_id
442 */
443 public function completeOrderTracking($order_id)
444 {
445 $order = wc_get_order($order_id);
446
447 $order->add_meta_data('_woo_ml_order_tracked', true);
448 $order->save_meta_data();
449 }
450
451 /**
452 * On change of order status to processing send order data
453 * woo_ml_payment_status_processing
454 *
455 * @param Integer $order_id
456 *
457 * @return void
458 */
459 public function paymentStatusProcessing($order_id)
460 {
461 $order = wc_get_order($order_id);
462
463 if ($order->get_status() === 'processing') {
464 $data = [];
465 $customer_email = $order->get_billing_email();
466
467 // load the checkout id from the cookie first
468 // if that fails, then check the mailerlite checkouts table
469 $checkoutId = null;
470 if (isset($_COOKIE['mailerlite_checkout_token'])) {
471
472 $checkoutId = $_COOKIE['mailerlite_checkout_token'];
473 } else {
474
475 $saved_checkout = CheckoutProcess::getInstance()->getSavedCheckoutByEmail($customer_email);
476 $checkoutId = !empty($saved_checkout) ? $saved_checkout->checkout_id : null;
477 }
478
479 $data['checkout_id'] = $checkoutId;
480 $data['order_id'] = $order_id;
481 $data['payment_method'] = $order->get_payment_method();
482
483 @setcookie('mailerlite_checkout_email', null, -1, '/');
484 @setcookie('mailerlite_checkout_token', null, -1, '/');
485 @setcookie('mailerlite_accepts_marketing', null, -1, '/');
486
487 $this->addSubscriberSaveOrder($data, 'order_processing');
488 CheckoutProcess::getInstance()->removeCheckout($customer_email);
489
490 if ((int)get_option('woo_mailerlite_platform', 1) === ApiType::CURRENT) {
491
492 $this->processOrderSubscription($order_id);
493 }
494 }
495 }
496
497 /**
498 * Mark order as "subscriber was updated"
499 * woo_ml_complete_order_subscriber_updated
500 *
501 * @param $order_id
502 */
503 public function markOrderSubscriberUpdated($order_id)
504 {
505 $order = wc_get_order($order_id);
506
507 $order->add_meta_data('_woo_ml_subscriber_updated', true);
508 $order->save_meta_data();
509 }
510
511 /**
512 * Check whether a subscriber was updated from order or not
513 * woo_ml_order_subscriber_updated
514 *
515 * @param $order_id
516 *
517 * @return bool
518 */
519 public function checkOrderSubscriberUpdated($order_id)
520 {
521 $order = wc_get_order($order_id);
522
523 $subscriber_updated_from_order = $order->get_meta('_woo_ml_subscriber_updated');
524
525 return ('1' == $subscriber_updated_from_order) ? true : false;
526 }
527
528 /**
529 *
530 * woo_ml_complete_order_customer_already_subscribed
531 *
532 * @param $order_id
533 *
534 * @return void
535 */
536 public function completeOrderCustomerAlreadySubscribed($order_id)
537 {
538 $order = wc_get_order($order_id);
539
540 $order->add_meta_data('_woo_ml_already_subscribed', true);
541 $order->save_meta_data();
542 }
543
544 /**
545 * Mark order as "customer subscribed via API"
546 * woo_ml_complete_order_customer_subscribed
547 *
548 * @param $order_id
549 */
550 public function markOrderSubscribedViaApi($order_id)
551 {
552 $order = wc_get_order($order_id);
553
554 $order->add_meta_data('_woo_ml_subscribed', true);
555 $order->save_meta_data();
556 }
557
558 /**
559 *
560 * woo_ml_order_customer_already_subscribed
561 *
562 * @param $order_id
563 *
564 * @return bool
565 */
566 public function orderCustomerAlreadySubscribed($order_id)
567 {
568
569 $order = wc_get_order($order_id);
570
571 $already_subscribed = $order->get_meta('_woo_ml_already_subscribed');
572
573 return ('1' == $already_subscribed) ? true : false;
574 }
575
576 /**
577 * Check whether a customer was subscribed via API or not
578 *subscribe
579 * woo_ml_order_customer_subscribed
580 *
581 * @param $order_id
582 *
583 * @return bool
584 */
585 public function checkCustomerSubscribed($order_id)
586 {
587
588 $order = wc_get_order($order_id);
589
590 $subscribed = $order->get_meta('_woo_ml_subscribed');
591
592 return ('1' == $subscribed) ? true : false;
593 }
594
595 /**
596 * Sending order data on creation of order and/or order status change to processing
597 * mailerlite_wp_add_subscriber_and_save_order
598 *
599 * @param array $data
600 * @param string $event
601 *
602 * @return bool
603 */
604 public function addSubscriberSaveOrder($data, $event)
605 {
606 if (!ApiSettings::getInstance()->wpApiKeyExists()) {
607 return false;
608 }
609
610 try {
611 $mailerliteClient = new PlatformAPI(MAILERLITE_WP_API_KEY);
612
613 $shop_id = '';
614
615 $shop_url = site_url();
616 $data['shop_url'] = home_url();
617 $data['order_url'] = $shop_url . "/wp-admin/post.php?post=" . $data['order_id'] . "&action=edit";
618 //order_created case also takes care of processing sub if they have ticked the box to
619 //receive newsletters
620
621 if ($mailerliteClient->getApiType() === ApiType::CLASSIC) {
622 if ($event === 'order_created') {
623 $result = $mailerliteClient->sendSubscriberData($shop_id, $data);
624
625 if (isset($result->added_to_group) && isset($result->updated_fields)) {
626 return $result;
627 } elseif (isset($result->deactivate) && $result->deactivate) {
628 woo_ml_deactivate_woo_ml_plugin(true);
629
630 return false;
631 } else {
632 return false;
633 }
634 } else {
635
636 $result = $mailerliteClient->sendOrderProcessing($shop_id, $data);
637 if (isset($result->deactivate) && $result->deactivate) {
638 woo_ml_deactivate_woo_ml_plugin(true);
639 }
640
641 if ($event === 'order_processing') {
642 $this->sendCompletedOrder($data['order_id']);
643 $this->processOrderTracking($data['order_id']);
644 }
645
646 return true;
647 }
648 }
649
650 } catch (\Exception $e) {
651 return false;
652 }
653 }
654
655 /**
656 * Sends completed order data to api to be evaluated and saved and/if trigger automations
657 * mailerlite_wp_send_order
658 *
659 * @param array $order_data
660 *
661 * @return bool|void
662 */
663 public function wpSendOrder($order_data)
664 {
665 if (!ApiSettings::getInstance()->wpApiKeyExists()) {
666 return false;
667 }
668
669 try {
670 $mailerliteClient = new PlatformAPI(MAILERLITE_WP_API_KEY);
671
672 if ($mailerliteClient->getApiType() == ApiType::CLASSIC) {
673
674 $store = home_url();
675
676 $shop_url = site_url();
677 $order_data['order_url'] = $shop_url . "/wp-admin/post.php?post=" . $order_data['order']['id'] . "&action=edit";
678
679 $result = $mailerliteClient->saveOrder($store, $order_data);
680
681 if (isset($result->deactivate) && $result->deactivate) {
682 woo_ml_deactivate_woo_ml_plugin(true);
683 }
684 }
685
686 if ($mailerliteClient->getApiType() == ApiType::CURRENT) {
687
688 $shop = get_option('woo_ml_shop_id', false);
689
690 if ($shop === false) {
691
692 return false;
693 }
694
695 $subscribe = $this->orderCustomerSubscribe($order_data['order']['id']);
696
697 $cart_details = CartProcess::getInstance()->getCartDetails($order_data['order']['id']);
698
699 $customer_data = $this->getCustomerDataFromOrder($order_data['order']['id']);
700 $subscriber_fields = MailerLiteSettings::getInstance()->getSubscriberFieldsFromCustomerData($customer_data);
701
702 //rename zip key for API
703 $zip = $subscriber_fields['zip'] ?? '';
704 unset($subscriber_fields['zip']);
705 $subscriber_fields['z_i_p'] = $zip;
706
707 $order_customer = [
708 'email' => $order_data['order']['billing']['email'],
709 'create_subscriber' => $subscribe,
710 'accepts_marketing' => $subscribe,
711 'subscriber_fields' => $subscriber_fields
712 ];
713
714 if (strval($cart_details['customer_id']) !== "0") {
715
716 $order_customer['resource_id'] = (string)$cart_details['customer_id'];
717
718 // check customer fields
719 $wc_customer = new \WC_Customer($cart_details['customer_id']);
720
721 if (!empty($wc_customer->get_email())) {
722
723 $order_customer['orders_count'] = $wc_customer->get_order_count();
724 $order_customer['total_spent'] = $wc_customer->get_total_spent();
725 }
726 }
727
728 $order_cart = [
729 'items' => $cart_details['items']
730 ];
731
732 if (is_numeric($order_data['order']['id'])) {
733 $order_data['order']['status'] = 'completed';
734 }
735
736 $mailerliteClient->syncOrder($shop, $order_data['order']['id'], $order_customer, $order_cart,
737 $order_data['order']['status'], $cart_details['total_price'], $cart_details['created_at']);
738
739 if ($mailerliteClient->responseCode() === 201 || $mailerliteClient->responseCode() === 200) {
740
741 $this->orderDataSubmitted($order_data['order']['id']);
742
743 // Delete existing cart (abandoned checkout)
744 if ($order_data['checkout_id'] !== null) {
745
746 $mailerliteClient->deleteOrder($shop, $order_data['checkout_id']);
747 }
748 }
749
750 return true;
751 }
752 } catch (\Exception $e) {
753 return false;
754 }
755 }
756 }