AI store generator for ecommerce, Malaysia first. Laravel 13 + React + TypeScript.
Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

Checkout.php 5.2KB

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