Bläddra i källkod

Add GrabPay, and DuitNow QR and e-wallets through HitPay

- GrabPay is switched on for every merchant's own Stripe account, like FPX; stores set up earlier get it on their next check
- Merchants can connect their own HitPay account in Settings with their API key (checked with HitPay, stored encrypted) and choose DuitNow QR, Touch 'n Go and ShopeePay
- At checkout, shoppers choose Stripe (card, FPX, GrabPay) or HitPay (DuitNow QR, e-wallets); a store with only HitPay can take orders too
- HitPay orders are marked paid only after asking HitPay directly, on the return page and from HitPay's webhook
- Methods HitPay refuses are left out for an hour, the shopper pays with what is left, and the merchant sees a warning in Settings
- The HitPay key is kept out of error logs
- HITPAY_SANDBOX setting; run php artisan migrate (grabpay_requested, hitpay_accounts)
grabpay-and-hitpay
fahmisaad 10 timmar sedan
förälder
incheckning
acf0e3d283
36 ändrade filer med 1744 tillägg och 57 borttagningar
  1. 4
    0
      .env
  2. 36
    15
      PROGRESS.md
  3. 132
    0
      app/Commerce/Payments/HitPay/HitPayApi.php
  4. 128
    0
      app/Commerce/Payments/HitPay/HitPayGateway.php
  5. 19
    0
      app/Commerce/Payments/HitPay/HitPayRefusedMethods.php
  6. 4
    2
      app/Commerce/Payments/MerchantAccounts.php
  7. 1
    1
      app/Commerce/Payments/PaymentException.php
  8. 8
    1
      app/Commerce/Payments/PaymentGateway.php
  9. 45
    0
      app/Commerce/Payments/PaymentGateways.php
  10. 13
    9
      app/Commerce/Payments/StripeConnect.php
  11. 12
    0
      app/Commerce/Payments/StripeGateway.php
  12. 7
    7
      app/Commerce/Payments/StripeMerchantAccounts.php
  13. 22
    7
      app/Http/Controllers/CheckoutController.php
  14. 102
    0
      app/Http/Controllers/HitPayController.php
  15. 37
    0
      app/Http/Controllers/HitPayWebhookController.php
  16. 10
    1
      app/Http/Controllers/StoreSettingsController.php
  17. 97
    0
      app/Models/HitPayAccount.php
  18. 10
    0
      app/Models/Store.php
  19. 20
    2
      app/Models/StripeAccount.php
  20. 1
    1
      bootstrap/app.php
  21. 6
    0
      config/services.php
  22. 25
    0
      database/migrations/2026_12_01_000001_add_grabpay_requested_to_stripe_accounts.php
  23. 27
    0
      database/migrations/2026_12_02_000001_create_hitpay_accounts_table.php
  24. 24
    0
      database/migrations/2026_12_02_000002_add_refused_methods_to_hitpay_accounts.php
  25. 3
    2
      resources/js/components/stores/get-paid-setup.tsx
  26. 384
    0
      resources/js/components/stores/hitpay-setup.tsx
  27. 6
    0
      resources/js/pages/stores/settings.tsx
  28. 56
    2
      resources/js/storefront/pages/checkout.tsx
  29. 1
    0
      resources/js/storefront/renderer.tsx
  30. 24
    2
      resources/js/storefront/text.ts
  31. 15
    1
      resources/js/storefront/types.ts
  32. 8
    0
      routes/web.php
  33. 410
    0
      tests/Feature/Stores/HitPayTest.php
  34. 33
    2
      tests/Feature/Stores/StripeConnectTest.php
  35. 5
    0
      tests/Support/FakeGateway.php
  36. 9
    2
      tests/Support/FakeMerchantAccounts.php

+ 4
- 0
.env Visa fil

@@ -106,5 +106,9 @@ STRIPE_CONNECT_WEBHOOK_SECRET=
106 106
 EASYPARCEL_CLIENT_ID=
107 107
 EASYPARCEL_CLIENT_SECRET=
108 108
 
109
+# HitPay (DuitNow QR, Touch 'n Go, ShopeePay). Merchants paste their own API key in Settings.
110
+# true: talk to HitPay's sandbox (test accounts). Set to false on the real server.
111
+HITPAY_SANDBOX=true
112
+
109 113
 # Published stores open at <store name>.<this domain>. Leave blank on a development machine to use localhost.
110 114
 STOREFRONT_DOMAIN=

+ 36
- 15
PROGRESS.md Visa fil

@@ -3,9 +3,9 @@
3 3
 This file is the single source of truth for the project plan and status.
4 4
 Update it at the end of every work session.
5 5
 
6
-**Last updated:** 2026-11-30
7
-**Current step:** Stripe Connect, shopper emails, store contact email, store logos and EasyParcel are on `main`. On `main` (not committed yet): the logo in the store footer and as the browser tab icon. Step 9 part 8 on hold
8
-**Next action:** Commit the footer and tab icon work. Later: live courier rate at checkout, tracking updates, a lawyer reads the legal pages, backup AI provider, hosting
6
+**Last updated:** 2026-12-02
7
+**Current step:** Everything up to the store logo (footer and tab icon) is on `main`. GrabPay is switched on for merchants and tested, and DuitNow QR, Touch 'n Go and ShopeePay through HitPay are built and tested with a real HitPay sandbox payment (order #1011, DuitNow). Both not committed yet. Step 9 part 8 on hold
8
+**Next action:** Commit GrabPay and HitPay. Later: live courier rate at checkout, tracking updates, a lawyer reads the legal pages, backup AI provider, hosting
9 9
 
10 10
 Status marks: `[ ]` not started · `[~]` in progress · `[x]` done
11 11
 
@@ -27,14 +27,14 @@ A customer describes their brand, and the AI builds a complete online store.
27 27
 
28 28
 ### Confirmed
29 29
 
30
-| Topic                         | Decision                                                       |
31
-| ----------------------------- | -------------------------------------------------------------- |
32
-| Backend                       | Laravel 13 on PHP 8.3 / 8.4                                    |
33
-| Frontend                      | React + TypeScript                                             |
34
-| Payments                      | Stripe Malaysia                                                |
35
-| AI for first store generation | Claude Sonnet 5.5 (`claude-sonnet-5-5`)                        |
36
-| Pricing rule                  | Each plan has a limited number of full regenerations per month |
37
-| Template reuse                | Later improvement (see section 6)                              |
30
+| Topic                         | Decision                                                          |
31
+| ----------------------------- | ----------------------------------------------------------------- |
32
+| Backend                       | Laravel 13 on PHP 8.3 / 8.4                                       |
33
+| Frontend                      | React + TypeScript                                                |
34
+| Payments                      | Stripe Malaysia; HitPay for DuitNow QR and e-wallets (2026-12-02) |
35
+| AI for first store generation | Claude Sonnet 5.5 (`claude-sonnet-5-5`)                           |
36
+| Pricing rule                  | Each plan has a limited number of full regenerations per month    |
37
+| Template reuse                | Later improvement (see section 6)                                 |
38 38
 
39 39
 ### Confirmed on 2026-11-14 (previously proposed)
40 40
 
@@ -140,6 +140,20 @@ Changing from Claude to another AI model (or back) must be a settings change, no
140 140
 - Our own monthly plans (Billing) stay on our own Stripe account. Nothing changes there.
141 141
 - Plan B, if Stripe will not run Connect for a Malaysian platform: each merchant connects their own Malaysian payment gateway (such as CHIP or Billplz) instead, in the same "connect" way. The `PaymentGateway` interface already allows a second provider.
142 142
 
143
+### DuitNow QR and e-wallets through HitPay (decided 2026-12-02)
144
+
145
+- Stripe does not offer DuitNow QR, Touch 'n Go or ShopeePay in Malaysia, so these go through **HitPay**, as a second choice next to Stripe. Stripe stays the main way (card, FPX, GrabPay).
146
+- Fees compared on 2026-12-02 (from Stripe's and HitPay's own pricing pages; the merchant pays them, we take no cut): Malaysian card Stripe 3% + RM 1 vs HitPay 1.2% + RM 1; FPX Stripe 3% + RM 1 vs HitPay RM 2.50 flat; GrabPay Stripe 3% vs HitPay 2%; DuitNow QR 1.2%, Touch 'n Go 1.9%, ShopeePay 2.2% (HitPay only). Neither has a setup or monthly fee. HitPay adds 0.2% for its own payment links and online store, not for the API we use.
147
+- Each merchant connects **their own HitPay account** by pasting their API key (HitPay: Settings > API Keys) in Settings, card "DuitNow QR and e-wallets". We check the key with HitPay (`GET /v1/account-status`) before saving it, encrypted, in `hitpay_accounts`. HitPay's "Connect your HitPay account" button (OAuth) is still in beta and needs a platform app approved by HitPay, so it was not used.
148
+- The merchant ticks which of DuitNow QR, Touch 'n Go and ShopeePay shoppers see (all three at first). Only methods switched on in their HitPay account should be ticked; HitPay refuses a payment page with a method it does not offer, and the shopper is then told payment is unavailable.
149
+- At checkout, when both are connected, the shopper picks "Card, FPX online banking or GrabPay" (Stripe) or "DuitNow QR, Touch 'n Go eWallet or ShopeePay" (HitPay). A store with only HitPay can take orders too. The order saves `payment_provider` = `hitpay` and the payment request id.
150
+- An order counts as paid only after we ask HitPay directly (with the merchant's key) and the amount (in MYR) matches. This happens on the shopper's return page and when HitPay calls `/hitpay/webhook/{order public id}`. The webhook message itself is not trusted (no signature needed): it only makes us ask HitPay. HitPay only calls public https addresses, so the webhook is sent only when `APP_URL` is https.
151
+- `HITPAY_SANDBOX=true` (in `.env.local`) talks to HitPay's sandbox; set it to false on the real server.
152
+- Real sandbox test (2026-12-02): the sandbox account can be a Malaysian business (HitPay's docs said Singapore only). A new HitPay account has **every payment method switched off**, even cards; HitPay then refuses the payment page ("The selected payment method (duitnow) is unavailable for your account"). After turning on "Touch 'n Go & DuitNow", "ShopeePay / SPayLater" and "Cards and FPX" in HitPay's Payment Methods, order #1011 (RM 50) was paid by DuitNow QR: the sandbox QR code opens a "Mock Payment" page with a Pay button. The shopper came back to the store with `?reference=<payment request id>&status=completed`, and the order was marked paid after asking HitPay. HitPay's fee was RM 0.60 (1.2%). The webhook was not tried (it needs a public https address).
153
+- **Methods switched off in HitPay (added 2026-12-02):** the HitPay card's guide tells merchants to click Turn On in HitPay's Payment Methods first. When HitPay still refuses ticked methods at checkout, we remember them (`refused_methods`, `refused_at`), try once more with the methods left (so the shopper still pays), and leave them out of checkout for an hour. The HitPay card shows "HitPay turned down …" with what to do. Saving the methods, a new key, or HitPay accepting them later clears the warning. If every method is refused, the shopper is told payment is unavailable and only Stripe is offered for that hour.
154
+- Refunds are done in the merchant's HitPay dashboard. DuitNow payments cannot be refunded through HitPay.
155
+- Code: `app/Commerce/Payments/HitPay/` (`HitPayApi`, `HitPayGateway`), `PaymentGateways` (the ways to pay), `HitPayController`, `HitPayWebhookController`, `resources/js/components/stores/hitpay-setup.tsx`.
156
+
143 157
 ### How shipping and WhatsApp work (added in Step 7)
144 158
 
145 159
 - Shipping fees are stored on the store in sen (`shipping_west`, `shipping_east`, `free_shipping_over`). Sabah, Sarawak and Labuan use the east fee; every other state uses the west fee.
@@ -344,6 +358,7 @@ Changing from Claude to another AI model (or back) must be a settings change, no
344 358
 - Store pulse (`app/Dashboard/StorePulse.php`, table `dashboard_pulses`): AI task `pulse` (DeepSeek by default, `AI_PULSE_PROVIDER`/`AI_PULSE_MODEL`, 400 tokens). Written once per Malaysian day per view (all stores, or one store) and saved, so refreshing costs nothing; it loads just after the page (deferred). Only numbers, store names and product names go to the AI, never shoppers' details (the privacy page says so).
345 359
 - "Write again" asks for a fresh note, 3 times a day in all (`AI_PULSE_DAILY_REWRITES`), shown under the button ("2 of 3 left today"). It does not count toward the plan's AI changes. A failed AI answer does not use a turn.
346 360
 - If the AI cannot answer, the note is written from the numbers instead. The buttons under the note (ship, restock, publish) are worked out by us from the numbers, not by the AI.
361
+- **Look kept as it is (decided 2026-12-01):** a calmer redesign (grey surfaces, no sparklines, no coloured cards) was tried and dropped. The merchant prefers the original colourful Overview.
347 362
 - First real note: 442 tokens in, 63 out.
348 363
 - **Theme switch (added 2026-11-25):** Light and Dark sit in the sidebar footer, just above the user (`components/theme-switch.tsx`), one click each. With the sidebar folded it is one sun or moon button that flips between them. No System choice there: someone who never chose still follows their device, and the switch highlights how the page looks now. It uses the starter kit's `useAppearance` (browser storage and an `appearance` cookie); Settings → Appearance still offers System.
349 364
 
@@ -464,7 +479,7 @@ Part 1 (done 2026-11-16, no new accounts needed):
464 479
 
465 480
 Part 2 (needs outside accounts):
466 481
 
467
-- [ ] Switch on FPX and GrabPay in the Stripe dashboard (your action), then test an FPX payment
482
+- [x] FPX and GrabPay: switched on for each merchant's own Stripe account by the app (FPX 2026-11-30, GrabPay 2026-12-01), not in our dashboard. Both tested with real test payments
468 483
 - [~] EasyParcel (branch `feature/easyparcel`):
469 484
     - [x] Connect the merchant's own EasyParcel account with a guided setup in Settings, pickup address, usual parcel size
470 485
     - [x] Book a courier on a paid order: compare prices, book, print the label, tracking number and "on its way" email
@@ -474,7 +489,7 @@ Part 2 (needs outside accounts):
474 489
         - [ ] Tracking updates by themselves (collected, in transit, delivered)
475 490
         - [ ] Product weights, for a more exact parcel weight
476 491
 - [ ] Automatic WhatsApp order notifications (needs a WhatsApp Business Platform account from Meta, with approved message templates)
477
-- [ ] DuitNow QR and Malaysian e-wallets: only through a second payment provider (for example Billplz, ToyyibPay, HitPay or Fiuu). Decide whether it is worth it
492
+- [x] DuitNow QR and Malaysian e-wallets through HitPay (built 2026-12-02): merchants paste their HitPay API key in Settings and tick DuitNow QR, Touch 'n Go and ShopeePay; shoppers choose Stripe or HitPay at checkout; orders are marked paid only after asking HitPay. Tested with a real HitPay sandbox payment: order #1011 paid by DuitNow QR (see section 2)
478 493
 
479 494
 ### Step 8 — Discounts and product options
480 495
 
@@ -535,6 +550,7 @@ Notes:
535 550
     - [x] Tests with a pretend Stripe (`FakeMerchantAccounts`): 15 new tests, 341 in all pass
536 551
     - [x] Real test on 2026-11-30: Luna Skin signed up on Stripe's test form (sole proprietorship, Stripe's test values and test bank), came back "Connected", then order #1008 (Gentle Gel Cleanser RM 42 + RM 8 shipping) was paid with Stripe's test card. Stripe's page said "Pay Luna Skin Enterprise"; RM 50.00 landed in Luna Skin's own test account (RM 47.00 after Stripe's fee), nothing in ours, no cut. Order marked paid, email sent. Payouts turned on a minute later
537 552
     - [x] FPX test on 2026-11-30: order #1009 (Light Water-Gel Moisturiser 50ml RM 39 + RM 8 shipping) paid with FPX (Maybank2E, Stripe's test bank page). RM 47.00 landed in Luna Skin's own account (RM 44.59 after Stripe's fee), nothing in ours. Order marked paid on the return page
553
+    - [x] GrabPay (2026-12-01): asked for on each merchant's account once the sign-up form is finished, like FPX (`grabpay_payments` capability, then switched on in the account's payment method settings). Stores connected before this get it switched on the next time the app checks their account. New column `stripe_accounts.grabpay_requested`. Real test: Luna Skin order #1010 (RM 50) paid with GrabPay on Stripe's test page; RM 50.00 landed in Luna Skin's own account (RM 48.50 after Stripe's 3% GrabPay fee), nothing in ours
538 554
     - [ ] Before going live: switch on Connect in live mode, add our name, logo and colour for Stripe's sign-up page
