0, 'paid' => 0, 'failed' => 0, 'reminded' => 0, 'given_up' => 0]; $orders = Order::query() ->with('store') ->where('status', OrderStatus::Pending) ->whereNotNull('payment_checkout_id') ->where('created_at', '<=', now()->subMinutes(self::FIRST_CHECK_AFTER_MINUTES)) ->where('created_at', '>', now()->subHours(self::GIVE_UP_AFTER_HOURS)) ->lazyById(100); foreach ($orders as $order) { $remind = $this->needsReminder($order); if (! $remind && ! self::isDue($order, now())) { continue; } // Saved before asking, so a provider that is down is not asked again on the very next run. $order->payment_checked_at = now(); $order->saveQuietly(); $result['checked']++; try { if ($this->checkout->markPaid($order, $this->gateways->for($order)->checkPayment($order))) { $result['paid']++; continue; } } catch (PaymentException $e) { // Not knowing whether they paid, no reminder is sent this time. report($e); $result['failed']++; continue; } if ($remind && $this->remind($order)) { $result['reminded']++; } } // A day later: the shopper gave up. $result['given_up'] = Order::query() ->where('status', OrderStatus::Pending) ->where('created_at', '<=', now()->subHours(self::GIVE_UP_AFTER_HOURS)) ->update(['status' => OrderStatus::Unpaid, 'updated_at' => now()]); return $result; } /** * Whether the shopper should get the "Complete your payment" email now: 30 minutes after ordering, once, while * there is still at least an hour to pay, and only for their latest order in the store. */ private function needsReminder(Order $order): bool { if ($order->payment_reminded_at !== null || $order->payment_url === null || $order->created_at->gt(now()->subMinutes(self::REMIND_AFTER_MINUTES)) || $order->payment_expires_at === null || $order->payment_expires_at->lt(now()->addHour())) { return false; } return ! Order::query() ->where('store_id', $order->store_id) ->where('customer_email', $order->customer_email) ->where('id', '>', $order->id) ->exists(); } /** * Send the reminder. Marked as sent first, so a shopper never gets it twice, even if sending fails. */ private function remind(Order $order): bool { $order->payment_reminded_at = now(); $order->saveQuietly(); try { Mail::to($order->customer_email)->send(new PaymentReminder($order)); } catch (Throwable $e) { report($e); return false; } return true; } /** * Whether it is time to ask about the order again. A little early is fine, because the schedule runs every * 5 minutes and never exactly on the second. */ public static function isDue(Order $order, CarbonInterface $now): bool { if ($order->payment_checked_at === null) { return true; } $age = $order->created_at->diffInMinutes($now); $gap = match (true) { $age < 15 => 5, $age < 60 => 15, default => 60, }; return $order->payment_checked_at->diffInSeconds($now) >= $gap * 60 - 30; } }