@heyama/pay-react-native 0.0.0-stage → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (120) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +99 -2
  3. package/assets/fonts/Figtree-Bold.ttf +0 -0
  4. package/assets/fonts/Figtree-ExtraBold.ttf +0 -0
  5. package/assets/fonts/Figtree-Medium.ttf +0 -0
  6. package/assets/fonts/Figtree-Regular.ttf +0 -0
  7. package/assets/fonts/Figtree-SemiBold.ttf +0 -0
  8. package/assets/fonts/OFL.txt +93 -0
  9. package/assets/logos/apple-pay.png +0 -0
  10. package/assets/logos/card.png +0 -0
  11. package/assets/logos/google-pay.png +0 -0
  12. package/assets/logos/mastercard.png +0 -0
  13. package/assets/logos/mixx.png +0 -0
  14. package/assets/logos/moov.png +0 -0
  15. package/assets/logos/mtn.png +0 -0
  16. package/assets/logos/orange.png +0 -0
  17. package/assets/logos/paypal.png +0 -0
  18. package/assets/logos/visa.png +0 -0
  19. package/assets/logos/wave.png +0 -0
  20. package/dist/checkout-core/hooks/use-checkout-controller.d.ts +9 -0
  21. package/dist/checkout-core/hooks/use-checkout-controller.js +319 -0
  22. package/dist/checkout-core/hooks/use-checkout-timers.d.ts +15 -0
  23. package/dist/checkout-core/hooks/use-checkout-timers.js +44 -0
  24. package/dist/checkout-core/hooks/use-phone-number.d.ts +7 -0
  25. package/dist/checkout-core/hooks/use-phone-number.js +82 -0
  26. package/dist/checkout-core/messages/en.d.ts +252 -0
  27. package/dist/checkout-core/messages/en.js +242 -0
  28. package/dist/checkout-core/messages/fr.d.ts +4 -0
  29. package/dist/checkout-core/messages/fr.js +244 -0
  30. package/dist/checkout-core/models/checkout.card.utils.d.ts +22 -0
  31. package/dist/checkout-core/models/checkout.card.utils.js +101 -0
  32. package/dist/checkout-core/models/checkout.constants.d.ts +56 -0
  33. package/dist/checkout-core/models/checkout.constants.js +142 -0
  34. package/dist/checkout-core/models/checkout.enum.d.ts +131 -0
  35. package/dist/checkout-core/models/checkout.enum.js +148 -0
  36. package/dist/checkout-core/models/checkout.interface.d.ts +417 -0
  37. package/dist/checkout-core/models/checkout.interface.js +1 -0
  38. package/dist/checkout-core/models/checkout.money.utils.d.ts +7 -0
  39. package/dist/checkout-core/models/checkout.money.utils.js +21 -0
  40. package/dist/checkout-core/models/checkout.phone.utils.d.ts +33 -0
  41. package/dist/checkout-core/models/checkout.phone.utils.js +159 -0
  42. package/dist/checkout-core/models/checkout.view.utils.d.ts +34 -0
  43. package/dist/checkout-core/models/checkout.view.utils.js +205 -0
  44. package/dist/checkout-core/models/domain.enum.d.ts +56 -0
  45. package/dist/checkout-core/models/domain.enum.js +62 -0
  46. package/dist/components/BrissotoPayProvider.d.ts +6 -0
  47. package/dist/components/BrissotoPayProvider.js +41 -0
  48. package/dist/components/PaymentSheetModal.d.ts +8 -0
  49. package/dist/components/PaymentSheetModal.js +72 -0
  50. package/dist/components/SheetBone.d.ts +3 -0
  51. package/dist/components/SheetBone.js +12 -0
  52. package/dist/components/SheetButton.d.ts +3 -0
  53. package/dist/components/SheetButton.js +33 -0
  54. package/dist/components/SheetCardFields.d.ts +8 -0
  55. package/dist/components/SheetCardFields.js +66 -0
  56. package/dist/components/SheetCodeField.d.ts +8 -0
  57. package/dist/components/SheetCodeField.js +95 -0
  58. package/dist/components/SheetContent.d.ts +3 -0
  59. package/dist/components/SheetContent.js +106 -0
  60. package/dist/components/SheetFailed.d.ts +3 -0
  61. package/dist/components/SheetFailed.js +43 -0
  62. package/dist/components/SheetForm.d.ts +7 -0
  63. package/dist/components/SheetForm.js +100 -0
  64. package/dist/components/SheetHeader.d.ts +6 -0
  65. package/dist/components/SheetHeader.js +69 -0
  66. package/dist/components/SheetIcon.d.ts +3 -0
  67. package/dist/components/SheetIcon.js +70 -0
  68. package/dist/components/SheetLayout.d.ts +8 -0
  69. package/dist/components/SheetLayout.js +35 -0
  70. package/dist/components/SheetLogo.d.ts +3 -0
  71. package/dist/components/SheetLogo.js +20 -0
  72. package/dist/components/SheetMessage.d.ts +3 -0
  73. package/dist/components/SheetMessage.js +15 -0
  74. package/dist/components/SheetMethodCard.d.ts +3 -0
  75. package/dist/components/SheetMethodCard.js +39 -0
  76. package/dist/components/SheetPhoneField.d.ts +3 -0
  77. package/dist/components/SheetPhoneField.js +56 -0
  78. package/dist/components/SheetRow.d.ts +3 -0
  79. package/dist/components/SheetRow.js +28 -0
  80. package/dist/components/SheetSimulator.d.ts +6 -0
  81. package/dist/components/SheetSimulator.js +39 -0
  82. package/dist/components/SheetSkeleton.d.ts +5 -0
  83. package/dist/components/SheetSkeleton.js +23 -0
  84. package/dist/components/SheetSuccess.d.ts +3 -0
  85. package/dist/components/SheetSuccess.js +51 -0
  86. package/dist/components/SheetSummary.d.ts +3 -0
  87. package/dist/components/SheetSummary.js +32 -0
  88. package/dist/components/SheetTerminal.d.ts +3 -0
  89. package/dist/components/SheetTerminal.js +21 -0
  90. package/dist/components/SheetText.d.ts +5 -0
  91. package/dist/components/SheetText.js +25 -0
  92. package/dist/components/SheetToast.d.ts +3 -0
  93. package/dist/components/SheetToast.js +24 -0
  94. package/dist/components/SheetWaiting.d.ts +7 -0
  95. package/dist/components/SheetWaiting.js +77 -0
  96. package/dist/hooks/use-native-platform.d.ts +10 -0
  97. package/dist/hooks/use-native-platform.js +47 -0
  98. package/dist/hooks/use-payment-sheet.d.ts +4 -0
  99. package/dist/hooks/use-payment-sheet.js +10 -0
  100. package/dist/hooks/use-sheet-motion.d.ts +7 -0
  101. package/dist/hooks/use-sheet-motion.js +62 -0
  102. package/dist/hooks/use-sheet-resize.d.ts +6 -0
  103. package/dist/hooks/use-sheet-resize.js +15 -0
  104. package/dist/hooks/use-sheet-theme.d.ts +4 -0
  105. package/dist/hooks/use-sheet-theme.js +12 -0
  106. package/dist/hooks/use-watched-payment.d.ts +6 -0
  107. package/dist/hooks/use-watched-payment.js +17 -0
  108. package/dist/index.d.ts +3 -0
  109. package/dist/index.js +2 -0
  110. package/dist/models/sheet.constants.d.ts +39 -0
  111. package/dist/models/sheet.constants.js +78 -0
  112. package/dist/models/sheet.enum.d.ts +16 -0
  113. package/dist/models/sheet.enum.js +18 -0
  114. package/dist/models/sheet.interface.d.ts +225 -0
  115. package/dist/models/sheet.interface.js +1 -0
  116. package/dist/models/sheet.utils.d.ts +43 -0
  117. package/dist/models/sheet.utils.js +132 -0
  118. package/dist/services/checkout.service.d.ts +7 -0
  119. package/dist/services/checkout.service.js +39 -0
  120. package/package.json +58 -4
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Brissoto Pay
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,100 @@
1
- # Temporary Holding Version
1
+ # @heyama/pay-react-native
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Take payments in your Expo app through Brissoto Pay: a payment sheet slides up, the payer pays in it and never leaves the app. Pure JavaScript: it runs in Expo Go and any Expo app, with no native code and no rebuild.
4
+
5
+ ```sh
6
+ npx expo install @heyama/pay-react-native convex expo-font react-native-webview
7
+ ```
8
+
9
+ ## 1. Create the payment on your server
10
+
11
+ The payment is created on your server with [`@heyama/pay`](https://www.npmjs.com/package/@heyama/pay), as for the web. Its key stays there: the app only gets the payment id.
12
+
13
+ ```ts
14
+ const payment = await pay.createPayment({
15
+ amount: 15000,
16
+ currency: 'XAF',
17
+ orderRef: order.id,
18
+ returnUrl: `kola://orders/${order.id}`, // your app's deep link
19
+ items: [{ name: 'Ndolé', quantity: 1, unitAmount: 15000 }],
20
+ payer: { phone: '+237690000000' },
21
+ })
22
+
23
+ res.json({ paymentId: payment.id })
24
+ ```
25
+
26
+ ## 2. Wrap the app in the provider
27
+
28
+ ```tsx
29
+ import { BrissotoPayProvider } from '@heyama/pay-react-native'
30
+
31
+ export default function RootLayout() {
32
+ return (
33
+ <BrissotoPayProvider>
34
+ <Stack />
35
+ </BrissotoPayProvider>
36
+ )
37
+ }
38
+ ```
39
+
40
+ ## 3. Open the payment sheet
41
+
42
+ ```tsx
43
+ import { usePaymentSheet } from '@heyama/pay-react-native'
44
+
45
+ function PayButton({ orderId }: { orderId: string }) {
46
+ const { presentPayment } = usePaymentSheet()
47
+
48
+ const pay = async () => {
49
+ const { paymentId } = await api.post(`/orders/${orderId}/pay`)
50
+ const result = await presentPayment({ paymentId })
51
+ if (result.status === 'paid') router.push(`/orders/${orderId}`)
52
+ }
53
+
54
+ return <Button title="Pay" onPress={pay} />
55
+ }
56
+ ```
57
+
58
+ `presentPayment` resolves when the sheet closes. One sheet at a time: a second call while one is open rejects.
59
+
60
+ ## Results
61
+
62
+ | `result.status` | When |
63
+ | --------------- | ----------------------------------------------------------------------------------------- |
64
+ | `paid` | The payment is paid. |
65
+ | `pending` | The payer closed the sheet while a prompt waited on their phone: it may still go through. |
66
+ | `closed` | The payer closed the sheet with the payment still open. |
67
+ | `cancelled` | The payment was cancelled. |
68
+ | `expired` | The payment expired. |
69
+ | `locked` | Too many failed tries: the payment can no longer be paid. |
70
+
71
+ When the sheet could not show the payment, `status` is `closed` and `result.error` says why: `not_found` (no payment has this id) or `network` (it could not load).
72
+
73
+ **The result proves nothing.** It comes from the phone. Ship the order on the `payment.paid` webhook, or once `getPayment` on your server says `paid`. Use the result only to move the payer on.
74
+
75
+ ## Deep link return URL
76
+
77
+ The sheet closes by itself; `returnUrl` brings the payer back when they pay on the checkout link (`checkoutUrl`) in a browser instead. Pass your app's deep link:
78
+
79
+ 1. Add your app's scheme (`scheme` in `app.json`) to the server's return URLs in the dashboard (Apps, your app, Integration), the scheme alone: `kola://`.
80
+ 2. Any link on it is then accepted: `kola://orders/12`.
81
+
82
+ ## Test with the Simulator
83
+
84
+ A payment created with a `bp_test_…` key opens with a Test badge and the Simulator: pick what happens to it (Approve, Decline, Wrong PIN, Low balance…) and the sheet follows. No money moves and no provider is called. The app changes nothing: the payment decides.
85
+
86
+ ## Language and theme
87
+
88
+ The sheet takes the payment's `language` and `theme`. Without them it follows the phone: French or English (English for any other language), light or dark.
89
+
90
+ ## Options
91
+
92
+ `BrissotoPayProvider` takes:
93
+
94
+ | Option | Default | What it is |
95
+ | ------ | ------------------------------ | ------------------------------------------------------------------------------------------------------- |
96
+ | `url` | `https://api-pay.brissoto.com` | The Brissoto Pay backend. One serves Live and Test. Set it only to point the sheet at a dev deployment. |
97
+
98
+ ```tsx
99
+ <BrissotoPayProvider url={process.env.EXPO_PUBLIC_BRISSOTO_PAY_URL}>
100
+ ```
Binary file
Binary file
Binary file
@@ -0,0 +1,93 @@
1
+ Copyright 2022 The Figtree Project Authors (https://github.com/erikdkennedy/figtree)
2
+
3
+ This Font Software is licensed under the SIL Open Font License, Version 1.1.
4
+ This license is copied below, and is also available with a FAQ at:
5
+ http://scripts.sil.org/OFL
6
+
7
+
8
+ -----------------------------------------------------------
9
+ SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
10
+ -----------------------------------------------------------
11
+
12
+ PREAMBLE
13
+ The goals of the Open Font License (OFL) are to stimulate worldwide
14
+ development of collaborative font projects, to support the font creation
15
+ efforts of academic and linguistic communities, and to provide a free and
16
+ open framework in which fonts may be shared and improved in partnership
17
+ with others.
18
+
19
+ The OFL allows the licensed fonts to be used, studied, modified and
20
+ redistributed freely as long as they are not sold by themselves. The
21
+ fonts, including any derivative works, can be bundled, embedded,
22
+ redistributed and/or sold with any software provided that any reserved
23
+ names are not used by derivative works. The fonts and derivatives,
24
+ however, cannot be released under any other type of license. The
25
+ requirement for fonts to remain under this license does not apply
26
+ to any document created using the fonts or their derivatives.
27
+
28
+ DEFINITIONS
29
+ "Font Software" refers to the set of files released by the Copyright
30
+ Holder(s) under this license and clearly marked as such. This may
31
+ include source files, build scripts and documentation.
32
+
33
+ "Reserved Font Name" refers to any names specified as such after the
34
+ copyright statement(s).
35
+
36
+ "Original Version" refers to the collection of Font Software components as
37
+ distributed by the Copyright Holder(s).
38
+
39
+ "Modified Version" refers to any derivative made by adding to, deleting,
40
+ or substituting -- in part or in whole -- any of the components of the
41
+ Original Version, by changing formats or by porting the Font Software to a
42
+ new environment.
43
+
44
+ "Author" refers to any designer, engineer, programmer, technical
45
+ writer or other person who contributed to the Font Software.
46
+
47
+ PERMISSION & CONDITIONS
48
+ Permission is hereby granted, free of charge, to any person obtaining
49
+ a copy of the Font Software, to use, study, copy, merge, embed, modify,
50
+ redistribute, and sell modified and unmodified copies of the Font
51
+ Software, subject to the following conditions:
52
+
53
+ 1) Neither the Font Software nor any of its individual components,
54
+ in Original or Modified Versions, may be sold by itself.
55
+
56
+ 2) Original or Modified Versions of the Font Software may be bundled,
57
+ redistributed and/or sold with any software, provided that each copy
58
+ contains the above copyright notice and this license. These can be
59
+ included either as stand-alone text files, human-readable headers or
60
+ in the appropriate machine-readable metadata fields within text or
61
+ binary files as long as those fields can be easily viewed by the user.
62
+
63
+ 3) No Modified Version of the Font Software may use the Reserved Font
64
+ Name(s) unless explicit written permission is granted by the corresponding
65
+ Copyright Holder. This restriction only applies to the primary font name as
66
+ presented to the users.
67
+
68
+ 4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
69
+ Software shall not be used to promote, endorse or advertise any
70
+ Modified Version, except to acknowledge the contribution(s) of the
71
+ Copyright Holder(s) and the Author(s) or with their explicit written
72
+ permission.
73
+
74
+ 5) The Font Software, modified or unmodified, in part or in whole,
75
+ must be distributed entirely under this license, and must not be
76
+ distributed under any other license. The requirement for fonts to
77
+ remain under this license does not apply to any document created
78
+ using the Font Software.
79
+
80
+ TERMINATION
81
+ This license becomes null and void if any of the above conditions are
82
+ not met.
83
+
84
+ DISCLAIMER
85
+ THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
86
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
87
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
88
+ OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
89
+ COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
90
+ INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
91
+ DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
92
+ FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
93
+ OTHER DEALINGS IN THE FONT SOFTWARE.
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
Binary file
@@ -0,0 +1,9 @@
1
+ import type { CheckoutControllerOptions, CheckoutCore, CheckoutView } from '../models/checkout.interface.js';
2
+ /**
3
+ * The whole checkout for one payment, on any platform: the gateway's live
4
+ * view of it, what the payer does, the number, the clocks, and every action
5
+ * the screens can take. What only a platform can do (coming back, the
6
+ * clipboard, leaving for the app, the card fields page) comes in `platform`.
7
+ * The language is not here: it comes from the IntlProvider around it.
8
+ */
9
+ export declare function useCheckoutController(view: CheckoutView | null | undefined, { clues, mutations, platform }: CheckoutControllerOptions): CheckoutCore;
@@ -0,0 +1,319 @@
1
+ import { useCallback, useEffect, useRef, useState } from 'react';
2
+ import { useFormatter, useTranslations } from 'use-intl';
3
+ import { COPIED_MS, FLOW_TRAITS, OTP_MAX_LENGTH, OTP_PATTERN, } from "../models/checkout.constants.js";
4
+ import { CardFieldsMessageEnum, CheckoutScreenEnum, CheckoutTabEnum, MethodFlowEnum, MethodStateEnum, PayRefusalEnum, } from "../models/checkout.enum.js";
5
+ import { CountryEnum } from "../models/domain.enum.js";
6
+ import { cardLabel } from "../models/checkout.card.utils.js";
7
+ import { formatMoney } from "../models/checkout.money.utils.js";
8
+ import { maskE164 } from "../models/checkout.phone.utils.js";
9
+ import { countriesOf, deriveCheckout, initialUi, screenOf, waitLeftOf, } from "../models/checkout.view.utils.js";
10
+ import { useNow, useReturnCountdown, useToast } from "./use-checkout-timers.js";
11
+ import { usePhoneNumber } from "./use-phone-number.js";
12
+ /** Before the payment has loaded, or for a link that matches none. */
13
+ const NO_PAYMENT_UI = {
14
+ tab: CheckoutTabEnum.MOBILE_MONEY,
15
+ country: CountryEnum.CAMEROON,
16
+ method: null,
17
+ code: '',
18
+ cardComplete: false,
19
+ cardPaying: false,
20
+ pickerOpen: true,
21
+ summaryOpen: false,
22
+ submitting: false,
23
+ dismissed: null,
24
+ redirecting: false,
25
+ };
26
+ /**
27
+ * The whole checkout for one payment, on any platform: the gateway's live
28
+ * view of it, what the payer does, the number, the clocks, and every action
29
+ * the screens can take. What only a platform can do (coming back, the
30
+ * clipboard, leaving for the app, the card fields page) comes in `platform`.
31
+ * The language is not here: it comes from the IntlProvider around it.
32
+ */
33
+ export function useCheckoutController(view, { clues, mutations, platform }) {
34
+ const t = useTranslations('checkout');
35
+ const format = useFormatter();
36
+ const [patch, setPatch] = useState({});
37
+ const [helpOpen, setHelpOpen] = useState(false);
38
+ const [copied, setCopied] = useState(false);
39
+ const copiedTimer = useRef(undefined);
40
+ /** A Pay press is on its way: a second tap must not start another attempt. */
41
+ const paying = useRef(false);
42
+ const [cardHeight, setCardHeight] = useState(null);
43
+ const toast = useToast();
44
+ const ui = {
45
+ ...(view ? initialUi(view, clues) : NO_PAYMENT_UI),
46
+ ...patch,
47
+ };
48
+ const update = useCallback((next) => setPatch((previous) => ({ ...previous, ...next })), []);
49
+ const countries = view ? countriesOf(view.methods) : [];
50
+ const phone = usePhoneNumber({
51
+ country: ui.country,
52
+ countries,
53
+ // A full number of another country moves the page there.
54
+ onCountryChange: (country) => update({ country, method: null, pickerOpen: true }),
55
+ });
56
+ const derived = view
57
+ ? deriveCheckout(view, ui, phone.status)
58
+ : {
59
+ screen: screenOf(view, ui),
60
+ countries,
61
+ wallets: [],
62
+ cards: [],
63
+ selected: null,
64
+ canPay: false,
65
+ mismatch: null,
66
+ suggestion: null,
67
+ };
68
+ const { screen } = derived;
69
+ const attempt = view?.attempt ?? null;
70
+ // The payer's number from the app, once the field exists.
71
+ const prefill = view?.payer.phone;
72
+ const { fill } = phone;
73
+ useEffect(() => {
74
+ if (prefill)
75
+ fill(prefill);
76
+ }, [prefill, fill]);
77
+ const waiting = screen === CheckoutScreenEnum.WAITING;
78
+ const now = useNow(waiting);
79
+ const waitLeft = attempt ? waitLeftOf(attempt.startedAt, now) : 0;
80
+ const attemptReference = attempt?.reference;
81
+ const noAnswer = t('toast.no_answer');
82
+ const showToast = toast.show;
83
+ useEffect(() => {
84
+ if (!waiting || waitLeft > 0)
85
+ return;
86
+ update({ dismissed: attemptReference });
87
+ showToast(noAnswer);
88
+ }, [waiting, waitLeft, attemptReference, noAnswer, showToast, update]);
89
+ const paymentId = view?.id;
90
+ // A payer opened the link, said once per page (the dashboard's preview has no mutations).
91
+ const opened = useRef(null);
92
+ useEffect(() => {
93
+ if (!paymentId || !mutations || opened.current === paymentId)
94
+ return;
95
+ opened.current = paymentId;
96
+ void mutations.open({ paymentId });
97
+ }, [paymentId, mutations]);
98
+ // Coming back to the page or the app while waiting: ask the provider now (ADR 0001).
99
+ useEffect(() => {
100
+ if (!waiting || !paymentId || !mutations)
101
+ return undefined;
102
+ return platform.onReturn(() => void mutations.checkNow({ paymentId }));
103
+ }, [waiting, paymentId, mutations, platform]);
104
+ const goBack = useCallback(() => update({ redirecting: true }), [update]);
105
+ const countdown = useReturnCountdown(screen === CheckoutScreenEnum.SUCCESS, goBack);
106
+ const returnUrl = view?.returnUrl;
107
+ useEffect(() => {
108
+ if (ui.redirecting && returnUrl)
109
+ platform.openUrl(returnUrl);
110
+ }, [ui.redirecting, returnUrl, platform]);
111
+ useEffect(() => () => clearTimeout(copiedTimer.current), []);
112
+ const failedToast = t('toast.failed');
113
+ const refusals = useCallback((reason) => t(`refusals.${reason}`), [t]);
114
+ // The card fields page says how it stands; the card itself never comes here.
115
+ useEffect(() => {
116
+ const onMessage = (message) => {
117
+ switch (message.type) {
118
+ case CardFieldsMessageEnum.HEIGHT:
119
+ setCardHeight(message.height);
120
+ break;
121
+ case CardFieldsMessageEnum.STATE:
122
+ // Incomplete on Pay: the fields say what is missing, the form stays.
123
+ update({
124
+ cardComplete: message.complete,
125
+ ...(message.complete ? {} : { cardPaying: false }),
126
+ });
127
+ break;
128
+ // The card is with its provider: the waiting screen follows the checks.
129
+ case CardFieldsMessageEnum.DONE:
130
+ update({ cardPaying: false });
131
+ break;
132
+ case CardFieldsMessageEnum.REFUSED:
133
+ update({ cardPaying: false });
134
+ showToast(message.reason ? refusals(message.reason) : failedToast);
135
+ break;
136
+ }
137
+ };
138
+ return platform.onCardMessage(onMessage);
139
+ }, [update, showToast, refusals, failedToast, platform]);
140
+ /* ---------------------------------------------------------- helpers */
141
+ const reference = attempt?.reference ?? view?.id ?? '';
142
+ const comingSoon = (name) => toast.show(t('toast.soon', { method: name }));
143
+ /**
144
+ * Starts an attempt with the number, and the payment code of an OTP
145
+ * method; a second tap while one is on its way does nothing.
146
+ */
147
+ const submit = (method, { phone: e164, otp }) => {
148
+ if (paying.current)
149
+ return;
150
+ paying.current = true;
151
+ update({ submitting: true });
152
+ const args = { paymentId: view.id, method, phone: e164 };
153
+ void (otp === undefined
154
+ ? mutations.pay(args)
155
+ : mutations.payWithCode({ ...args, otp }))
156
+ .then((result) => {
157
+ if (!result.ok)
158
+ toast.show(t(`refusals.${result.reason}`));
159
+ })
160
+ .catch(() => toast.show(t('toast.failed')))
161
+ .finally(() => {
162
+ paying.current = false;
163
+ update({ submitting: false });
164
+ });
165
+ };
166
+ const receiptText = (payment) => [
167
+ t('receipt_title'),
168
+ '',
169
+ payment.app.name,
170
+ `${t('amount')}: ${formatMoney(payment.amount, payment.currency)}`,
171
+ `${t('method')}: ${attempt.methodName}`,
172
+ // A card paid by hand may come without what its provider reported.
173
+ ...(attempt.phone
174
+ ? [`${t('number')}: ${maskE164(attempt.phone)}`]
175
+ : attempt.card
176
+ ? [`${t('card')}: ${cardLabel(attempt.card)}`]
177
+ : []),
178
+ `${t('date')}: ${format.dateTime(payment.paidAt, { dateStyle: 'medium', timeStyle: 'short' })}`,
179
+ `${t('reference')}: ${reference}`,
180
+ ].join('\n');
181
+ /* ---------------------------------------------------------- actions */
182
+ const actions = {
183
+ toggleSummary: () => update({ summaryOpen: !ui.summaryOpen }),
184
+ setTab: (tab) => update({ tab }),
185
+ setCountry: (country) => update({ country, method: null, pickerOpen: true }),
186
+ selectMethod: (method) => {
187
+ if (method.state === MethodStateEnum.SOON) {
188
+ comingSoon(method.name);
189
+ }
190
+ else if (method.state === MethodStateEnum.MAINTENANCE) {
191
+ toast.show(method.note ?? t('toast.unavailable', { method: method.name }));
192
+ }
193
+ else {
194
+ update({
195
+ method: method.id,
196
+ pickerOpen: false,
197
+ code: '',
198
+ cardComplete: false,
199
+ });
200
+ }
201
+ },
202
+ comingSoon,
203
+ openPicker: () => update({ pickerOpen: true }),
204
+ // Only offered while the number belongs to another method.
205
+ switchToDetected: () => {
206
+ const detected = derived.mismatch;
207
+ update({ method: detected.id });
208
+ toast.show(t('toast.switched', { method: detected.name }));
209
+ },
210
+ pay: () => {
211
+ const { selected } = derived;
212
+ if (!selected)
213
+ return;
214
+ // The preview offers no card: it shows Mobile Money only.
215
+ if (selected.flow === MethodFlowEnum.CARD_FIELDS) {
216
+ // The fields page pays with its provider, then says how it went.
217
+ update({ cardPaying: true });
218
+ platform.submitCard();
219
+ return;
220
+ }
221
+ if (!phone.status.valid) {
222
+ phone.reject();
223
+ platform.onPhoneRejected();
224
+ return;
225
+ }
226
+ const otp = selected.flow === MethodFlowEnum.OTP;
227
+ if (otp && !OTP_PATTERN.test(ui.code)) {
228
+ toast.show(t(`refusals.${PayRefusalEnum.CODE}`));
229
+ return;
230
+ }
231
+ if (!mutations) {
232
+ toast.show(t('toast.preview'));
233
+ return;
234
+ }
235
+ submit(selected.id, {
236
+ phone: phone.e164,
237
+ ...(otp ? { otp: ui.code } : {}),
238
+ });
239
+ },
240
+ // Only offered while an OTP method, which always has its code, is picked.
241
+ cannotDial: () => {
242
+ const method = derived.selected;
243
+ toast.show(t('toast.dial', { code: method.otpCode, method: method.name }));
244
+ },
245
+ // Only on the failure screen, which the preview never shows.
246
+ retry: () => {
247
+ // A payment code works once, a card is typed again: back to the form.
248
+ const traits = FLOW_TRAITS[attempt.flow];
249
+ if (!traits.prompt) {
250
+ update({
251
+ dismissed: attempt.reference,
252
+ tab: traits.tab,
253
+ method: attempt.method,
254
+ pickerOpen: false,
255
+ code: '',
256
+ cardComplete: false,
257
+ });
258
+ return;
259
+ }
260
+ submit(attempt.method, { phone: attempt.phone });
261
+ },
262
+ setCode: (code) => update({ code: code.replace(/\D/g, '').slice(0, OTP_MAX_LENGTH) }),
263
+ useAnother: () => {
264
+ const { suggestion } = derived;
265
+ update({
266
+ dismissed: attempt.reference,
267
+ tab: CheckoutTabEnum.MOBILE_MONEY,
268
+ country: suggestion?.country ?? ui.country,
269
+ method: suggestion?.id ?? null,
270
+ pickerOpen: !suggestion,
271
+ });
272
+ },
273
+ resend: () => {
274
+ void mutations
275
+ .resend({ paymentId: view.id })
276
+ .then((result) => toast.show(result.ok
277
+ ? t('toast.resent', { phone: maskE164(attempt.phone) })
278
+ : t('toast.resend_wait')))
279
+ .catch(() => toast.show(t('toast.failed')));
280
+ },
281
+ cancel: () => {
282
+ void mutations
283
+ .cancel({ paymentId: view.id })
284
+ .catch(() => toast.show(t('toast.failed')));
285
+ },
286
+ returnNow: goBack,
287
+ stayHere: countdown.stop,
288
+ openHelp: () => setHelpOpen(true),
289
+ closeHelp: () => setHelpOpen(false),
290
+ copyReference: () => {
291
+ platform.copyText(reference);
292
+ clearTimeout(copiedTimer.current);
293
+ setCopied(true);
294
+ copiedTimer.current = setTimeout(() => setCopied(false), COPIED_MS);
295
+ toast.show(t('toast.copied'));
296
+ },
297
+ downloadReceipt: () => {
298
+ platform.saveReceipt(`receipt-${reference}.txt`, receiptText(view));
299
+ toast.show(t('toast.downloaded'));
300
+ },
301
+ simulate: (outcome) => {
302
+ void mutations.simulate({ paymentId: view.id, outcome });
303
+ },
304
+ };
305
+ return {
306
+ view: view ?? null,
307
+ ui,
308
+ derived,
309
+ phone,
310
+ waitLeft,
311
+ returnLeft: countdown.left,
312
+ helpOpen,
313
+ toastMessage: toast.message,
314
+ copied,
315
+ preview: !mutations,
316
+ cardHeight,
317
+ actions,
318
+ };
319
+ }
@@ -0,0 +1,15 @@
1
+ /** The time now, moving once a second while `running`: the waiting screen's clock. */
2
+ export declare function useNow(running: boolean): number;
3
+ /**
4
+ * The success screen's countdown back to the app: from 5 while `running`,
5
+ * calling `onDone` at 0. `stop` leaves the payer on the page.
6
+ */
7
+ export declare function useReturnCountdown(running: boolean, onDone: () => void): {
8
+ left: number | null;
9
+ stop: () => void;
10
+ };
11
+ /** One short message at a time at the top of the page. */
12
+ export declare function useToast(): {
13
+ message: string | null;
14
+ show: (next: string) => void;
15
+ };
@@ -0,0 +1,44 @@
1
+ import { useCallback, useEffect, useRef, useState } from 'react';
2
+ import { RETURN_SECONDS, TICK_MS, TOAST_MS, } from "../models/checkout.constants.js";
3
+ /** The time now, moving once a second while `running`: the waiting screen's clock. */
4
+ export function useNow(running) {
5
+ const [now, setNow] = useState(() => Date.now());
6
+ useEffect(() => {
7
+ if (!running)
8
+ return undefined;
9
+ setNow(Date.now());
10
+ const tick = setInterval(() => setNow(Date.now()), TICK_MS);
11
+ return () => clearInterval(tick);
12
+ }, [running]);
13
+ return now;
14
+ }
15
+ /**
16
+ * The success screen's countdown back to the app: from 5 while `running`,
17
+ * calling `onDone` at 0. `stop` leaves the payer on the page.
18
+ */
19
+ export function useReturnCountdown(running, onDone) {
20
+ const [left, setLeft] = useState(RETURN_SECONDS);
21
+ useEffect(() => {
22
+ if (!running || left === null)
23
+ return undefined;
24
+ if (left === 0) {
25
+ onDone();
26
+ return undefined;
27
+ }
28
+ const tick = setTimeout(() => setLeft(left - 1), TICK_MS);
29
+ return () => clearTimeout(tick);
30
+ }, [running, left, onDone]);
31
+ return { left, stop: () => setLeft(null) };
32
+ }
33
+ /** One short message at a time at the top of the page. */
34
+ export function useToast() {
35
+ const [message, setMessage] = useState(null);
36
+ const timer = useRef(undefined);
37
+ useEffect(() => () => clearTimeout(timer.current), []);
38
+ const show = useCallback((next) => {
39
+ clearTimeout(timer.current);
40
+ setMessage(next);
41
+ timer.current = setTimeout(() => setMessage(null), TOAST_MS);
42
+ }, []);
43
+ return { message, show };
44
+ }
@@ -0,0 +1,7 @@
1
+ import type { PhoneNumber, PhoneNumberOptions } from '../models/checkout.interface.js';
2
+ /**
3
+ * The Mobile Money number, checked by the country's own rules
4
+ * (libphonenumber-js) and grouped as the payer types. A space deleted takes
5
+ * the digit before it. The field itself is the platform's.
6
+ */
7
+ export declare function usePhoneNumber({ country, countries, onCountryChange, }: PhoneNumberOptions): PhoneNumber;