AI store generator for ecommerce, Malaysia first. Laravel 13 + React + TypeScript.
Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

CheckoutController.php 7.8KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188
  1. <?php
  2. namespace App\Http\Controllers;
  3. use App\Commerce\Checkout;
  4. use App\Commerce\MalaysianStates;
  5. use App\Commerce\Payments\PaymentException;
  6. use App\Commerce\Payments\PaymentGateway;
  7. use App\Commerce\Payments\PaymentGateways;
  8. use App\Commerce\Shipping\ShippingProvider;
  9. use App\Http\Controllers\Concerns\RendersStorefront;
  10. use App\Models\Order;
  11. use App\Storefront\StorefrontText;
  12. use Illuminate\Http\RedirectResponse;
  13. use Illuminate\Http\Request;
  14. use Illuminate\Validation\Rule;
  15. use Illuminate\Validation\ValidationException;
  16. use Inertia\Inertia;
  17. use Inertia\Response;
  18. use Symfony\Component\HttpFoundation\Response as HttpResponse;
  19. /**
  20. * Checkout: the shopper's details, the trip to the payment page, and the page they come back to.
  21. */
  22. class CheckoutController extends Controller
  23. {
  24. use RendersStorefront;
  25. /**
  26. * The form for the shopper's contact details and delivery address.
  27. */
  28. public function show(Request $request, ShippingProvider $shipping, PaymentGateways $gateways): Response|RedirectResponse
  29. {
  30. $storefront = $this->storefront($request);
  31. $lines = $this->cart($request, $storefront->store)->lines();
  32. if ($lines->isEmpty()) {
  33. return redirect($storefront->path('/cart'));
  34. }
  35. $cart = $this->cart($request, $storefront->store);
  36. $subtotal = (int) $lines->sum('line_total');
  37. $applied = $cart->applied($lines);
  38. // Shipping is worked out on what the shopper pays for the products, after any discount.
  39. $afterDiscount = $subtotal - ($applied !== null ? $applied->amount : 0);
  40. $ways = $gateways->available($storefront->store);
  41. return $this->renderStorefront($request, $storefront, [
  42. 'type' => 'checkout',
  43. 'states' => MalaysianStates::ALL,
  44. // False until the merchant connects their own Stripe account (and Stripe approves it) or HitPay.
  45. 'takingOrders' => $ways !== [],
  46. // The ways to pay, for the shopper to choose: Stripe (card, FPX, GrabPay) and HitPay (DuitNow QR, e-wallets).
  47. 'payWays' => collect($ways)
  48. ->map(fn (PaymentGateway $gateway, string $key) => ['key' => $key, 'methods' => $gateway->methods($storefront->store)])
  49. ->values()
  50. ->all(),
  51. // The fee for each state, in ringgit, so the page can show it as soon as a state is chosen.
  52. 'shippingByState' => collect(MalaysianStates::ALL)
  53. ->mapWithKeys(fn (string $state) => [$state => $shipping->quote($storefront->store, $afterDiscount, $state) / 100])
  54. ->all(),
  55. ]);
  56. }
  57. /**
  58. * Save the order, then send the shopper to the payment page.
  59. */
  60. public function store(Request $request, Checkout $checkout, PaymentGateways $gateways): HttpResponse
  61. {
  62. $storefront = $this->storefront($request);
  63. $store = $storefront->store;
  64. $ways = $gateways->available($store);
  65. $details = $request->validate([
  66. 'name' => ['required', 'string', 'min:2', 'max:120'],
  67. 'email' => ['required', 'email', 'max:160'],
  68. 'phone' => ['required', 'string', 'regex:/^[0-9+\-\s]{7,20}$/'],
  69. 'line1' => ['required', 'string', 'min:3', 'max:200'],
  70. 'line2' => ['nullable', 'string', 'max:200'],
  71. 'city' => ['required', 'string', 'min:2', 'max:100'],
  72. 'postcode' => ['required', 'string', 'regex:/^[0-9]{5}$/'],
  73. 'state' => ['required', Rule::in(MalaysianStates::ALL)],
  74. // Which way to pay. Optional: the first way is used when the shopper had no choice to make.
  75. 'pay_with' => ['nullable', 'string', 'max:20'],
  76. ], StorefrontText::checkoutMessages($store->language->value), StorefrontText::checkoutFields($store->language->value));
  77. if ($ways === []) {
  78. throw ValidationException::withMessages(['cart' => StorefrontText::line($store->language->value, 'not_taking_orders')]);
  79. }
  80. // A way that is no longer offered (the merchant disconnected it meanwhile) falls back to the first one.
  81. $gateway = $ways[$details['pay_with'] ?? ''] ?? reset($ways);
  82. unset($details['pay_with']);
  83. $order = $checkout->placeOrder($store, $this->cart($request, $store), $details);
  84. // Set before the payment page is made, so the page and what the shopper is told end at the same time.
  85. $order->payment_expires_at = now()->addHours(Checkout::PAY_WITHIN_HOURS);
  86. try {
  87. $link = $gateway->startCheckout(
  88. $order,
  89. successUrl: $storefront->url('/orders/'.$order->public_id),
  90. cancelUrl: $storefront->url('/cart'),
  91. );
  92. } catch (PaymentException $e) {
  93. report($e);
  94. $order->delete();
  95. throw ValidationException::withMessages([
  96. 'cart' => StorefrontText::line($store->language->value, 'payment_unavailable'),
  97. ]);
  98. }
  99. $order->payment_provider = $gateway->name();
  100. $order->payment_checkout_id = $link->id;
  101. $order->payment_url = $link->url;
  102. $order->payment_account = $link->account;
  103. $order->save();
  104. // So the cart page can offer "Complete payment" if the shopper leaves the payment page.
  105. $this->cart($request, $store)->rememberUnpaidOrder($order);
  106. // The payment page is on another website, so this is a full browser redirect.
  107. return Inertia::location($link->url);
  108. }
  109. /**
  110. * Where the shopper lands after paying. The long random id in the address is what protects the page.
  111. */
  112. public function order(Request $request, Checkout $checkout, PaymentGateways $gateways): Response
  113. {
  114. $storefront = $this->storefront($request);
  115. $store = $storefront->store;
  116. $order = $this->findOrder($request, $checkout, $gateways);
  117. if ($order->isPaid()) {
  118. $this->cart($request, $store)->clear();
  119. }
  120. return $this->renderStorefront($request, $storefront, [
  121. 'type' => 'order',
  122. 'order' => $order->toDisplay(),
  123. // "Complete payment" while the payment page still takes payments; "closed" once it no longer does.
  124. 'payment' => $order->isPaid() || $order->payment_expires_at === null ? null : [
  125. 'can_pay' => $order->canStillPay(),
  126. 'expires_at' => $order->payment_expires_at->toIso8601String(),
  127. ],
  128. ]);
  129. }
  130. /**
  131. * "Complete payment": back to the same payment page, for a shopper who left it. Used by the order page, the
  132. * cart page and the reminder email. Asks the provider first, so a shopper who already paid sees the thank-you.
  133. */
  134. public function pay(Request $request, Checkout $checkout, PaymentGateways $gateways): HttpResponse
  135. {
  136. $storefront = $this->storefront($request);
  137. $order = $this->findOrder($request, $checkout, $gateways);
  138. if (! $order->canStillPay()) {
  139. return redirect($storefront->path('/orders/'.$order->public_id));
  140. }
  141. // The payment page is on another website, so this is a full browser redirect.
  142. return Inertia::location((string) $order->payment_url);
  143. }
  144. /**
  145. * The order in the address, marked paid first if the provider says it was. Nothing in the web address is trusted.
  146. */
  147. private function findOrder(Request $request, Checkout $checkout, PaymentGateways $gateways): Order
  148. {
  149. /** @var Order $order */
  150. $order = $this->storefront($request)->store->orders()->with('items')->where('public_id', (string) $request->route('publicId'))->firstOrFail();
  151. if (! $order->isPaid() && $order->payment_checkout_id !== null) {
  152. try {
  153. $checkout->markPaid($order, $gateways->for($order)->checkPayment($order));
  154. } catch (PaymentException $e) {
  155. report($e);
  156. }
  157. }
  158. return $order;
  159. }
  160. }