AI store generator for ecommerce, Malaysia first. Laravel 13 + React + TypeScript.
Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

CheckoutController.php 6.1KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151
  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. try {
  85. $link = $gateway->startCheckout(
  86. $order,
  87. successUrl: $storefront->url('/orders/'.$order->public_id),
  88. cancelUrl: $storefront->url('/cart'),
  89. );
  90. } catch (PaymentException $e) {
  91. report($e);
  92. $order->delete();
  93. throw ValidationException::withMessages([
  94. 'cart' => StorefrontText::line($store->language->value, 'payment_unavailable'),
  95. ]);
  96. }
  97. $order->payment_provider = $gateway->name();
  98. $order->payment_checkout_id = $link->id;
  99. $order->payment_account = $link->account;
  100. $order->save();
  101. // The payment page is on another website, so this is a full browser redirect.
  102. return Inertia::location($link->url);
  103. }
  104. /**
  105. * Where the shopper lands after paying. The long random id in the address is what protects the page.
  106. */
  107. public function order(Request $request, Checkout $checkout, PaymentGateways $gateways): Response
  108. {
  109. $storefront = $this->storefront($request);
  110. $store = $storefront->store;
  111. /** @var Order $order */
  112. $order = $store->orders()->with('items')->where('public_id', (string) $request->route('publicId'))->firstOrFail();
  113. // Ask the payment provider directly. Nothing in the web address is trusted.
  114. if (! $order->isPaid() && $order->payment_checkout_id !== null) {
  115. try {
  116. $checkout->markPaid($order, $gateways->for($order)->checkPayment($order));
  117. } catch (PaymentException $e) {
  118. report($e);
  119. }
  120. }
  121. if ($order->isPaid()) {
  122. $this->cart($request, $store)->clear();
  123. }
  124. return $this->renderStorefront($request, $storefront, [
  125. 'type' => 'order',
  126. 'order' => $order->toDisplay(),
  127. ]);
  128. }
  129. }