AI store generator for ecommerce, Malaysia first. Laravel 13 + React + TypeScript.
Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

PaymentDoubleCheck.php 5.7KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160
  1. <?php
  2. namespace App\Commerce;
  3. use App\Commerce\Payments\PaymentException;
  4. use App\Commerce\Payments\PaymentGateways;
  5. use App\Enums\OrderStatus;
  6. use App\Mail\PaymentReminder;
  7. use App\Models\Order;
  8. use Carbon\CarbonInterface;
  9. use Illuminate\Support\Facades\Mail;
  10. use Throwable;
  11. /**
  12. * The double-check for unpaid orders, run every 5 minutes (orders:check-payments).
  13. *
  14. * Normally an order is marked paid when the shopper comes back to the store, or when Stripe or HitPay tells our
  15. * webhook. If both are missed (the shopper closed the phone and the webhook failed, or there is no public https
  16. * address yet), this asks the provider itself.
  17. *
  18. * To stay light, new orders are asked about often and older ones rarely, and nothing is asked after a day:
  19. * - not before the order is 2 minutes old (most payments are confirmed by then anyway)
  20. * - every 5 minutes for the first 15 minutes, every 15 minutes until 1 hour, then every hour
  21. * - after 25 hours the order becomes "Not paid" and is never asked about again. Both payment pages expire
  22. * after 23 hours (Checkout::PAY_WITHIN_HOURS), so nobody can pay after that.
  23. * That is about 30 questions per abandoned order in total, and none for orders that were paid normally.
  24. *
  25. * It also sends the "Complete your payment" email, once, about 30 minutes after an order that is still not paid.
  26. * Not sooner: many shoppers are still on the payment page in the first minutes (scanning a QR code, waiting for a
  27. * bank code), and an email then would only confuse them. It is sent only after the provider confirms the order is
  28. * unpaid, and not when the shopper has placed a newer order since (they probably started again).
  29. */
  30. class PaymentDoubleCheck
  31. {
  32. public const int FIRST_CHECK_AFTER_MINUTES = 2;
  33. public const int GIVE_UP_AFTER_HOURS = 25;
  34. public const int REMIND_AFTER_MINUTES = 30;
  35. public function __construct(
  36. private readonly PaymentGateways $gateways,
  37. private readonly Checkout $checkout,
  38. ) {}
  39. /**
  40. * @return array{checked: int, paid: int, failed: int, reminded: int, given_up: int}
  41. */
  42. public function run(): array
  43. {
  44. $result = ['checked' => 0, 'paid' => 0, 'failed' => 0, 'reminded' => 0, 'given_up' => 0];
  45. $orders = Order::query()
  46. ->with('store')
  47. ->where('status', OrderStatus::Pending)
  48. ->whereNotNull('payment_checkout_id')
  49. ->where('created_at', '<=', now()->subMinutes(self::FIRST_CHECK_AFTER_MINUTES))
  50. ->where('created_at', '>', now()->subHours(self::GIVE_UP_AFTER_HOURS))
  51. ->lazyById(100);
  52. foreach ($orders as $order) {
  53. $remind = $this->needsReminder($order);
  54. if (! $remind && ! self::isDue($order, now())) {
  55. continue;
  56. }
  57. // Saved before asking, so a provider that is down is not asked again on the very next run.
  58. $order->payment_checked_at = now();
  59. $order->saveQuietly();
  60. $result['checked']++;
  61. try {
  62. if ($this->checkout->markPaid($order, $this->gateways->for($order)->checkPayment($order))) {
  63. $result['paid']++;
  64. continue;
  65. }
  66. } catch (PaymentException $e) {
  67. // Not knowing whether they paid, no reminder is sent this time.
  68. report($e);
  69. $result['failed']++;
  70. continue;
  71. }
  72. if ($remind && $this->remind($order)) {
  73. $result['reminded']++;
  74. }
  75. }
  76. // A day later: the shopper gave up.
  77. $result['given_up'] = Order::query()
  78. ->where('status', OrderStatus::Pending)
  79. ->where('created_at', '<=', now()->subHours(self::GIVE_UP_AFTER_HOURS))
  80. ->update(['status' => OrderStatus::Unpaid, 'updated_at' => now()]);
  81. return $result;
  82. }
  83. /**
  84. * Whether the shopper should get the "Complete your payment" email now: 30 minutes after ordering, once, while
  85. * there is still at least an hour to pay, and only for their latest order in the store.
  86. */
  87. private function needsReminder(Order $order): bool
  88. {
  89. if ($order->payment_reminded_at !== null
  90. || $order->payment_url === null
  91. || $order->created_at->gt(now()->subMinutes(self::REMIND_AFTER_MINUTES))
  92. || $order->payment_expires_at === null
  93. || $order->payment_expires_at->lt(now()->addHour())) {
  94. return false;
  95. }
  96. return ! Order::query()
  97. ->where('store_id', $order->store_id)
  98. ->where('customer_email', $order->customer_email)
  99. ->where('id', '>', $order->id)
  100. ->exists();
  101. }
  102. /**
  103. * Send the reminder. Marked as sent first, so a shopper never gets it twice, even if sending fails.
  104. */
  105. private function remind(Order $order): bool
  106. {
  107. $order->payment_reminded_at = now();
  108. $order->saveQuietly();
  109. try {
  110. Mail::to($order->customer_email)->send(new PaymentReminder($order));
  111. } catch (Throwable $e) {
  112. report($e);
  113. return false;
  114. }
  115. return true;
  116. }
  117. /**
  118. * Whether it is time to ask about the order again. A little early is fine, because the schedule runs every
  119. * 5 minutes and never exactly on the second.
  120. */
  121. public static function isDue(Order $order, CarbonInterface $now): bool
  122. {
  123. if ($order->payment_checked_at === null) {
  124. return true;
  125. }
  126. $age = $order->created_at->diffInMinutes($now);
  127. $gap = match (true) {
  128. $age < 15 => 5,
  129. $age < 60 => 15,
  130. default => 60,
  131. };
  132. return $order->payment_checked_at->diffInSeconds($now) >= $gap * 60 - 30;
  133. }
  134. }