pa-sdk-react-native 3.0.2 → 3.0.4

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 (59) hide show
  1. package/README.md +21 -12
  2. package/example/App.tsx +583 -0
  3. package/example/README.md +105 -0
  4. package/example/android/app/build.gradle +130 -0
  5. package/example/android/app/debug.keystore +0 -0
  6. package/example/android/app/proguard-rules.pro +10 -0
  7. package/example/android/app/src/debug/AndroidManifest.xml +9 -0
  8. package/example/android/app/src/main/AndroidManifest.xml +26 -0
  9. package/example/android/app/src/main/java/com/pademo/MainActivity.kt +22 -0
  10. package/example/android/app/src/main/java/com/pademo/MainApplication.kt +45 -0
  11. package/example/android/app/src/main/res/drawable/rn_edit_text_material.xml +37 -0
  12. package/example/android/app/src/main/res/mipmap-hdpi/ic_launcher.png +0 -0
  13. package/example/android/app/src/main/res/mipmap-hdpi/ic_launcher_round.png +0 -0
  14. package/example/android/app/src/main/res/mipmap-mdpi/ic_launcher.png +0 -0
  15. package/example/android/app/src/main/res/mipmap-mdpi/ic_launcher_round.png +0 -0
  16. package/example/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png +0 -0
  17. package/example/android/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png +0 -0
  18. package/example/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png +0 -0
  19. package/example/android/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png +0 -0
  20. package/example/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png +0 -0
  21. package/example/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png +0 -0
  22. package/example/android/app/src/main/res/values/strings.xml +3 -0
  23. package/example/android/app/src/main/res/values/styles.xml +9 -0
  24. package/example/android/build.gradle +21 -0
  25. package/example/android/gradle/wrapper/gradle-wrapper.jar +0 -0
  26. package/example/android/gradle/wrapper/gradle-wrapper.properties +7 -0
  27. package/example/android/gradle.properties +39 -0
  28. package/example/android/gradlew +251 -0
  29. package/example/android/gradlew.bat +94 -0
  30. package/example/android/settings.gradle +8 -0
  31. package/example/app.json +4 -0
  32. package/example/index.js +4 -0
  33. package/example/ios/.xcode.env +11 -0
  34. package/example/ios/.xcode.env.local +1 -0
  35. package/example/ios/PaSdkExample/AppDelegate.swift +111 -0
  36. package/example/ios/PaSdkExample/Images.xcassets/AppIcon.appiconset/Contents.json +53 -0
  37. package/example/ios/PaSdkExample/Images.xcassets/Contents.json +6 -0
  38. package/example/ios/PaSdkExample/Info.plist +81 -0
  39. package/example/ios/PaSdkExample/LaunchScreen.storyboard +47 -0
  40. package/example/ios/PaSdkExample/PrivacyInfo.xcprivacy +37 -0
  41. package/example/ios/PaSdkExample.xcodeproj/project.pbxproj +468 -0
  42. package/example/ios/PaSdkExample.xcodeproj/xcshareddata/xcschemes/PaSdkExample.xcscheme +88 -0
  43. package/example/ios/PaSdkExample.xcworkspace/contents.xcworkspacedata +10 -0
  44. package/example/ios/Podfile +39 -0
  45. package/example/ios/Podfile.lock +1990 -0
  46. package/example/metro.config.js +17 -0
  47. package/example/package.json +29 -0
  48. package/example/patches/react-native+0.79.0.patch +215 -0
  49. package/lib/api.d.ts +3 -0
  50. package/lib/api.js +9 -2
  51. package/lib/confirm.js +78 -32
  52. package/lib/locales.generated.js +108 -4
  53. package/locales/en-US.json +27 -1
  54. package/locales/ms-MY.json +27 -1
  55. package/locales/zh-CN.json +27 -1
  56. package/locales/zh-TW.json +27 -1
  57. package/native/ios/PaSdk3ds.swift +3 -2
  58. package/native/ios/PaSdk3dsModule.m +2 -1
  59. package/package.json +10 -2
