PluginProbe
MailerLite – WooCommerce integration / 1.8.7
MailerLite – WooCommerce integration v1.8.7
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.7, at includes/classes/process/OrderProcess.php

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