@fire-spark/payments-nuvei-card 0.0.0-stage → 0.15.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.
@@ -0,0 +1,116 @@
1
+ import { PaymentAdapter, PaymentContext, PaymentPolicy } from "@fire-spark/payments";
2
+ //#region src/types.d.ts
3
+ /** Answer of the Spark `status` operation (no secret, no card data). */
4
+ type NuveiOutcome = {
5
+ status: "PAID" | "FAILED" | "PENDING";
6
+ transaction_status: string | null;
7
+ transaction_id: string | null;
8
+ client_unique_id: string | null;
9
+ auth_code: string | null;
10
+ amount: number | null;
11
+ currency: string | null;
12
+ transaction_type: string | null;
13
+ three_d: {
14
+ eci: string | null;
15
+ liability_shift: boolean | null;
16
+ } | null;
17
+ error_code: number | null;
18
+ error_reason: string | null;
19
+ };
20
+ /** `open_order` answer: the Nuvei session and the public ids. */
21
+ type NuveiOpenOrder = {
22
+ session_token: string;
23
+ order_id: string | number | null;
24
+ merchant_id: string;
25
+ merchant_site_id: string;
26
+ env: "int" | "prod";
27
+ amount: number;
28
+ currency: string;
29
+ country: string;
30
+ email: string | null;
31
+ };
32
+ /** What the channel's Nuvei UI needs (Web SDK `SafeCharge()` + `createPayment()`). */
33
+ type NuveiCheckoutInput = {
34
+ sessionToken: string;
35
+ merchantId: string;
36
+ merchantSiteId: string;
37
+ /** Web SDK environment: `int` (sandbox) or `prod`. */
38
+ env: "int" | "prod";
39
+ amount: number;
40
+ currency: string;
41
+ /** Billing country (ISO 3166-1 alpha-2) for `createPayment`. */
42
+ country: string;
43
+ email: string | null;
44
+ attemptReference: string;
45
+ /** Aborted on timeout or cancel: close the form, resolve `cancelled`. */
46
+ signal: AbortSignal;
47
+ };
48
+ /** Card shown to the customer, only for the receipt (never trusted). */
49
+ type NuveiCardDisplay = {
50
+ brand?: string | null;
51
+ last4?: string | null;
52
+ };
53
+ /**
54
+ * How the Nuvei UI ended. `completed` means the customer submitted the
55
+ * card (approved, declined or pending): Spark asks Nuvei for the real
56
+ * result. `cancelled` means the customer closed it without paying.
57
+ */
58
+ type NuveiCheckoutOutcome = {
59
+ type: "completed";
60
+ card?: NuveiCardDisplay;
61
+ } | {
62
+ type: "cancelled";
63
+ };
64
+ /**
65
+ * Implemented once per template: renders Nuvei's own card UI (Web SDK
66
+ * Nuvei Fields + `createPayment`, or Simply Connect `checkout()`) on the
67
+ * session. Nuvei runs 3-D Secure inside it. The card never reaches Spark.
68
+ */
69
+ type NuveiCheckoutBridge = {
70
+ pay(input: NuveiCheckoutInput): Promise<NuveiCheckoutOutcome>;
71
+ };
72
+ //#endregion
73
+ //#region src/card.d.ts
74
+ type NuveiCardOptions = {
75
+ /** Renders Nuvei's card UI on the session Spark opened. */
76
+ bridge: NuveiCheckoutBridge;
77
+ /** Billing data for Nuvei's risk checks (AVS) when the customer has none. */
78
+ billing?: (ctx: PaymentContext) => Promise<Record<string, string> | null>;
79
+ };
80
+ /**
81
+ * Nuvei card: Spark opens a Nuvei order for the tender with the secret
82
+ * key (`open_order`), the template renders Nuvei's own card UI on that
83
+ * session (`bridge`, Nuvei runs 3-D Secure), and Spark asks Nuvei for the
84
+ * result (`status`): the browser's answer is never trusted. A paid charge
85
+ * is voided or refunded by Spark with the order cancel or refund.
86
+ */
87
+ declare const nuveiCardPayments: (options: NuveiCardOptions) => PaymentAdapter;
88
+ //#endregion
89
+ //#region src/constants.d.ts
90
+ declare const NUVEI_PROVIDER = "nuvei";
91
+ /**
92
+ * Card form, 3-D Secure and the server check. One automatic attempt: a
93
+ * retry is a new Nuvei order.
94
+ */
95
+ declare const NUVEI_CARD_POLICY: Partial<PaymentPolicy>;
96
+ /** Status reads after the UI ends, while Nuvei still answers PENDING. */
97
+ declare const NUVEI_STATUS_READS = 5;
98
+ //#endregion
99
+ //#region src/errors.d.ts
100
+ /**
101
+ * Nuvei `transactionStatus` values. The `gwErrorCode` /
102
+ * `gwExtendedErrorCode` catalog is not mapped yet (ficha §13); a decline
103
+ * falls back to `CARD_DECLINED`.
104
+ */
105
+ declare const nuveiErrors: Readonly<Record<string, import("@fire-spark/payments").PaymentErrorEntry>> & {
106
+ DECLINED: {
107
+ code: "CARD_DECLINED";
108
+ source: string;
109
+ };
110
+ ERROR: {
111
+ code: "PROVIDER_UNAVAILABLE";
112
+ source: string;
113
+ };
114
+ };
115
+ //#endregion
116
+ export { NUVEI_CARD_POLICY, NUVEI_PROVIDER, NUVEI_STATUS_READS, type NuveiCardDisplay, NuveiCardOptions, type NuveiCheckoutBridge, type NuveiCheckoutInput, type NuveiCheckoutOutcome, type NuveiOpenOrder, type NuveiOutcome, nuveiCardPayments, nuveiErrors };
package/dist/index.js ADDED
@@ -0,0 +1,284 @@
1
+ import { PaymentError, createPaymentError, definePaymentErrors, toPaymentError } from "@fire-spark/payments";
2
+ //#region src/constants.ts
3
+ const NUVEI_PROVIDER = "nuvei";
4
+ /**
5
+ * Card form, 3-D Secure and the server check. One automatic attempt: a
6
+ * retry is a new Nuvei order.
7
+ */
8
+ const NUVEI_CARD_POLICY = {
9
+ timeout_ms: 9e5,
10
+ poll_interval_ms: 3e3,
11
+ max_attempts: 1
12
+ };
13
+ /** Status reads after the UI ends, while Nuvei still answers PENDING. */
14
+ const NUVEI_STATUS_READS = 5;
15
+ //#endregion
16
+ //#region src/errors.ts
17
+ const source = "docs/payments/nuvei/card.md#11-errores";
18
+ /**
19
+ * Nuvei `transactionStatus` values. The `gwErrorCode` /
20
+ * `gwExtendedErrorCode` catalog is not mapped yet (ficha §13); a decline
21
+ * falls back to `CARD_DECLINED`.
22
+ */
23
+ const nuveiErrors = definePaymentErrors({
24
+ DECLINED: {
25
+ code: "CARD_DECLINED",
26
+ source
27
+ },
28
+ ERROR: {
29
+ code: "PROVIDER_UNAVAILABLE",
30
+ source
31
+ }
32
+ });
33
+ //#endregion
34
+ //#region src/result.ts
35
+ const last4Of = (digits) => {
36
+ const clean = (digits ?? "").replace(/\D/g, "");
37
+ return clean.length >= 4 ? clean.slice(-4) : null;
38
+ };
39
+ /** Ids, auth code and 3-D Secure result of a Nuvei outcome. */
40
+ const nuveiMetadataOf = (ctx, outcome, card) => {
41
+ const p1 = { provider_transaction_id: outcome.transaction_id };
42
+ const p2 = {
43
+ authorization_code: outcome.auth_code,
44
+ reference: outcome.auth_code ?? outcome.transaction_id
45
+ };
46
+ const p3 = {
47
+ brand: card?.brand ?? null,
48
+ last4: last4Of(card?.last4)
49
+ };
50
+ const payment = {
51
+ ...p1,
52
+ ...p2,
53
+ ...p3
54
+ };
55
+ const r1 = { transaction_id: outcome.transaction_id };
56
+ const r2 = { transaction_status: outcome.transaction_status };
57
+ const r3 = { three_d: outcome.three_d };
58
+ const provider = {
59
+ ...r1,
60
+ ...r2,
61
+ ...r3
62
+ };
63
+ return {
64
+ attempt_reference: ctx.attemptReference,
65
+ payment,
66
+ provider
67
+ };
68
+ };
69
+ const detailsOf = (outcome, card) => {
70
+ const brand = card?.brand ?? null;
71
+ const last4 = last4Of(card?.last4);
72
+ if (!brand || !last4) return null;
73
+ const auth = outcome.auth_code;
74
+ return {
75
+ method: "CARD",
76
+ brand,
77
+ last4,
78
+ ...auth ? { auth_code: auth } : {}
79
+ };
80
+ };
81
+ const failedResult = (ctx, error, metadata) => {
82
+ const base = metadata ?? { attempt_reference: ctx.attemptReference };
83
+ const review = error.code === "AMBIGUOUS" ? { needs_review: true } : {};
84
+ const m = {
85
+ ...base,
86
+ ...review,
87
+ error
88
+ };
89
+ return {
90
+ status: "FAILED",
91
+ amount: ctx.amount.value,
92
+ metadata: m,
93
+ error
94
+ };
95
+ };
96
+ /** PAID / FAILED / PENDING result of a server-checked Nuvei outcome. */
97
+ const nuveiResultOf = (ctx, outcome, card) => {
98
+ const metadata = nuveiMetadataOf(ctx, outcome, card);
99
+ const amount = ctx.amount.value;
100
+ if (outcome.status === "PAID") {
101
+ const details = detailsOf(outcome, card);
102
+ return {
103
+ status: "PAID",
104
+ amount,
105
+ metadata,
106
+ ...details ? { details } : {}
107
+ };
108
+ }
109
+ if (outcome.status === "PENDING") return {
110
+ status: "PENDING",
111
+ amount,
112
+ metadata
113
+ };
114
+ const error = toPaymentError(nuveiErrors, {
115
+ code: outcome.transaction_status,
116
+ message: outcome.error_reason,
117
+ attempt: ctx.attempt,
118
+ fallback: "CARD_DECLINED"
119
+ });
120
+ return failedResult(ctx, error, metadata);
121
+ };
122
+ /** Spark operation failures: a missing answer may still have charged. */
123
+ const serverErrorOf = (ctx, cause) => {
124
+ const e = cause;
125
+ const extra = {
126
+ provider_message: e?.message ?? "Nuvei request failed",
127
+ attempt: ctx.attempt
128
+ };
129
+ if (e?.code === "AMBIGUOUS" || e?.status === 504) return createPaymentError("AMBIGUOUS", extra);
130
+ if (e?.status === 409) return createPaymentError("INVALID_CREDENTIALS", extra);
131
+ if (e?.status === 400) return createPaymentError("INVALID_REQUEST", extra);
132
+ return createPaymentError("PROVIDER_UNAVAILABLE", extra);
133
+ };
134
+ //#endregion
135
+ //#region src/card.ts
136
+ const storageKey = (attemptReference) => {
137
+ return `nuvei:session:${attemptReference}`;
138
+ };
139
+ const readSaved = (raw) => {
140
+ try {
141
+ const value = raw ? JSON.parse(raw) : null;
142
+ if (!value?.session) return null;
143
+ return {
144
+ session: value.session,
145
+ card: value.card ?? null
146
+ };
147
+ } catch {
148
+ return null;
149
+ }
150
+ };
151
+ /** Sleeps `ms`, or less when `signal` aborts. */
152
+ const wait = (ms, signal) => {
153
+ return new Promise((resolve) => {
154
+ if (signal.aborted) return resolve();
155
+ const timer = setTimeout(done, ms);
156
+ function done() {
157
+ clearTimeout(timer);
158
+ signal.removeEventListener("abort", done);
159
+ resolve();
160
+ }
161
+ signal.addEventListener("abort", done);
162
+ });
163
+ };
164
+ /**
165
+ * Nuvei card: Spark opens a Nuvei order for the tender with the secret
166
+ * key (`open_order`), the template renders Nuvei's own card UI on that
167
+ * session (`bridge`, Nuvei runs 3-D Secure), and Spark asks Nuvei for the
168
+ * result (`status`): the browser's answer is never trusted. A paid charge
169
+ * is voided or refunded by Spark with the order cancel or refund.
170
+ */
171
+ const nuveiCardPayments = (options) => {
172
+ const { bridge } = options;
173
+ const status = (ctx, session) => {
174
+ const input = { session_token: session };
175
+ return ctx.server.call("status", input);
176
+ };
177
+ /** Reads the status until Nuvei settles it or the reads run out. */
178
+ const settle = async (ctx, saved) => {
179
+ const every = ctx.policy.poll_interval_ms || 3e3;
180
+ let outcome = await status(ctx, saved.session);
181
+ for (let i = 1; i < 5; i++) {
182
+ if (outcome.status !== "PENDING" || ctx.signal.aborted) break;
183
+ await wait(every, ctx.signal);
184
+ outcome = await status(ctx, saved.session);
185
+ }
186
+ return nuveiResultOf(ctx, outcome, saved.card);
187
+ };
188
+ /**
189
+ * After the customer submitted the card Nuvei may have charged, so a
190
+ * failed status read is never a clean failure: it goes to review.
191
+ */
192
+ const unknownAfterSubmit = (ctx, cause) => {
193
+ return failedResult(ctx, createPaymentError("AMBIGUOUS", {
194
+ provider_message: cause?.message ?? "Nuvei status could not be read",
195
+ attempt: ctx.attempt
196
+ }));
197
+ };
198
+ const start = async (ctx) => {
199
+ let submitted = false;
200
+ try {
201
+ const billing = options.billing ? await options.billing(ctx) : null;
202
+ const order = await ctx.server.call("open_order", billing ? { billing } : {});
203
+ const session = order.session_token;
204
+ const s1 = {
205
+ sessionToken: session,
206
+ merchantId: order.merchant_id
207
+ };
208
+ const s2 = {
209
+ merchantSiteId: order.merchant_site_id,
210
+ env: order.env
211
+ };
212
+ const s3 = {
213
+ amount: order.amount,
214
+ currency: order.currency
215
+ };
216
+ const s4 = {
217
+ country: order.country,
218
+ email: order.email
219
+ };
220
+ const s5 = {
221
+ attemptReference: ctx.attemptReference,
222
+ signal: ctx.signal
223
+ };
224
+ const ended = await bridge.pay({
225
+ ...s1,
226
+ ...s2,
227
+ ...s3,
228
+ ...s4,
229
+ ...s5
230
+ });
231
+ submitted = ended.type === "completed";
232
+ const saved = {
233
+ session,
234
+ card: ended.type === "completed" ? ended.card ?? null : null
235
+ };
236
+ await ctx.storage.set(storageKey(ctx.attemptReference), JSON.stringify(saved));
237
+ ctx.ui.message({
238
+ text: "Confirmando pago…",
239
+ kind: "waiting"
240
+ });
241
+ const result = await settle(ctx, saved);
242
+ if (ended.type === "cancelled" && result.status === "PENDING") return failedResult(ctx, createPaymentError("CANCELLED_BY_USER", { attempt: ctx.attempt }));
243
+ return result;
244
+ } catch (cause) {
245
+ if (submitted) return unknownAfterSubmit(ctx, cause);
246
+ if (cause instanceof PaymentError) return failedResult(ctx, cause.error);
247
+ return failedResult(ctx, serverErrorOf(ctx, cause));
248
+ }
249
+ };
250
+ /** A result still PENDING: asks Nuvei again for the saved session. */
251
+ const query = async (ctx, result) => {
252
+ if (result.status !== "PENDING") return result;
253
+ const raw = await ctx.storage.get(storageKey(ctx.attemptReference));
254
+ const saved = readSaved(raw);
255
+ if (!saved) return result;
256
+ try {
257
+ return nuveiResultOf(ctx, await status(ctx, saved.session), saved.card);
258
+ } catch (cause) {
259
+ return unknownAfterSubmit(ctx, cause);
260
+ }
261
+ };
262
+ /** An unpaid Nuvei session just expires; nothing to undo. */
263
+ const cancel = async (_ctx, result) => {
264
+ return {
265
+ ...result,
266
+ status: "CANCELLED"
267
+ };
268
+ };
269
+ const reversalFor = (result) => {
270
+ return result.status === "PAID" ? "server" : "cancel";
271
+ };
272
+ return {
273
+ provider: NUVEI_PROVIDER,
274
+ method: "CARD",
275
+ errors: nuveiErrors,
276
+ policy: NUVEI_CARD_POLICY,
277
+ start,
278
+ query,
279
+ cancel,
280
+ reversalFor
281
+ };
282
+ };
283
+ //#endregion
284
+ export { NUVEI_CARD_POLICY, NUVEI_PROVIDER, NUVEI_STATUS_READS, nuveiCardPayments, nuveiErrors };
package/package.json CHANGED
@@ -1,6 +1,59 @@
1
1
  {
2
2
  "name": "@fire-spark/payments-nuvei-card",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.15.0",
4
+ "description": "Fire Spark Nuvei card adapter: the channel shows Nuvei's own card UI (Web SDK) on a session Fire Spark opens with the secret key, and Fire Spark checks the result server-side",
5
+ "type": "module",
6
+ "sideEffects": false,
7
+ "files": [
8
+ "dist"
9
+ ],
10
+ "main": "./dist/index.js",
11
+ "types": "./dist/index.d.ts",
12
+ "exports": {
13
+ ".": {
14
+ "types": "./dist/index.d.ts",
15
+ "import": "./dist/index.js",
16
+ "default": "./dist/index.js"
17
+ }
18
+ },
19
+ "dependencies": {
20
+ "@fire-spark/types": "^0.15.0",
21
+ "@fire-spark/payments": "^0.15.0"
22
+ },
23
+ "devDependencies": {
24
+ "tsdown": "^0.22.14",
25
+ "typescript": "^7.0.2",
26
+ "vitest": "^2.1.8"
27
+ },
28
+ "publishConfig": {
29
+ "access": "public"
30
+ },
31
+ "tsdown": {
32
+ "entry": [
33
+ "src/index.ts"
34
+ ],
35
+ "format": [
36
+ "esm"
37
+ ],
38
+ "platform": "neutral",
39
+ "dts": {
40
+ "tsconfig": "tsconfig.build.json"
41
+ },
42
+ "clean": true,
43
+ "deps": {
44
+ "neverBundle": [
45
+ "@fire-spark/payments",
46
+ "@fire-spark/types"
47
+ ]
48
+ }
49
+ },
50
+ "scripts": {
51
+ "build": "tsdown",
52
+ "dev": "tsdown --watch",
53
+ "check-types": "tsc --noEmit",
54
+ "test:utils": "vitest run",
55
+ "lint": "oxlint ./src --max-warnings=0",
56
+ "format": "oxfmt ./src",
57
+ "check-format": "oxfmt --check ./src"
58
+ }
6
59
  }
package/README.md DELETED
@@ -1,3 +0,0 @@
1
- # Temporary Holding Version
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.