package/README.md CHANGED
@@ -90,7 +90,7 @@ init({
90
90
  TW: 'mt_tw_...',
91
91
  },
92
92
  defaultAccount: 'HK',
93
- locale: 'zh_HK', // en_US / zh_HK / zh_CN / my_MY
93
+ locale: 'zh-TW', // en-US / zh-TW / zh-CN / ms-MY (aliases zh_HK, my_MY accepted)
94
94
  origin: 'https://app.yourdomain.com',
95
95
  threeDsReturnUrls: { // consumed by the SDK
96
96
  scheme: 'yourapp://',
@@ -212,22 +212,31 @@ await cancelIntent({ intentToken, clientToken }); // -> { status: 'cancelled' }
212
212
 
213
213
  ## Sandbox test cards
214
214
 
215
- Sandbox only — never real cards. Pass `threeDsAction: 'force'` in the confirm
216
- options to run an interactive 3DS challenge on any sandbox card.
215
+ Sandbox only — never real cards. To exercise the interactive challenge, use a
216
+ 3DS challenge card below, or create the intent with
217
+ `three_ds_action: 'force'` (server-side, at intent creation — the confirm-time
218
+ `threeDsAction` option is advisory only and is not applied by the gateway).
217
219
 
218
220
  | Scenario | Card number |
219
221
  |---|---|
220
- | Success | 4000 0000 0000 0069 |
221
- | Insufficient funds | 4000 0000 0000 9995 |
222
- | Expired card | 4000 0000 0000 0120 |
222
+ | Success (Visa) | 4242 4242 4242 4242 |
223
+ | Success (Mastercard) | 5555 5555 5555 4444 |
224
+ | Success (Mastercard 2-series) | 2223 0031 2200 3222 |
225
+ | Insufficient funds | 4000 0000 0000 0002 |
226
+ | Insufficient funds (Mastercard) | 5424 0000 0000 0007 |
223
227
  | Generic decline | 4111 1111 1111 1111 |
224
- | 3DS challenge — pass | 4000 0000 0000 3220 |
225
- | 3DS challenge — fail | 4000 0000 0000 3221 |
226
- | 3DS challenge — cancel | 4000 0000 0000 3222 |
228
+ | Expired card | 4000 0000 0000 0127 |
229
+ | Unsupported brand (Amex) | 3782 822463 10005 |
230
+ | 3DS frictionless | 4000 0000 0000 0010 |
231
+ | 3DS frictionless (Mastercard) | 5200 8282 8282 8210 |
232
+ | 3DS challenge — interactive page | 4000 0000 0000 0028 |
233
+ | 3DS challenge (Mastercard) | 5454 5454 5454 5454 |
234
+ | 3DS challenge fail | 4000 0000 0000 0036 |
235
+ | 3DS challenge fail (Mastercard) | 5105 1051 0510 5100 |
227
236
  | Redirect fallback | 4000 0000 0000 0044 |
228
- | Delayed / processing | 4000 0000 0000 9976 |
229
- | Mastercard | 5100 0000 0000 0008 |
230
- | Mastercard 2-series | 2221 0000 0000 0009 |
237
+ | Redirect fallback (Mastercard) | 5522 5000 0000 0098 |
238
+ | Delayed / processing | 4000 0000 0000 0051 |
239
+ | Delayed / processing (Mastercard) | 2223 0000 0000 0007 |
231
240
 
232
241
  ## Validation helpers
233
242
 
@@ -0,0 +1,583 @@
1
+ /**
2
+ * PA SDK React Native — example app (RN-32).
3
+ *
4
+ * Flows exercised:
5
+ * 1. One-off payment — confirmWithCard (combined)
6
+ * 2. Two-step payment — tokenizeCard -> confirmWithToken (RN-14)
7
+ * 3. Save during payment — saveCard: true on a Sale intent (COM-14 / RN-23)
8
+ * 4. Manual save — $0 verification intent (amount "0"; the
9
+ * gateway treats amount=0 as card-setup
10
+ * verification, nothing is charged) +
11
+ * saveCard: true (COM-15 / RN-24)
12
+ * 5. 3DS challenge + cancel — SDK-presented WebView (RN-19); the Cancel
13
+ * button at the top-right of the challenge
14
+ * returns 'cancelled' (R4)
15
+ * 6. Multi-market — init with HK + MY accounts, per-call
16
+ * market switch (COM-40 / R10)
17
+ * 7. Saved-card reuse — confirmWithToken with a pa_token saved by
18
+ * flow 3/4 or step 4a
19
+ * 8. App-switch return — the SDK's handleReturnUrl gets first
20
+ * refusal on every URL the app receives
21
+ * (iOS AppDelegate + Linking listener
22
+ * below); consumed 3DS returns are ignored
23
+ * and logged
24
+ *
25
+ * Environment defaults to 'sandbox' (aligned with example/README.md); the
26
+ * visible toggle re-inits the SDK and switches the demo mint gateway host.
27
+ *
28
+ * Idempotency: the key is stable for one logical attempt — retrying a flow
29
+ * button re-sends the same key (the gateway returns the stored result for
30
+ * an already-confirmed intent instead of double-charging). A new attempt
31
+ * (fresh intent minted, or "Start new attempt") regenerates it.
32
+ *
33
+ * Tokens: the app itself never holds a secret key (COM-01). Paste an
34
+ * intent_token + client_token from YOUR server (created per A1) into the
35
+ * fields, or point the MOCK notes in example/README.md at your sandbox
36
+ * backend to mint them.
37
+ */
38
+
39
+ import React, { useCallback, useEffect, useMemo, useState } from 'react';
40
+ import {
41
+ ActivityIndicator,
42
+ Alert,
43
+ KeyboardAvoidingView,
44
+ Linking,
45
+ Platform,
46
+ ScrollView,
47
+ StyleSheet,
48
+ Text,
49
+ TextInput,
50
+ TouchableOpacity,
51
+ View,
52
+ } from 'react-native';
53
+ import {
54
+ confirmWithCard,
55
+ confirmWithToken,
56
+ getLocaleStrings,
57
+ handleReturnUrl,
58
+ init,
59
+ isPaError,
60
+ PaError,
61
+ PaSdk3dsHost,
62
+ tokenizeCard,
63
+ validateCard,
64
+ type PaymentResult,
65
+ } from 'pa-sdk-react-native';
66
+
67
+ const LOCALES = ['en_US', 'zh_HK', 'zh_CN', 'my_MY'] as const;
68
+ const MARKETS = ['HK', 'MY'] as const;
69
+ const ENVIRONMENTS = ['sandbox', 'production'] as const;
70
+ type Environment = (typeof ENVIRONMENTS)[number];
71
+
72
+ type Flow = 'oneoff' | 'save_during' | 'manual_save' | 'saved_reuse';
73
+
74
+ const FLOWS: Array<{ id: Flow; label: string; hint: string }> = [
75
+ {
76
+ id: 'oneoff',
77
+ label: 'One-off payment',
78
+ hint: 'Mints a Sale intent; confirmWithCard pays it. No card saving.',
79
+ },
80
+ {
81
+ id: 'save_during',
82
+ label: 'Save during payment',
83
+ hint: 'Sale intent + saveCard: true — pa_token, brand and last4 return with the payment result.',
84
+ },
85
+ {
86
+ id: 'manual_save',
87
+ label: 'Manual save ($0 verify)',
88
+ hint: 'Mints a $0 verification intent (amount "0" — nothing is charged) and confirms it with saveCard: true; pa_token returns synchronously.',
89
+ },
90
+ {
91
+ id: 'saved_reuse',
92
+ label: 'Saved-card reuse',
93
+ hint: 'Mints a normal Sale intent, then confirms it with a pa_token saved earlier (confirmWithToken). Save or tokenize a card first.',
94
+ },
95
+ ];
96
+
97
+ // Gateway host per environment — the demo mint below uses the same host as
98
+ // init(). Sandbox is the default so the example matches example/README.md.
99
+ const GATEWAY: Record<Environment, string> = {
100
+ sandbox: 'https://gateway-sandbox.pa-sys.com/pasdk/v1',
101
+ production: 'https://gateway.pa-sys.com/pasdk/v1',
102
+ };
103
+
104
+ // Replace with your sandbox publishable merchant tokens (per market).
105
+ const DEMO_API_KEY = ''; // OPTIONAL local demo only — paste a test API key; production apps mint intents from THEIR server (COM-01)
106
+ const MERCHANT_TOKENS: Record<string, string> = {
107
+ HK: 'REPLACE_WITH_HK_MERCHANT_TOKEN',
108
+ MY: 'REPLACE_WITH_MY_MERCHANT_TOKEN',
109
+ };
110
+
111
+ export default function App(): React.JSX.Element {
112
+ const [ready, setReady] = useState(false);
113
+ const [environment, setEnvironment] = useState<Environment>('sandbox');
114
+ const [locale, setLocaleTag] = useState<string>('en_US');
115
+ const [market, setMarket] = useState<'HK' | 'MY'>('HK');
116
+ const [flow, setFlow] = useState<Flow>('oneoff');
117
+
118
+ // Idempotency key — stable across retries of the SAME logical attempt.
119
+ const [attemptKey, setAttemptKey] = useState(() => `flow-example-${Date.now()}`);
120
+ // pa_token from the latest successful save/tokenize — used by saved_reuse.
121
+ const [savedToken, setSavedToken] = useState<string | null>(null);
122
+ // Last URL the APP itself received (SDK-consumed 3DS returns never surface).
123
+ const [lastAppUrl, setLastAppUrl] = useState<string | null>(null);
124
+
125
+ const [cardNumber, setCardNumber] = useState('4242 4242 4242 4242');
126
+ const [expiry, setExpiry] = useState('12/29');
127
+ const [cvc, setCvc] = useState('123');
128
+ const [holderName, setHolderName] = useState('');
129
+ const [saveCard, setSaveCard] = useState(false);
130
+
131
+ const [intentToken, setIntentToken] = useState('');
132
+ const [clientToken, setClientToken] = useState('');
133
+ const [amount, setAmount] = useState('0.10');
134
+ const [tokenized, setTokenized] = useState<string | null>(null);
135
+
136
+ const [threeDsVisible, setThreeDsVisible] = useState(false);
137
+ const [busy, setBusy] = useState(false);
138
+ const [result, setResult] = useState<PaymentResult | null>(null);
139
+ const [errorText, setErrorText] = useState<string | null>(null);
140
+
141
+ const strings = useMemo(() => getLocaleStrings(locale), [locale]);
142
+
143
+ // App-switch return (README "iOS app-switch returns"): give the SDK first
144
+ // refusal on every URL reaching the app's own handler. `handleReturnUrl`
145
+ // consumes the URL only when it matches the PENDING 3DS challenge's
146
+ // return URLs (then the app ignores it); otherwise it resolves false and
147
+ // the URL is the app's own deep linking — surfaced below. On Android the
148
+ // SDK consumes 3DS returns at the OS level, so this listener effectively
149
+ // only sees non-3DS URLs there.
150
+ useEffect(() => {
151
+ const sub = Linking.addEventListener('url', ({ url }) => {
152
+ handleReturnUrl(url).then((consumed) => {
153
+ if (consumed) {
154
+ console.log('[PaSdkExample] 3DS return consumed by the SDK:', url);
155
+ } else {
156
+ console.log('[PaSdkExample] app received URL:', url);
157
+ setLastAppUrl(url);
158
+ }
159
+ });
160
+ });
161
+ return () => sub.remove();
162
+ }, []);
163
+
164
+ const doInit = useCallback(() => {
165
+ init({
166
+ environment, // default 'sandbox' — visible toggle below
167
+ accounts: MERCHANT_TOKENS,
168
+ defaultAccount: 'HK',
169
+ locale,
170
+ origin: 'https://app.flowtheroom.com',
171
+ threeDsReturnUrls: {
172
+ scheme: 'flow://', // consumed by the SDK; also registered on iOS (Info.plist CFBundleURLTypes)
173
+ universalLinkHost: 'https://app.flowtheroom.com',
174
+ },
175
+ });
176
+ setReady(true);
177
+ }, [environment, locale]);
178
+
179
+ // Re-init when the environment or locale changes after the first init.
180
+ useEffect(() => {
181
+ if (ready) {
182
+ doInit();
183
+ }
184
+ // eslint-disable-next-line react-hooks/exhaustive-deps
185
+ }, [environment, locale]);
186
+
187
+ const mintIntent = useCallback(async () => {
188
+ setBusy(true);
189
+ setErrorText(null);
190
+ // Manual save mints a $0 verification intent (amount "0" — the gateway
191
+ // treats amount=0 as card-setup verification, no capture); every other
192
+ // flow mints a normal Sale.
193
+ const isVerification = flow === 'manual_save';
194
+ try {
195
+ const res = await fetch(`${GATEWAY[environment]}/${MERCHANT_TOKENS[market]}/payment-intent`, {
196
+ method: 'POST',
197
+ headers: { 'Content-Type': 'application/json', 'X-API-KEY': DEMO_API_KEY },
198
+ body: JSON.stringify({
199
+ merchant_reference: `RNDEMO-${Date.now()}`,
200
+ currency: 'HKD',
201
+ amount: isVerification ? '0' : amount.trim() || '0.10',
202
+ type: 'Sale', // gateway supports "Sale" | "Authorize"; the $0 amount is what makes it a verification intent
203
+ }),
204
+ });
205
+ const j = await res.json();
206
+ if (j?.payload?.intent_token) {
207
+ setIntentToken(j.payload.intent_token);
208
+ setClientToken(j.payload.client_token);
209
+ // A fresh intent = a NEW logical attempt: regenerate the idempotency
210
+ // key. Retries of THIS attempt keep the same key (see attemptKey).
211
+ setAttemptKey(`flow-example-${Date.now()}`);
212
+ if (!ready) { doInit(); }
213
+ } else {
214
+ setErrorText(`mint failed: ${j?.response?.message ?? res.status}`);
215
+ }
216
+ } catch (e) {
217
+ setErrorText(String(e));
218
+ } finally {
219
+ setBusy(false);
220
+ }
221
+ }, [amount, environment, flow, market, ready, doInit]);
222
+
223
+ const parsedCard = useMemo(
224
+ () => ({
225
+ cardNumber,
226
+ expiryMonth: expiry.split('/')[0]?.trim() ?? '',
227
+ expiryYear: expiry.split('/')[1]?.trim() ?? '',
228
+ cvc,
229
+ cardHolderName: holderName || undefined,
230
+ }),
231
+ [cardNumber, expiry, cvc, holderName]
232
+ );
233
+
234
+ const run = useCallback(
235
+ async (action: () => Promise<PaymentResult>) => {
236
+ setBusy(true);
237
+ setResult(null);
238
+ setErrorText(null);
239
+ try {
240
+ const outcome = await action();
241
+ setResult(outcome);
242
+ if (outcome.paToken) {
243
+ setSavedToken(outcome.paToken); // feeds the saved-card reuse flow
244
+ }
245
+ if (outcome.status === 'failed' && outcome.userMessage) {
246
+ // RN-29: show PA's localized user message, log the code.
247
+ Alert.alert(outcome.status, `${outcome.userMessage}\n[code: ${outcome.errorCode}]`);
248
+ }
249
+ } catch (error) {
250
+ if (isPaError(error)) {
251
+ setErrorText(`${error.code}: ${error.developerMessage}`);
252
+ Alert.alert(error.code, error.userMessage);
253
+ } else {
254
+ setErrorText(String(error));
255
+ }
256
+ } finally {
257
+ setBusy(false);
258
+ setThreeDsVisible(false);
259
+ }
260
+ },
261
+ []
262
+ );
263
+
264
+ const baseOptions = () => ({
265
+ intentToken: intentToken.trim(),
266
+ clientToken: clientToken.trim(),
267
+ market,
268
+ // Stable per logical attempt — retrying re-sends the same key; a NEW
269
+ // attempt (new intent / "Start new attempt") gets a fresh one.
270
+ idempotencyKey: attemptKey,
271
+ saveCard,
272
+ billing: holderName ? { cardholderName: holderName } : undefined,
273
+ onThreeDsWillPresent: () => setThreeDsVisible(true), // RN-19
274
+ onThreeDsEnded: () => setThreeDsVisible(false),
275
+ });
276
+
277
+ const payCombined = () =>
278
+ run(async () => {
279
+ const validation = validateCard(parsedCard, ['visa', 'mastercard']);
280
+ if (!validation.complete) {
281
+ throw new PaError(validation.fields.cardNumber || validation.fields.expiry || validation.fields.cvc || 'invalid_number');
282
+ }
283
+ return confirmWithCard({ ...baseOptions(), card: parsedCard, allowedBrands: ['visa', 'mastercard'] });
284
+ });
285
+
286
+ const payWithSavedCard = () =>
287
+ run(async () => {
288
+ const token = savedToken ?? tokenized;
289
+ if (!token) {
290
+ throw new PaError('request_invalid', {
291
+ developerMessage: 'No saved card yet — run a save flow first (they return a pa_token) or use step 4a.',
292
+ });
293
+ }
294
+ // Reusing a saved token never re-saves (saveCard: false).
295
+ return confirmWithToken({ ...baseOptions(), saveCard: false, paToken: token });
296
+ });
297
+
298
+ const tokenize = () =>
299
+ run(async () => {
300
+ const validation = validateCard(parsedCard, ['visa', 'mastercard']);
301
+ if (!validation.complete) {
302
+ throw new PaError(validation.fields.cardNumber || validation.fields.expiry || validation.fields.cvc || 'invalid_number');
303
+ }
304
+ const { result: tokenResult } = await tokenizeCard(apiClient(), {
305
+ card: parsedCard,
306
+ merchantToken: MERCHANT_TOKENS[market],
307
+ });
308
+ setTokenized(tokenResult.paToken);
309
+ setSavedToken(tokenResult.paToken);
310
+ return {
311
+ status: 'succeeded' as const,
312
+ intentToken: intentToken.trim(),
313
+ paToken: tokenResult.paToken,
314
+ brand: tokenResult.brand,
315
+ last4: tokenResult.last4,
316
+ requestReference: null,
317
+ merchantReference: null,
318
+ errorCode: null,
319
+ errorMessage: null,
320
+ userMessage: null,
321
+ };
322
+ });
323
+
324
+ const payWithToken = () =>
325
+ run(async () => {
326
+ if (!tokenized) {
327
+ throw new PaError('request_invalid', { developerMessage: 'Tokenize first (step 2).' });
328
+ }
329
+ return confirmWithToken({ ...baseOptions(), saveCard: false, paToken: tokenized });
330
+ });
331
+
332
+ // Flow picker: picks the mint shape (Sale vs $0 verification) and what the
333
+ // primary "Pay" button does for the selected flow.
334
+ const onFlowChange = (next: Flow) => {
335
+ setFlow(next);
336
+ // Sensible save-card default per flow; the checkbox below stays editable.
337
+ setSaveCard(next === 'save_during' || next === 'manual_save');
338
+ };
339
+
340
+ // New logical attempt without minting: fresh idempotency key, clean slate.
341
+ const newAttempt = () => {
342
+ setAttemptKey(`flow-example-${Date.now()}`);
343
+ setResult(null);
344
+ setErrorText(null);
345
+ };
346
+
347
+ const reusableToken = savedToken ?? tokenized;
348
+ const payLabel =
349
+ flow === 'saved_reuse'
350
+ ? reusableToken
351
+ ? '5. Pay with saved card (confirmWithToken)'
352
+ : '5. Pay with saved card — save or tokenize a card first'
353
+ : flow === 'save_during'
354
+ ? '3. Pay + save card (confirmWithCard, saveCard: true)'
355
+ : flow === 'manual_save'
356
+ ? '3. Save card ($0 verification intent, confirmWithCard)'
357
+ : '3. Pay (combined confirmWithCard)';
358
+
359
+ const startFlow = () => {
360
+ if (flow === 'saved_reuse') {
361
+ payWithSavedCard();
362
+ } else {
363
+ payCombined();
364
+ }
365
+ };
366
+
367
+ return (
368
+ <KeyboardAvoidingView behavior={Platform.OS === 'ios' ? 'padding' : undefined} style={styles.flex}>
369
+ <ScrollView style={styles.flex} contentContainerStyle={styles.container}>
370
+ <Text style={styles.h1}>PA SDK — Flow Travel example</Text>
371
+
372
+ {!ready && (
373
+ <TouchableOpacity style={[styles.button, styles.primary]} onPress={doInit}>
374
+ <Text style={styles.buttonText}>1. init (environment, accounts, locale)</Text>
375
+ </TouchableOpacity>
376
+ )}
377
+
378
+ <Text style={styles.h2}>Environment</Text>
379
+ <View style={styles.row}>
380
+ {ENVIRONMENTS.map((env) => (
381
+ <TouchableOpacity
382
+ key={env}
383
+ style={[styles.chip, environment === env && styles.chipOn]}
384
+ onPress={() => setEnvironment(env)}
385
+ >
386
+ <Text style={[styles.chipText, environment === env && styles.chipTextOn]}>{env}</Text>
387
+ </TouchableOpacity>
388
+ ))}
389
+ </View>
390
+ <Text style={styles.dim}>
391
+ Default 'sandbox' (matches example/README.md). Toggling re-inits the SDK and switches the demo mint gateway.
392
+ </Text>
393
+
394
+ <Text style={styles.h2}>Locale (COM-34/35)</Text>
395
+ <View style={styles.row}>
396
+ {LOCALES.map((tag) => (
397
+ <TouchableOpacity
398
+ key={tag}
399
+ style={[styles.chip, locale === tag && styles.chipOn]}
400
+ onPress={() => setLocaleTag(tag)}
401
+ >
402
+ <Text style={[styles.chipText, locale === tag && styles.chipTextOn]}>{tag}</Text>
403
+ </TouchableOpacity>
404
+ ))}
405
+ </View>
406
+
407
+ <Text style={styles.h2}>Market / merchant account (COM-40)</Text>
408
+ <View style={styles.row}>
409
+ {MARKETS.map((m) => (
410
+ <TouchableOpacity key={m} style={[styles.chip, market === m && styles.chipOn]} onPress={() => setMarket(m)}>
411
+ <Text style={[styles.chipText, market === m && styles.chipTextOn]}>{m}</Text>
412
+ </TouchableOpacity>
413
+ ))}
414
+ </View>
415
+
416
+ <Text style={styles.h2}>Flow (RN-32)</Text>
417
+ <View style={styles.rowWrap}>
418
+ {FLOWS.map((f) => (
419
+ <TouchableOpacity
420
+ key={f.id}
421
+ style={[styles.chip, flow === f.id && styles.chipOn]}
422
+ onPress={() => onFlowChange(f.id)}
423
+ >
424
+ <Text style={[styles.chipText, flow === f.id && styles.chipTextOn]}>{f.label}</Text>
425
+ </TouchableOpacity>
426
+ ))}
427
+ </View>
428
+ <Text style={styles.dim}>{FLOWS.find((f) => f.id === flow)?.hint}</Text>
429
+
430
+ <Text style={styles.h2}>Card (Flow's own UI — RN-12/13)</Text>
431
+ <TextInput style={styles.input} value={cardNumber} onChangeText={setCardNumber} placeholder="Card number" keyboardType="number-pad" />
432
+ <View style={styles.row}>
433
+ <TextInput style={[styles.input, styles.half]} value={expiry} onChangeText={setExpiry} placeholder="MM/YY" keyboardType="number-pad" />
434
+ <TextInput style={[styles.input, styles.half]} value={cvc} onChangeText={setCvc} placeholder="CVC" keyboardType="number-pad" />
435
+ </View>
436
+ <TextInput style={styles.input} value={holderName} onChangeText={setHolderName} placeholder="Cardholder name (optional)" />
437
+
438
+ <TouchableOpacity style={[styles.checkbox]} onPress={() => setSaveCard((v) => !v)}>
439
+ <Text>{saveCard ? '[x]' : '[ ]'} Save this card (RN-23 / RN-24)</Text>
440
+ </TouchableOpacity>
441
+
442
+ <Text style={styles.h2}>Intent credentials from YOUR server (COM-01)</Text>
443
+ <View style={styles.row}>
444
+ <TextInput
445
+ style={[styles.input, styles.half]}
446
+ value={amount}
447
+ onChangeText={setAmount}
448
+ placeholder="Amount (HKD)"
449
+ keyboardType="decimal-pad"
450
+ editable={flow !== 'manual_save'}
451
+ />
452
+ <TouchableOpacity style={[styles.button, styles.primary, styles.half]} disabled={busy} onPress={mintIntent}>
453
+ <Text style={styles.buttonText}>Mint demo intent</Text>
454
+ </TouchableOpacity>
455
+ </View>
456
+ <Text style={styles.dim}>
457
+ {flow === 'manual_save'
458
+ ? 'Manual save: minting ignores this field and creates a $0 verification intent (amount "0").'
459
+ : 'DEMO ONLY: this button mints an intent with a test API key. In production, intents come from YOUR server (COM-01).'}
460
+ </Text>
461
+ <TextInput style={styles.input} value={intentToken} onChangeText={setIntentToken} placeholder="intent_token" autoCapitalize="none" />
462
+ <TextInput style={styles.input} value={clientToken} onChangeText={setClientToken} placeholder="client_token" autoCapitalize="none" />
463
+
464
+ <Text style={styles.h2}>Idempotency (retry-safe)</Text>
465
+ <Text style={styles.mono}>idempotency_key: {attemptKey}</Text>
466
+ <TouchableOpacity style={styles.button} onPress={newAttempt}>
467
+ <Text style={styles.buttonTextDark}>Start new attempt (fresh idempotency key)</Text>
468
+ </TouchableOpacity>
469
+ <Text style={styles.dim}>
470
+ Retrying a flow button re-uses the key above (the gateway returns the stored result instead of double-charging). Minting a new intent or "Start new attempt" regenerates it.
471
+ </Text>
472
+
473
+ <Text style={styles.h2}>Flows</Text>
474
+ <TouchableOpacity
475
+ style={[styles.button, styles.primary]}
476
+ disabled={busy || !ready || (flow === 'saved_reuse' && !reusableToken)}
477
+ onPress={startFlow}
478
+ >
479
+ <Text style={styles.buttonText}>{payLabel}</Text>
480
+ </TouchableOpacity>
481
+ <TouchableOpacity style={styles.button} disabled={busy || !ready} onPress={tokenize}>
482
+ <Text style={styles.buttonTextDark}>4a. Tokenize (two-step, RN-14)</Text>
483
+ </TouchableOpacity>
484
+ <TouchableOpacity style={styles.button} disabled={busy || !ready} onPress={payWithToken}>
485
+ <Text style={styles.buttonTextDark}>4b. Confirm with token</Text>
486
+ </TouchableOpacity>
487
+
488
+ {busy && <ActivityIndicator style={styles.spinner} size="large" />}
489
+ {threeDsVisible && (
490
+ <View style={styles.threedsNoteBox}>
491
+ <Text style={styles.threedsNote}>3DS challenge presented by the SDK (RN-19)…</Text>
492
+ <Text style={styles.dim}>
493
+ Cancel path: tap the challenge screen's own Cancel button (top-right, SDK chrome) — the confirm result comes back as 'cancelled' (R4).
494
+ {'\n'}
495
+ Approve path: approve in your banking app and return; the SDK consumes the return URL (flow:// or the universal-link host) itself and keeps polling.
496
+ </Text>
497
+ </View>
498
+ )}
499
+ {lastAppUrl ? (
500
+ <Text style={styles.dim}>Last URL received by the app's OWN handler: {lastAppUrl}</Text>
501
+ ) : null}
502
+
503
+ <Text style={styles.h2}>Result (A3)</Text>
504
+ {result ? (
505
+ <View style={[styles.resultBox, result.status === 'failed' && styles.resultFailed]}>
506
+ <Text style={styles.resultStatus}>{result.status}</Text>
507
+ {result.requestReference ? <Text>request_reference: {result.requestReference}</Text> : null}
508
+ {result.paToken ? <Text>pa_token: {result.paToken}</Text> : null}
509
+ {result.brand ? <Text>brand / last4: {result.brand} · {result.last4}</Text> : null}
510
+ {result.errorCode ? <Text>error_code: {result.errorCode}</Text> : null}
511
+ {result.userMessage ? <Text>user message: {result.userMessage}</Text> : null}
512
+ </View>
513
+ ) : (
514
+ <Text style={styles.dim}>No result yet. 'processing' means unknown — reconcile via your server (COM-06).</Text>
515
+ )}
516
+ {errorText ? <Text style={styles.errorText}>{errorText}</Text> : null}
517
+
518
+ <Text style={styles.dim}>
519
+ {strings.t('error.generic')}
520
+ </Text>
521
+ </ScrollView>
522
+ <PaSdk3dsHost />
523
+ </KeyboardAvoidingView>
524
+ );
525
+ }
526
+
527
+ // Small helper so the example can tokenize before init-time API access is
528
+ // otherwise exposed; the SDK instance created by init() above is reused.
529
+ function apiClient(): any {
530
+ const { getSdk } = require('pa-sdk-react-native');
531
+ return getSdk().api;
532
+ }
533
+
534
+ const styles = StyleSheet.create({
535
+ flex: { flex: 1 },
536
+ container: { padding: 16, paddingBottom: 48 },
537
+ h1: { fontSize: 20, fontWeight: '700', marginBottom: 12 },
538
+ h2: { fontSize: 14, fontWeight: '700', marginTop: 16, marginBottom: 6 },
539
+ row: { flexDirection: 'row', gap: 8 },
540
+ rowWrap: { flexDirection: 'row', flexWrap: 'wrap', gap: 8 },
541
+ half: { flex: 1 },
542
+ input: {
543
+ borderWidth: StyleSheet.hairlineWidth,
544
+ borderColor: '#c9c9c9',
545
+ borderRadius: 8,
546
+ paddingHorizontal: 12,
547
+ paddingVertical: 10,
548
+ marginBottom: 8,
549
+ backgroundColor: '#ffffff',
550
+ },
551
+ button: {
552
+ borderRadius: 8,
553
+ paddingVertical: 12,
554
+ alignItems: 'center',
555
+ marginTop: 8,
556
+ backgroundColor: '#e8e8ec',
557
+ },
558
+ primary: { backgroundColor: '#1d4ed8' },
559
+ buttonText: { color: '#ffffff', fontWeight: '600' },
560
+ buttonTextDark: { color: '#1f2937', fontWeight: '600' },
561
+ chip: {
562
+ paddingHorizontal: 12,
563
+ paddingVertical: 6,
564
+ borderRadius: 20,
565
+ borderWidth: StyleSheet.hairlineWidth,
566
+ borderColor: '#999999',
567
+ marginRight: 8,
568
+ marginBottom: 4,
569
+ },
570
+ chipOn: { backgroundColor: '#1d4ed8', borderColor: '#1d4ed8' },
571
+ chipText: { color: '#333333' },
572
+ chipTextOn: { color: '#ffffff' },
573
+ checkbox: { marginTop: 4, marginBottom: 4 },
574
+ mono: { fontSize: 12, color: '#374151' },
575
+ spinner: { marginTop: 12 },
576
+ threedsNote: { marginTop: 8, color: '#b45309', fontWeight: '600' },
577
+ threedsNoteBox: { marginTop: 4, padding: 12, borderRadius: 8, backgroundColor: '#fffbeb' },
578
+ resultBox: { marginTop: 4, padding: 12, borderRadius: 8, backgroundColor: '#eef2ff' },
579
+ resultFailed: { backgroundColor: '#fee2e2' },
580
+ resultStatus: { fontWeight: '700', fontSize: 16 },
581
+ errorText: { marginTop: 8, color: '#b91c1c' },
582
+ dim: { marginTop: 12, color: '#6b7280', fontSize: 12 },
583
+ });