pa-sdk-react-native 0.0.0-stage → 3.0.1
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.
- package/LICENSE +21 -0
- package/README.md +280 -2
- package/lib/api.d.ts +88 -0
- package/lib/api.js +163 -0
- package/lib/confirm.d.ts +65 -0
- package/lib/confirm.js +358 -0
- package/lib/errors.d.ts +38 -0
- package/lib/errors.generated.d.ts +13 -0
- package/lib/errors.generated.js +63 -0
- package/lib/errors.js +80 -0
- package/lib/index.d.ts +43 -0
- package/lib/index.js +94 -0
- package/lib/init.d.ts +47 -0
- package/lib/init.js +96 -0
- package/lib/locales.d.ts +36 -0
- package/lib/locales.generated.d.ts +22 -0
- package/lib/locales.generated.js +134 -0
- package/lib/locales.js +100 -0
- package/lib/poll.d.ts +61 -0
- package/lib/poll.js +172 -0
- package/lib/threeDs.d.ts +59 -0
- package/lib/threeDs.js +64 -0
- package/lib/threeDsHost.d.ts +17 -0
- package/lib/threeDsHost.js +159 -0
- package/lib/tokenize.d.ts +22 -0
- package/lib/tokenize.js +50 -0
- package/lib/types.d.ts +127 -0
- package/lib/types.js +16 -0
- package/lib/validator.d.ts +71 -0
- package/lib/validator.js +190 -0
- package/locales/en-US.json +30 -0
- package/locales/ms-MY.json +30 -0
- package/locales/zh-CN.json +30 -0
- package/locales/zh-TW.json +30 -0
- package/native/android/build.gradle +49 -0
- package/native/android/src/main/AndroidManifest.xml +42 -0
- package/native/android/src/main/java/com/pasdk/reactnative/PaSdk3dsActivity.kt +243 -0
- package/native/android/src/main/java/com/pasdk/reactnative/PaSdk3dsModule.kt +110 -0
- package/native/android/src/main/java/com/pasdk/reactnative/PaSdkReactNativePackage.kt +27 -0
- package/native/ios/PaSdk3ds.swift +311 -0
- package/native/ios/PaSdk3dsModule.m +47 -0
- package/pa-sdk-react-native.podspec +23 -0
- package/package.json +47 -4
- package/scripts/generate-errors.js +86 -0
- package/scripts/generate-locales.js +95 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Payment Asia
|
|
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,281 @@
|
|
|
1
|
-
#
|
|
1
|
+
# PA SDK React Native
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
**Payment Asia card payment SDK for React Native** — headless card validation,
|
|
4
|
+
direct tokenization, payment confirmation with built-in 3D Secure
|
|
5
|
+
(SDK-presented challenge), card saving, and multi-market merchant accounts.
|
|
6
|
+
Shares its error codes, locales and gateway contract with the PA SDK web
|
|
7
|
+
component.
|
|
8
|
+
|
|
9
|
+
- Scope: **Visa and Mastercard** (other schemes are detected early so the app
|
|
10
|
+
can block them).
|
|
11
|
+
- Result states (exactly five): `succeeded` · `authorized` · `processing`
|
|
12
|
+
· `cancelled` · `failed`. Unknown outcomes resolve `processing`, never
|
|
13
|
+
`failed`.
|
|
14
|
+
|
|
15
|
+
## Requirements
|
|
16
|
+
|
|
17
|
+
| | |
|
|
18
|
+
|---|---|
|
|
19
|
+
| React Native | >= 0.79 (New Architecture + Hermes) |
|
|
20
|
+
| iOS | 13.0+ |
|
|
21
|
+
| Android | API 24+ (Android 7.0) |
|
|
22
|
+
| Native dependency | `react-native-webview` ^13 (used by the JS fallback presenter; the primary 3DS presenter is the SDK's own native WebView) |
|
|
23
|
+
|
|
24
|
+
No other native dependencies — no ads, analytics or billing SDKs.
|
|
25
|
+
|
|
26
|
+
## Install
|
|
27
|
+
|
|
28
|
+
```bash
|
|
29
|
+
npm install pa-sdk-react-native
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
### iOS
|
|
33
|
+
|
|
34
|
+
The podspec ships with the package (autolinked by RN 0.79+):
|
|
35
|
+
|
|
36
|
+
```bash
|
|
37
|
+
cd ios && pod install && cd ..
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
The native 3DS module is a classic NativeModules bridge
|
|
41
|
+
(`native/ios/PaSdk3dsModule.m` + `PaSdk3ds.swift`). It runs unchanged on the
|
|
42
|
+
New Architecture through React Native's interop layer — no codegen setup
|
|
43
|
+
needed.
|
|
44
|
+
|
|
45
|
+
### Android
|
|
46
|
+
|
|
47
|
+
Autolinking picks up `native/android` — the only setup is the return-URL
|
|
48
|
+
placeholders. The library manifest registers a full-screen 3DS challenge
|
|
49
|
+
activity (`PaSdk3dsActivity`) whose intent-filters read two manifest
|
|
50
|
+
placeholders. Define your 3DS return URLs once in your app's
|
|
51
|
+
`android/app/build.gradle`:
|
|
52
|
+
|
|
53
|
+
```gradle
|
|
54
|
+
android {
|
|
55
|
+
defaultConfig {
|
|
56
|
+
manifestPlaceholders = [
|
|
57
|
+
paSdk3dsReturnScheme: "yourapp", // custom scheme, no "://"
|
|
58
|
+
paSdk3dsReturnHost: "links.yourdomain.com" // universal-link host, no "https://"
|
|
59
|
+
]
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
The build fails if the placeholders are missing, so a missing configuration
|
|
65
|
+
is caught before release, not in production. The values must match the
|
|
66
|
+
`threeDsReturnUrls` you pass to `init()`.
|
|
67
|
+
|
|
68
|
+
While a challenge is pending, the SDK **consumes** its own 3DS return URIs
|
|
69
|
+
(the custom scheme and universal-link host above); the app's own deep-link
|
|
70
|
+
handler never sees them. When no challenge is pending, matched URIs are
|
|
71
|
+
re-dispatched to the app's launch intent, so the app's normal link handling
|
|
72
|
+
proceeds. Do not declare overlapping intent-filters for those exact paths
|
|
73
|
+
unless you also want to handle them outside 3DS.
|
|
74
|
+
|
|
75
|
+
## Quickstart
|
|
76
|
+
|
|
77
|
+
```tsx
|
|
78
|
+
import { PaSdk3dsHost } from 'pa-sdk-react-native'; // optional JS 3DS fallback
|
|
79
|
+
|
|
80
|
+
// 1. Init — once, from your app's build config. One init, many merchant
|
|
81
|
+
// accounts. Publishable merchant tokens only — never a secret key.
|
|
82
|
+
import { init } from 'pa-sdk-react-native';
|
|
83
|
+
|
|
84
|
+
init({
|
|
85
|
+
environment: 'sandbox', // or 'production'
|
|
86
|
+
accounts: {
|
|
87
|
+
HK: 'mt_hk_...', // publishable merchantToken
|
|
88
|
+
MY: 'mt_my_...',
|
|
89
|
+
SG: 'mt_sg_...',
|
|
90
|
+
TW: 'mt_tw_...',
|
|
91
|
+
},
|
|
92
|
+
defaultAccount: 'HK',
|
|
93
|
+
locale: 'zh_HK', // en_US / zh_HK / zh_CN / my_MY
|
|
94
|
+
origin: 'https://app.yourdomain.com',
|
|
95
|
+
threeDsReturnUrls: { // consumed by the SDK
|
|
96
|
+
scheme: 'yourapp://',
|
|
97
|
+
universalLinkHost: 'https://links.yourdomain.com',
|
|
98
|
+
},
|
|
99
|
+
});
|
|
100
|
+
|
|
101
|
+
// Mount the fallback presenter once if the native module may be absent:
|
|
102
|
+
// <PaSdk3dsHost />
|
|
103
|
+
```
|
|
104
|
+
|
|
105
|
+
### One-off payment (combined)
|
|
106
|
+
|
|
107
|
+
```tsx
|
|
108
|
+
import { confirmWithCard } from 'pa-sdk-react-native';
|
|
109
|
+
|
|
110
|
+
const result = await confirmWithCard({
|
|
111
|
+
card: { cardNumber, expiryMonth, expiryYear, cvc, cardHolderName }, // from YOUR UI
|
|
112
|
+
intentToken, clientToken, // from your server only
|
|
113
|
+
idempotencyKey, // yours, unique per attempt
|
|
114
|
+
allowedBrands: ['visa', 'mastercard'], // from your server
|
|
115
|
+
onThreeDsWillPresent: () => hideLoadingOverlay(),
|
|
116
|
+
market: 'HK', // merchant account selection
|
|
117
|
+
});
|
|
118
|
+
// result.status: 'succeeded' | 'authorized' | 'processing' | 'cancelled' | 'failed'
|
|
119
|
+
```
|
|
120
|
+
|
|
121
|
+
### Two-step payment (tokenize + confirm)
|
|
122
|
+
|
|
123
|
+
```tsx
|
|
124
|
+
import { tokenizeCard, confirmWithToken } from 'pa-sdk-react-native';
|
|
125
|
+
|
|
126
|
+
// Step 1: card data goes straight to PA, never through your app's server
|
|
127
|
+
const { result: token } = await tokenizeCard(getSdk().api, {
|
|
128
|
+
card,
|
|
129
|
+
merchantToken: 'mt_hk_...', // per-market publishable token
|
|
130
|
+
});
|
|
131
|
+
// token = { paToken, last4, brand }
|
|
132
|
+
|
|
133
|
+
// Step 2: confirm the intent with the token
|
|
134
|
+
const result = await confirmWithToken({
|
|
135
|
+
paToken: token.paToken,
|
|
136
|
+
intentToken, clientToken, idempotencyKey,
|
|
137
|
+
onThreeDsWillPresent: () => hideLoadingOverlay(),
|
|
138
|
+
});
|
|
139
|
+
```
|
|
140
|
+
|
|
141
|
+
### Save the card during payment
|
|
142
|
+
|
|
143
|
+
```tsx
|
|
144
|
+
const result = await confirmWithCard({ card, intentToken, clientToken,
|
|
145
|
+
saveCard: true, idempotencyKey });
|
|
146
|
+
// result.paToken / result.brand / result.last4 arrive synchronously.
|
|
147
|
+
// The token is MIT-ready: your server charges it later via the Backend
|
|
148
|
+
// Recurring Payment API (/recurring/pay) or an intent-based server-side
|
|
149
|
+
// confirm.
|
|
150
|
+
```
|
|
151
|
+
|
|
152
|
+
### Add a card without paying (verification intent)
|
|
153
|
+
|
|
154
|
+
Same call against a **verification intent** your server creates (zero amount,
|
|
155
|
+
or a minimal amount settable per request). `saveCard: true`, 3DS runs if the
|
|
156
|
+
issuer requires it; nothing is charged; `pa_token` returns synchronously.
|
|
157
|
+
|
|
158
|
+
### 3D Secure
|
|
159
|
+
|
|
160
|
+
Everything is inside confirm:
|
|
161
|
+
|
|
162
|
+
- The SDK presents the challenge (full-screen native WebView; Cardinal StepUp
|
|
163
|
+
JWT POST, or ACS `creq` POST for the 3DS1 / non-frameable fallback).
|
|
164
|
+
- `onThreeDsWillPresent` fires immediately before it appears (dismiss your
|
|
165
|
+
overlay there), `onThreeDsEnded` when it is gone (informational).
|
|
166
|
+
- The user can cancel the challenge → `cancelled` (the SDK also cancels the
|
|
167
|
+
intent server-side, best effort).
|
|
168
|
+
- While the challenge is open the SDK polls `intent-status`; the gateway
|
|
169
|
+
posts the result server-side, and the first observed terminal state wins.
|
|
170
|
+
- App-switch (banking app): polling is **AppState-aware** — the schedule is
|
|
171
|
+
2s x 15 then 5s x 12, suspended time while backgrounded does not count
|
|
172
|
+
against the budget, and polling resumes on return. Budget exhausted with
|
|
173
|
+
no answer → `processing`, never `failed`.
|
|
174
|
+
- The challenge's return URLs (configured scheme + universal link) are
|
|
175
|
+
consumed by the SDK without surfacing to the app's link handler.
|
|
176
|
+
|
|
177
|
+
### Multi-market
|
|
178
|
+
|
|
179
|
+
One init; pick the account per call with `market`. Currency and country are
|
|
180
|
+
per intent on your server.
|
|
181
|
+
|
|
182
|
+
### Cancel an intent
|
|
183
|
+
|
|
184
|
+
```tsx
|
|
185
|
+
import { cancelIntent } from 'pa-sdk-react-native';
|
|
186
|
+
await cancelIntent({ intentToken, clientToken }); // -> { status: 'cancelled' }
|
|
187
|
+
```
|
|
188
|
+
|
|
189
|
+
## Validation helpers
|
|
190
|
+
|
|
191
|
+
```tsx
|
|
192
|
+
import { validateCard, validateCardNumber, validateExpiry, validateCvc, detectBrand } from 'pa-sdk-react-native';
|
|
193
|
+
|
|
194
|
+
detectBrand('222100...').brand // 'mastercard' — 2-series 2221–2720 recognised
|
|
195
|
+
validateCardNumber('4242...', ['visa']) // Luhn, length, brand filter
|
|
196
|
+
validateCard(card, ['visa', 'mastercard'])
|
|
197
|
+
// -> { brand, complete, fields: { cardNumber?, expiry?, cvc? } }
|
|
198
|
+
// field codes: incomplete_number, invalid_number, incomplete_expiry,
|
|
199
|
+
// invalid_expiry, incomplete_cvc, invalid_cvc, unsupported_brand
|
|
200
|
+
```
|
|
201
|
+
|
|
202
|
+
Rules: Visa/Mastercard lengths, Luhn, current BIN ranges (Mastercard 2-series
|
|
203
|
+
2221–2720 included), 3-digit CVC, expiry not in the past — no valid Visa /
|
|
204
|
+
Mastercard is ever blocked.
|
|
205
|
+
|
|
206
|
+
## Results and errors
|
|
207
|
+
|
|
208
|
+
```ts
|
|
209
|
+
interface PaymentResult {
|
|
210
|
+
status: 'succeeded' | 'authorized' | 'processing' | 'cancelled' | 'failed';
|
|
211
|
+
intentToken?: string;
|
|
212
|
+
requestReference?: string | null; // PA's reference for this attempt
|
|
213
|
+
merchantReference?: string | null;
|
|
214
|
+
paToken?: string | null; // set when a card was saved
|
|
215
|
+
brand?: string | null;
|
|
216
|
+
last4?: string | null;
|
|
217
|
+
errorCode?: string | null; // shared error-code table, for 'failed'
|
|
218
|
+
errorMessage?: string | null; // English developer message
|
|
219
|
+
userMessage?: string | null; // localized — show this, log the code
|
|
220
|
+
}
|
|
221
|
+
```
|
|
222
|
+
|
|
223
|
+
Every rejection is a `PaError` with `code`, `developerMessage` (English, from
|
|
224
|
+
the shared error table used across PA SDK components — API, webhooks, web and
|
|
225
|
+
this SDK) and `userMessage` (localized). Technical failures reject with typed
|
|
226
|
+
errors and are never payment results. Client-side, a second confirm on an
|
|
227
|
+
in-flight intent rejects with `duplicate_confirm`; confirming an
|
|
228
|
+
already-final intent returns its stored result.
|
|
229
|
+
|
|
230
|
+
## Locales
|
|
231
|
+
|
|
232
|
+
`en-US`, `zh-TW` (serves `zh_HK`/`zh-HK`), `zh-CN`, `ms-MY`.
|
|
233
|
+
Accepts underscore/hyphen, case-insensitive (`zh_HK`, `zh-hk`, `ms`). Unknown
|
|
234
|
+
tags fall back along exact tag → same language → `en-US`, never error.
|
|
235
|
+
Change locale at runtime with `updateLocale('zh_CN')`.
|
|
236
|
+
|
|
237
|
+
## Gateway endpoints used
|
|
238
|
+
|
|
239
|
+
All POST JSON under `https://gateway.pa-sys.com/pasdk/v1` (prod) /
|
|
240
|
+
`https://gateway-sandbox.pa-sys.com/pasdk/v1` (sandbox), envelope
|
|
241
|
+
`{request, response:{code,message}, payload}`; business errors ride HTTP 200
|
|
242
|
+
with `response.code != 200`:
|
|
243
|
+
|
|
244
|
+
| Endpoint | Used by |
|
|
245
|
+
|---|---|
|
|
246
|
+
| `/{merchantToken}/element-sessions` | `createElementSession` |
|
|
247
|
+
| `/tokenize` | `tokenizeCard` |
|
|
248
|
+
| `/confirm` | `confirmWithToken` / `confirmWithCard` |
|
|
249
|
+
| `/intent-cancel` | `cancelIntent`, 3DS user-cancel |
|
|
250
|
+
| `/intent-status` | polling (2s x 15, then 5s x 12) |
|
|
251
|
+
|
|
252
|
+
## Error-code / locale generation (maintainers)
|
|
253
|
+
|
|
254
|
+
`src/errors.generated.ts` and `src/locales.generated.ts` ship pre-generated
|
|
255
|
+
in the package; merchants never need to run these. Regeneration is only
|
|
256
|
+
required when the shared PA SDK tables change:
|
|
257
|
+
|
|
258
|
+
```bash
|
|
259
|
+
node scripts/generate-errors.js [path/to/errors.json]
|
|
260
|
+
node scripts/generate-locales.js # mirrors locales/*.json into src/
|
|
261
|
+
```
|
|
262
|
+
|
|
263
|
+
## Example app
|
|
264
|
+
|
|
265
|
+
See `example/` — a runnable RN 0.79 (New Architecture) app covering one-off
|
|
266
|
+
payment, two-step payment, save during payment, manual save, 3DS
|
|
267
|
+
challenge/cancel and multi-market switching.
|
|
268
|
+
|
|
269
|
+
## Technical notes
|
|
270
|
+
|
|
271
|
+
- The native 3DS modules use the classic `NativeModules` bridge via
|
|
272
|
+
`RCT_EXTERN_METHOD` (iOS) and `ReactPackage` (Android). On the New
|
|
273
|
+
Architecture this runs through RN's interop layer — supported, but not a
|
|
274
|
+
codegen TurboModule spec yet.
|
|
275
|
+
- The JS fallback presenter (`<PaSdk3dsHost />`, backed by
|
|
276
|
+
`react-native-webview`) is only used when the native module is missing;
|
|
277
|
+
its return-URL consumption happens via WebView navigation interception.
|
|
278
|
+
- `confirmWithCard` validates with `allowedBrands` before any network call;
|
|
279
|
+
brand detection and `allowedBrands` filtering both live in `validator.ts`.
|
|
280
|
+
- Android: when no 3DS challenge is pending, `PaSdk3dsActivity` re-dispatches
|
|
281
|
+
a matched URI to the app's launch intent so non-3DS deep links are not lost.
|
package/lib/api.d.ts
ADDED
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Gateway API client.
|
|
3
|
+
*
|
|
4
|
+
* All endpoints are POST JSON on the pasdk/v1 base URL. Responses use the
|
|
5
|
+
* PA envelope:
|
|
6
|
+
* { request, response: { code, message }, payload }
|
|
7
|
+
* Business errors ride HTTP 200 with response.code != 200 and are converted
|
|
8
|
+
* to PaError with a shared-table code. Transport failures reject
|
|
9
|
+
* with `network_error` / `rate_limited` / `provider_error`.
|
|
10
|
+
*/
|
|
11
|
+
import type { ConfirmGatewayPayload, Environment } from './types';
|
|
12
|
+
export declare const GATEWAY_BASE_URLS: {
|
|
13
|
+
[env in Environment]: string;
|
|
14
|
+
};
|
|
15
|
+
export interface ApiCallOptions {
|
|
16
|
+
/** Publishable merchantToken — used for per-account paths. */
|
|
17
|
+
merchantToken?: string;
|
|
18
|
+
/** Caller-supplied idempotency key, sent as a body field. */
|
|
19
|
+
idempotencyKey?: string;
|
|
20
|
+
}
|
|
21
|
+
export interface ElementSessionPayload {
|
|
22
|
+
session_token: string;
|
|
23
|
+
expiry_time?: string;
|
|
24
|
+
}
|
|
25
|
+
export interface TokenizePayload {
|
|
26
|
+
pa_token: string;
|
|
27
|
+
last4: string;
|
|
28
|
+
brand: string;
|
|
29
|
+
}
|
|
30
|
+
export interface IntentStatusPayload {
|
|
31
|
+
status: string;
|
|
32
|
+
request_reference?: string | null;
|
|
33
|
+
merchant_reference?: string | null;
|
|
34
|
+
pa_token?: string | null;
|
|
35
|
+
brand?: string | null;
|
|
36
|
+
last4?: string | null;
|
|
37
|
+
error_code?: string | null;
|
|
38
|
+
error_message?: string | null;
|
|
39
|
+
}
|
|
40
|
+
export type ConfirmPayload = ConfirmGatewayPayload;
|
|
41
|
+
export declare class ApiClient {
|
|
42
|
+
readonly environment: Environment;
|
|
43
|
+
readonly baseUrl: string;
|
|
44
|
+
/** App origin, sent as the Origin header where the gateway recommends it. */
|
|
45
|
+
origin?: string;
|
|
46
|
+
/** Hook for extra headers (tests / tracing). */
|
|
47
|
+
extraHeaders?: {
|
|
48
|
+
[name: string]: string;
|
|
49
|
+
};
|
|
50
|
+
constructor(environment: Environment, origin?: string);
|
|
51
|
+
/** Map an HTTP-level failure to a shared-table code. */
|
|
52
|
+
private static codeForHttpStatus;
|
|
53
|
+
private post;
|
|
54
|
+
/** POST /{merchantToken}/element-sessions — public app session (publishable
|
|
55
|
+
* credential is the merchantToken, never a secret key). */
|
|
56
|
+
createElementSession(merchantToken: string): Promise<ElementSessionPayload>;
|
|
57
|
+
/** POST /tokenize — card data goes straight from the app to PA. */
|
|
58
|
+
tokenize(params: {
|
|
59
|
+
sessionToken: string;
|
|
60
|
+
cardNumber: string;
|
|
61
|
+
expiryMonth: number | string;
|
|
62
|
+
expiryYear: number | string;
|
|
63
|
+
cvc: string;
|
|
64
|
+
cardHolderName?: string;
|
|
65
|
+
}): Promise<TokenizePayload>;
|
|
66
|
+
/** POST /confirm — one confirm per attempt; while status is
|
|
67
|
+
* requires_action / processing the app keeps polling (see poll.ts). */
|
|
68
|
+
confirm(params: {
|
|
69
|
+
clientToken: string;
|
|
70
|
+
intentToken: string;
|
|
71
|
+
paToken?: string;
|
|
72
|
+
idempotencyKey?: string;
|
|
73
|
+
saveCard?: boolean;
|
|
74
|
+
billing?: Record<string, unknown>;
|
|
75
|
+
}): Promise<ConfirmPayload>;
|
|
76
|
+
/** POST /intent-cancel. */
|
|
77
|
+
intentCancel(params: {
|
|
78
|
+
clientToken: string;
|
|
79
|
+
intentToken: string;
|
|
80
|
+
}): Promise<{
|
|
81
|
+
status: string;
|
|
82
|
+
}>;
|
|
83
|
+
/** POST /intent-status — polled until a terminal status or budget end. */
|
|
84
|
+
intentStatus(params: {
|
|
85
|
+
clientToken: string;
|
|
86
|
+
intentToken: string;
|
|
87
|
+
}): Promise<IntentStatusPayload>;
|
|
88
|
+
}
|
package/lib/api.js
ADDED
|
@@ -0,0 +1,163 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* Gateway API client.
|
|
4
|
+
*
|
|
5
|
+
* All endpoints are POST JSON on the pasdk/v1 base URL. Responses use the
|
|
6
|
+
* PA envelope:
|
|
7
|
+
* { request, response: { code, message }, payload }
|
|
8
|
+
* Business errors ride HTTP 200 with response.code != 200 and are converted
|
|
9
|
+
* to PaError with a shared-table code. Transport failures reject
|
|
10
|
+
* with `network_error` / `rate_limited` / `provider_error`.
|
|
11
|
+
*/
|
|
12
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
13
|
+
exports.ApiClient = exports.GATEWAY_BASE_URLS = void 0;
|
|
14
|
+
const errors_1 = require("./errors");
|
|
15
|
+
const errors_generated_1 = require("./errors.generated");
|
|
16
|
+
/** Whether a code exists in the shared table. */
|
|
17
|
+
function ERROR_TABLE_HAS(code) {
|
|
18
|
+
return Object.prototype.hasOwnProperty.call(errors_generated_1.ERROR_DEVELOPER_MESSAGES, code);
|
|
19
|
+
}
|
|
20
|
+
exports.GATEWAY_BASE_URLS = {
|
|
21
|
+
production: 'https://gateway.pa-sys.com/pasdk/v1',
|
|
22
|
+
sandbox: 'https://gateway-sandbox.pa-sys.com/pasdk/v1',
|
|
23
|
+
};
|
|
24
|
+
const HTTP_OK = 200;
|
|
25
|
+
class ApiClient {
|
|
26
|
+
constructor(environment, origin) {
|
|
27
|
+
this.environment = environment;
|
|
28
|
+
this.baseUrl = exports.GATEWAY_BASE_URLS[environment];
|
|
29
|
+
this.origin = origin;
|
|
30
|
+
}
|
|
31
|
+
/** Map an HTTP-level failure to a shared-table code. */
|
|
32
|
+
static codeForHttpStatus(status) {
|
|
33
|
+
if (status === 429) {
|
|
34
|
+
return 'rate_limited';
|
|
35
|
+
}
|
|
36
|
+
if (status === 401 || status === 403) {
|
|
37
|
+
return 'invalid_client_token';
|
|
38
|
+
}
|
|
39
|
+
if (status >= 500) {
|
|
40
|
+
return 'provider_error';
|
|
41
|
+
}
|
|
42
|
+
if (status >= 400) {
|
|
43
|
+
return 'request_invalid';
|
|
44
|
+
}
|
|
45
|
+
return 'network_error';
|
|
46
|
+
}
|
|
47
|
+
async post(path, body, options = {}) {
|
|
48
|
+
const url = options.merchantToken
|
|
49
|
+
? `${this.baseUrl}/${encodeURIComponent(options.merchantToken)}${path}`
|
|
50
|
+
: `${this.baseUrl}${path}`;
|
|
51
|
+
const headers = {
|
|
52
|
+
'Content-Type': 'application/json',
|
|
53
|
+
...(this.extraHeaders || {}),
|
|
54
|
+
};
|
|
55
|
+
if (this.origin) {
|
|
56
|
+
// Recommended by the gateway; note that some fetch runtimes treat
|
|
57
|
+
// Origin as a forbidden header and ignore it — harmless.
|
|
58
|
+
headers['Origin'] = this.origin;
|
|
59
|
+
}
|
|
60
|
+
let response;
|
|
61
|
+
try {
|
|
62
|
+
response = await fetch(url, {
|
|
63
|
+
method: 'POST',
|
|
64
|
+
headers,
|
|
65
|
+
body: JSON.stringify(body),
|
|
66
|
+
});
|
|
67
|
+
}
|
|
68
|
+
catch (cause) {
|
|
69
|
+
// Technical failure -> typed error, never a payment result.
|
|
70
|
+
throw new errors_1.PaError('network_error', {
|
|
71
|
+
developerMessage: `Network error calling ${path}.`,
|
|
72
|
+
cause,
|
|
73
|
+
});
|
|
74
|
+
}
|
|
75
|
+
if (response.status !== HTTP_OK) {
|
|
76
|
+
throw new errors_1.PaError(ApiClient.codeForHttpStatus(response.status), {
|
|
77
|
+
developerMessage: `Gateway returned HTTP ${response.status} for ${path}.`,
|
|
78
|
+
});
|
|
79
|
+
}
|
|
80
|
+
let envelope;
|
|
81
|
+
try {
|
|
82
|
+
envelope = (await response.json());
|
|
83
|
+
}
|
|
84
|
+
catch (cause) {
|
|
85
|
+
throw new errors_1.PaError('provider_error', {
|
|
86
|
+
developerMessage: `Gateway returned a non-JSON body for ${path}.`,
|
|
87
|
+
cause,
|
|
88
|
+
});
|
|
89
|
+
}
|
|
90
|
+
const responseCode = envelope.response && typeof envelope.response.code === 'number' ? envelope.response.code : HTTP_OK;
|
|
91
|
+
if (responseCode !== HTTP_OK) {
|
|
92
|
+
// Business error riding HTTP 200 — map to the shared table.
|
|
93
|
+
const payload = (envelope.payload || {});
|
|
94
|
+
const code = payload.error_code && ERROR_TABLE_HAS(payload.error_code)
|
|
95
|
+
? payload.error_code
|
|
96
|
+
: ApiClient.codeForHttpStatus(responseCode);
|
|
97
|
+
throw new errors_1.PaError(code, {
|
|
98
|
+
developerMessage: payload.error_message || (envelope.response && envelope.response.message) || undefined,
|
|
99
|
+
});
|
|
100
|
+
}
|
|
101
|
+
return envelope.payload;
|
|
102
|
+
}
|
|
103
|
+
/** POST /{merchantToken}/element-sessions — public app session (publishable
|
|
104
|
+
* credential is the merchantToken, never a secret key). */
|
|
105
|
+
createElementSession(merchantToken) {
|
|
106
|
+
return this.post('/element-sessions', {
|
|
107
|
+
origin: this.origin,
|
|
108
|
+
element_type: 'card',
|
|
109
|
+
}, { merchantToken });
|
|
110
|
+
}
|
|
111
|
+
/** POST /tokenize — card data goes straight from the app to PA. */
|
|
112
|
+
tokenize(params) {
|
|
113
|
+
return this.post('/tokenize', {
|
|
114
|
+
session_token: params.sessionToken,
|
|
115
|
+
card_number: params.cardNumber,
|
|
116
|
+
card_expiry_month: String(params.expiryMonth).padStart(2, '0'),
|
|
117
|
+
card_expiry_year: String(params.expiryYear),
|
|
118
|
+
card_cvv: params.cvc,
|
|
119
|
+
card_holder_name: params.cardHolderName,
|
|
120
|
+
});
|
|
121
|
+
}
|
|
122
|
+
/** POST /confirm — one confirm per attempt; while status is
|
|
123
|
+
* requires_action / processing the app keeps polling (see poll.ts). */
|
|
124
|
+
confirm(params) {
|
|
125
|
+
const body = {
|
|
126
|
+
client_token: params.clientToken,
|
|
127
|
+
intent_token: params.intentToken,
|
|
128
|
+
payment_method: 'card',
|
|
129
|
+
browser_info: {
|
|
130
|
+
channel: 'app',
|
|
131
|
+
framework: 'react-native',
|
|
132
|
+
},
|
|
133
|
+
};
|
|
134
|
+
if (params.paToken) {
|
|
135
|
+
body.pa_token = params.paToken;
|
|
136
|
+
}
|
|
137
|
+
if (params.idempotencyKey) {
|
|
138
|
+
body.idempotency_key = params.idempotencyKey;
|
|
139
|
+
}
|
|
140
|
+
if (params.saveCard != null) {
|
|
141
|
+
body.save_card = params.saveCard;
|
|
142
|
+
}
|
|
143
|
+
if (params.billing) {
|
|
144
|
+
body.billing = params.billing; // pass-through
|
|
145
|
+
}
|
|
146
|
+
return this.post('/confirm', body);
|
|
147
|
+
}
|
|
148
|
+
/** POST /intent-cancel. */
|
|
149
|
+
intentCancel(params) {
|
|
150
|
+
return this.post('/intent-cancel', {
|
|
151
|
+
client_token: params.clientToken,
|
|
152
|
+
intent_token: params.intentToken,
|
|
153
|
+
});
|
|
154
|
+
}
|
|
155
|
+
/** POST /intent-status — polled until a terminal status or budget end. */
|
|
156
|
+
intentStatus(params) {
|
|
157
|
+
return this.post('/intent-status', {
|
|
158
|
+
client_token: params.clientToken,
|
|
159
|
+
intent_token: params.intentToken,
|
|
160
|
+
});
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
exports.ApiClient = ApiClient;
|
package/lib/confirm.d.ts
ADDED
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Confirm orchestration.
|
|
3
|
+
*
|
|
4
|
+
* Both mandatory forms are exported:
|
|
5
|
+
* - confirmWithToken() — the two-step flow: tokenizeCard() first, then
|
|
6
|
+
* confirm with the pa_token.
|
|
7
|
+
* - confirmWithCard() — combined convenience call: validates, tokenizes
|
|
8
|
+
* and confirms in one await.
|
|
9
|
+
*
|
|
10
|
+
* Exactly one final result per confirm: any 3DS runs inside the
|
|
11
|
+
* call (SDK-presented WebView); requires_action / processing are
|
|
12
|
+
* polled until terminal; when the poll budget is exhausted the result is
|
|
13
|
+
* `processing`, never `failed`.
|
|
14
|
+
*/
|
|
15
|
+
import { PaError } from './errors';
|
|
16
|
+
import type { BillingDetails, CardInput, PaymentResult } from './types';
|
|
17
|
+
export interface ConfirmBaseOptions {
|
|
18
|
+
intentToken: string;
|
|
19
|
+
clientToken: string;
|
|
20
|
+
/** Market key selecting the merchant account when it is not the default. */
|
|
21
|
+
market?: string;
|
|
22
|
+
/** Caller-supplied idempotency key — repeated taps never double charge. */
|
|
23
|
+
idempotencyKey?: string;
|
|
24
|
+
/** Save the card during payment. */
|
|
25
|
+
saveCard?: boolean;
|
|
26
|
+
/** Optional pass-through billing details. */
|
|
27
|
+
billing?: BillingDetails;
|
|
28
|
+
/** Fires immediately before the 3DS challenge appears — dismiss
|
|
29
|
+
* your loading overlay here. */
|
|
30
|
+
onThreeDsWillPresent?: () => void;
|
|
31
|
+
/** Fires when the 3DS challenge UI is gone (informational). */
|
|
32
|
+
onThreeDsEnded?: () => void;
|
|
33
|
+
}
|
|
34
|
+
export interface ConfirmWithTokenOptions extends ConfirmBaseOptions {
|
|
35
|
+
/** Token from tokenizeCard(). */
|
|
36
|
+
paToken: string;
|
|
37
|
+
}
|
|
38
|
+
export interface ConfirmWithCardOptions extends ConfirmBaseOptions {
|
|
39
|
+
/** Card from the app's own UI. */
|
|
40
|
+
card: CardInput;
|
|
41
|
+
/** Optional allowed-brands filter; rejects other brands with
|
|
42
|
+
* `unsupported_brand` before any network call. */
|
|
43
|
+
allowedBrands?: readonly string[];
|
|
44
|
+
}
|
|
45
|
+
export declare class AlreadyFinalError extends PaError {
|
|
46
|
+
readonly result: PaymentResult;
|
|
47
|
+
constructor(result: PaymentResult);
|
|
48
|
+
}
|
|
49
|
+
/**
|
|
50
|
+
* Confirm a payment intent with a tokenized card (mandatory two-step:
|
|
51
|
+
* tokenizeCard() -> confirmWithToken()).
|
|
52
|
+
*/
|
|
53
|
+
export declare function confirmWithToken(options: ConfirmWithTokenOptions): Promise<PaymentResult>;
|
|
54
|
+
/**
|
|
55
|
+
* Combined confirm: validate + tokenize + confirm in one call.
|
|
56
|
+
* Throws the shared field codes before any network call when validation fails.
|
|
57
|
+
*/
|
|
58
|
+
export declare function confirmWithCard(options: ConfirmWithCardOptions): Promise<PaymentResult>;
|
|
59
|
+
/** Cancel an intent explicitly (resolves `cancelled` via intent-cancel). */
|
|
60
|
+
export declare function cancelIntent(options: {
|
|
61
|
+
intentToken: string;
|
|
62
|
+
clientToken: string;
|
|
63
|
+
}): Promise<PaymentResult>;
|
|
64
|
+
/** Test/diagnostic helper: clear the in-process final-result cache. */
|
|
65
|
+
export declare function resetConfirmState(): void;
|