539 555
 - [ ] Choose hosting and deploy
540 556
 - [x] Privacy policy and terms of service, naming the AI providers (done 2026-11-22, `/privacy` and `/terms`; a lawyer should read them before launch)
@@ -647,7 +663,7 @@ Then, from the project folder:
647 663
 ## 5. Open questions
648 664
 
649 665
 - **Who receives the money?** Decided 2026-11-30: Stripe Connect, each merchant's own Stripe account, no cut for us (see "How merchants get paid"). Still open: whether Stripe runs Connect for our Malaysian account (we find out once Connect is switched on).
650
-- **DuitNow QR and e-wallets:** Stripe does not offer them. Adding them means a second payment provider. Decide later, based on what merchants ask for.
666
+- **DuitNow QR and e-wallets:** decided 2026-12-02: through HitPay, next to Stripe (section 2).
651 667
 - Hosting provider (decide at Step 10)
652 668
 
653 669
 ## 6. Later improvements
@@ -720,4 +736,9 @@ Add one line per work session: date, what was done, what is next.
720 736
 | 2026-11-30 | Restyled the shopper emails (order paid, order shipped) in each store's own colours, fonts and corners, with View order, WhatsApp and Track parcel buttons and plain-text versions. Checked on desktop and phone width for Luna Skin, Sambal Nenek (Malay, serif) and Crunch & Co. 349 tests pass.                                                                                                                                                                                                                                                                                                                                                                                                                                                       | Commit and merge                                                |
721 737
 | 2026-11-30 | Store contact email: "How shoppers reach you" card in Settings (WhatsApp + email for shoppers); order emails are sent under the store's name with replies to that email, shown in the footer. 352 tests pass; saved and checked for Luna Skin.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           | Commit and merge                                                |
722 738
 | 2026-11-30 | Store logos: Logo box in the Design tab (upload, 8 ready designs, Claude draws 3 per try with 3 lifetime tries per store), shown in the store header and (uploads) in order emails; Claude's SVG cleaned by LogoSvg. Real Claude test drew a moon logo for Luna Skin. 360 tests pass.                                                                                                                                                                                                                                                                                                                                                                                                                                                                    | Commit and merge                                                |
