| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160 |
- <?php
-
- namespace App\Commerce;
-
- use App\Commerce\Payments\PaymentException;
- use App\Commerce\Payments\PaymentGateways;
- use App\Enums\OrderStatus;
- use App\Mail\PaymentReminder;
- use App\Models\Order;
- use Carbon\CarbonInterface;
- use Illuminate\Support\Facades\Mail;
- use Throwable;
-
- /**
- * The double-check for unpaid orders, run every 5 minutes (orders:check-payments).
- *
- * Normally an order is marked paid when the shopper comes back to the store, or when Stripe or HitPay tells our
- * webhook. If both are missed (the shopper closed the phone and the webhook failed, or there is no public https
- * address yet), this asks the provider itself.
- *
- * To stay light, new orders are asked about often and older ones rarely, and nothing is asked after a day:
- * - not before the order is 2 minutes old (most payments are confirmed by then anyway)
- * - every 5 minutes for the first 15 minutes, every 15 minutes until 1 hour, then every hour
- * - after 25 hours the order becomes "Not paid" and is never asked about again. Both payment pages expire
- * after 23 hours (Checkout::PAY_WITHIN_HOURS), so nobody can pay after that.
- * That is about 30 questions per abandoned order in total, and none for orders that were paid normally.
- *
- * It also sends the "Complete your payment" email, once, about 30 minutes after an order that is still not paid.
- * Not sooner: many shoppers are still on the payment page in the first minutes (scanning a QR code, waiting for a
- * bank code), and an email then would only confuse them. It is sent only after the provider confirms the order is
- * unpaid, and not when the shopper has placed a newer order since (they probably started again).
- */
- class PaymentDoubleCheck
- {
- public const int FIRST_CHECK_AFTER_MINUTES = 2;
-
- public const int GIVE_UP_AFTER_HOURS = 25;
-
- public const int REMIND_AFTER_MINUTES = 30;
-
- public function __construct(
- private readonly PaymentGateways $gateways,
- private readonly Checkout $checkout,
- ) {}
-
- /**
- * @return array{checked: int, paid: int, failed: int, reminded: int, given_up: int}
- */
- public function run(): array
- {
- $result = ['checked' => 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;
- }
- }
|