@fire-spark/payments-placetopay-checkout 0.0.0-stage → 0.17.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,143 @@
1
+ import { PaymentAdapter, PaymentPolicy } from "@fire-spark/payments";
2
+ //#region src/types.d.ts
3
+ /** Answer of the Spark PlacetoPay operations (no secret, no card data). */
4
+ type PlacetopayOutcome = {
5
+ status: "PAID" | "FAILED" | "PENDING";
6
+ session_status: string | null;
7
+ reason: string | null;
8
+ message: string | null;
9
+ request_id: number | null;
10
+ reference: string | null;
11
+ internal_reference: number | null;
12
+ authorization: string | null;
13
+ receipt: string | null;
14
+ franchise: string | null;
15
+ payment_method: string | null;
16
+ payment_method_name: string | null;
17
+ issuer_name: string | null;
18
+ last_digits: string | null;
19
+ amount: number | null;
20
+ currency: string | null;
21
+ };
22
+ /** `create_session` answer: the WebCheckout session of this attempt. */
23
+ type PlacetopaySession = {
24
+ request_id: number;
25
+ process_url: string;
26
+ expiration: string;
27
+ };
28
+ /** `cancel_session` answer. */
29
+ type PlacetopayCancelAnswer = {
30
+ cancelled: boolean;
31
+ outcome: PlacetopayOutcome;
32
+ reason?: string | null;
33
+ };
34
+ type PlacetopayRedirectInput = {
35
+ /** WebCheckout page to open in the browser (`processUrl`). */
36
+ url: string;
37
+ attemptReference: string;
38
+ returnUrl: string;
39
+ /** Aborted on timeout or cancel: close the tab, resolve `cancelled`. */
40
+ signal: AbortSignal;
41
+ };
42
+ /**
43
+ * How the redirect ended. A popup or new tab resolves `returned` when the
44
+ * `returnUrl` page loads (e.g. it sends a `postMessage`); a full page
45
+ * navigation resolves `redirected` and the checkout resumes with the
46
+ * session saved for the attempt.
47
+ */
48
+ type PlacetopayRedirectOutcome = {
49
+ type: "returned";
50
+ } | {
51
+ type: "cancelled";
52
+ } | {
53
+ type: "redirected";
54
+ };
55
+ /**
56
+ * Implemented once per web template. PlacetoPay's result is never read
57
+ * from the browser: Fire Spark asks PlacetoPay for the session status.
58
+ */
59
+ type PlacetopayRedirectBridge = {
60
+ open(input: PlacetopayRedirectInput): Promise<PlacetopayRedirectOutcome>;
61
+ };
62
+ //#endregion
63
+ //#region src/checkout.d.ts
64
+ type PlacetopayCheckoutOptions = {
65
+ /** Opens WebCheckout in a browser tab and reports the return. */
66
+ bridge: PlacetopayRedirectBridge;
67
+ /** https page PlacetoPay sends the customer back to ("Volver al comercio"). */
68
+ returnUrl: string;
69
+ /** https page for "No deseo continuar"; default: PlacetoPay's own page. */
70
+ cancelUrl?: string;
71
+ /** `es_EC` (default), `en_US` or any `xx_YY` locale PlacetoPay supports. */
72
+ locale?: string;
73
+ /** Skip PlacetoPay's result page and return straight to `returnUrl`. */
74
+ skipResult?: boolean;
75
+ };
76
+ /**
77
+ * Attempt reference of a PlacetoPay return URL (the page at `returnUrl` or
78
+ * `cancelUrl`); `null` if it is not one.
79
+ */
80
+ declare const parsePlacetopayReturn: (url: string) => string | null;
81
+ /**
82
+ * PlacetoPay card on the web (WebCheckout). Spark opens the session with
83
+ * the site's secret key (`create_session`), the template sends the
84
+ * customer to PlacetoPay (`bridge`), and Spark reads the session status
85
+ * from PlacetoPay (`status`): the browser's return is never trusted. A
86
+ * session the customer leaves is cancelled (`cancel_session`) so it cannot
87
+ * be paid later. A paid charge is reversed by Spark with the order cancel
88
+ * or refund, whole transactions only.
89
+ */
90
+ declare const placetopayCheckoutPayments: (options: PlacetopayCheckoutOptions) => PaymentAdapter;
91
+ //#endregion
92
+ //#region src/constants.d.ts
93
+ declare const PLACETOPAY_PROVIDER = "place_to_pay";
94
+ /** Query param the API adds to `returnUrl` / `cancelUrl`: our attempt. */
95
+ declare const PLACETOPAY_RETURN_PARAM = "placetopay_reference";
96
+ /**
97
+ * The WebCheckout session lives 15 minutes. One automatic attempt: a retry
98
+ * is a new session. A pending transaction is read every 5 seconds.
99
+ */
100
+ declare const PLACETOPAY_POLICY: Partial<PaymentPolicy>;
101
+ //#endregion
102
+ //#region src/errors.d.ts
103
+ /**
104
+ * PlacetoPay `status.reason` values from the public docs; the full reason
105
+ * catalog is pending (ficha §13). Unknown reasons fall back to
106
+ * `CARD_DECLINED`.
107
+ */
108
+ declare const placetopayErrors: Readonly<Record<string, import("@fire-spark/payments").PaymentErrorEntry>> & {
109
+ "?C": {
110
+ code: "CANCELLED_BY_USER";
111
+ source: string;
112
+ };
113
+ MC: {
114
+ code: "CANCELLED_BY_USER";
115
+ source: string;
116
+ };
117
+ XN: {
118
+ code: "CARD_DECLINED";
119
+ source: string;
120
+ };
121
+ PT: {
122
+ code: "AMBIGUOUS";
123
+ source: string;
124
+ };
125
+ "401": {
126
+ code: "INVALID_CREDENTIALS";
127
+ source: string;
128
+ };
129
+ "103": {
130
+ code: "INVALID_CREDENTIALS";
131
+ source: string;
132
+ };
133
+ request_not_valid: {
134
+ code: "INVALID_REQUEST";
135
+ source: string;
136
+ };
137
+ transaction_request_error: {
138
+ code: "PROVIDER_UNAVAILABLE";
139
+ source: string;
140
+ };
141
+ };
142
+ //#endregion
143
+ export { PLACETOPAY_POLICY, PLACETOPAY_PROVIDER, PLACETOPAY_RETURN_PARAM, type PlacetopayCancelAnswer, PlacetopayCheckoutOptions, type PlacetopayOutcome, type PlacetopayRedirectBridge, type PlacetopayRedirectInput, type PlacetopayRedirectOutcome, type PlacetopaySession, parsePlacetopayReturn, placetopayCheckoutPayments, placetopayErrors };
package/dist/index.js ADDED
@@ -0,0 +1,310 @@
1
+ import { PaymentError, createPaymentError, definePaymentErrors, toPaymentError } from "@fire-spark/payments";
2
+ //#region src/constants.ts
3
+ const PLACETOPAY_PROVIDER = "place_to_pay";
4
+ /** Query param the API adds to `returnUrl` / `cancelUrl`: our attempt. */
5
+ const PLACETOPAY_RETURN_PARAM = "placetopay_reference";
6
+ /**
7
+ * The WebCheckout session lives 15 minutes. One automatic attempt: a retry
8
+ * is a new session. A pending transaction is read every 5 seconds.
9
+ */
10
+ const PLACETOPAY_POLICY = {
11
+ timeout_ms: 9e5,
12
+ max_attempts: 1,
13
+ poll_interval_ms: 5e3,
14
+ qr_ttl_ms: 9e5
15
+ };
16
+ //#endregion
17
+ //#region src/errors.ts
18
+ const source = "docs/payments/placetopay/checkout.md#11-errores";
19
+ /**
20
+ * PlacetoPay `status.reason` values from the public docs; the full reason
21
+ * catalog is pending (ficha §13). Unknown reasons fall back to
22
+ * `CARD_DECLINED`.
23
+ */
24
+ const placetopayErrors = definePaymentErrors({
25
+ "?C": {
26
+ code: "CANCELLED_BY_USER",
27
+ source
28
+ },
29
+ MC: {
30
+ code: "CANCELLED_BY_USER",
31
+ source
32
+ },
33
+ XN: {
34
+ code: "CARD_DECLINED",
35
+ source
36
+ },
37
+ PT: {
38
+ code: "AMBIGUOUS",
39
+ source
40
+ },
41
+ "401": {
42
+ code: "INVALID_CREDENTIALS",
43
+ source
44
+ },
45
+ "103": {
46
+ code: "INVALID_CREDENTIALS",
47
+ source
48
+ },
49
+ request_not_valid: {
50
+ code: "INVALID_REQUEST",
51
+ source
52
+ },
53
+ transaction_request_error: {
54
+ code: "PROVIDER_UNAVAILABLE",
55
+ source
56
+ }
57
+ });
58
+ //#endregion
59
+ //#region src/result.ts
60
+ const last4Of = (digits) => {
61
+ const clean = (digits ?? "").replace(/\D/g, "");
62
+ return clean.length >= 4 ? clean.slice(-4) : null;
63
+ };
64
+ /** Ids and card data of a PlacetoPay outcome; nothing sensitive. */
65
+ const placetopayMetadataOf = (ctx, outcome) => {
66
+ const internal = outcome.internal_reference != null ? String(outcome.internal_reference) : null;
67
+ const payment = {
68
+ provider_transaction_id: internal,
69
+ authorization_code: outcome.authorization,
70
+ reference: outcome.receipt ?? outcome.authorization ?? internal,
71
+ brand: outcome.payment_method_name ?? outcome.franchise,
72
+ last4: last4Of(outcome.last_digits)
73
+ };
74
+ const provider = {
75
+ request_id: outcome.request_id,
76
+ internal_reference: outcome.internal_reference,
77
+ session_status: outcome.session_status,
78
+ reason: outcome.reason,
79
+ franchise: outcome.franchise,
80
+ payment_method: outcome.payment_method,
81
+ issuer_name: outcome.issuer_name,
82
+ receipt: outcome.receipt
83
+ };
84
+ return {
85
+ attempt_reference: ctx.attemptReference,
86
+ payment,
87
+ provider
88
+ };
89
+ };
90
+ const cardDetailsOf = (outcome) => {
91
+ const brand = outcome.payment_method_name ?? outcome.franchise;
92
+ const last4 = last4Of(outcome.last_digits);
93
+ if (!brand || !last4) return null;
94
+ const auth = outcome.authorization;
95
+ return {
96
+ method: "CARD",
97
+ brand,
98
+ last4,
99
+ ...auth ? { auth_code: auth } : {}
100
+ };
101
+ };
102
+ const failedResult = (ctx, error, metadata) => {
103
+ const base = metadata ?? { attempt_reference: ctx.attemptReference };
104
+ const review = error.code === "AMBIGUOUS" ? { needs_review: true } : {};
105
+ const m = {
106
+ ...base,
107
+ ...review,
108
+ error
109
+ };
110
+ return {
111
+ status: "FAILED",
112
+ amount: ctx.amount.value,
113
+ metadata: m,
114
+ error
115
+ };
116
+ };
117
+ /** PAID / FAILED / PENDING result of a PlacetoPay outcome. */
118
+ const placetopayResultOf = (ctx, outcome) => {
119
+ const metadata = placetopayMetadataOf(ctx, outcome);
120
+ const amount = ctx.amount.value;
121
+ if (outcome.status === "PAID") return {
122
+ status: "PAID",
123
+ amount,
124
+ metadata,
125
+ details: cardDetailsOf(outcome)
126
+ };
127
+ if (outcome.status === "PENDING") return {
128
+ status: "PENDING",
129
+ amount,
130
+ metadata
131
+ };
132
+ const error = toPaymentError(placetopayErrors, {
133
+ code: outcome.reason,
134
+ message: outcome.message,
135
+ attempt: ctx.attempt,
136
+ fallback: "CARD_DECLINED"
137
+ });
138
+ return failedResult(ctx, error, metadata);
139
+ };
140
+ /** Spark operation failures: a missing answer may still have charged. */
141
+ const serverErrorOf = (ctx, cause) => {
142
+ const e = cause;
143
+ const extra = {
144
+ provider_message: e?.message ?? "PlacetoPay request failed",
145
+ attempt: ctx.attempt
146
+ };
147
+ if (e?.code === "AMBIGUOUS" || e?.status === 504) return createPaymentError("AMBIGUOUS", extra);
148
+ if (e?.code === "INVALID_CREDENTIALS") return createPaymentError("INVALID_CREDENTIALS", extra);
149
+ if (e?.status === 409) return createPaymentError("AMBIGUOUS", extra);
150
+ if (e?.status === 400) return createPaymentError("INVALID_REQUEST", extra);
151
+ return createPaymentError("PROVIDER_UNAVAILABLE", extra);
152
+ };
153
+ //#endregion
154
+ //#region src/checkout.ts
155
+ /**
156
+ * Attempt reference of a PlacetoPay return URL (the page at `returnUrl` or
157
+ * `cancelUrl`); `null` if it is not one.
158
+ */
159
+ const parsePlacetopayReturn = (url) => {
160
+ try {
161
+ return new URL(url).searchParams.get("placetopay_reference") || null;
162
+ } catch {
163
+ return null;
164
+ }
165
+ };
166
+ const storageKey = (attemptReference) => {
167
+ return `placetopay:session:${attemptReference}`;
168
+ };
169
+ const userAgentOf = () => {
170
+ const nav = globalThis.navigator;
171
+ return typeof nav?.userAgent === "string" ? nav.userAgent : null;
172
+ };
173
+ /** `request_id` of the attempt: the result metadata, else the storage. */
174
+ const requestIdOf = async (ctx, result) => {
175
+ const provider = (result?.metadata)?.provider;
176
+ const fromResult = Number(provider?.request_id);
177
+ if (Number.isInteger(fromResult) && fromResult > 0) return fromResult;
178
+ const saved = await ctx.storage.get(storageKey(ctx.attemptReference));
179
+ const fromStorage = Number(saved);
180
+ return Number.isInteger(fromStorage) && fromStorage > 0 ? fromStorage : null;
181
+ };
182
+ /**
183
+ * PlacetoPay card on the web (WebCheckout). Spark opens the session with
184
+ * the site's secret key (`create_session`), the template sends the
185
+ * customer to PlacetoPay (`bridge`), and Spark reads the session status
186
+ * from PlacetoPay (`status`): the browser's return is never trusted. A
187
+ * session the customer leaves is cancelled (`cancel_session`) so it cannot
188
+ * be paid later. A paid charge is reversed by Spark with the order cancel
189
+ * or refund, whole transactions only.
190
+ */
191
+ const placetopayCheckoutPayments = (options) => {
192
+ const { bridge } = options;
193
+ const pendingOf = (ctx, requestId) => {
194
+ const metadata = {
195
+ attempt_reference: ctx.attemptReference,
196
+ provider: { request_id: requestId }
197
+ };
198
+ return {
199
+ status: "PENDING",
200
+ amount: ctx.amount.value,
201
+ metadata
202
+ };
203
+ };
204
+ const readStatus = async (ctx, requestId) => {
205
+ const input = { request_id: requestId };
206
+ const result = placetopayResultOf(ctx, await ctx.server.call("status", input));
207
+ if (result.status === "PENDING") return pendingOf(ctx, requestId);
208
+ return result;
209
+ };
210
+ /** Customer closed the tab: paid meanwhile, or cancel the session. */
211
+ const leave = async (ctx, requestId) => {
212
+ const input = { request_id: requestId };
213
+ const answer = await ctx.server.call("cancel_session", input);
214
+ if (answer.outcome.status === "PAID") return placetopayResultOf(ctx, answer.outcome);
215
+ if (answer.cancelled || answer.outcome.status === "FAILED") return failedResult(ctx, createPaymentError("CANCELLED_BY_USER", { attempt: ctx.attempt }));
216
+ return pendingOf(ctx, requestId);
217
+ };
218
+ const start = async (ctx) => {
219
+ try {
220
+ const r1 = { return_url: options.returnUrl };
221
+ const r2 = options.cancelUrl ? { cancel_url: options.cancelUrl } : {};
222
+ const r3 = { locale: options.locale ?? "es_EC" };
223
+ const r4 = options.skipResult ? { skip_result: true } : {};
224
+ const agent = userAgentOf();
225
+ const r5 = agent ? { user_agent: agent } : {};
226
+ const input = {
227
+ ...r1,
228
+ ...r2,
229
+ ...r3,
230
+ ...r4,
231
+ ...r5
232
+ };
233
+ const session = await ctx.server.call("create_session", input);
234
+ if (!session.process_url || !session.request_id) return failedResult(ctx, createPaymentError("PROVIDER_UNAVAILABLE", {
235
+ provider_message: "PlacetoPay returned no session",
236
+ attempt: ctx.attempt
237
+ }));
238
+ const requestId = session.request_id;
239
+ await ctx.storage.set(storageKey(ctx.attemptReference), `${requestId}`);
240
+ const b1 = { url: session.process_url };
241
+ const b2 = { attemptReference: ctx.attemptReference };
242
+ const b3 = {
243
+ returnUrl: options.returnUrl,
244
+ signal: ctx.signal
245
+ };
246
+ const outcome = await bridge.open({
247
+ ...b1,
248
+ ...b2,
249
+ ...b3
250
+ });
251
+ if (outcome.type === "redirected") return pendingOf(ctx, requestId);
252
+ ctx.ui.message({
253
+ text: "Confirmando pago…",
254
+ kind: "waiting"
255
+ });
256
+ if (outcome.type === "cancelled") return await leave(ctx, requestId);
257
+ return await readStatus(ctx, requestId);
258
+ } catch (cause) {
259
+ if (cause instanceof PaymentError) return failedResult(ctx, cause.error);
260
+ return failedResult(ctx, serverErrorOf(ctx, cause));
261
+ }
262
+ };
263
+ /** Pending session (redirect or pending transaction): read its status. */
264
+ const query = async (ctx, result) => {
265
+ if (result.status !== "PENDING") return result;
266
+ const requestId = await requestIdOf(ctx, result);
267
+ if (!requestId) return result;
268
+ try {
269
+ return await readStatus(ctx, requestId);
270
+ } catch (cause) {
271
+ return failedResult(ctx, serverErrorOf(ctx, cause));
272
+ }
273
+ };
274
+ /**
275
+ * Timeout or cancel of a pending attempt: cancels the session at
276
+ * PlacetoPay. Anything but a cancelled session stays for review.
277
+ */
278
+ const cancel = async (ctx, result) => {
279
+ const requestId = await requestIdOf(ctx, result);
280
+ if (!requestId) return {
281
+ ...result,
282
+ status: "CANCELLED"
283
+ };
284
+ try {
285
+ const next = await leave(ctx, requestId);
286
+ if (next.error?.code === "CANCELLED_BY_USER") return {
287
+ ...result,
288
+ status: "CANCELLED"
289
+ };
290
+ return next;
291
+ } catch {
292
+ return result;
293
+ }
294
+ };
295
+ const reversalFor = (result) => {
296
+ return result.status === "PAID" ? "server" : "cancel";
297
+ };
298
+ return {
299
+ provider: PLACETOPAY_PROVIDER,
300
+ method: "CARD",
301
+ errors: placetopayErrors,
302
+ policy: PLACETOPAY_POLICY,
303
+ start,
304
+ query,
305
+ cancel,
306
+ reversalFor
307
+ };
308
+ };
309
+ //#endregion
310
+ export { PLACETOPAY_POLICY, PLACETOPAY_PROVIDER, PLACETOPAY_RETURN_PARAM, parsePlacetopayReturn, placetopayCheckoutPayments, placetopayErrors };
package/package.json CHANGED
@@ -1,6 +1,59 @@
1
1
  {
2
2
  "name": "@fire-spark/payments-placetopay-checkout",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.17.0",
4
+ "description": "Fire Spark PlacetoPay adapter (Ecuador): card payments through the WebCheckout redirect on the web, verified and reversed by the Fire Spark API",
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/payments": "^0.17.0",
21
+ "@fire-spark/types": "^0.17.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.