723
-| 2026-12-01 | Store logo in the footer and as the browser tab icon (uploaded logo as a square PNG, otherwise the store's initials on its main colour); "In the browser tab" preview in the Logo box. Fixed an Overview test that failed on the 1st of each month. 362 tests pass; checked on Luna Skin. | Commit |
739
+| 2026-12-01 | Store logo in the footer and as the browser tab icon (uploaded logo as a square PNG, otherwise the store's initials on its main colour); "In the browser tab" preview in the Logo box. Fixed an Overview test that failed on the 1st of each month. 362 tests pass; checked on Luna Skin.                                                                                                                                                                                                                                                                                                                                                                                                                                                                | Commit                                                          |
740
+| 2026-12-01 | Tried a calmer Overview redesign, then reverted it on request; the original design stays.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                | Choose next                                                     |
741
+| 2026-12-01 | GrabPay switched on for every merchant's own Stripe account (like FPX); tested with order #1010 paid by GrabPay into Luna Skin's account. Researched DuitNow QR and e-wallets: HitPay recommended. 364 tests pass.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       | Commit; decide on HitPay                                        |
742
+| 2026-12-02 | Compared Stripe and HitPay fees. Built DuitNow QR, Touch 'n Go and ShopeePay through each merchant's own HitPay account: API key in Settings, choice of Stripe or HitPay at checkout, paid only after asking HitPay (return page and webhook). 376 tests pass; Settings card and checkout choice checked in the browser.                                                                                                                                                                                                                                                                                                                                                                                                                                 | Real HitPay sandbox test; commit                                |
743
+| 2026-12-02 | Real HitPay sandbox test: Malaysian sandbox account, methods switched on in HitPay first (all start off), order #1011 (RM 50) paid by DuitNow QR and marked paid; fee RM 0.60. HitPay key kept out of error logs. 376 tests pass.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        | Commit; warn merchants when HitPay refuses a method             |
744
+| 2026-12-02 | HitPay reminder: the card's guide says to Turn On methods in HitPay first; methods HitPay refuses are remembered, left out of checkout for an hour (the shopper still pays with what is left) and shown as a warning in the card until the merchant saves. 379 tests pass; warning checked in the browser. | Commit |

+ 132
- 0
app/Commerce/Payments/HitPay/HitPayApi.php Visa fil

@@ -0,0 +1,132 @@
1
+<?php
2
+
3
+namespace App\Commerce\Payments\HitPay;
4
+
5
+use App\Commerce\Payments\PaymentException;
6
+use Illuminate\Http\Client\ConnectionException;
7
+use Illuminate\Http\Client\PendingRequest;
8
+use Illuminate\Http\Client\Response;
9
+use Illuminate\Support\Facades\Http;
10
+
11
+/**
12
+ * Talks to HitPay's API with a merchant's own API key. Docs: docs.hitpayapp.com.
13
+ */
14
+class HitPayApi
15
+{
16
+    public function baseUrl(): string
17
+    {
18
+        return config('services.hitpay.sandbox') ? 'https://api.sandbox.hit-pay.com/v1' : 'https://api.hit-pay.com/v1';
19
+    }
20
+
21
+    /**
22
+     * Whether HitPay accepts the API key. Reads the account's status, which changes nothing.
23
+     *
24
+     * @throws PaymentException When HitPay cannot be reached.
25
+     */
26
+    public function acceptsKey(#[\SensitiveParameter] string $apiKey): bool
27
+    {
28
+        $response = $this->send(fn () => $this->request($apiKey)->get('/account-status'));
29
+
30
+        if ($response->successful()) {
31
+            return true;
32
+        }
33
+
34
+        if (in_array($response->status(), [401, 403, 404, 422], true)) {
35
+            return false;
36
+        }
37
+
38
+        throw new PaymentException('HitPay could not check the API key: HTTP '.$response->status());
39
+    }
40
+
41
+    /**
42
+     * Create a payment page ("payment request").
43
+     *
44
+     * @param  array<string, mixed>  $fields
45
+     * @return array<string, mixed>
46
+     *
47
+     * @throws PaymentException
48
+     */
49
+    public function createPaymentRequest(#[\SensitiveParameter] string $apiKey, array $fields): array
50
+    {
51
+        $response = $this->send(fn () => $this->request($apiKey)->asForm()->post('/payment-requests', $fields));
52
+        $refused = $this->refusedMethods($response, $fields['payment_methods'] ?? []);
53
+
54
+        if ($refused !== []) {
55
+            throw new HitPayRefusedMethods($refused, 'HitPay refused payment methods: '.implode(', ', $refused).'. '.$response->json('message'));
56
+        }
57
+
58
+        if (! $response->successful() || ! is_string($response->json('id')) || ! is_string($response->json('url'))) {
59
+            throw new PaymentException('HitPay could not create the payment page: HTTP '.$response->status().' '.mb_substr($response->body(), 0, 500));
60
+        }
61
+
62
+        return $response->json();
63
+    }
64
+
65
+    /**
66
+     * A payment page and the payments made on it.
67
+     *
68
+     * @return array<string, mixed>
69
+     *
70
+     * @throws PaymentException
71
+     */
72
+    public function paymentRequest(#[\SensitiveParameter] string $apiKey, string $id): array
73
+    {
74
+        $response = $this->send(fn () => $this->request($apiKey)->get('/payment-requests/'.rawurlencode($id)));
75
+
76
+        if (! $response->successful() || ! is_array($response->json())) {
77
+            throw new PaymentException('HitPay could not find the payment: HTTP '.$response->status());
78
+        }
79
+
80
+        return $response->json();
81
+    }
82
+
83
+    /**
84
+     * The methods HitPay said are unavailable for the account. It answers 422 with an error per method,
85
+     * such as "payment_methods.0": "The selected payment method (duitnow) is unavailable for your account ...".
86
+     *
87
+     * @param  list<string>  $methods  The methods that were sent, in order
88
+     * @return list<string>
89
+     */
90
+    private function refusedMethods(Response $response, array $methods): array
91
+    {
92
+        if ($response->status() !== 422 || ! is_array($response->json('errors'))) {
93
+            return [];
94
+        }
95
+
96
+        $refused = [];
97
+
98
+        foreach (array_keys($response->json('errors')) as $field) {
99
+            if (preg_match('/^payment_methods\.(\d+)$/', (string) $field, $match) === 1 && isset($methods[(int) $match[1]])) {
100
+                $refused[] = $methods[(int) $match[1]];
101
+            }
102
+        }
103
+
104
+        return array_values(array_unique($refused));
105
+    }
106
+
107
+    private function request(#[\SensitiveParameter] string $apiKey): PendingRequest
108
+    {
109
+        return Http::baseUrl($this->baseUrl())
110
+            ->acceptJson()
111
+            ->timeout(20)
112
+            ->withHeaders([
113
+                'X-BUSINESS-API-KEY' => $apiKey,
114
+                // HitPay's FAQ: without this header some calls answer "Invalid Business API Key".
115
+                'X-Requested-With' => 'XMLHttpRequest',
116
+            ]);
117
+    }
118
+
119
+    /**
120
+     * @param  callable(): Response  $call
121
+     *
122
+     * @throws PaymentException
123
+     */
124
+    private function send(callable $call): Response
125
+    {
126
+        try {
127
+            return $call();
128
+        } catch (ConnectionException $e) {
129
+            throw new PaymentException('HitPay could not be reached: '.$e->getMessage(), 0, $e);
130
+        }
131
+    }
132
+}

+ 128
- 0
app/Commerce/Payments/HitPay/HitPayGateway.php Visa fil

@@ -0,0 +1,128 @@
1
+<?php
2
+
3
+namespace App\Commerce\Payments\HitPay;
4
+
5
+use App\Commerce\Payments\CheckoutLink;
6
+use App\Commerce\Payments\PaymentException;
7
+use App\Commerce\Payments\PaymentGateway;
8
+use App\Commerce\Payments\PaymentStatus;
9
+use App\Models\Order;
10
+use App\Models\Store;
11
+use App\Support\MalaysianPhone;
12
+
13
+/**
14
+ * DuitNow QR, Touch 'n Go and ShopeePay through the merchant's own HitPay account. HitPay hosts the payment page.
15
+ *
16
+ * The page is made with the merchant's API key, so the money goes straight to them. We take no cut.
17
+ * Messages from HitPay are not trusted: they only tell us to ask HitPay about an order (HitPayWebhookController).
18
+ */
19
+final class HitPayGateway implements PaymentGateway
20
+{
21
+    public function __construct(private readonly HitPayApi $api) {}
22
+
23
+    public function name(): string
24
+    {
25
+        return 'hitpay';
26
+    }
27
+
28
+    public function canTakePayments(Store $store): bool
29
+    {
30
+        return $this->methods($store) !== [];
31
+    }
32
+
33
+    public function methods(Store $store): array
34
+    {
35
+        return $store->hitpayAccount?->offeredMethods() ?? [];
36
+    }
37
+
38
+    public function startCheckout(Order $order, string $successUrl, string $cancelUrl): CheckoutLink
39
+    {
40
+        $account = $order->store->hitpayAccount;
41
+
42
+        if ($account === null || $account->offeredMethods() === []) {
43
+            throw new PaymentException('The store has not connected HitPay.');
44
+        }
45
+
46
+        $methods = $this->methods($order->store);
47
+        $phone = MalaysianPhone::normalize($order->customer_phone);
48
+        $webhook = rtrim((string) config('app.url'), '/').route('hitpay.webhook', $order->public_id, false);
49
+
50
+        $fields = [
51
+            'amount' => number_format($order->total / 100, 2, '.', ''),
52
+            'currency' => 'MYR',
53
+            'payment_methods' => $methods,
54
+            'email' => $order->customer_email,
55
+            'name' => $order->customer_name,
56
+            // HitPay wants the country code with a plus, such as +60123456789.
57
+            ...($phone !== null ? ['phone' => '+'.$phone] : []),
58
+            'purpose' => mb_substr($order->store->name.' order #'.$order->number, 0, 255),
59
+            'reference_number' => (string) $order->number,
60
+            'redirect_url' => $successUrl,
61
+            'allow_repeated_payments' => 'false',
62
+            // The store sends its own email once the order is paid.
63
+            'send_email' => 'false',
64
+            // HitPay only calls public https addresses, so a development machine relies on the shopper coming back.
65
+            ...(str_starts_with($webhook, 'https://') ? ['webhook' => $webhook] : []),
66
+        ];
67
+
68
+        try {
69
+            $request = $this->api->createPaymentRequest($account->api_key, $fields);
70
+
71
+            // Methods refused earlier were accepted this time: the merchant switched them on in HitPay.
72
+            if ($account->refused_methods !== null && array_diff($account->refused_methods, $methods) === []) {
73
+                $account->clearRefused();
74
+                $account->save();
75
+            }
76
+        } catch (HitPayRefusedMethods $e) {
77
+            // Some ticked methods are switched off in the merchant's HitPay account. Remember them, so the
78
+            // merchant is told in Settings and shoppers are not offered them for a while, then try once more
79
+            // with the methods that are left.
80
+            $account->refused($e->methods);
81
+            report($e);
82
+            $left = array_values(array_diff($methods, $e->methods));
83
+
84
+            if ($left === []) {
85
+                throw $e;
86
+            }
87
+
88
+            $request = $this->api->createPaymentRequest($account->api_key, [...$fields, 'payment_methods' => $left]);
89
+        }
90
+
91
+        return new CheckoutLink($request['id'], $request['url']);
92
+    }
93
+
94
+    public function checkPayment(Order $order): PaymentStatus
95
+    {
96
+        $account = $order->store->hitpayAccount;
97
+
98
+        if ($order->payment_checkout_id === null || $account === null) {
99
+            throw new PaymentException('The order has no HitPay payment page, or the store disconnected HitPay.');
100
+        }
101
+
102
+        $request = $this->api->paymentRequest($account->api_key, $order->payment_checkout_id);
103
+        $payments = is_array($request['payments'] ?? null) ? $request['payments'] : [];
104
+        $payment = collect($payments)->first(fn ($payment) => is_array($payment) && ($payment['status'] ?? null) === 'succeeded');
105
+        $inRinggit = strtolower((string) ($request['currency'] ?? '')) === 'myr';
106
+
107
+        return new PaymentStatus(
108
+            checkoutId: (string) ($request['id'] ?? $order->payment_checkout_id),
109
+            paid: $inRinggit && ($payment !== null || ($request['status'] ?? null) === 'completed'),
110
+            reference: is_string($payment['id'] ?? null) ? $payment['id'] : null,
111
+            amount: self::sen($payment['amount'] ?? $request['amount'] ?? null),
112
+        );
113
+    }
114
+
115
+    /**
116
+     * Not used: HitPay's messages go to HitPayWebhookController, which asks HitPay directly instead of trusting them.
117
+     */
118
+    public function readWebhook(string $payload, string $signature, bool $fromMerchants = false): ?PaymentStatus
119
+    {
120
+        return null;
121
+    }
122
+
123
+    /** HitPay sends amounts as text in ringgit, such as "50.00". */
124
+    private static function sen(mixed $amount): ?int
125
+    {
126
+        return is_numeric($amount) ? (int) round(((float) $amount) * 100) : null;
127
+    }
128
+}

+ 19
- 0
app/Commerce/Payments/HitPay/HitPayRefusedMethods.php Visa fil

@@ -0,0 +1,19 @@
1
+<?php
2
+
3
+namespace App\Commerce\Payments\HitPay;
4
+
5
+use App\Commerce\Payments\PaymentException;
6
+
7
+/**
8
+ * HitPay refused some payment methods: they are not switched on in the merchant's HitPay account.
9
+ */
10
+final class HitPayRefusedMethods extends PaymentException
11
+{
12
+    /**
13
+     * @param  list<string>  $methods  HitPay's names, such as "duitnow"
14
+     */
15
+    public function __construct(public readonly array $methods, string $message)
16
+    {
17
+        parent::__construct($message);
18
+    }
19
+}

+ 4
- 2
app/Commerce/Payments/MerchantAccounts.php Visa fil

@@ -30,10 +30,12 @@ interface MerchantAccounts
30 30
     public function status(string $accountId): MerchantAccountStatus;
31 31
 
32 32
     /**
33
-     * Ask the provider to switch on FPX (online banking) for the account, and show it to shoppers.
33
+     * Ask the provider to switch on a payment method for the account, and show it to shoppers.
34 34
      * Only possible once the merchant has finished the sign-up form.
35 35
      *
36
+     * @param  string  $method  One of StripeAccount::METHODS: "fpx" (online banking) or "grabpay".
37
+     *
36 38
      * @throws PaymentException
37 39
      */
38
-    public function requestFpx(string $accountId): void;
40
+    public function requestMethod(string $accountId, string $method): void;
39 41
 }

+ 1
- 1
app/Commerce/Payments/PaymentException.php Visa fil

@@ -7,4 +7,4 @@ use RuntimeException;
7 7
 /**
8 8
  * Anything that goes wrong while talking to the payment provider.
9 9
  */
10
-final class PaymentException extends RuntimeException {}
10
+class PaymentException extends RuntimeException {}

+ 8
- 1
app/Commerce/Payments/PaymentGateway.php Visa fil

@@ -7,7 +7,7 @@ use App\Models\Store;
7 7
 
8 8
 /**
9 9
  * The one interface the app uses to take payments.
10
- * Stripe is the first provider. Another provider only needs a class that implements this.
10
+ * Stripe is the main provider and HitPay the second (PaymentGateways). Another provider only needs a class that implements this.
11 11
  */
12 12
 interface PaymentGateway
13 13
 {
@@ -19,6 +19,13 @@ interface PaymentGateway
19 19
      */
20 20
     public function canTakePayments(Store $store): bool;
21 21
 
22
+    /**
23
+     * The payment methods shoppers will see on this provider's page, such as ["card", "fpx", "grabpay"].
24
+     *
25
+     * @return list<string>
26
+     */
27
+    public function methods(Store $store): array;
28
+
22 29
     /**
23 30
      * Create a payment page for the order and say where to send the shopper.
24 31
      *

+ 45
- 0
app/Commerce/Payments/PaymentGateways.php Visa fil

@@ -0,0 +1,45 @@
1
+<?php
2
+
3
+namespace App\Commerce\Payments;
4
+
5
+use App\Commerce\Payments\HitPay\HitPayGateway;
6
+use App\Models\Order;
7
+use App\Models\Store;
8
+
9
+/**
10
+ * The ways a store can be paid. Stripe (cards, FPX, GrabPay) comes first; HitPay (DuitNow QR and e-wallets) is a
11
+ * second choice when the merchant connected it. The shopper picks one at checkout.
12
+ */
13
+class PaymentGateways
14
+{
15
+    public function __construct(
16
+        private readonly PaymentGateway $main,
17
+        private readonly HitPayGateway $hitpay,
18
+    ) {}
19
+
20
+    /**
21
+     * The ways shoppers can pay this store now, by name, in the order shown.
22
+     *
23
+     * @return array<string, PaymentGateway>
24
+     */
25
+    public function available(Store $store): array
26
+    {
27
+        $ways = [];
28
+
29
+        foreach ([$this->main, $this->hitpay] as $gateway) {
30
+            if ($gateway->canTakePayments($store)) {
31
+                $ways[$gateway->name()] = $gateway;
32
+            }
33
+        }
34
+
35
+        return $ways;
36
+    }
37
+
38
+    /**
39
+     * The provider an order was sent to. Orders from before HitPay were all Stripe's.
40
+     */
41
+    public function for(Order $order): PaymentGateway
42
+    {
43
+        return $order->payment_provider === $this->hitpay->name() ? $this->hitpay : $this->main;
44
+    }
45
+}

+ 13
- 9
app/Commerce/Payments/StripeConnect.php Visa fil

@@ -43,7 +43,7 @@ class StripeConnect
43 43
 
44 44
     /**
45 45
      * Ask Stripe about the store's account and save the answer.
46
-     * The first time the sign-up form is finished, FPX is asked for too.
46
+     * Once the sign-up form is finished, FPX and GrabPay are asked for too, each once.
47 47
      *
48 48
      * @throws PaymentException
49 49
      */
@@ -64,13 +64,15 @@ class StripeConnect
64 64
             'checked_at' => now(),
65 65
         ]);
66 66
 
67
-        if ($status->detailsSubmitted && ! $account->fpx_requested) {
68
-            try {
69
-                $this->accounts->requestFpx($account->account_id);
70
-                $account->fpx_requested = true;
71
-            } catch (PaymentException $e) {
72
-                // Cards still work. We try again next time.
73
-                report($e);
67
+        if ($status->detailsSubmitted) {
68
+            foreach ($account->methodsToRequest() as $method) {
69
+                try {
70
+                    $this->accounts->requestMethod($account->account_id, $method);
71
+                    $account->{StripeAccount::METHODS[$method]} = true;
72
+                } catch (PaymentException $e) {
73
+                    // Cards still work. We try again next time.
74
+                    report($e);
75
+                }
74 76
             }
75 77
         }
76 78
 
@@ -87,7 +89,9 @@ class StripeConnect
87 89
     {
88 90
         $account = $store->stripeAccount;
89 91
 
90
-        if ($account === null || ($account->charges_enabled && $account->payouts_enabled)) {
92
+        // A fully set up store is not asked about again, unless a payment method we added later
93
+        // (such as GrabPay, added 2026-12-01) still has to be switched on for it.
94
+        if ($account === null || ($account->charges_enabled && $account->payouts_enabled && $account->methodsToRequest() === [])) {
91 95
             return $account;
92 96
         }
93 97
 

+ 12
- 0
app/Commerce/Payments/StripeGateway.php Visa fil

@@ -35,6 +35,18 @@ final class StripeGateway implements PaymentGateway
35 35
         return $this->connect->canTakePayments($store);
36 36
     }
37 37
 
38
+    public function methods(Store $store): array
39
+    {
40
+        $account = $store->stripeAccount;
41
+
42
+        // FPX and GrabPay are asked for once the merchant finishes Stripe's form. Cards are always on.
43
+        return array_values(array_filter([
44
+            'card',
45
+            $account?->fpx_requested ? 'fpx' : null,
46
+            $account?->grabpay_requested ? 'grabpay' : null,
47
+        ]));
48
+    }
49
+
38 50
     public function startCheckout(Order $order, string $successUrl, string $cancelUrl): CheckoutLink
39 51
     {
40 52
         $account = $order->store->stripeAccount?->account_id;

+ 7
- 7
app/Commerce/Payments/StripeMerchantAccounts.php Visa fil

@@ -69,22 +69,22 @@ final class StripeMerchantAccounts implements MerchantAccounts
69 69
         );
70 70
     }
71 71
 
72
-    public function requestFpx(string $accountId): void
72
+    public function requestMethod(string $accountId, string $method): void
73 73
     {
74 74
         try {
75
-            // The older capability call. The v2 update refuses Malaysian sole proprietors
76
-            // ("sole_proprietorship is not supported for entity type company"), found on 2026-11-30.
75
+            // The older capability call ("fpx_payments", "grabpay_payments"). The v2 update refuses Malaysian
76
+            // sole proprietors ("sole_proprietorship is not supported for entity type company"), found on 2026-11-30.
77 77
             $client = $this->client();
78 78
             $in = ['stripe_account' => $accountId];
79
-            $client->accounts->updateCapability($accountId, 'fpx_payments', ['requested' => true]);
79
+            $client->accounts->updateCapability($accountId, $method.'_payments', ['requested' => true]);
80 80
 
81
-            // Approved is not enough: FPX also starts switched off in the account's payment method
81
+            // Approved is not enough: the method also starts switched off in the account's payment method
82 82
             // settings, so shoppers would only see cards. Switch it on there too.
83 83
             foreach ($client->paymentMethodConfigurations->all(['limit' => 10], $in)->data as $configuration) {
84
-                $client->paymentMethodConfigurations->update($configuration->id, ['fpx' => ['display_preference' => ['preference' => 'on']]], $in);
84
+                $client->paymentMethodConfigurations->update($configuration->id, [$method => ['display_preference' => ['preference' => 'on']]], $in);
85 85
             }
86 86
         } catch (ApiErrorException $e) {
87
-            throw new PaymentException('Stripe could not switch on FPX: '.$e->getMessage(), 0, $e);
87
+            throw new PaymentException("Stripe could not switch on {$method}: ".$e->getMessage(), 0, $e);
88 88
         }
89 89
     }
90 90
 

+ 22
- 7
app/Http/Controllers/CheckoutController.php Visa fil

@@ -6,6 +6,7 @@ use App\Commerce\Checkout;
6 6
 use App\Commerce\MalaysianStates;
7 7
 use App\Commerce\Payments\PaymentException;
8 8
 use App\Commerce\Payments\PaymentGateway;
9
+use App\Commerce\Payments\PaymentGateways;
9 10
 use App\Commerce\Shipping\ShippingProvider;
10 11
 use App\Http\Controllers\Concerns\RendersStorefront;
11 12
 use App\Models\Order;
@@ -28,7 +29,7 @@ class CheckoutController extends Controller
28 29
     /**
29 30
      * The form for the shopper's contact details and delivery address.
30 31
      */
31
-    public function show(Request $request, ShippingProvider $shipping, PaymentGateway $gateway): Response|RedirectResponse
32
+    public function show(Request $request, ShippingProvider $shipping, PaymentGateways $gateways): Response|RedirectResponse
32 33
     {
33 34
         $storefront = $this->storefront($request);
34 35
         $lines = $this->cart($request, $storefront->store)->lines();
@@ -43,11 +44,18 @@ class CheckoutController extends Controller
43 44
         // Shipping is worked out on what the shopper pays for the products, after any discount.
44 45
         $afterDiscount = $subtotal - ($applied !== null ? $applied->amount : 0);
45 46
 
47
+        $ways = $gateways->available($storefront->store);
48
+
46 49
         return $this->renderStorefront($request, $storefront, [
47 50
             'type' => 'checkout',
48 51
             'states' => MalaysianStates::ALL,
49
-            // False until the merchant connects their own Stripe account and Stripe approves it.
50
-            'takingOrders' => $gateway->canTakePayments($storefront->store),
52
+            // False until the merchant connects their own Stripe account (and Stripe approves it) or HitPay.
53
+            'takingOrders' => $ways !== [],
54
+            // The ways to pay, for the shopper to choose: Stripe (card, FPX, GrabPay) and HitPay (DuitNow QR, e-wallets).
55
+            'payWays' => collect($ways)
56
+                ->map(fn (PaymentGateway $gateway, string $key) => ['key' => $key, 'methods' => $gateway->methods($storefront->store)])
57
+                ->values()
58
+                ->all(),
51 59
             // The fee for each state, in ringgit, so the page can show it as soon as a state is chosen.
52 60
             'shippingByState' => collect(MalaysianStates::ALL)
53 61
                 ->mapWithKeys(fn (string $state) => [$state => $shipping->quote($storefront->store, $afterDiscount, $state) / 100])
@@ -58,10 +66,11 @@ class CheckoutController extends Controller
58 66
     /**
59 67
      * Save the order, then send the shopper to the payment page.
60 68
      */
61
-    public function store(Request $request, Checkout $checkout, PaymentGateway $gateway): HttpResponse
69
+    public function store(Request $request, Checkout $checkout, PaymentGateways $gateways): HttpResponse
62 70
     {
63 71
         $storefront = $this->storefront($request);
64 72
         $store = $storefront->store;
73
+        $ways = $gateways->available($store);
65 74
 
66 75
         $details = $request->validate([
67 76
             'name' => ['required', 'string', 'min:2', 'max:120'],
@@ -72,12 +81,18 @@ class CheckoutController extends Controller
72 81
             'city' => ['required', 'string', 'min:2', 'max:100'],
73 82
             'postcode' => ['required', 'string', 'regex:/^[0-9]{5}$/'],
74 83
             'state' => ['required', Rule::in(MalaysianStates::ALL)],
84
+            // Which way to pay. Optional: the first way is used when the shopper had no choice to make.
85
+            'pay_with' => ['nullable', 'string', 'max:20'],
75 86
         ], StorefrontText::checkoutMessages($store->language->value), StorefrontText::checkoutFields($store->language->value));
76 87
 
77
-        if (! $gateway->canTakePayments($store)) {
88
+        if ($ways === []) {
78 89
             throw ValidationException::withMessages(['cart' => StorefrontText::line($store->language->value, 'not_taking_orders')]);
79 90
         }
80 91
 
92
+        // A way that is no longer offered (the merchant disconnected it meanwhile) falls back to the first one.
93
+        $gateway = $ways[$details['pay_with'] ?? ''] ?? reset($ways);
94
+        unset($details['pay_with']);
95
+
81 96
         $order = $checkout->placeOrder($store, $this->cart($request, $store), $details);
82 97
 
83 98
         try {
@@ -107,7 +122,7 @@ class CheckoutController extends Controller
107 122
     /**
108 123
      * Where the shopper lands after paying. The long random id in the address is what protects the page.
109 124
      */
110
-    public function order(Request $request, Checkout $checkout, PaymentGateway $gateway): Response
125
+    public function order(Request $request, Checkout $checkout, PaymentGateways $gateways): Response
111 126
     {
112 127
         $storefront = $this->storefront($request);
113 128
         $store = $storefront->store;
@@ -118,7 +133,7 @@ class CheckoutController extends Controller
118 133
         // Ask the payment provider directly. Nothing in the web address is trusted.
119 134
         if (! $order->isPaid() && $order->payment_checkout_id !== null) {
120 135
             try {
121
-                $checkout->markPaid($order, $gateway->checkPayment($order));
136
+                $checkout->markPaid($order, $gateways->for($order)->checkPayment($order));
122 137
             } catch (PaymentException $e) {
123 138
                 report($e);
124 139
             }

+ 102
- 0
app/Http/Controllers/HitPayController.php Visa fil

@@ -0,0 +1,102 @@
1
+<?php
2
+
3
+namespace App\Http\Controllers;
4
+
5
+use App\Commerce\Payments\HitPay\HitPayApi;
6
+use App\Commerce\Payments\PaymentException;
7
+use App\Models\HitPayAccount;
8
+use App\Models\Store;
9
+use Illuminate\Http\RedirectResponse;
10
+use Illuminate\Http\Request;
11
+use Illuminate\Validation\Rule;
12
+use Illuminate\Validation\ValidationException;
13
+use Inertia\Inertia;
14
+
15
+/**
16
+ * Connecting a store to the merchant's own HitPay account, for DuitNow QR, Touch 'n Go and ShopeePay.
17
+ * The merchant pastes their API key from HitPay. We check it with HitPay before saving it.
18
+ */
19
+class HitPayController extends Controller
20
+{
21
+    public function connect(Request $request, string $slug, HitPayApi $api): RedirectResponse
22
+    {
23
+        $store = $this->ownedStore($request, $slug);
24
+
25
+        $validated = $request->validate([
26
+            'api_key' => ['required', 'string', 'min:10', 'max:200', 'regex:/^\S+$/'],
27
+        ], [
28
+            'api_key.required' => __('Paste your HitPay API key.'),
29
+            'api_key.*' => __('That does not look like a HitPay API key. Copy it again from HitPay.'),
30
+        ]);
31
+
32
+        $key = trim($validated['api_key']);
33
+
34
+        try {
35
+            $accepted = $api->acceptsKey($key);
36
+        } catch (PaymentException $e) {
37
+            report($e);
38
+
39
+            throw ValidationException::withMessages(['api_key' => __('HitPay could not be reached. Please try again in a moment.')]);
40
+        }
41
+
42
+        if (! $accepted) {
43
+            throw ValidationException::withMessages(['api_key' => config('services.hitpay.sandbox')
44
+                ? __('HitPay did not accept this key. This app uses HitPay sandbox (test) accounts, so use a key from dashboard.sandbox.hit-pay.com.')
45
+                : __('HitPay did not accept this key. Copy it again from HitPay, under Settings > API Keys.')]);
46
+        }
47
+
48
+        $store->hitpayAccount()->updateOrCreate([], [
49
+            'api_key' => $key,
50
+            'methods' => $store->hitpayAccount->methods ?? HitPayAccount::METHODS,
51
+            // A new key may be a different HitPay account: try every method again.
52
+            'refused_methods' => null,
53
+            'refused_at' => null,
54
+        ]);
55
+
56
+        Inertia::flash('toast', ['type' => 'success', 'message' => __('HitPay is connected. Shoppers can now pay by DuitNow QR and e-wallets.')]);
57
+
58
+        return to_route('stores.settings', $store->slug);
59
+    }
60
+
61
+    /**
62
+     * Which HitPay methods shoppers see. Only methods switched on in the merchant's HitPay account should be ticked.
63
+     */
64
+    public function update(Request $request, string $slug): RedirectResponse
65
+    {
66
+        $store = $this->ownedStore($request, $slug);
67
+        $account = $store->hitpayAccount ?? abort(404);
68
+
69
+        $validated = $request->validate([
70
+            'methods' => ['required', 'array', 'min:1'],
71
+            'methods.*' => ['string', Rule::in(HitPayAccount::METHODS)],
72
+        ], [
73
+            'methods.required' => __('Tick at least one way to pay, or disconnect HitPay.'),
74
+            'methods.min' => __('Tick at least one way to pay, or disconnect HitPay.'),
75
+        ]);
76
+
77
+        // Kept in our own order, without repeats.
78
+        $account->methods = array_values(array_intersect(HitPayAccount::METHODS, $validated['methods']));
79
+        // The merchant may have switched refused methods on in HitPay meanwhile: offer them again.
80
+        $account->clearRefused();
81
+        $account->save();
82
+
83
+        Inertia::flash('toast', ['type' => 'success', 'message' => __('Saved.')]);
84
+
85
+        return to_route('stores.settings', $store->slug);
86
+    }
87
+
88
+    public function disconnect(Request $request, string $slug): RedirectResponse
89
+    {
90
+        $store = $this->ownedStore($request, $slug);
91
+        $store->hitpayAccount()->delete();
92
+
93
+        Inertia::flash('toast', ['type' => 'success', 'message' => __('HitPay is disconnected. Shoppers can no longer pay by DuitNow QR or e-wallets.')]);
94
+
95
+        return to_route('stores.settings', $store->slug);
96
+    }
97
+
98
+    private function ownedStore(Request $request, string $slug): Store
99
+    {
100
+        return $request->user()->stores()->where('slug', $slug)->firstOrFail();
101
+    }
102
+}

+ 37
- 0
app/Http/Controllers/HitPayWebhookController.php Visa fil

@@ -0,0 +1,37 @@
1
+<?php
2
+
3
+namespace App\Http\Controllers;
4
+
5
+use App\Commerce\Checkout;
6
+use App\Commerce\Payments\HitPay\HitPayGateway;
7
+use App\Commerce\Payments\PaymentException;
8
+use App\Models\Order;
9
+use Illuminate\Http\Response;
10
+
11
+/**
12
+ * HitPay calls this address when an order's payment page changes. The address names the order.
13
+ *
14
+ * Nothing in the message is trusted: it only tells us to ask HitPay about the order, with the merchant's own key,
15
+ * the same way the shopper's return page does. So a fake message cannot mark an order paid.
16
+ * It is the safety net for shoppers who pay but close the browser before coming back to the store.
17
+ */
18
+class HitPayWebhookController extends Controller
19
+{
20
+    public function __invoke(string $publicId, HitPayGateway $hitpay, Checkout $checkout): Response
21
+    {
22
+        $order = Order::query()
23
+            ->where('public_id', $publicId)
24
+            ->where('payment_provider', $hitpay->name())
25
+            ->first();
26
+
27
+        if ($order !== null && ! $order->isPaid()) {
28
+            try {
29
+                $checkout->markPaid($order, $hitpay->checkPayment($order));
30
+            } catch (PaymentException $e) {
31
+                report($e);
32
+            }
33
+        }
34
+
35
+        return response('OK');
36
+    }
37
+}

+ 10
- 1
app/Http/Controllers/StoreSettingsController.php Visa fil

@@ -18,7 +18,7 @@ use Inertia\Inertia;
18 18
 use Inertia\Response;
19 19
 
20 20
 /**
21
- * Store-wide settings that are not part of the design: getting paid, WhatsApp number, contact email, shipping fees, EasyParcel and the announcement bar.
21
+ * Store-wide settings that are not part of the design: getting paid (Stripe and HitPay), WhatsApp number, contact email, shipping fees, EasyParcel and the announcement bar.
22 22
  */
23 23
 class StoreSettingsController extends Controller
24 24
 {
@@ -66,6 +66,15 @@ class StoreSettingsController extends Controller
66 66
                 'can_take_payments' => (bool) $payments?->charges_enabled,
67 67
                 'payouts_enabled' => (bool) $payments?->payouts_enabled,
68 68
             ],
69
+            // The merchant's own HitPay account, for DuitNow QR and e-wallets. The key itself is never sent to the page.
70
+            'hitpay' => [
71
+                'connected' => $store->hitpayAccount !== null,
72
+                'methods' => $store->hitpayAccount->methods ?? [],
73
+                // Ticked methods HitPay refused when a shopper tried to pay: switched off in the merchant's HitPay account.
74
+                'refused' => $store->hitpayAccount->refused_methods ?? [],
75
+                'refused_at' => $store->hitpayAccount?->refused_at?->toIso8601String(),
76
+                'sandbox' => (bool) config('services.hitpay.sandbox'),
77
+            ],
69 78
             'easyparcel' => [
70 79
                 // False until the app's own EasyParcel keys are in .env.local.
71 80
                 'available' => $easyparcel->isConfigured(),

+ 97
- 0
app/Models/HitPayAccount.php Visa fil

@@ -0,0 +1,97 @@
1
+<?php
2
+
3
+namespace App\Models;
4
+
5
+use Carbon\CarbonInterface;
6
+use Illuminate\Database\Eloquent\Attributes\Fillable;
7
+use Illuminate\Database\Eloquent\Model;
8
+use Illuminate\Database\Eloquent\Relations\BelongsTo;
9
+
10
+/**
11
+ * A store's own HitPay account, for DuitNow QR, Touch 'n Go and ShopeePay. Shoppers' payments go straight into it.
12
+ *
13
+ * @property int $id
14
+ * @property int $store_id
15
+ * @property string $api_key The merchant's HitPay API key (encrypted)
16
+ * @property list<string> $methods HitPay's names for the methods the merchant ticked
17
+ * @property list<string>|null $refused_methods Ticked methods HitPay refused (switched off in the merchant's HitPay account)
18
+ * @property CarbonInterface|null $refused_at When HitPay last refused them
19
+ * @property CarbonInterface|null $created_at
20
+ * @property CarbonInterface|null $updated_at
21
+ * @property-read Store $store
22
+ */
23
+#[Fillable(['api_key', 'methods', 'refused_methods', 'refused_at'])]
24
+class HitPayAccount extends Model
25
+{
26
+    protected $table = 'hitpay_accounts';
27
+
28
+    protected $hidden = ['api_key'];
29
+
30
+    /**
31
+     * The HitPay methods we offer, by HitPay's own name. Cards, FPX and GrabPay stay with Stripe.
32
+     */
33
+    public const array METHODS = ['duitnow', 'touch_n_go', 'shopee_pay'];
34
+
35
+    /**
36
+     * How long a refused method is left out of checkout before we try it again. The merchant may have
37
+     * switched it on in HitPay meanwhile; saving the methods in Settings tries again at once.
38
+     */
39
+    public const int RETRY_REFUSED_AFTER_MINUTES = 60;
40
+
41
+    /**
42
+     * The ticked methods to show shoppers: refused ones are left out for a while, so shoppers are not
43
+     * offered something that fails.
44
+     *
45
+     * @return list<string>
46
+     */
47
+    public function offeredMethods(): array
48
+    {
49
+        $ticked = array_values(array_intersect(self::METHODS, $this->methods ?? []));
50
+
51
+        if ($this->refused_at === null || $this->refused_at->lt(now()->subMinutes(self::RETRY_REFUSED_AFTER_MINUTES))) {
52
+            return $ticked;
53
+        }
54
+
55
+        return array_values(array_diff($ticked, $this->refused_methods ?? []));
56
+    }
57
+
58
+    /**
59
+     * Remember that HitPay refused these methods.
60
+     *
61
+     * @param  list<string>  $methods
62
+     */
63
+    public function refused(array $methods): void
64
+    {
65
+        $this->refused_methods = array_values(array_intersect(self::METHODS, $methods));
66
+        $this->refused_at = now();
67
+        $this->save();
68
+    }
69
+
70
+    /** The merchant changed their methods or key: try every ticked method again. */
71
+    public function clearRefused(): void
72
+    {
73
+        $this->refused_methods = null;
74
+        $this->refused_at = null;
75
+    }
76
+
77
+    /**
78
+     * @return BelongsTo<Store, $this>
79
+     */
80
+    public function store(): BelongsTo
81
+    {
82
+        return $this->belongsTo(Store::class);
83
+    }
84
+
85
+    /**
86
+     * @return array<string, string>
87
+     */
88
+    protected function casts(): array
89
+    {
90
+        return [
91
+            'api_key' => 'encrypted',
92
+            'methods' => 'array',
93
+            'refused_methods' => 'array',
94
+            'refused_at' => 'datetime',
95
+        ];
96
+    }
97
+}

+ 10
- 0
app/Models/Store.php Visa fil

@@ -201,6 +201,16 @@ class Store extends Model
201 201
         return $this->hasOne(StripeAccount::class);
202 202
     }
203 203
 
204
+    /**
205
+     * The merchant's own HitPay account, for DuitNow QR and e-wallets.
206
+     *
207
+     * @return HasOne<HitPayAccount, $this>
208
+     */
209
+    public function hitpayAccount(): HasOne
210
+    {
211
+        return $this->hasOne(HitPayAccount::class);
212
+    }
213
+
204 214
     /**
205 215
      * @return HasMany<Order, $this>
206 216
      */

+ 20
- 2
app/Models/StripeAccount.php Visa fil

@@ -16,13 +16,14 @@ use Illuminate\Database\Eloquent\Relations\BelongsTo;
16 16
  * @property bool $charges_enabled Stripe lets the account take payments
17 17
  * @property bool $payouts_enabled Stripe pays the money into the merchant's bank
18 18
  * @property bool $details_submitted The merchant finished Stripe's sign-up form
19
- * @property bool $fpx_requested
19
+ * @property bool $fpx_requested FPX (online banking) was asked for
20
+ * @property bool $grabpay_requested GrabPay was asked for
20 21
  * @property CarbonInterface|null $checked_at When we last asked Stripe
21 22
  * @property CarbonInterface|null $created_at
22 23
  * @property CarbonInterface|null $updated_at
23 24
  * @property-read Store $store
24 25
  */
25
-#[Fillable(['account_id', 'charges_enabled', 'payouts_enabled', 'details_submitted', 'fpx_requested', 'checked_at'])]
26
+#[Fillable(['account_id', 'charges_enabled', 'payouts_enabled', 'details_submitted', 'fpx_requested', 'grabpay_requested', 'checked_at'])]
26 27
 class StripeAccount extends Model
27 28
 {
28 29
     /**
@@ -33,6 +34,22 @@ class StripeAccount extends Model
33 34
         return $this->belongsTo(Store::class);
34 35
     }
35 36
 
37
+    /**
38
+     * Malaysian payment methods asked for on the account, by our name, with the column that remembers it.
39
+     * Cards are always on.
40
+     */
41
+    public const array METHODS = ['fpx' => 'fpx_requested', 'grabpay' => 'grabpay_requested'];
42
+
43
+    /**
44
+     * The methods not asked for yet.
45
+     *
46
+     * @return list<string>
47
+     */
48
+    public function methodsToRequest(): array
49
+    {
50
+        return array_keys(array_filter(self::METHODS, fn (string $column) => ! $this->{$column}));
51
+    }
52
+
36 53
     /**
37 54
      * @return array<string, string>
38 55
      */
@@ -43,6 +60,7 @@ class StripeAccount extends Model
43 60
             'payouts_enabled' => 'boolean',
44 61
             'details_submitted' => 'boolean',
45 62
             'fpx_requested' => 'boolean',
63
+            'grabpay_requested' => 'boolean',
46 64
             'checked_at' => 'datetime',
47 65
         ];
48 66
     }

+ 1
- 1
bootstrap/app.php Visa fil

@@ -18,7 +18,7 @@ $app = Application::configure(basePath: dirname(__DIR__))
18 18
         $middleware->encryptCookies(except: ['appearance', 'sidebar_state']);
19 19
 
20 20
         // Stripe cannot send our form-protection token. Its messages are checked by signature instead.
21
-        $middleware->validateCsrfTokens(except: ['stripe/webhook', 'stripe/connect-webhook']);
21
+        $middleware->validateCsrfTokens(except: ['stripe/webhook', 'stripe/connect-webhook', 'hitpay/webhook/*']);
22 22
 
23 23
         $middleware->web(append: [
24 24
             HandleAppearance::class,

+ 6
- 0
config/services.php Visa fil

@@ -46,6 +46,12 @@ return [
46 46
         'connect_webhook_secret' => env('STRIPE_CONNECT_WEBHOOK_SECRET'),
47 47
     ],
48 48
 
49
+    'hitpay' => [
50
+        // Each merchant pastes their own HitPay API key in Settings. This only says which HitPay to talk to:
51
+        // true for HitPay's sandbox (test) accounts, false for real ones. Sandbox keys only work with the sandbox.
52
+        'sandbox' => (bool) env('HITPAY_SANDBOX', false),
53
+    ],
54
+
49 55
     'easyparcel' => [
50 56
         // From the app made in EasyParcel's Developer Hub (developer.easyparcel.com). Each merchant then connects their own account.
51 57
         'client_id' => env('EASYPARCEL_CLIENT_ID'),

+ 25
- 0
database/migrations/2026_12_01_000001_add_grabpay_requested_to_stripe_accounts.php Visa fil

@@ -0,0 +1,25 @@
1
+<?php
2
+
3
+use Illuminate\Database\Migrations\Migration;
4
+use Illuminate\Database\Schema\Blueprint;
5
+use Illuminate\Support\Facades\Schema;
6
+
7
+return new class extends Migration
8
+{
9
+    /**
10
+     * GrabPay is asked for on each merchant's Stripe account, like FPX.
11
+     */
12
+    public function up(): void
13
+    {
14
+        Schema::table('stripe_accounts', function (Blueprint $table) {
15
+            $table->boolean('grabpay_requested')->default(false)->after('fpx_requested');
16
+        });
17
+    }
18
+
19
+    public function down(): void
20
+    {
21
+        Schema::table('stripe_accounts', function (Blueprint $table) {
22
+            $table->dropColumn('grabpay_requested');
23
+        });
24
+    }
25
+};

+ 27
- 0
database/migrations/2026_12_02_000001_create_hitpay_accounts_table.php Visa fil

@@ -0,0 +1,27 @@
1
+<?php
2
+
3
+use Illuminate\Database\Migrations\Migration;
4
+use Illuminate\Database\Schema\Blueprint;
5
+use Illuminate\Support\Facades\Schema;
6
+
7
+return new class extends Migration
8
+{
9
+    public function up(): void
10
+    {
11
+        // The merchant's own HitPay account for each store, for DuitNow QR and e-wallets. Shopper payments go straight into it.
12
+        Schema::create('hitpay_accounts', function (Blueprint $table) {
13
+            $table->id();
14
+            $table->foreignId('store_id')->unique()->constrained()->cascadeOnDelete();
15
+            // The merchant's API key from HitPay (Settings > API Keys). Saved encrypted.
16
+            $table->text('api_key');
17
+            // The HitPay payment methods shown to shoppers, such as ["duitnow", "touch_n_go", "shopee_pay"].
18
+            $table->json('methods');
19
+            $table->timestamps();
20
+        });
21
+    }
22
+
23
+    public function down(): void
24
+    {
25
+        Schema::dropIfExists('hitpay_accounts');
26
+    }
27
+};

+ 24
- 0
database/migrations/2026_12_02_000002_add_refused_methods_to_hitpay_accounts.php Visa fil

@@ -0,0 +1,24 @@
1
+<?php
2
+
3
+use Illuminate\Database\Migrations\Migration;
4
+use Illuminate\Database\Schema\Blueprint;
5
+use Illuminate\Support\Facades\Schema;
6
+
7
+return new class extends Migration
8
+{
9
+    public function up(): void
10
+    {
11
+        Schema::table('hitpay_accounts', function (Blueprint $table) {
12
+            // Methods HitPay refused when a shopper tried to pay (switched off in the merchant's HitPay account), and when.
13
+            $table->json('refused_methods')->nullable()->after('methods');
14
+            $table->timestamp('refused_at')->nullable()->after('refused_methods');
15
+        });
16
+    }
17
+
18
+    public function down(): void
19
+    {
20
+        Schema::table('hitpay_accounts', function (Blueprint $table) {
21
+            $table->dropColumn(['refused_methods', 'refused_at']);
22
+        });
23
+    }
24
+};

+ 3
- 2
resources/js/components/stores/get-paid-setup.tsx Visa fil

@@ -129,8 +129,9 @@ export function GetPaidSetup({
129 129
                                 stripeButton('Update details', 'default')}
130 130
                         </div>
131 131
                         <p className="text-xs text-muted-foreground">
132
-                            Refunds, payouts and payment methods (such as FPX)
133
-                            are managed in your Stripe Dashboard.
132
+                            Shoppers can pay by card, FPX online banking or
133
+                            GrabPay. Refunds, payouts and payment methods are
134
+                            managed in your Stripe Dashboard.
134 135
                         </p>
135 136
                     </div>
136 137
                 ) : payments.details_submitted ? (

+ 384
- 0
resources/js/components/stores/hitpay-setup.tsx Visa fil

@@ -0,0 +1,384 @@
1
+import { router } from '@inertiajs/react';
2
+import {
3
+    AlertTriangle,
4
+    Check,
5
+    ExternalLink,
6
+    KeyRound,
7
+    Unlink,
8
+} from 'lucide-react';
9
+import type { KeyboardEvent } from 'react';
10
+import { useState } from 'react';
11
+import HitPayController from '@/actions/App/Http/Controllers/HitPayController';
12
+import InputError from '@/components/input-error';
13
+import { Badge } from '@/components/ui/badge';
14
+import { Button } from '@/components/ui/button';
15
+import {
16
+    Card,
17
+    CardContent,
18
+    CardDescription,
19
+    CardHeader,
20
+    CardTitle,
21
+} from '@/components/ui/card';
22
+import { Checkbox } from '@/components/ui/checkbox';
23
+import { Input } from '@/components/ui/input';
24
+import { Label } from '@/components/ui/label';
25
+import { Spinner } from '@/components/ui/spinner';
26
+import type { StoreSummary } from '@/types';
27
+
28
+export type HitPayMethod = 'duitnow' | 'touch_n_go' | 'shopee_pay';
29
+
30
+export type HitPaySettings = {
31
+    connected: boolean;
32
+    /** The HitPay methods the merchant ticked. */
33
+    methods: HitPayMethod[];
34
+    /** Ticked methods HitPay refused when a shopper tried to pay: switched off in the merchant's HitPay account. */
35
+    refused: HitPayMethod[];
36
+    refused_at: string | null;
37
+    /** True when the app talks to HitPay's sandbox (test accounts). */
38
+    sandbox: boolean;
39
+};
40
+
41
+/** Keep in step with HitPayAccount::METHODS. HitPay's own fees, checked 2 Dec 2026. */
42
+const METHODS: { key: HitPayMethod; label: string; fee: string }[] = [
43
+    { key: 'duitnow', label: 'DuitNow QR', fee: '1.2%' },
44
+    { key: 'touch_n_go', label: 'Touch ’n Go eWallet', fee: '1.9%' },
45
+    { key: 'shopee_pay', label: 'ShopeePay', fee: '2.2%' },
46
+];
47
+
48
+/** "DuitNow QR and Touch ’n Go eWallet". */
49
+function listNames(keys: HitPayMethod[]): string {
50
+    const names = METHODS.filter((method) => keys.includes(method.key)).map(
51
+        (method) => method.label,
52
+    );
53
+
54
+    return names.length > 1
55
+        ? `${names.slice(0, -1).join(', ')} and ${names[names.length - 1]}`
56
+        : (names[0] ?? '');
57
+}
58
+
59
+/**
60
+ * DuitNow QR and e-wallets through the merchant's own HitPay account. The merchant pastes their API key.
61
+ * It sits inside the Settings form, so its buttons never submit that form.
62
+ */
63
+export function HitPaySetup({
64
+    store,
65
+    hitpay,
66
+}: {
67
+    store: StoreSummary;
68
+    hitpay: HitPaySettings;
69
+}) {
70
+    const [apiKey, setApiKey] = useState('');
71
+    const [changingKey, setChangingKey] = useState(false);
72
+    const [methods, setMethods] = useState<HitPayMethod[]>(hitpay.methods);
73
+    const [busy, setBusy] = useState<'connect' | 'save' | 'disconnect' | null>(
74
+        null,
75
+    );
76
+    const [errors, setErrors] = useState<Record<string, string>>({});
77
+
78
+    const dashboardUrl = hitpay.sandbox
79
+        ? 'https://dashboard.sandbox.hit-pay.com'
80
+        : 'https://dashboard.hit-pay.com';
81
+    const signUpUrl = hitpay.sandbox
82
+        ? 'https://dashboard.sandbox.hit-pay.com/register'
83
+        : 'https://hitpayapp.com/my';
84
+
85
+    const send = (
86
+        kind: 'connect' | 'save' | 'disconnect',
87
+        visit: (options: {
88
+            preserveScroll: true;
89
+            onStart: () => void;
90
+            onError: (errors: Record<string, string>) => void;
91
+            onSuccess: () => void;
92
+            onFinish: () => void;
93
+        }) => void,
94
+    ) =>
95
+        visit({
96
+            preserveScroll: true,
97
+            onStart: () => {
98
+                setBusy(kind);
99
+                setErrors({});
100
+            },
101
+            onError: (next) => setErrors(next),
102
+            onSuccess: () => {
103
+                setApiKey('');
104
+                setChangingKey(false);
105
+            },
106
+            onFinish: () => setBusy(null),
107
+        });
108
+
109
+    const connect = () =>
110
+        send('connect', (options) =>
111
+            router.post(
112
+                HitPayController.connect.url(store.slug),
113
+                { api_key: apiKey },
114
+                options,
115
+            ),
116
+        );
117
+
118
+    const save = () =>
119
+        send('save', (options) =>
120
+            router.put(
121
+                HitPayController.update.url(store.slug),
122
+                { methods },
123
+                options,
124
+            ),
125
+        );
126
+
127
+    const disconnect = () => {
128
+        if (
129
+            !window.confirm(
130
+                'Disconnect HitPay? Shoppers will no longer see DuitNow QR, Touch ’n Go or ShopeePay.',
131
+            )
132
+        ) {
133
+            return;
134
+        }
135
+
136
+        send('disconnect', (options) =>
137
+            router.delete(HitPayController.disconnect.url(store.slug), options),
138
+        );
139
+    };
140
+
141
+    // Enter in the key box connects, instead of saving the whole Settings form.
142
+    const onKeyDown = (event: KeyboardEvent<HTMLInputElement>) => {
143
+        if (event.key === 'Enter') {
144
+            event.preventDefault();
145
+            connect();
146
+        }
147
+    };
148
+
149
+    const keyField = (
150
+        <div className="grid gap-2">
151
+            <Label htmlFor="hitpay-api-key">HitPay API key</Label>
152
+            <div className="flex flex-col gap-2 sm:flex-row">
153
+                <Input
154
+                    id="hitpay-api-key"
155
+                    type="password"
156
+                    autoComplete="off"
157
+                    spellCheck={false}
158
+                    value={apiKey}
159
+                    onChange={(event) => setApiKey(event.target.value)}
160
+                    onKeyDown={onKeyDown}
161
+                    placeholder="Paste your key"
162
+                    aria-invalid={errors.api_key ? true : undefined}
163
+                    data-test="hitpay-api-key"
164
+                />
165
+                <Button
166
+                    type="button"
167
+                    onClick={connect}
168
+                    disabled={busy !== null || apiKey.trim() === ''}
169
+                    data-test="hitpay-connect"
170
+                >
171
+                    {busy === 'connect' ? <Spinner /> : <KeyRound />}
172
+                    Connect HitPay
173
+                </Button>
174
+            </div>
175
+            <InputError message={errors.api_key} />
176
+            <p className="text-xs text-muted-foreground">
177
+                We check the key with HitPay before saving it. It is stored
178
+                encrypted and never shown again.
179
+            </p>
180
+        </div>
181
+    );
182
+
183
+    return (
184
+        <Card id="hitpay" data-test="hitpay">
185
+            <CardHeader>
186
+                <CardTitle className="flex flex-wrap items-center gap-2">
187
+                    DuitNow QR and e-wallets
188
+                    {hitpay.connected && (
189
+                        <Badge className="bg-emerald-600 text-white hover:bg-emerald-600">
190
+                            <Check className="size-3" />
191
+                            Connected
192
+                        </Badge>
193
+                    )}
194
+                </CardTitle>
195
+                <CardDescription>
196
+                    Let shoppers pay by DuitNow QR, Touch ’n Go or ShopeePay,
197
+                    through your own HitPay account. HitPay pays it into your
198
+                    bank. We take no cut. You only pay HitPay’s fees.
199
+                </CardDescription>
200
+            </CardHeader>
201
+            <CardContent className="space-y-5 text-sm">
202
+                {hitpay.sandbox && (
203
+                    <p
204
+                        className="rounded-md bg-muted p-3 text-xs"
205
+                        data-test="hitpay-sandbox"
206
+                    >
207
+                        Test mode: this app uses HitPay’s sandbox, so connect a
208
+                        sandbox account. No real money moves.
209
+                    </p>
210
+                )}
211
+
212
+                {!hitpay.connected ? (
213
+                    <>
214
+                        <ol className="list-decimal space-y-1.5 pl-5 text-muted-foreground">
215
+                            <li>
216
+                                <a
217
+                                    href={signUpUrl}
218
+                                    target="_blank"
219
+                                    rel="noreferrer"
220
+                                    className="font-medium text-foreground underline underline-offset-4"
221
+                                >
222
+                                    Sign up for HitPay
223
+                                </a>{' '}
224
+                                as a Malaysian business. It is free, with no
225
+                                monthly fee.
226
+                            </li>
227
+                            <li>
228
+                                In HitPay, open{' '}
229
+                                <span className="font-medium text-foreground">
230
+                                    Payment Methods
231
+                                </span>{' '}
232
+                                and click Turn On for Touch ’n Go &amp; DuitNow
233
+                                and for ShopeePay. New HitPay accounts start
234
+                                with every method off.
235
+                            </li>
236
+                            <li>
237
+                                Open Developers, then API Keys, and copy your
238
+                                API key.
239
+                            </li>
240
+                            <li>Paste it below.</li>
241
+                        </ol>
242
+                        {keyField}
243
+                    </>
244
+                ) : (
245
+                    <>
246
+                        {hitpay.refused.length > 0 && (
247
+                            <div
248
+                                role="alert"
249
+                                className="flex items-start gap-2 rounded-md border border-amber-300 bg-amber-50 p-3 text-amber-900 dark:border-amber-800 dark:bg-amber-950/40 dark:text-amber-200"
250
+                                data-test="hitpay-refused"
251
+                            >
252
+                                <AlertTriangle className="mt-0.5 size-4 shrink-0" />
253
+                                <div className="space-y-1">
254
+                                    <p className="font-medium">
255
+                                        HitPay turned down{' '}
256
+                                        {listNames(hitpay.refused)}
257
+                                        {hitpay.refused_at &&
258
+                                            ` on ${new Date(hitpay.refused_at).toLocaleString('en-MY', { day: 'numeric', month: 'short', hour: 'numeric', minute: '2-digit' })}`}
259
+                                    </p>
260
+                                    <p>
261
+                                        {hitpay.refused.length === 1
262
+                                            ? 'It is'
263
+                                            : 'They are'}{' '}
264
+                                        switched off in your HitPay account, so
265
+                                        shoppers do not see{' '}
266
+                                        {hitpay.refused.length === 1
267
+                                            ? 'it'
268
+                                            : 'them'}{' '}
269
+                                        for now. In HitPay, open Payment Methods
270
+                                        and click Turn On, then click Save here.
271
+                                        Or untick{' '}
272
+                                        {hitpay.refused.length === 1
273
+                                            ? 'it'
274
+                                            : 'them'}{' '}
275
+                                        and Save.
276
+                                    </p>
277
+                                </div>
278
+                            </div>
279
+                        )}
280
+
281
+                        <fieldset className="space-y-3">
282
+                            <legend className="font-medium">
283
+                                Shoppers can pay by
284
+                            </legend>
285
+                            {METHODS.map((method) => (
286
+                                <div
287
+                                    key={method.key}
288
+                                    className="flex items-center gap-3"
289
+                                >
290
+                                    <Checkbox
291
+                                        id={`hitpay-${method.key}`}
292
+                                        checked={methods.includes(method.key)}
293
+                                        onCheckedChange={(checked) =>
294
+                                            setMethods((current) =>
295
+                                                checked === true
296
+                                                    ? [...current, method.key]
297
+                                                    : current.filter(
298
+                                                          (key) =>
299
+                                                              key !==
300
+                                                              method.key,
301
+                                                      ),
302
+                                            )
303
+                                        }
304
+                                    />
305
+                                    <Label
306
+                                        htmlFor={`hitpay-${method.key}`}
307
+                                        className="font-normal"
308
+                                    >
309
+                                        {method.label}
310
+                                        <span className="ml-2 text-muted-foreground tabular-nums">
311
+                                            {method.fee} fee
312
+                                        </span>
313
+                                    </Label>
314
+                                </div>
315
+                            ))}
316
+                            <InputError message={errors.methods} />
317
+                            <p className="text-xs text-muted-foreground">
318
+                                Each one must also be switched on in your HitPay
319
+                                account: in HitPay, open Payment Methods and
320
+                                click Turn On. New HitPay accounts start with
321
+                                every method off.
322
+                            </p>
323
+                        </fieldset>
324
+
325
+                        <div className="flex flex-wrap gap-2">
326
+                            <Button
327
+                                type="button"
328
+                                onClick={save}
329
+                                disabled={busy !== null}
330
+                                data-test="hitpay-save"
331
+                            >
332
+                                {busy === 'save' && <Spinner />}
333
+                                Save
334
+                            </Button>
335
+                            <Button type="button" variant="outline" asChild>
336
+                                <a
337
+                                    href={dashboardUrl}
338
+                                    target="_blank"
339
+                                    rel="noreferrer"
340
+                                >
341
+                                    <ExternalLink />
342
+                                    Open HitPay
343
+                                </a>
344
+                            </Button>
345
+                            {!changingKey && (
346
+                                <Button
347
+                                    type="button"
348
+                                    variant="outline"
349
+                                    onClick={() => setChangingKey(true)}
350
+                                >
351
+                                    <KeyRound />
352
+                                    Change key
353
+                                </Button>
354
+                            )}
355
+                            <Button
356
+                                type="button"
357
+                                variant="ghost"
358
+                                onClick={disconnect}
359
+                                disabled={busy !== null}
360
+                                className="text-red-700 hover:text-red-800 dark:text-red-400"
361
+                                data-test="hitpay-disconnect"
362
+                            >
363
+                                {busy === 'disconnect' ? (
364
+                                    <Spinner />
365
+                                ) : (
366
+                                    <Unlink />
367
+                                )}
368
+                                Disconnect
369
+                            </Button>
370
+                        </div>
371
+
372
+                        {changingKey && keyField}
373
+
374
+                        <p className="text-xs text-muted-foreground">
375
+                            Refunds and payouts are managed in your HitPay
376
+                            dashboard. DuitNow payments cannot be refunded
377
+                            through HitPay.
378
+                        </p>
379
+                    </>
380
+                )}
381
+            </CardContent>
382
+        </Card>
383
+    );
384
+}

+ 6
- 0
resources/js/pages/stores/settings.tsx Visa fil

@@ -8,6 +8,8 @@ import type { EasyParcelSettings } from '@/components/stores/easyparcel-setup';
8 8
 import { EasyParcelSetup } from '@/components/stores/easyparcel-setup';
9 9
 import type { PaymentSettings } from '@/components/stores/get-paid-setup';
10 10
 import { GetPaidSetup } from '@/components/stores/get-paid-setup';
11
+import type { HitPaySettings } from '@/components/stores/hitpay-setup';
12
+import { HitPaySetup } from '@/components/stores/hitpay-setup';
11 13
 import StoreNav from '@/components/stores/store-nav';
12 14
 import { Button } from '@/components/ui/button';
13 15
 import { Checkbox } from '@/components/ui/checkbox';
@@ -54,6 +56,7 @@ export default function StoreSettings({
54 56
     states,
55 57
     accountEmail,
56 58
     payments,
59
+    hitpay,
57 60
     easyparcel,
58 61
     easyparcelBalance,
59 62
 }: {
@@ -64,6 +67,7 @@ export default function StoreSettings({
64 67
     /** The merchant's sign-in email, offered as a quick fill for the contact email. */
65 68
     accountEmail: string;
66 69
     payments: PaymentSettings;
70
+    hitpay: HitPaySettings;
67 71
     easyparcel: EasyParcelSettings;
68 72
     /** Loaded after the page shows. Null when EasyParcel is not connected. */
69 73
     easyparcelBalance?: { amount: number | null; error: string | null } | null;
@@ -91,6 +95,8 @@ export default function StoreSettings({
91 95
                         <>
92 96
                             <GetPaidSetup store={store} payments={payments} />
93 97
 
98
+                            <HitPaySetup store={store} hitpay={hitpay} />
99
+
94 100
                             <ContactCard
95 101
                                 settings={settings}
96 102
                                 accountEmail={accountEmail}

+ 56
- 2
resources/js/storefront/pages/checkout.tsx Visa fil

@@ -3,6 +3,7 @@ import type { FormEvent, ReactNode } from 'react';
3 3
 import { useStorefront } from '../context';
4 4
 import { storefrontText } from '../text';
5 5
 import { formatPrice } from '../theme';
6
+import type { PayWay } from '../types';
6 7
 import { Container, SfLink } from '../ui';
7 8
 
8 9
 const inputClass =
@@ -34,15 +35,22 @@ function Field({
34 35
     );
35 36
 }
36 37
 
38
+/** The name shoppers see for a payment provider's page. */
39
+function providerName(key: string): string {
40
+    return key === 'hitpay' ? 'HitPay' : 'Stripe';
41
+}
42
+
37 43
 /** The shopper's details and address, before going to the payment page. */
38 44
 export function CheckoutPage({
39 45
     states,
40 46
     shippingByState,
41 47
     takingOrders,
48
+    payWays,
42 49
 }: {
43 50
     states: string[];
44 51
     shippingByState: Record<string, number>;
45 52
     takingOrders: boolean;
53
+    payWays: PayWay[];
46 54
 }) {
47 55
     const { cart, language, baseUrl } = useStorefront();
48 56
     const t = storefrontText(language);
@@ -55,6 +63,7 @@ export function CheckoutPage({
55 63
         city: '',
56 64
         postcode: '',
57 65
         state: '',
66
+        pay_with: payWays[0]?.key ?? '',
58 67
     });
59 68
     // "cart" errors come from the server: an empty cart, or the payment page could not be opened.
60 69
     const errors = form.errors as typeof form.errors & { cart?: string };
@@ -68,8 +77,17 @@ export function CheckoutPage({
68 77
         form.post(`${baseUrl}/checkout`, { preserveScroll: true });
69 78
     }
70 79
 
80
+    /** "Card, FPX online banking or GrabPay". */
81
+    function methodList(way: PayWay): string {
82
+        const names = way.methods.map((method) => t.payMethods[method]);
83
+
84
+        return names.length > 1
85
+            ? `${names.slice(0, -1).join(', ')} ${t.or} ${names[names.length - 1]}`
86
+            : (names[0] ?? '');
87
+    }
88
+
71 89
     function text(
72
-        name: keyof typeof form.data,
90
+        name: Exclude<keyof typeof form.data, 'pay_with'>,
73 91
         label: string,
74 92
         props: React.InputHTMLAttributes<HTMLInputElement> = {},
75 93
     ) {
@@ -204,6 +222,42 @@ export function CheckoutPage({
204 222
                             </div>
205 223
                         </fieldset>
206 224
 
225
+                        {payWays.length > 1 && (
226
+                            <fieldset
227
+                                className="space-y-3"
228
+                                data-test="pay-ways"
229
+                            >
230
+                                <legend className="sf-heading mb-5 text-xl font-semibold">
231
+                                    {t.howToPay}
232
+                                </legend>
233
+                                {payWays.map((way) => (
234
+                                    <label
235
+                                        key={way.key}
236
+                                        className="flex cursor-pointer items-center gap-3 rounded-(--sf-radius) border border-(--sf-border) bg-(--sf-bg) p-4 has-checked:border-(--sf-primary) has-checked:ring-1 has-checked:ring-(--sf-primary)"
237
+                                    >
238
+                                        <input
239
+                                            type="radio"
240
+                                            name="pay_with"
241
+                                            value={way.key}
242
+                                            checked={
243
+                                                form.data.pay_with === way.key
244
+                                            }
245
+                                            onChange={() =>
246
+                                                form.setData(
247
+                                                    'pay_with',
248
+                                                    way.key,
249
+                                                )
250
+                                            }
251
+                                            className="size-4 shrink-0 appearance-none rounded-full border border-(--sf-muted) bg-(--sf-bg) checked:border-[5px] checked:border-(--sf-primary) focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-(--sf-primary)"
252
+                                        />
253
+                                        <span className="text-sm font-medium">
254
+                                            {methodList(way)}
255
+                                        </span>
256
+                                    </label>
257
+                                ))}
258
+                            </fieldset>
259
+                        )}
260
+
207 261
                         <div>
208 262
                             <button
209 263
                                 type="submit"
@@ -213,7 +267,7 @@ export function CheckoutPage({
213 267
                                 {t.payNow}
214 268
                             </button>
215 269
                             <p className="mt-2 text-xs text-(--sf-muted)">
216
-                                {t.paySecure}
270
+                                {t.paySecure(providerName(form.data.pay_with))}
217 271
                             </p>
218 272
                         </div>
219 273
                     </form>

+ 1
- 0
resources/js/storefront/renderer.tsx Visa fil

@@ -95,6 +95,7 @@ function PageBody({ plan, view }: { plan: StorePlan; view: StorefrontView }) {
95 95
                 states={view.states}
96 96
                 shippingByState={view.shippingByState}
97 97
                 takingOrders={view.takingOrders}
98
+                payWays={view.payWays}
98 99
             />
99 100
         );
100 101
     }

+ 24
- 2
resources/js/storefront/text.ts Visa fil

@@ -72,7 +72,18 @@ const words = {
72 72
         orderSummary: 'Order summary',
73 73
         total: 'Total',
74 74
         payNow: 'Continue to payment',
75
-        paySecure: 'You will pay on a secure Stripe page.',
75
+        paySecure: (provider: string) =>
76
+            `You will pay on a secure ${provider} page.`,
77
+        howToPay: 'How to pay',
78
+        or: 'or',
79
+        payMethods: {
80
+            card: 'Card',
81
+            fpx: 'FPX online banking',
82
+            grabpay: 'GrabPay',
83
+            duitnow: 'DuitNow QR',
84
+            touch_n_go: 'Touch ’n Go eWallet',
85
+            shopee_pay: 'ShopeePay',
86
+        },
76 87
         notTakingOrders:
77 88
             'This store is not taking orders yet. Please check back soon.',
78 89
         backToCart: 'Back to cart',
@@ -183,7 +194,18 @@ const words = {
183 194
         orderSummary: 'Ringkasan pesanan',
184 195
         total: 'Jumlah',
185 196
         payNow: 'Teruskan ke pembayaran',
186
-        paySecure: 'Anda akan membayar di halaman Stripe yang selamat.',
197
+        paySecure: (provider: string) =>
198
+            `Anda akan membayar di halaman ${provider} yang selamat.`,
199
+        howToPay: 'Cara bayar',
200
+        or: 'atau',
201
+        payMethods: {
202
+            card: 'Kad',
203
+            fpx: 'Perbankan dalam talian FPX',
204
+            grabpay: 'GrabPay',
205
+            duitnow: 'DuitNow QR',
206
+            touch_n_go: 'Touch ’n Go eWallet',
207
+            shopee_pay: 'ShopeePay',
208
+        },
187 209
         notTakingOrders:
188 210
             'Kedai ini belum menerima pesanan. Sila datang semula nanti.',
189 211
         backToCart: 'Kembali ke troli',

+ 15
- 1
resources/js/storefront/types.ts Visa fil

@@ -383,6 +383,18 @@ export type ShopInfo = {
383 383
     offers: { name: string; text: string; product_ids: number[] | null }[];
384 384
 };
385 385
 
386
+/** A payment method's name, as the server sends it. */
387
+export type PayMethod =
388
+    | 'card'
389
+    | 'fpx'
390
+    | 'grabpay'
391
+    | 'duitnow'
392
+    | 'touch_n_go'
393
+    | 'shopee_pay';
394
+
395
+/** One way to pay at checkout: a payment provider and the methods on its page. */
396
+export type PayWay = { key: string; methods: PayMethod[] };
397
+
386 398
 /** Which storefront page to show. */
387 399
 export type StorefrontView =
388 400
     | { type: 'page'; pageId: string }
@@ -393,8 +405,10 @@ export type StorefrontView =
393 405
           states: string[];
394 406
           /** Shipping fee in ringgit for each state. */
395 407
           shippingByState: Record<string, number>;
396
-          /** False until the merchant has connected Stripe, so shoppers cannot pay yet. */
408
+          /** False until the merchant has connected Stripe or HitPay, so shoppers cannot pay yet. */
397 409
           takingOrders: boolean;
410
+          /** The ways to pay, for the shopper to choose. */
411
+          payWays: PayWay[];
398 412
       }
399 413
     | { type: 'order'; order: StoreOrder }
400 414
     | { type: 'product'; product: StoreProduct; related?: StoreProduct[] }

+ 8
- 0
routes/web.php Visa fil

@@ -11,6 +11,8 @@ use App\Http\Controllers\DiscountCodeController;
11 11
 use App\Http\Controllers\EasyParcelController;
12 12
 use App\Http\Controllers\FeaturedProductController;
13 13
 use App\Http\Controllers\HeroImageController;
14
+use App\Http\Controllers\HitPayController;
15
+use App\Http\Controllers\HitPayWebhookController;
14 16
 use App\Http\Controllers\HomeController;
15 17
 use App\Http\Controllers\LegalController;
16 18
 use App\Http\Controllers\OrderController;
@@ -74,6 +76,8 @@ Route::get('terms', [LegalController::class, 'terms'])->name('terms');
74 76
 Route::post('stripe/webhook', StripeWebhookController::class)->name('stripe.webhook');
75 77
 // Payments made in merchants' own Stripe accounts. A second webhook in Stripe, listening to "Connected accounts".
76 78
 Route::post('stripe/connect-webhook', StripeConnectWebhookController::class)->name('stripe.connect-webhook');
79
+// HitPay says an order's payment page changed. Nothing in the message is trusted: we ask HitPay about the order ourselves.
80
+Route::post('hitpay/webhook/{publicId}', HitPayWebhookController::class)->middleware('throttle:60,1')->name('hitpay.webhook');
77 81
 
78 82
 Route::middleware(['auth', 'verified'])->group(function () {
79 83
     Route::get('dashboard', [DashboardController::class, 'index'])->name('dashboard');
@@ -135,6 +139,10 @@ Route::middleware(['auth', 'verified'])->group(function () {
135 139
     Route::post('stores/{slug}/payments/connect', [StripeConnectController::class, 'connect'])->middleware('throttle:10,1')->name('stores.payments.connect');
136 140
     Route::get('stores/{slug}/payments/return', [StripeConnectController::class, 'return'])->name('stores.payments.return');
137 141
     Route::get('stores/{slug}/payments/resume', [StripeConnectController::class, 'resume'])->middleware('throttle:10,1')->name('stores.payments.resume');
142
+    // DuitNow QR and e-wallets: the merchant's own HitPay account, connected with their API key.
143
+    Route::post('stores/{slug}/hitpay', [HitPayController::class, 'connect'])->middleware('throttle:10,1')->name('stores.hitpay.connect');
144
+    Route::put('stores/{slug}/hitpay', [HitPayController::class, 'update'])->name('stores.hitpay.update');
145
+    Route::delete('stores/{slug}/hitpay', [HitPayController::class, 'disconnect'])->name('stores.hitpay.disconnect');
138 146
     // EasyParcel sends the merchant back here after they click Allow. One address for every store (the store is kept in the session).
139 147
     Route::get('easyparcel/callback', [EasyParcelController::class, 'callback'])->name('easyparcel.callback');
140 148
 

+ 410
- 0
tests/Feature/Stores/HitPayTest.php Visa fil

@@ -0,0 +1,410 @@
1
+<?php
2
+
3
+namespace Tests\Feature\Stores;
4
+
5
+use App\Commerce\Payments\PaymentGateway;
6
+use App\Mail\OrderConfirmation;
7
+use App\Models\HitPayAccount;
8
+use App\Models\Order;
9
+use App\Models\Product;
10
+use App\Models\Store;
11
+use App\Models\User;
12
+use App\StorePlan\SamplePlan;
13
+use Illuminate\Foundation\Testing\RefreshDatabase;
14
+use Illuminate\Http\Client\Request as HttpRequest;
15
+use Illuminate\Support\Facades\DB;
16
+use Illuminate\Support\Facades\Http;
17
+use Illuminate\Support\Facades\Mail;
18
+use Inertia\Testing\AssertableInertia as Assert;
19
+use Tests\Support\FakeGateway;
20
+use Tests\TestCase;
21
+
22
+/**
23
+ * DuitNow QR and e-wallets through the merchant's own HitPay account, next to Stripe.
24
+ */
25
+class HitPayTest extends TestCase
26
+{
27
+    use RefreshDatabase;
28
+
29
+    private const string API = 'https://api.sandbox.hit-pay.com/v1';
30
+
31
+    private User $user;
32
+
33
+    private Store $store;
34
+
35
+    /** @var array<string, mixed> What the fake HitPay says about the payment page. */
36
+    private array $hitpay = [];
37
+
38
+    private bool $hitpayFaked = false;
39
+
40
+    /** @var list<string> Methods the fake HitPay says are switched off in the merchant's account. */
41
+    private array $switchedOff = [];
42
+
43
+    protected function setUp(): void
44
+    {
45
+        parent::setUp();
46
+
47
+        Mail::fake();
48
+        Http::preventStrayRequests();
49
+        config(['services.hitpay.sandbox' => true]);
50
+
51
+        $this->user = User::factory()->create();
52
+        $this->store = Store::factory()->for($this->user)->create(['name' => 'Kedai Ali']);
53
+        $this->store->plan = SamplePlan::for($this->store);
54
+        $this->store->save();
55
+        $this->actingAs($this->user);
56
+    }
57
+
58
+    private function connectHitPay(array $methods = HitPayAccount::METHODS): HitPayAccount
59
+    {
60
+        return $this->store->hitpayAccount()->create(['api_key' => 'hp_test_key_123456', 'methods' => $methods]);
61
+    }
62
+
63
+    /**
64
+     * HitPay's answers: a new payment page, and that page with whatever payments were made on it.
65
+     * Can be called again to change the answers.
66
+     *
67
+     * @param  list<array<string, mixed>>  $payments
68
+     */
69
+    private function fakeHitPay(string $status = 'pending', array $payments = [], string $amount = '50.00', string $currency = 'myr'): void
70
+    {
71
+        $this->hitpay = ['status' => $status, 'payments' => $payments, 'amount' => $amount, 'currency' => $currency];
72
+
73
+        if ($this->hitpayFaked) {
74
+            return;
75
+        }
76
+
77
+        $this->hitpayFaked = true;
78
+
79
+        Http::fake(function (HttpRequest $request) {
80
+            if ($request->url() === self::API.'/payment-requests') {
81
+                // Like HitPay: one error per method that is switched off, by its place in the list.
82
+                $errors = [];
83
+
84
+                foreach (array_values((array) $request['payment_methods']) as $i => $method) {
85
+                    if (in_array($method, $this->switchedOff, true)) {
86
+                        $errors["payment_methods.{$i}"] = ["The selected payment method ({$method}) is unavailable for your account or the currency is invalid. Please check the payment method you selected."];
87
+                    }
88
+                }
89
+
90
+                if ($errors !== []) {
91
+                    return Http::response(['error_code' => 'validation_error', 'message' => 'The given data was invalid.', 'errors' => $errors], 422);
92
+                }
93
+
94
+                return Http::response([
95
+                    'id' => 'hp_req_1',
96
+                    'url' => 'https://securecheckout.sandbox.hit-pay.com/payment-request/@kedai-ali/hp_req_1/checkout',
97
+                    'status' => 'pending',
98
+                    'amount' => $this->hitpay['amount'],
99
+                    'currency' => $this->hitpay['currency'],
100
+                ]);
101
+            }
102
+
103
+            if ($request->url() === self::API.'/payment-requests/hp_req_1') {
104
+                return Http::response(['id' => 'hp_req_1', ...$this->hitpay]);
105
+            }
106
+
107
+            return Http::response(['message' => 'Not found.'], 404);
108
+        });
109
+    }
110
+
111
+    /** RM 42 of products and the default RM 8 shipping to Selangor: RM 50. */
112
+    private function placeOrder(string $payWith = 'hitpay')
113
+    {
114
+        $product = Product::factory()->for($this->store)->create(['name' => 'Sambal', 'price' => 4200, 'stock' => 10]);
115
+        $this->post(route('stores.preview.cart.add', $this->store->slug), ['product_id' => $product->id, 'quantity' => 1]);
116
+
117
+        return $this->post(route('stores.preview.checkout.store', $this->store->slug), [
118
+            'name' => 'Aminah binti Ali',
119
+            'email' => 'aminah@example.com',
120
+            'phone' => '012-345 6789',
121
+            'line1' => '12 Jalan Mawar',
122
+            'city' => 'Shah Alam',
123
+            'postcode' => '40000',
124
+            'state' => 'Selangor',
125
+            'pay_with' => $payWith,
126
+        ]);
127
+    }
128
+
129
+    public function test_a_merchant_connects_hitpay_with_a_key_that_hitpay_accepts()
130
+    {
131
+        // HitPay refuses the first key and accepts the second.
132
+        Http::fake([self::API.'/account-status' => Http::sequence()
133
+            ->push(['message' => 'Unauthenticated.'], 401)
134
+            ->push(['verification' => ['overall_status' => 'verified']])]);
135
+
136
+        $this->post(route('stores.hitpay.connect', $this->store->slug), ['api_key' => 'wrong_key_123456'])
137
+            ->assertSessionHasErrors('api_key');
138
+        $this->assertNull($this->store->fresh()->hitpayAccount);
139
+
140
+        $this->post(route('stores.hitpay.connect', $this->store->slug), ['api_key' => ' hp_test_key_123456 '])
141
+            ->assertSessionHasNoErrors()
142
+            ->assertRedirect(route('stores.settings', $this->store->slug));
143
+
144
+        $account = $this->store->fresh()->hitpayAccount;
145
+        $this->assertSame('hp_test_key_123456', $account->api_key);
146
+        $this->assertSame(['duitnow', 'touch_n_go', 'shopee_pay'], $account->methods);
147
+        // Saved encrypted.
148
+        $this->assertStringNotContainsString('hp_test_key_123456', (string) DB::table('hitpay_accounts')->value('api_key'));
149
+
150
+        Http::assertSent(fn (HttpRequest $request) => $request->url() === self::API.'/account-status'
151
+            && $request->hasHeader('X-BUSINESS-API-KEY', 'hp_test_key_123456'));
152
+
153
+        // Settings says it is connected, and never sends the key back to the page.
154
+        $this->get(route('stores.settings', $this->store->slug))
155
+            ->assertInertia(fn (Assert $page) => $page
156
+                ->where('hitpay.connected', true)
157
+                ->where('hitpay.methods', ['duitnow', 'touch_n_go', 'shopee_pay'])
158
+                ->where('hitpay.sandbox', true))
159
+            ->assertDontSee('hp_test_key_123456');
160
+    }
161
+
162
+    public function test_hitpay_being_down_while_connecting_says_so()
163
+    {
164
+        Http::fake([self::API.'/account-status' => Http::failedConnection()]);
165
+
166
+        $this->post(route('stores.hitpay.connect', $this->store->slug), ['api_key' => 'hp_test_key_123456'])
167
+            ->assertSessionHasErrors(['api_key' => 'HitPay could not be reached. Please try again in a moment.']);
168
+
169
+        $this->assertNull($this->store->fresh()->hitpayAccount);
170
+    }
171
+
172
+    public function test_the_merchant_chooses_which_hitpay_methods_shoppers_see_and_can_disconnect()
173
+    {
174
+        $this->connectHitPay();
175
+
176
+        $this->put(route('stores.hitpay.update', $this->store->slug), ['methods' => ['shopee_pay', 'duitnow', 'duitnow']])
177
+            ->assertSessionHasNoErrors();
178
+        $this->assertSame(['duitnow', 'shopee_pay'], $this->store->fresh()->hitpayAccount->methods);
179
+
180
+        $this->put(route('stores.hitpay.update', $this->store->slug), ['methods' => []])->assertSessionHasErrors('methods');
181
+        $this->put(route('stores.hitpay.update', $this->store->slug), ['methods' => ['card']])->assertSessionHasErrors('methods.0');
182
+        $this->assertSame(['duitnow', 'shopee_pay'], $this->store->fresh()->hitpayAccount->methods);
183
+
184
+        $this->delete(route('stores.hitpay.disconnect', $this->store->slug))->assertRedirect(route('stores.settings', $this->store->slug));
185
+        $this->assertNull($this->store->fresh()->hitpayAccount);
186
+    }
187
+
188
+    public function test_another_merchants_hitpay_cannot_be_changed()
189
+    {
190
+        $other = Store::factory()->create();
191
+        $other->hitpayAccount()->create(['api_key' => 'theirs_123456', 'methods' => HitPayAccount::METHODS]);
192
+
193
+        $this->post(route('stores.hitpay.connect', $other->slug), ['api_key' => 'hp_test_key_123456'])->assertNotFound();
194
+        $this->put(route('stores.hitpay.update', $other->slug), ['methods' => ['duitnow']])->assertNotFound();
195
+        $this->delete(route('stores.hitpay.disconnect', $other->slug))->assertNotFound();
196
+
197
+        $this->assertNotNull($other->fresh()->hitpayAccount);
198
+    }
199
+
200
+    public function test_shoppers_choose_between_stripe_and_hitpay_at_checkout()
201
+    {
202
+        $this->connectHitPay(['duitnow', 'touch_n_go']);
203
+        $this->post(route('stores.preview.cart.add', $this->store->slug), [
204
+            'product_id' => Product::factory()->for($this->store)->create(['price' => 4200])->id,
205
+            'quantity' => 1,
206
+        ]);
207
+
208
+        $this->get(route('stores.preview.checkout', $this->store->slug))
209
+            ->assertInertia(fn (Assert $page) => $page
210
+                ->where('view.takingOrders', true)
211
+                ->where('view.payWays', [
212
+                    ['key' => 'fake', 'methods' => ['card', 'fpx', 'grabpay']],
213
+                    ['key' => 'hitpay', 'methods' => ['duitnow', 'touch_n_go']],
214
+                ]));
215
+
216
+        // A store with only HitPay can take orders too.
217
+        $stripe = app(PaymentGateway::class);
218
+        $this->assertInstanceOf(FakeGateway::class, $stripe);
219
+        $stripe->takingPayments = false;
220
+
221
+        $this->get(route('stores.preview.checkout', $this->store->slug))
222
+            ->assertInertia(fn (Assert $page) => $page
223
+                ->where('view.takingOrders', true)
224
+                ->where('view.payWays', [['key' => 'hitpay', 'methods' => ['duitnow', 'touch_n_go']]]));
225
+    }
226
+
227
+    public function test_paying_with_hitpay_opens_a_hitpay_page_in_the_merchants_account()
228
+    {
229
+        $this->connectHitPay();
230
+        $this->fakeHitPay();
231
+
232
+        $response = $this->placeOrder();
233
+
234
+        $order = Order::firstOrFail();
235
+        $response->assertRedirect('https://securecheckout.sandbox.hit-pay.com/payment-request/@kedai-ali/hp_req_1/checkout');
236
+        $this->assertSame('hitpay', $order->payment_provider);
237
+        $this->assertSame('hp_req_1', $order->payment_checkout_id);
238
+        $this->assertSame(5000, $order->total);
239
+
240
+        Http::assertSent(function (HttpRequest $request) use ($order) {
241
+            return $request->url() === self::API.'/payment-requests'
242
+                && $request->method() === 'POST'
243
+                && $request->hasHeader('X-BUSINESS-API-KEY', 'hp_test_key_123456')
244
+                && $request['amount'] === '50.00'
245
+                && $request['currency'] === 'MYR'
246
+                && $request['payment_methods'] === ['duitnow', 'touch_n_go', 'shopee_pay']
247
+                && $request['phone'] === '+60123456789'
248
+                && $request['reference_number'] === '1001'
249
+                && $request['purpose'] === 'Kedai Ali order #1001'
250
+                && $request['redirect_url'] === route('stores.preview.order', [$this->store->slug, $order->public_id])
251
+                && $request['send_email'] === 'false'
252
+                // A development machine has no public https address for HitPay to call.
253
+                && ! isset($request['webhook']);
254
+        });
255
+    }
256
+
257
+    public function test_on_a_public_server_hitpay_is_told_where_to_send_news_about_the_order()
258
+    {
259
+        config(['app.url' => 'https://shop.example.com']);
260
+        $this->connectHitPay();
261
+        $this->fakeHitPay();
262
+
263
+        $this->placeOrder();
264
+
265
+        $order = Order::firstOrFail();
266
+        Http::assertSent(fn (HttpRequest $request) => $request->url() === self::API.'/payment-requests'
267
+            && $request['webhook'] === 'https://shop.example.com/hitpay/webhook/'.$order->public_id);
268
+    }
269
+
270
+    public function test_hitpay_being_down_leaves_no_order_behind()
271
+    {
272
+        $this->connectHitPay();
273
+        Http::fake([self::API.'/payment-requests' => Http::response(['message' => 'The selected payment methods is invalid.'], 422)]);
274
+
275
+        $this->placeOrder()->assertSessionHasErrors('cart');
276
+
277
+        $this->assertSame(0, Order::count());
278
+    }
279
+
280
+    public function test_a_way_that_is_not_offered_falls_back_to_stripe()
281
+    {
282
+        // HitPay is not connected, so the choice is ignored.
283
+        $this->placeOrder('hitpay')->assertRedirect('https://pay.test/cs_fake_1');
284
+
285
+        $this->assertSame('fake', Order::firstOrFail()->payment_provider);
286
+    }
287
+
288
+    public function test_the_order_is_paid_once_hitpay_says_so_when_the_shopper_comes_back()
289
+    {
290
+        $this->connectHitPay();
291
+        $this->fakeHitPay();
292
+        $this->placeOrder();
293
+        $order = Order::firstOrFail();
294
+
295
+        // Not paid yet.
296
+        $this->get(route('stores.preview.order', [$this->store->slug, $order->public_id]))
297
+            ->assertInertia(fn (Assert $page) => $page->where('view.order.status', 'pending'));
298
+        $this->assertFalse($order->fresh()->isPaid());
299
+
300
+        $this->fakeHitPay('completed', [['id' => 'hp_pay_9', 'status' => 'succeeded', 'amount' => '50.00', 'payment_type' => 'duitnow']]);
301
+
302
+        $this->get(route('stores.preview.order', [$this->store->slug, $order->public_id]))
303
+            ->assertInertia(fn (Assert $page) => $page->where('view.order.status', 'paid')->where('cart.count', 0));
304
+
305
+        $order->refresh();
306
+        $this->assertTrue($order->isPaid());
307
+        $this->assertSame('hp_pay_9', $order->payment_reference);
308
+        $this->assertSame(9, Product::firstOrFail()->stock);
309
+        Mail::assertSent(OrderConfirmation::class, 1);
310
+    }
311
+
312
+    public function test_a_payment_of_the_wrong_amount_or_currency_does_not_count()
313
+    {
314
+        $this->connectHitPay();
315
+        $this->fakeHitPay();
316
+        $this->placeOrder();
317
+        $order = Order::firstOrFail();
318
+
319
+        $this->fakeHitPay('completed', [['id' => 'hp_pay_9', 'status' => 'succeeded', 'amount' => '5.00']], amount: '5.00');
320
+        $this->get(route('stores.preview.order', [$this->store->slug, $order->public_id]));
321
+        $this->assertFalse($order->fresh()->isPaid());
322
+
323
+        $this->fakeHitPay('completed', [['id' => 'hp_pay_9', 'status' => 'succeeded', 'amount' => '50.00']], currency: 'sgd');
324
+        $this->get(route('stores.preview.order', [$this->store->slug, $order->public_id]));
325
+        $this->assertFalse($order->fresh()->isPaid());
326
+
327
+        Mail::assertNothingSent();
328
+    }
329
+
330
+    public function test_a_message_from_hitpay_is_checked_with_hitpay_before_the_order_counts_as_paid()
331
+    {
332
+        $this->connectHitPay();
333
+        $this->fakeHitPay();
334
+        $this->placeOrder();
335
+        $order = Order::firstOrFail();
336
+
337
+        // A message claiming the order was paid, while HitPay itself says it was not.
338
+        $this->post(route('hitpay.webhook', $order->public_id), ['status' => 'completed', 'payment_request_id' => 'hp_req_1'])
339
+            ->assertOk();
340
+        $this->assertFalse($order->fresh()->isPaid());
341
+
342
+        // The shopper paid and closed the browser: HitPay's message gets the order marked paid.
343
+        $this->fakeHitPay('completed', [['id' => 'hp_pay_9', 'status' => 'succeeded', 'amount' => '50.00']]);
344
+        $this->post(route('hitpay.webhook', $order->public_id))->assertOk();
345
+        $this->post(route('hitpay.webhook', $order->public_id))->assertOk();
346
+
347
+        $this->assertTrue($order->fresh()->isPaid());
348
+        Mail::assertSent(OrderConfirmation::class, 1);
349
+
350
+        // Unknown orders are ignored.
351
+        $this->post(route('hitpay.webhook', 'not-an-order'))->assertOk();
352
+    }
353
+
354
+    public function test_methods_switched_off_in_hitpay_are_left_out_and_the_merchant_is_told()
355
+    {
356
+        $this->connectHitPay();
357
+        $this->fakeHitPay();
358
+        $this->switchedOff = ['duitnow', 'touch_n_go'];
359
+
360
+        // The shopper still gets a payment page, with the method that works.
361
+        $this->placeOrder()->assertRedirect('https://securecheckout.sandbox.hit-pay.com/payment-request/@kedai-ali/hp_req_1/checkout');
362
+        Http::assertSent(fn (HttpRequest $request) => $request->url() === self::API.'/payment-requests'
363
+            && $request['payment_methods'] === ['shopee_pay']);
364
+
365
+        $account = $this->store->fresh()->hitpayAccount;
366
+        $this->assertSame(['duitnow', 'touch_n_go'], $account->refused_methods);
367
+        $this->assertNotNull($account->refused_at);
368
+
369
+        // The next shoppers are only offered what works, and the merchant sees why.
370
+        $this->get(route('stores.preview.checkout', $this->store->slug))
371
+            ->assertInertia(fn (Assert $page) => $page->where('view.payWays.1', ['key' => 'hitpay', 'methods' => ['shopee_pay']]));
372
+        $this->get(route('stores.settings', $this->store->slug))
373
+            ->assertInertia(fn (Assert $page) => $page->where('hitpay.refused', ['duitnow', 'touch_n_go'])->whereNot('hitpay.refused_at', null));
374
+
375
+        // An hour later they are tried again, in case the merchant switched them on in HitPay.
376
+        $this->travel(61)->minutes();
377
+        $this->switchedOff = [];
378
+        $this->get(route('stores.preview.checkout', $this->store->slug))
379
+            ->assertInertia(fn (Assert $page) => $page->where('view.payWays.1.methods', ['duitnow', 'touch_n_go', 'shopee_pay']));
380
+
381
+        // This time HitPay takes them all, so the warning goes away.
382
+        $this->placeOrder();
383
+        $this->assertNull($this->store->fresh()->hitpayAccount->refused_methods);
384
+    }
385
+
386
+    public function test_saving_the_methods_tries_refused_ones_again_at_once()
387
+    {
388
+        $this->connectHitPay()->refused(['duitnow']);
389
+
390
+        $this->put(route('stores.hitpay.update', $this->store->slug), ['methods' => ['duitnow', 'shopee_pay']]);
391
+
392
+        $account = $this->store->fresh()->hitpayAccount;
393
+        $this->assertNull($account->refused_methods);
394
+        $this->assertSame(['duitnow', 'shopee_pay'], $account->offeredMethods());
395
+    }
396
+
397
+    public function test_when_hitpay_refuses_every_method_the_shopper_is_told_and_hitpay_is_hidden_for_a_while()
398
+    {
399
+        $this->connectHitPay(['duitnow']);
400
+        $this->fakeHitPay();
401
+        $this->switchedOff = ['duitnow'];
402
+
403
+        $this->placeOrder()->assertSessionHasErrors('cart');
404
+        $this->assertSame(0, Order::count());
405
+
406
+        // Only Stripe is offered until the merchant fixes it (or an hour passes).
407
+        $this->get(route('stores.preview.checkout', $this->store->slug))
408
+            ->assertInertia(fn (Assert $page) => $page->where('view.payWays', [['key' => 'fake', 'methods' => ['card', 'fpx', 'grabpay']]]));
409
+    }
410
+}

+ 33
- 2
tests/Feature/Stores/StripeConnectTest.php Visa fil

@@ -66,6 +66,8 @@ class StripeConnectTest extends TestCase
66 66
             'charges_enabled' => $ready,
67 67
             'payouts_enabled' => $ready,
68 68
             'details_submitted' => $ready,
69
+            'fpx_requested' => $ready,
70
+            'grabpay_requested' => $ready,
69 71
             'checked_at' => now(),
70 72
         ]);
71 73
         $this->accounts->statuses[$account->account_id] = new MerchantAccountStatus($ready, $ready, $ready);
@@ -115,7 +117,7 @@ class StripeConnectTest extends TestCase
115 117
         $this->assertSame([], $this->accounts->fpxRequested);
116 118
     }
117 119
 
118
-    public function test_coming_back_finished_saves_the_account_and_asks_for_fpx_once()
120
+    public function test_coming_back_finished_saves_the_account_and_asks_for_fpx_and_grabpay_once()
119 121
     {
120 122
         $this->connect();
121 123
         $this->accounts->approve('acct_fake_'.$this->store->id);
@@ -128,9 +130,10 @@ class StripeConnectTest extends TestCase
128 130
         $this->assertTrue($account->charges_enabled);
129 131
         $this->assertTrue($account->payouts_enabled);
130 132
         $this->assertTrue($account->fpx_requested);
133
+        $this->assertTrue($account->grabpay_requested);
131 134
 
132 135
         $this->get(route('stores.payments.return', $this->store->slug));
133
-        $this->assertCount(1, $this->accounts->fpxRequested);
136
+        $this->assertSame(["{$account->account_id}:fpx", "{$account->account_id}:grabpay"], $this->accounts->methodsRequested);
134 137
 
135 138
         $this->get(route('stores.settings', $this->store->slug))
136 139
             ->assertInertia(fn (Assert $page) => $page
@@ -199,6 +202,34 @@ class StripeConnectTest extends TestCase
199 202
         $this->assertSame(1, $this->accounts->statusCalls);
200 203
     }
201 204
 
205
+    public function test_a_store_set_up_before_grabpay_gets_it_switched_on_once()
206
+    {
207
+        // Connected and paid before GrabPay was added: FPX is on, GrabPay never asked for.
208
+        $account = $this->connectedAccount();
209
+        $account->forceFill(['grabpay_requested' => false, 'checked_at' => now()->subMinutes(5)])->save();
210
+
211
+        $connect = app(StripeConnect::class);
212
+        $this->assertTrue($connect->canTakePayments($this->store->refresh()));
213
+        $this->assertSame(["{$account->account_id}:grabpay"], $this->accounts->methodsRequested);
214
+        $this->assertTrue($account->fresh()->grabpay_requested);
215
+
216
+        // Done: a fully set up store is not asked about again.
217
+        $this->travel(2)->minutes();
218
+        $this->assertTrue($connect->canTakePayments($this->store->refresh()));
219
+        $this->assertSame(1, $this->accounts->statusCalls);
220
+        $this->assertCount(1, $this->accounts->methodsRequested);
221
+    }
222
+
223
+    public function test_stripe_being_down_while_switching_on_grabpay_keeps_the_store_open_and_tries_again_later()
224
+    {
225
+        $account = $this->connectedAccount();
226
+        $account->forceFill(['grabpay_requested' => false, 'checked_at' => now()->subMinutes(5)])->save();
227
+        $this->accounts->down = true;
228
+
229
+        $this->assertTrue(app(StripeConnect::class)->canTakePayments($this->store->refresh()));
230
+        $this->assertFalse($account->fresh()->grabpay_requested);
231
+    }
232
+
202 233
     public function test_the_real_gateway_will_not_open_a_payment_page_for_a_store_without_stripe()
203 234
     {
204 235
         $order = Order::factory()->for($this->store)->create();

+ 5
- 0
tests/Support/FakeGateway.php Visa fil

@@ -40,6 +40,11 @@ final class FakeGateway implements PaymentGateway
40 40
         return $this->takingPayments;
41 41
     }
42 42
 
43
+    public function methods(Store $store): array
44
+    {
45
+        return ['card', 'fpx', 'grabpay'];
46
+    }
47
+
43 48
     public function startCheckout(Order $order, string $successUrl, string $cancelUrl): CheckoutLink
44 49
     {
45 50
         if ($this->failToStart) {

+ 9
- 2
tests/Support/FakeMerchantAccounts.php Visa fil

@@ -25,6 +25,9 @@ final class FakeMerchantAccounts implements MerchantAccounts
25 25
     /** @var list<string> */
26 26
     public array $fpxRequested = [];
27 27
 
28
+    /** @var list<string> "account:method" for every payment method asked for. */
29
+    public array $methodsRequested = [];
30
+
28 31
     public int $statusCalls = 0;
29 32
 
30 33
     public bool $down = false;
@@ -57,11 +60,15 @@ final class FakeMerchantAccounts implements MerchantAccounts
57 60
         return $this->statuses[$accountId] ?? throw new PaymentException('Unknown account.');
58 61
     }
59 62
 
60
-    public function requestFpx(string $accountId): void
63
+    public function requestMethod(string $accountId, string $method): void
61 64
     {
62 65
         $this->failIfDown();
63 66
 
64
-        $this->fpxRequested[] = $accountId;
67
+        $this->methodsRequested[] = $accountId.':'.$method;
68
+
69
+        if ($method === 'fpx') {
70
+            $this->fpxRequested[] = $accountId;
71
+        }
65 72
     }
66 73
 
67 74
     /**

Laddar…
Avbryt
Spara