AI store generator for ecommerce, Malaysia first. Laravel 13 + React + TypeScript.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

Checkout.php 5.5KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150
  1. <?php
  2. namespace App\Commerce;
  3. use App\Commerce\Payments\PaymentStatus;
  4. use App\Commerce\Shipping\ShippingProvider;
  5. use App\Enums\OrderStatus;
  6. use App\Mail\OrderConfirmation;
  7. use App\Models\Order;
  8. use App\Models\Product;
  9. use App\Models\Store;
  10. use App\Storefront\StorefrontText;
  11. use Illuminate\Support\Facades\DB;
  12. use Illuminate\Support\Facades\Mail;
  13. use Illuminate\Support\Str;
  14. use Illuminate\Validation\ValidationException;
  15. /**
  16. * Turns a cart into an order, and an order into a paid order.
  17. */
  18. class Checkout
  19. {
  20. public function __construct(private readonly ShippingProvider $shipping) {}
  21. /** Stripe does not accept payments below RM 2.00. */
  22. public const int MINIMUM_TOTAL = 200;
  23. /** The first order number of every store. */
  24. private const int FIRST_NUMBER = 1001;
  25. /**
  26. * Save the cart as an order that is waiting for payment.
  27. * The order keeps its own copy of each product's name and price.
  28. *
  29. * @param array{name: string, email: string, phone: string, line1: string, line2?: string|null, city: string, postcode: string, state: string} $details
  30. *
  31. * @throws ValidationException When the cart is empty or the total is too small.
  32. */
  33. public function placeOrder(Store $store, Cart $cart, array $details): Order
  34. {
  35. $lines = $cart->lines();
  36. $subtotal = (int) $lines->sum('line_total');
  37. if ($lines->isEmpty()) {
  38. throw ValidationException::withMessages(['cart' => StorefrontText::line($store->language->value, 'cart_empty')]);
  39. }
  40. if ($subtotal < self::MINIMUM_TOTAL) {
  41. throw ValidationException::withMessages(['cart' => StorefrontText::line($store->language->value, 'minimum_total')]);
  42. }
  43. $shipping = $this->shipping->quote($store, $subtotal, $details['state']);
  44. return DB::transaction(function () use ($store, $lines, $subtotal, $shipping, $details): Order {
  45. // Lock the store row so two orders placed at the same moment cannot get the same number.
  46. Store::query()->whereKey($store->id)->lockForUpdate()->first();
  47. $order = new Order;
  48. $order->store_id = $store->id;
  49. $order->public_id = (string) Str::ulid();
  50. $order->number = max(self::FIRST_NUMBER, (int) $store->orders()->max('number') + 1);
  51. $order->status = OrderStatus::Pending;
  52. $order->customer_name = $details['name'];
  53. $order->customer_email = $details['email'];
  54. $order->customer_phone = $details['phone'];
  55. $order->shipping_address = [
  56. 'line1' => $details['line1'],
  57. 'line2' => $details['line2'] ?? null,
  58. 'city' => $details['city'],
  59. 'postcode' => $details['postcode'],
  60. 'state' => $details['state'],
  61. 'country' => 'MY',
  62. ];
  63. $order->subtotal = $subtotal;
  64. $order->shipping_total = $shipping;
  65. $order->total = $subtotal + $shipping;
  66. $order->currency = 'MYR';
  67. $order->save();
  68. foreach ($lines as $line) {
  69. $order->items()->create([
  70. 'store_id' => $store->id,
  71. 'product_id' => $line['product']->id,
  72. 'name' => $line['product']->name,
  73. 'unit_price' => $line['product']->price,
  74. 'quantity' => $line['quantity'],
  75. 'line_total' => $line['line_total'],
  76. ]);
  77. }
  78. return $order->load('items');
  79. });
  80. }
  81. /**
  82. * Record that an order was paid: mark it, lower the stock, and email the shopper.
  83. *
  84. * Safe to call more than once for the same order (the return page and the webhook may both call it).
  85. * Only the first call does anything. Returns true when this call marked the order paid.
  86. */
  87. public function markPaid(Order $order, PaymentStatus $payment): bool
  88. {
  89. if (! $payment->paid || $payment->checkoutId !== $order->payment_checkout_id) {
  90. return false;
  91. }
  92. // The provider must have collected the full order total.
  93. if ($payment->amount !== null && $payment->amount !== $order->total) {
  94. report(new \RuntimeException("Order {$order->id}: paid amount {$payment->amount} does not match total {$order->total}."));
  95. return false;
  96. }
  97. $marked = DB::transaction(function () use ($order, $payment): bool {
  98. $locked = Order::query()->whereKey($order->id)->lockForUpdate()->firstOrFail();
  99. if ($locked->isPaid()) {
  100. return false;
  101. }
  102. $locked->status = OrderStatus::Paid;
  103. $locked->payment_reference = $payment->reference;
  104. $locked->paid_at = now();
  105. $locked->save();
  106. foreach ($locked->items as $item) {
  107. // The product may have been deleted since the order was placed.
  108. $product = $item->product_id !== null
  109. ? Product::query()->whereKey($item->product_id)->lockForUpdate()->first()
  110. : null;
  111. if ($product !== null) {
  112. // Never below zero, even if stock was changed by hand in the meantime.
  113. $product->stock = max(0, $product->stock - $item->quantity);
  114. $product->save();
  115. }
  116. }
  117. return true;
  118. });
  119. $order->refresh();
  120. if ($marked) {
  121. Mail::to($order->customer_email)->send(new OrderConfirmation($order));
  122. }
  123. return $marked;
  124. }
  125. }