PluginProbe
MailerLite – WooCommerce integration / 3.1.27
MailerLite – WooCommerce integration v3.1.27
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 / controllers / WooMailerLiteOrderController.php

WooMailerLiteOrderController.php in MailerLite – WooCommerce integration 3.1.27, at includes/controllers/WooMailerLiteOrderController.php

262 lines 11.5 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2
3 class WooMailerLiteOrderController extends WooMailerLiteController
4 {
5
6 public function handleOrderStatusChanged($orderId)
7 {
8 try {
9
10 if (WooMailerLiteCache::get('order_sent:'.$orderId)) {
11 return true;
12 }
13 $order = wc_get_order($orderId);
14 if (!$order->get_billing_email()) {
15 return true;
16 }
17
18 WooMailerLiteLanguageService::persistToOrder($order);
19
20 if (WooMailerLiteSession::getMLCartHash()) {
21 $order->add_meta_data('_woo_ml_cart_hash', WooMailerLiteSession::getMLCartHash());
22 }
23 $customer = WooMailerLiteCustomer::selectAll(false)->where('email', $order->get_billing_email())->first();
24 if (!$customer) {
25 $customer = WooMailerLiteCustomer::selectAll(false)
26 ->getFromOrder()
27 ->where("email", $order->get_billing_email())
28 ->whereIn("status", WooMailerLiteOptions::allSupportedOrderStatuses())
29 ->first();
30 }
31 // Query live order stats directly to avoid stale wc_order_stats reads when
32 // multiple orders are placed in quick succession for the same email.
33 $liveOrders = wc_get_orders([
34 'billing_email' => $order->get_billing_email(),
35 'status' => WooMailerLiteOptions::COMPLETE_ORDER_STATUSES,
36 'limit' => -1,
37 ]);
38 $liveOrdersCount = count($liveOrders);
39 $liveTotalSpent = (float) array_sum(array_map(fn($o) => $o->get_total(), $liveOrders));
40
41 $cart = WooMailerLiteCart::where('email', $order->get_billing_email())->first();
42 if (!$cart) {
43 $cart = WooMailerLiteCart::where('hash', WooMailerLiteSession::getMLCartHash())
44 ->withoutPrefix(function($query) use ($order) {
45 $query->orWhere('hash', $order->get_meta('_woo_ml_cart_hash'));
46 })->first();
47 if ($cart instanceof WooMailerLiteCart) {
48 $cart->update([
49 'email' => $order->get_billing_email(),
50 ]);
51 }
52 }
53 if (!$cart && !$customer) {
54 return true;
55 }
56
57 if ((isset($cart->subscribe) && $cart->subscribe) || WooMailerLiteOptions::get("settings.checkoutHidden")) {
58 $order->add_meta_data('_woo_ml_subscribe', true);
59 }
60
61 $syncFields = WooMailerLiteOptions::get('syncFields', []);
62 if (empty($syncFields)) {
63 $syncFields = [
64 'name',
65 'email',
66 'company',
67 'city',
68 'zip',
69 'state',
70 'country',
71 'phone'
72 ];
73 WooMailerLiteOptions::update('syncFields', $syncFields);
74 }
75 $filteredCustomerData = array_filter($customer ? $customer->toArray() : [], function($value) {
76 return !is_null($value) && trim($value) !== '';
77 });
78
79 $syncFields[] = 'last_name';
80 if (!in_array('name', $syncFields)) {
81 $syncFields[] = 'name';
82 }
83
84 $customerFields = array_intersect_key($filteredCustomerData, array_flip($syncFields));
85
86 if (in_array('phone', $syncFields) && empty($customerFields['phone']) && $order->get_billing_phone()) {
87 $customerFields['phone'] = $order->get_billing_phone();
88 }
89
90 if (in_array('company', $syncFields) && empty($customerFields['company']) && $order->get_billing_company()) {
91 $customerFields['company'] = $order->get_billing_company();
92 }
93
94 $customerFields = WooMailerLiteLanguageService::applyTo($customerFields, $order);
95
96 $subscribe = false;
97 $email = $customer->email ?? $order->get_billing_email();
98 $subscribeCacheKey = 'woo_ml_subscribe_checkbox:'.$email;
99 if ($cart && isset($cart->subscribe)) {
100 $subscribe = $cart->subscribe;
101 }
102
103 if (WooMailerLiteOptions::get("settings.checkoutHidden") || $order->get_meta('_woo_ml_subscribe')) {
104 $subscribe = true;
105 }
106
107 if (WooMailerLiteCache::get($subscribeCacheKey) === null) {
108 WooMailerLiteCache::set($subscribeCacheKey, $subscribe, 20);
109 }
110
111 if (WooMailerLiteCache::get($subscribeCacheKey) === true) {
112 $subscribe = true;
113 }
114
115 $orderCustomer = [
116 'email' => $customer->email ?? $order->get_billing_email(),
117 'create_subscriber' => $subscribe,
118 'accepts_marketing' => $subscribe,
119 'subscriber_fields' => $customerFields,
120 'total_spent' => $liveTotalSpent,
121 'orders_count' => $liveOrdersCount,
122 'last_order_id' => $customer->last_order_id ?? null,
123 'last_order' => $customer->last_order ?? null
124 ];
125 $items = [];
126
127 foreach ($order->get_items() as $item) {
128 if ($item->get_product_id() !== 0) {
129 $items[] = [
130 'product_resource_id' => (string)$item->get_product_id(),
131 'ecommerce_product_variant_id' => (string) $item->get_variation_id(),
132 'variant' => $item->get_name(),
133 'quantity' => $item->get_quantity(),
134 'price' => (float)$item->get_product()->get_price()
135 ];
136 }
137 }
138 $cartData = [
139 'items' => $items
140 ];
141
142 if ($this->apiClient()->isClassic()) {
143 $orderData['order'] = $order->get_data();
144 $orderData['checkout_id'] = $cart->data['checkout_id'] ?? null;
145 $orderData['order_url'] = home_url() . "/wp-admin/post.php?post=" . $orderId . "&action=edit";
146 $customerFields['woo_total_spent'] = $liveTotalSpent;
147 $customerFields['woo_orders_count'] = $liveOrdersCount;
148 $customerFields['woo_last_order_id'] = $customer->last_order_id ?? null;
149 $customerFields['woo_last_order'] = $customer->last_order ?? nulL;
150 $data = [
151 'email' => $customer->email,
152 'checked_sub_to_mailist' => (bool)$subscribe ?? (bool)$cart->subscribe,
153 'checkout_id' => $cart->data['checkout_id'] ?? null,
154 'order_id' => $orderId,
155 'payment_method' => $order->get_payment_method(),
156 'fields' => $customerFields,
157 'shop_url' => home_url(),
158 'order_url' => home_url() . "/wp-admin/post.php?post=" . $orderId . "&action=edit",
159 'checkout_data' => WooMailerLiteCheckoutDataService::getCheckoutData($order->get_billing_email())
160 ];
161 $this->apiClient()->sendOrderProcessing($data);
162 if (WooMailerLiteOptions::isCompleteOrderStatus($order->get_status()) && $order->get_items()) {
163 $order_items = $order->get_items();
164 foreach ($order_items as $key => $value) {
165 $item_data = $value->get_data();
166 $orderData['order']['line_items'][$key] = $item_data;
167 $orderData['order']['line_items'][$key]['ignored_product'] = in_array($item_data['product_id'],
168 array_map('strval', array_keys(WooMailerLiteOptions::get('ignored_products', [])))) ? 1 : 0;
169 }
170 $orderData['order']['status'] = 'completed';
171 WooMailerLiteCache::set('order_sent:'.$orderId, true, 20);
172 $response = $this->apiClient()->syncOrder(home_url(), $orderData);
173 $this->apiClient()->sendSubscriberData($data);
174 }
175
176 } else {
177 $date = null;
178 if ($order->get_date_created()) {
179 $date = $order->get_date_created()->format('Y-m-d H:i:s');
180 }
181
182 $stage = WooMailerLiteOptions::isCompleteOrderStatus($order->get_status()) ? null : 'checkout';
183 $response = $this->apiClient()->syncOrder(
184 WooMailerLiteOptions::get('shopId'),
185 $orderId,
186 $orderCustomer,
187 $cartData,
188 $order->get_status(),
189 $order->get_total(),
190 $date,
191 $stage
192 );
193 }
194
195 if (isset($response) && $response->success) {
196 $order->add_meta_data('_woo_ml_order_data_submitted', true);
197 if (!empty($cart) && $cart instanceof WooMailerLiteCart) {
198 if ($this->apiClient()->isRewrite()) {
199 $this->apiClient()->deleteOrder($cart->data['checkout_id']);
200 }
201 if (WooMailerLiteOptions::isCompleteOrderStatus($order->get_status())) {
202 $cart->delete();
203 }
204 }
205
206 $createdAt = null;
207 $updatedAt = null;
208
209 if ($this->apiClient()->isClassic()) {
210 $response = $this->apiClient()->searchSubscriber($customer->email);
211
212 // For classic response, we have accesss to the date_created and date_updated fields
213 if ($response->success) {
214 $createdAt = $response->data->date_created;
215 $updatedAt = $response->data->date_updated;
216 }
217 }
218
219 // For rewrite response, we have accesss to the subscriber object
220 if (isset($response->data->customer->subscriber)) {
221 $createdAt = $response->data->customer->subscriber->created_at;
222 $updatedAt = $response->data->customer->subscriber->updated_at;
223 }
224
225 // We will only set the order meta when we have these dates
226 if ($createdAt && $updatedAt) {
227 $createdAt = strtotime($createdAt);
228 $updatedAt = strtotime($updatedAt);
229
230 // If the created and updated timestamps are within 60 seconds, the subscriber was just created
231 if (abs($createdAt - $updatedAt) < 60) {
232 $order->add_meta_data('_woo_ml_subscribed', true);
233 } else {
234 $order->add_meta_data('_woo_ml_already_subscribed', true);
235 $order->add_meta_data('_woo_ml_subscriber_updated', true);
236 }
237 }
238
239 $order->add_meta_data('_woo_ml_order_tracked', true);
240 }
241 $order->save();
242 } catch(\Throwable $e) {
243 WooMailerLiteLog()->error('handleOrderStatusChanged', [
244 'error' => $e->getMessage(),
245 'trace' => $e->getTraceAsString(),
246 'orderId' => $orderId
247 ]);
248
249 return true;
250 }
251 }
252
253 /**
254 * Snapshots the language while the order is being created, so gateway
255 * callbacks and later status changes do not need the shopper's session.
256 */
257 public function persistLanguageForOrder($order): void
258 {
259 WooMailerLiteLanguageService::persistToOrder($order);
260 }
261 }
262