@domdanao/finfactory-payments 0.0.0-stage → 0.1.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.
- package/CHANGELOG.md +26 -0
- package/LICENSE +21 -0
- package/README.md +766 -2
- package/dist/client.d.ts +130 -0
- package/dist/client.js +342 -0
- package/dist/errors.d.ts +108 -0
- package/dist/errors.js +158 -0
- package/dist/helpers.d.ts +19 -0
- package/dist/helpers.js +39 -0
- package/dist/index.d.ts +7 -0
- package/dist/index.js +4 -0
- package/dist/resources.d.ts +97 -0
- package/dist/resources.js +154 -0
- package/dist/types.d.ts +321 -0
- package/dist/types.js +8 -0
- package/dist/webhooks.d.ts +38 -0
- package/dist/webhooks.js +122 -0
- package/package.json +56 -4
package/README.md
CHANGED
|
@@ -1,3 +1,767 @@
|
|
|
1
|
-
#
|
|
1
|
+
# FinFactory Payments for JavaScript and TypeScript
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
A server-side SDK for the [FinFactory Payments Merchant API](https://docs.payments.finfactory.dev/merchant/guides/overview/).
|
|
4
|
+
Take payments by card, QR Ph and cash, through hosted checkout, embedded checkout or your own
|
|
5
|
+
page; refund them, follow disputes, and verify webhooks.
|
|
6
|
+
|
|
7
|
+
> **v0.1: early release.** It covers the whole Merchant API v1 and is tested, but it has not
|
|
8
|
+
> yet been used in production. Method names and options may still change before 1.0; pin the
|
|
9
|
+
> version and read the [changelog](CHANGELOG.md) when you upgrade.
|
|
10
|
+
|
|
11
|
+
- **No dependencies.** Built on `fetch` and Web Crypto.
|
|
12
|
+
- **Runs anywhere JavaScript runs on a server:** Node.js 20.19+, Deno, Bun, Cloudflare Workers,
|
|
13
|
+
Vercel and Netlify functions, AWS Lambda.
|
|
14
|
+
- **Fully typed.** Written in TypeScript; every request, response, event and error is typed.
|
|
15
|
+
- **Safe by default.** Gets and refreshes Access Tokens for you, sends an `Idempotency-Key` on
|
|
16
|
+
every write that takes one, and retries only what is safe to retry.
|
|
17
|
+
|
|
18
|
+
```sh
|
|
19
|
+
npm install @domdanao/finfactory-payments
|
|
20
|
+
```
|
|
21
|
+
|
|
22
|
+
```ts
|
|
23
|
+
import FinFactory from "@domdanao/finfactory-payments";
|
|
24
|
+
|
|
25
|
+
const finfactory = new FinFactory({
|
|
26
|
+
clientId: process.env.FINFACTORY_CLIENT_ID, // ci_test_...
|
|
27
|
+
clientSecret: process.env.FINFACTORY_CLIENT_SECRET, // sk_test_...
|
|
28
|
+
});
|
|
29
|
+
|
|
30
|
+
const intent = await finfactory.paymentIntents.create(
|
|
31
|
+
{
|
|
32
|
+
amount: 10000, // ₱100.00, in centavos
|
|
33
|
+
currency: "php",
|
|
34
|
+
description: "Order 1042",
|
|
35
|
+
return_url: "https://shop.example.com/orders/1042/paid",
|
|
36
|
+
cancel_url: "https://shop.example.com/cart",
|
|
37
|
+
},
|
|
38
|
+
{ idempotencyKey: "order-1042-1" },
|
|
39
|
+
);
|
|
40
|
+
|
|
41
|
+
if (intent.next_action?.type === "redirect_to_url") {
|
|
42
|
+
// Send the customer to hosted checkout.
|
|
43
|
+
redirect(intent.next_action.redirect_to_url.url);
|
|
44
|
+
}
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
---
|
|
48
|
+
|
|
49
|
+
## Contents
|
|
50
|
+
|
|
51
|
+
- [Requirements](#requirements)
|
|
52
|
+
- [Do I need a different package for Node.js, the browser or a mobile app?](#do-i-need-a-different-package-for-nodejs-the-browser-or-a-mobile-app)
|
|
53
|
+
- [Configuration](#configuration)
|
|
54
|
+
- [Authentication and Access Tokens](#authentication-and-access-tokens)
|
|
55
|
+
- [Taking a payment](#taking-a-payment)
|
|
56
|
+
- [Hosted checkout](#hosted-checkout)
|
|
57
|
+
- [Embedded checkout](#embedded-checkout)
|
|
58
|
+
- [Your own payment page (API-only)](#your-own-payment-page-api-only)
|
|
59
|
+
- [Drawing the QR Ph code](#drawing-the-qr-ph-code)
|
|
60
|
+
- [Cash](#cash)
|
|
61
|
+
- [Checking the outcome](#checking-the-outcome)
|
|
62
|
+
- [Cancelling](#cancelling)
|
|
63
|
+
- [Payment methods](#payment-methods)
|
|
64
|
+
- [Refunds](#refunds)
|
|
65
|
+
- [Disputes](#disputes)
|
|
66
|
+
- [Webhooks](#webhooks)
|
|
67
|
+
- [Managing endpoints](#managing-endpoints)
|
|
68
|
+
- [Receiving and verifying events](#receiving-and-verifying-events)
|
|
69
|
+
- [Framework recipes](#framework-recipes)
|
|
70
|
+
- [Rotating the secret](#rotating-the-secret)
|
|
71
|
+
- [Errors](#errors)
|
|
72
|
+
- [Idempotency and retries](#idempotency-and-retries)
|
|
73
|
+
- [Pagination](#pagination)
|
|
74
|
+
- [Test mode](#test-mode)
|
|
75
|
+
- [Helpers](#helpers)
|
|
76
|
+
- [Response metadata](#response-metadata)
|
|
77
|
+
- [Calling an endpoint the SDK does not have yet](#calling-an-endpoint-the-sdk-does-not-have-yet)
|
|
78
|
+
- [TypeScript](#typescript)
|
|
79
|
+
- [API reference](#api-reference)
|
|
80
|
+
- [Support](#support)
|
|
81
|
+
|
|
82
|
+
---
|
|
83
|
+
|
|
84
|
+
## Requirements
|
|
85
|
+
|
|
86
|
+
| Runtime | Version |
|
|
87
|
+
| --- | --- |
|
|
88
|
+
| Node.js | 20.19 or later (22 LTS or 24 LTS recommended). Tested in CI on 20, 22 and 24. |
|
|
89
|
+
| Deno | 2.x, as `npm:@domdanao/finfactory-payments` |
|
|
90
|
+
| Bun | current releases |
|
|
91
|
+
| Cloudflare Workers, Vercel Edge, Netlify Edge | any runtime with `fetch` and `crypto.subtle` |
|
|
92
|
+
|
|
93
|
+
The package is ES modules only. `import` works everywhere; `require("@domdanao/finfactory-payments")`
|
|
94
|
+
works on Node.js 20.19+ and 22.12+, which load ES modules from CommonJS.
|
|
95
|
+
|
|
96
|
+
## Do I need a different package for Node.js, the browser or a mobile app?
|
|
97
|
+
|
|
98
|
+
**Node.js: no.** This one package is for every server-side JavaScript runtime. It uses only the
|
|
99
|
+
web-standard `fetch` and `crypto.subtle`, which Node.js, Deno, Bun and edge runtimes all have.
|
|
100
|
+
|
|
101
|
+
**The browser or a mobile app: you do not use this SDK there, and you should not.** The Merchant
|
|
102
|
+
API is called with your client secret, or an Access Token made from it, and neither may reach a
|
|
103
|
+
browser or a mobile app: anyone who opens the page or installs the app can read them, and a token
|
|
104
|
+
can do everything the secret can while it lasts. The SDK refuses to run with either in a browser
|
|
105
|
+
or in a React Native app (Expo included); the app calls your own server, which uses the SDK. What a browser or an app needs is already provided by the platform:
|
|
106
|
+
|
|
107
|
+
| Where | What to use |
|
|
108
|
+
| --- | --- |
|
|
109
|
+
| Your server | This SDK |
|
|
110
|
+
| Your web page, hosted checkout | Nothing: redirect to `next_action.redirect_to_url.url` |
|
|
111
|
+
| Your web page, embedded checkout | The platform's `embedded-checkout.js`, loaded from your checkout host, with your **publishable key** (`pk_...`) and the intent's **client token** (`ct_...`) |
|
|
112
|
+
| A mobile app | A WebView of your page, as for embedded checkout; or your own screens that call your server |
|
|
113
|
+
| A QR Ph code in a page or an app | [`@domdanao/finfactory-qrph`](https://github.com/domdanao/finfactory-payments/tree/main/qrph-js), with the payload your server returns |
|
|
114
|
+
|
|
115
|
+
## Configuration
|
|
116
|
+
|
|
117
|
+
```ts
|
|
118
|
+
const finfactory = new FinFactory({
|
|
119
|
+
clientId: "ci_test_...",
|
|
120
|
+
clientSecret: "sk_test_...",
|
|
121
|
+
baseUrl: "https://api.payments.finfactory.dev", // your platform's API host
|
|
122
|
+
timeout: 30_000, // ms, per attempt
|
|
123
|
+
maxRetries: 2, // retries of a request that is safe to retry
|
|
124
|
+
});
|
|
125
|
+
```
|
|
126
|
+
|
|
127
|
+
| Option | Default | |
|
|
128
|
+
| --- | --- | --- |
|
|
129
|
+
| `clientId` | `FINFACTORY_CLIENT_ID` env | `ci_test_...` or `ci_live_...` |
|
|
130
|
+
| `clientSecret` | `FINFACTORY_CLIENT_SECRET` env | `sk_test_...` or `sk_live_...`. Keep it in your secret store. |
|
|
131
|
+
| `accessToken` | none | A token you manage yourself (a string, or a function returning one), instead of `clientId`/`clientSecret`. Server-side only, like the secret. |
|
|
132
|
+
| `baseUrl` | `FINFACTORY_BASE_URL` env, then `https://api.payments.finfactory.dev` | Your platform's API host, if it gave you another. |
|
|
133
|
+
| `timeout` | `30000` | Milliseconds per attempt. |
|
|
134
|
+
| `maxRetries` | `2` | See [Idempotency and retries](#idempotency-and-retries). |
|
|
135
|
+
| `tokenCache` | in memory | Share Access Tokens between processes. See below. |
|
|
136
|
+
| `fetch` | `globalThis.fetch` | A custom `fetch`, for a proxy or for tests. |
|
|
137
|
+
| `defaultHeaders` | `{}` | Headers sent on every request. |
|
|
138
|
+
| `dangerouslyAllowBrowser` | `false` | Lets the client be built with a secret or an Access Token in a browser or a React Native app. Only for test harnesses. |
|
|
139
|
+
|
|
140
|
+
With the environment variables set, `new FinFactory()` needs no arguments.
|
|
141
|
+
|
|
142
|
+
Every method takes **request options** as its last argument:
|
|
143
|
+
|
|
144
|
+
```ts
|
|
145
|
+
await finfactory.paymentIntents.retrieve("pi_...", {
|
|
146
|
+
timeout: 5_000,
|
|
147
|
+
maxRetries: 0,
|
|
148
|
+
signal: AbortSignal.timeout(10_000),
|
|
149
|
+
headers: { "X-Trace": "abc" },
|
|
150
|
+
});
|
|
151
|
+
```
|
|
152
|
+
|
|
153
|
+
## Authentication and Access Tokens
|
|
154
|
+
|
|
155
|
+
You give the SDK your client ID and secret; it exchanges them at `POST /oauth/token` for an
|
|
156
|
+
Access Token that lasts 15 minutes, sends only that token on `/v1` calls, and fetches a new one a
|
|
157
|
+
minute before it expires. Concurrent calls share one token request. If a token stops working early
|
|
158
|
+
(the key was revoked or rotated), the SDK gets a new one and sends the call again, once.
|
|
159
|
+
|
|
160
|
+
The token endpoint is rate limited, so a token should be shared as widely as it can be. In a
|
|
161
|
+
long-running server one client does that by itself: **create one client and reuse it.** Where
|
|
162
|
+
every invocation starts fresh (serverless functions), share tokens through a `tokenCache`:
|
|
163
|
+
|
|
164
|
+
```ts
|
|
165
|
+
import { createClient } from "redis";
|
|
166
|
+
const redis = await createClient().connect();
|
|
167
|
+
|
|
168
|
+
const finfactory = new FinFactory({
|
|
169
|
+
tokenCache: {
|
|
170
|
+
async get(key) {
|
|
171
|
+
const value = await redis.get(key);
|
|
172
|
+
return value ? JSON.parse(value) : null;
|
|
173
|
+
},
|
|
174
|
+
async set(key, token) {
|
|
175
|
+
await redis.set(key, JSON.stringify(token), { PXAT: token.expiresAt });
|
|
176
|
+
},
|
|
177
|
+
async delete(key) {
|
|
178
|
+
await redis.del(key);
|
|
179
|
+
},
|
|
180
|
+
},
|
|
181
|
+
});
|
|
182
|
+
```
|
|
183
|
+
|
|
184
|
+
An Access Token is a credential: keep the cache private to your servers.
|
|
185
|
+
|
|
186
|
+
To get a token yourself, for another tool: `await finfactory.accessTokens.create()`.
|
|
187
|
+
|
|
188
|
+
## Taking a payment
|
|
189
|
+
|
|
190
|
+
A **payment intent** is one payment to take. Its `status` moves through
|
|
191
|
+
`requires_payment_method` → `requires_confirmation` → `requires_action` → `processing` →
|
|
192
|
+
`succeeded`, or ends `canceled`. While it is `requires_action`, `next_action.type` says what the
|
|
193
|
+
customer is to do. A failed attempt does not end it: it goes back to `requires_payment_method`,
|
|
194
|
+
with `last_payment_error`, and can be confirmed again.
|
|
195
|
+
|
|
196
|
+
Amounts are integers in the currency's minor unit: `10000` in `php` is ₱100.00.
|
|
197
|
+
|
|
198
|
+
### Hosted checkout
|
|
199
|
+
|
|
200
|
+
Create the intent without a method. The customer chooses one on the platform's checkout page.
|
|
201
|
+
|
|
202
|
+
```ts
|
|
203
|
+
const intent = await finfactory.paymentIntents.create(
|
|
204
|
+
{
|
|
205
|
+
amount: 10000,
|
|
206
|
+
currency: "php",
|
|
207
|
+
description: "Order 1042",
|
|
208
|
+
return_url: "https://shop.example.com/orders/1042/paid",
|
|
209
|
+
cancel_url: "https://shop.example.com/cart",
|
|
210
|
+
customer_email: "maria@example.com", // pre-fills the receipt field
|
|
211
|
+
metadata: { order_id: "1042" },
|
|
212
|
+
},
|
|
213
|
+
{ idempotencyKey: "order-1042-1" },
|
|
214
|
+
);
|
|
215
|
+
|
|
216
|
+
// next_action.type is "redirect_to_url"
|
|
217
|
+
res.redirect(303, intent.next_action.redirect_to_url.url);
|
|
218
|
+
```
|
|
219
|
+
|
|
220
|
+
The link is good for one checkout session (30 minutes by default) and is the customer's
|
|
221
|
+
credential for this payment: send it only to them. Webhooks never carry it; retrieve the intent
|
|
222
|
+
to get it again.
|
|
223
|
+
|
|
224
|
+
When the customer comes back to `return_url`, `payment_intent` and `checkout_session` are added
|
|
225
|
+
to it. **That proves nothing**: [check the outcome](#checking-the-outcome) before you fulfil the
|
|
226
|
+
order.
|
|
227
|
+
|
|
228
|
+
### Embedded checkout
|
|
229
|
+
|
|
230
|
+
The same checkout, inside your own page. On your server:
|
|
231
|
+
|
|
232
|
+
```ts
|
|
233
|
+
const intent = await finfactory.paymentIntents.create(
|
|
234
|
+
{
|
|
235
|
+
amount: 10000,
|
|
236
|
+
currency: "php",
|
|
237
|
+
checkout_mode: "embedded",
|
|
238
|
+
return_url: "https://shop.example.com/orders/1042/paid", // needed for card
|
|
239
|
+
},
|
|
240
|
+
{ idempotencyKey: "order-1042-1" },
|
|
241
|
+
);
|
|
242
|
+
|
|
243
|
+
if (intent.next_action?.type === "mount_embedded_checkout") {
|
|
244
|
+
const clientToken = intent.next_action.mount_embedded_checkout.client_token;
|
|
245
|
+
// Store it with the order, and give it to the page paying this order.
|
|
246
|
+
}
|
|
247
|
+
```
|
|
248
|
+
|
|
249
|
+
On your page (not this SDK: the platform's library, from your checkout host):
|
|
250
|
+
|
|
251
|
+
```html
|
|
252
|
+
<script src="https://checkout.example.com/embedded-checkout.js"></script>
|
|
253
|
+
<div id="checkout"></div>
|
|
254
|
+
<script>
|
|
255
|
+
const checkout = EmbeddedCheckout("pk_test_...");
|
|
256
|
+
checkout.mount("#checkout", {
|
|
257
|
+
clientToken: "ct_...",
|
|
258
|
+
onComplete: ({ payment_intent }) => location.assign("/orders/1042/thanks"),
|
|
259
|
+
onCancel: ({ payment_intent }) => location.assign("/cart"),
|
|
260
|
+
});
|
|
261
|
+
</script>
|
|
262
|
+
```
|
|
263
|
+
|
|
264
|
+
Register your page's origin in the Merchant Dashboard first. `onComplete` is not proof of payment
|
|
265
|
+
either: check on your server.
|
|
266
|
+
|
|
267
|
+
### Your own payment page (API-only)
|
|
268
|
+
|
|
269
|
+
Show the methods yourself, then confirm with the one the customer chose:
|
|
270
|
+
|
|
271
|
+
```ts
|
|
272
|
+
const intent = await finfactory.paymentIntents.create(
|
|
273
|
+
{ amount: 10000, currency: "php" },
|
|
274
|
+
{ idempotencyKey: "order-1042-1" },
|
|
275
|
+
);
|
|
276
|
+
// intent.payment_method_types: the methods that can take this payment now, e.g. ["card", "qrph", "cash"]
|
|
277
|
+
|
|
278
|
+
const confirmed = await finfactory.paymentIntents.confirm(
|
|
279
|
+
intent.id,
|
|
280
|
+
{ payment_method_data: { type: "qrph" } },
|
|
281
|
+
{ idempotencyKey: "order-1042-confirm-1" },
|
|
282
|
+
);
|
|
283
|
+
|
|
284
|
+
switch (confirmed.next_action?.type) {
|
|
285
|
+
case "qrph_display_qr_code":
|
|
286
|
+
// Render as a QR code; show how long it has left.
|
|
287
|
+
showQr(qrphData(confirmed), qrphExpiresAt(confirmed)); // draw it: see below
|
|
288
|
+
break;
|
|
289
|
+
case "cash_display_reference":
|
|
290
|
+
showCashReference(confirmed.next_action.cash_display_reference);
|
|
291
|
+
break;
|
|
292
|
+
case "redirect_to_url":
|
|
293
|
+
// Card: send the whole page to the card page. return_url is required for card.
|
|
294
|
+
redirect(confirmed.next_action.redirect_to_url.url);
|
|
295
|
+
break;
|
|
296
|
+
default:
|
|
297
|
+
// A next action this version does not know. Ignore it, or fall back to hosted checkout.
|
|
298
|
+
}
|
|
299
|
+
```
|
|
300
|
+
|
|
301
|
+
Create and confirm in one call with `confirm: true` and `payment_method_data`. For card, add
|
|
302
|
+
`return_url` (to the create, or to the confirm).
|
|
303
|
+
|
|
304
|
+
### Drawing the QR Ph code
|
|
305
|
+
|
|
306
|
+
The SDK gives you the payload (`qrphData(intent)`). To draw it as a QR code with the QR Ph logo in
|
|
307
|
+
the centre, as the BSP asks of merchant codes, use the separate package
|
|
308
|
+
[`@domdanao/finfactory-qrph`](https://github.com/domdanao/finfactory-payments/tree/main/qrph-js):
|
|
309
|
+
|
|
310
|
+
```sh
|
|
311
|
+
npm install @domdanao/finfactory-qrph
|
|
312
|
+
```
|
|
313
|
+
|
|
314
|
+
```ts
|
|
315
|
+
import { qrphExpiresAt } from "@domdanao/finfactory-payments";
|
|
316
|
+
import { qrphSvg } from "@domdanao/finfactory-qrph";
|
|
317
|
+
|
|
318
|
+
const svg = qrphSvg(intent, { logo }); // null unless waiting for QR Ph
|
|
319
|
+
const expiresAt = qrphExpiresAt(intent); // for a countdown
|
|
320
|
+
```
|
|
321
|
+
|
|
322
|
+
It is separate so the SDK keeps no dependencies, and so it can draw any QR Ph payload, from
|
|
323
|
+
FinFactory or another provider, without the SDK. While the code is showing, check the intent's
|
|
324
|
+
status every few seconds (from your page, through your server) to move on once it is paid, and
|
|
325
|
+
fulfil from the `payment_intent.succeeded` webhook.
|
|
326
|
+
|
|
327
|
+
### Cash
|
|
328
|
+
|
|
329
|
+
Confirm with `{ payment_method_data: { type: "cash" } }`. The answer's
|
|
330
|
+
`next_action.cash_display_reference` has the `reference`, the exact `amount` and `currency`, when
|
|
331
|
+
it `expires_at` (48 hours by default) and `instructions` to show. Once paid at a collection
|
|
332
|
+
location the intent moves to `processing`, then `succeeded`. An unpaid reference that expires
|
|
333
|
+
fails the attempt (`payment_intent_payment_attempt_expired`); confirm again for a new one.
|
|
334
|
+
|
|
335
|
+
### Checking the outcome
|
|
336
|
+
|
|
337
|
+
Before you fulfil an order, read the intent, or wait for its webhook:
|
|
338
|
+
|
|
339
|
+
```ts
|
|
340
|
+
const intent = await finfactory.paymentIntents.retrieve("pi_...");
|
|
341
|
+
|
|
342
|
+
switch (intent.status) {
|
|
343
|
+
case "succeeded":
|
|
344
|
+
await fulfil(intent.metadata.order_id);
|
|
345
|
+
break;
|
|
346
|
+
case "processing":
|
|
347
|
+
// Paid; outcome not known yet. Not a failure.
|
|
348
|
+
break;
|
|
349
|
+
case "requires_payment_method":
|
|
350
|
+
// The attempt failed. Show intent.last_payment_error?.message and offer to try again.
|
|
351
|
+
break;
|
|
352
|
+
case "canceled":
|
|
353
|
+
break;
|
|
354
|
+
}
|
|
355
|
+
```
|
|
356
|
+
|
|
357
|
+
### Cancelling
|
|
358
|
+
|
|
359
|
+
```ts
|
|
360
|
+
await finfactory.paymentIntents.cancel(
|
|
361
|
+
"pi_...",
|
|
362
|
+
{ cancellation_reason: "requested_by_customer" }, // optional
|
|
363
|
+
{ idempotencyKey: "order-1042-cancel" },
|
|
364
|
+
);
|
|
365
|
+
```
|
|
366
|
+
|
|
367
|
+
Possible from `requires_payment_method`, `requires_confirmation` or `requires_action`; not once it
|
|
368
|
+
is `processing` or `succeeded` (`ConflictError`, code `intent_state`).
|
|
369
|
+
|
|
370
|
+
## Payment methods
|
|
371
|
+
|
|
372
|
+
What your account can take, and why a method cannot take a payment now:
|
|
373
|
+
|
|
374
|
+
```ts
|
|
375
|
+
const methods = await finfactory.paymentMethods.list();
|
|
376
|
+
for (const m of methods.data) {
|
|
377
|
+
console.log(m.method, m.available ? "available" : m.unavailable_reason);
|
|
378
|
+
}
|
|
379
|
+
```
|
|
380
|
+
|
|
381
|
+
## Refunds
|
|
382
|
+
|
|
383
|
+
```ts
|
|
384
|
+
const refund = await finfactory.refunds.create(
|
|
385
|
+
{
|
|
386
|
+
payment_intent: "pi_...",
|
|
387
|
+
amount: 2500, // leave out to refund what remains
|
|
388
|
+
reason: "requested_by_customer", // optional
|
|
389
|
+
},
|
|
390
|
+
{ idempotencyKey: "order-1042-refund-1" },
|
|
391
|
+
);
|
|
392
|
+
|
|
393
|
+
refund.status; // "created" | "processing" | "awaiting_approval" | "succeeded" | "failed"
|
|
394
|
+
```
|
|
395
|
+
|
|
396
|
+
- **Card:** all of it, or part of it. Part of a card payment cannot be refunded on the day it was
|
|
397
|
+
made (`refund_not_yet_available`).
|
|
398
|
+
- **Cash:** the whole payment only; the refund stays `processing` until the operator records the
|
|
399
|
+
cash handed back.
|
|
400
|
+
- **QR Ph:** not refundable through the API (`refund_not_possible` or
|
|
401
|
+
`refund_not_supported_by_provider`).
|
|
402
|
+
- Fees are not returned by a refund.
|
|
403
|
+
- `refund_in_progress` (`InProgressError`): another refund of the same payment is processing.
|
|
404
|
+
Wait for its `refund.succeeded` or `refund.failed`, then send the same request with the
|
|
405
|
+
**same** idempotency key.
|
|
406
|
+
|
|
407
|
+
```ts
|
|
408
|
+
const one = await finfactory.refunds.retrieve("re_...");
|
|
409
|
+
const page = await finfactory.refunds.list({ payment_intent: "pi_..." });
|
|
410
|
+
```
|
|
411
|
+
|
|
412
|
+
## Disputes
|
|
413
|
+
|
|
414
|
+
Read-only: you respond to a dispute from the Merchant Dashboard.
|
|
415
|
+
|
|
416
|
+
```ts
|
|
417
|
+
const open = await finfactory.disputes.list({ status: "open" });
|
|
418
|
+
const dispute = await finfactory.disputes.retrieve("dp_...");
|
|
419
|
+
dispute.evidence_due_date; // "2026-11-20"
|
|
420
|
+
dispute.debited; // what came off your balance
|
|
421
|
+
```
|
|
422
|
+
|
|
423
|
+
## Webhooks
|
|
424
|
+
|
|
425
|
+
### Managing endpoints
|
|
426
|
+
|
|
427
|
+
```ts
|
|
428
|
+
const endpoint = await finfactory.webhookEndpoints.create({
|
|
429
|
+
url: "https://shop.example.com/webhooks",
|
|
430
|
+
enabled_events: ["payment_intent.succeeded", "payment_intent.payment_failed", "refund.failed"],
|
|
431
|
+
// or ["*"] for every type, including ones added later
|
|
432
|
+
});
|
|
433
|
+
await saveSecret(endpoint.secret); // whsec_...: shown only now
|
|
434
|
+
|
|
435
|
+
await finfactory.webhookEndpoints.update(endpoint.id, { status: "enabled" });
|
|
436
|
+
await finfactory.webhookEndpoints.disable(endpoint.id);
|
|
437
|
+
const rotated = await finfactory.webhookEndpoints.rotateSecret(endpoint.id);
|
|
438
|
+
```
|
|
439
|
+
|
|
440
|
+
> Creating an endpoint takes no idempotency key, so the SDK **does not retry it** after a network
|
|
441
|
+
> failure or a 5xx: a second create would make a second endpoint. If a create fails that way,
|
|
442
|
+
> `list()` your endpoints; if it was made, `rotateSecret()` it to read a secret.
|
|
443
|
+
|
|
444
|
+
### Receiving and verifying events
|
|
445
|
+
|
|
446
|
+
Each delivery is a `POST` with a `Webhook-Signature` header. Verify it against the **raw body,
|
|
447
|
+
before parsing it**: re-serialized JSON does not match.
|
|
448
|
+
|
|
449
|
+
```ts
|
|
450
|
+
import { Webhooks, WebhookSignatureError } from "@domdanao/finfactory-payments";
|
|
451
|
+
|
|
452
|
+
const event = await Webhooks.constructEvent(rawBody, signatureHeader, process.env.FINFACTORY_WEBHOOK_SECRET!);
|
|
453
|
+
|
|
454
|
+
switch (event.type) {
|
|
455
|
+
case "payment_intent.succeeded":
|
|
456
|
+
await fulfil(event.data.object.id); // event.data.object is a PaymentIntent
|
|
457
|
+
break;
|
|
458
|
+
case "payment_intent.payment_failed":
|
|
459
|
+
await notifyFailed(event.data.object.last_payment_error);
|
|
460
|
+
break;
|
|
461
|
+
case "refund.failed":
|
|
462
|
+
await alert(event.data.object.failure_reason); // a Refund
|
|
463
|
+
break;
|
|
464
|
+
case "dispute.created":
|
|
465
|
+
await openCase(event.data.object.payment_intent); // a Dispute
|
|
466
|
+
break;
|
|
467
|
+
default:
|
|
468
|
+
// A type you did not handle, or one added later. Ignore it.
|
|
469
|
+
}
|
|
470
|
+
```
|
|
471
|
+
|
|
472
|
+
- `constructEvent` throws `WebhookSignatureError` if the signature does not match or its
|
|
473
|
+
timestamp is more than 5 minutes off (`{ tolerance: seconds }` to change). `Webhooks.verify`
|
|
474
|
+
only checks; `Webhooks.isValid` answers a boolean.
|
|
475
|
+
- Answer any 2xx within 10 seconds. Do slow work after answering, or in a queue.
|
|
476
|
+
- Deliveries arrive **at least once and in any order**: deduplicate on `event.id`, and go by the
|
|
477
|
+
object's `status`, not by the order events arrive in. When in doubt, retrieve the object.
|
|
478
|
+
- `finfactory.webhooks` is the same as `Webhooks`, if you prefer.
|
|
479
|
+
|
|
480
|
+
### Framework recipes
|
|
481
|
+
|
|
482
|
+
**Express.** Use `express.raw` on the webhook route only:
|
|
483
|
+
|
|
484
|
+
```ts
|
|
485
|
+
app.post("/webhooks", express.raw({ type: "application/json" }), async (req, res) => {
|
|
486
|
+
let event;
|
|
487
|
+
try {
|
|
488
|
+
event = await Webhooks.constructEvent(req.body, req.get("webhook-signature"), secret);
|
|
489
|
+
} catch (e) {
|
|
490
|
+
return res.status(400).send("Bad signature");
|
|
491
|
+
}
|
|
492
|
+
res.sendStatus(200);
|
|
493
|
+
await handle(event);
|
|
494
|
+
});
|
|
495
|
+
```
|
|
496
|
+
|
|
497
|
+
**Next.js (App Router), Remix, Hono, Cloudflare Workers, Deno, Bun** — anything with a web
|
|
498
|
+
`Request`:
|
|
499
|
+
|
|
500
|
+
```ts
|
|
501
|
+
export async function POST(request: Request) {
|
|
502
|
+
const body = await request.text();
|
|
503
|
+
try {
|
|
504
|
+
const event = await Webhooks.constructEvent(body, request.headers.get("webhook-signature"), secret);
|
|
505
|
+
await handle(event);
|
|
506
|
+
return new Response(null, { status: 200 });
|
|
507
|
+
} catch (e) {
|
|
508
|
+
if (e instanceof WebhookSignatureError) return new Response("Bad signature", { status: 400 });
|
|
509
|
+
throw e;
|
|
510
|
+
}
|
|
511
|
+
}
|
|
512
|
+
```
|
|
513
|
+
|
|
514
|
+
**Fastify.** Keep the raw body for the route:
|
|
515
|
+
|
|
516
|
+
```ts
|
|
517
|
+
fastify.addContentTypeParser("application/json", { parseAs: "buffer" }, (req, body, done) => done(null, body));
|
|
518
|
+
fastify.post("/webhooks", async (req, reply) => {
|
|
519
|
+
const event = await Webhooks.constructEvent(req.body as Buffer, req.headers["webhook-signature"] as string, secret);
|
|
520
|
+
// ...
|
|
521
|
+
});
|
|
522
|
+
```
|
|
523
|
+
|
|
524
|
+
**Testing your handler.** Sign a body yourself:
|
|
525
|
+
|
|
526
|
+
```ts
|
|
527
|
+
const body = JSON.stringify(fakeEvent);
|
|
528
|
+
const header = await Webhooks.generateTestHeader(body, "whsec_test_secret");
|
|
529
|
+
```
|
|
530
|
+
|
|
531
|
+
### Rotating the secret
|
|
532
|
+
|
|
533
|
+
For 24 hours after a rotation, deliveries carry a signature from each secret. Pass both:
|
|
534
|
+
|
|
535
|
+
```ts
|
|
536
|
+
await Webhooks.constructEvent(body, header, [newSecret, oldSecret]);
|
|
537
|
+
```
|
|
538
|
+
|
|
539
|
+
## Errors
|
|
540
|
+
|
|
541
|
+
Every error the SDK throws extends `FinFactoryError`. A refusal from the API is an `ApiError`
|
|
542
|
+
subclass, one per error `type`:
|
|
543
|
+
|
|
544
|
+
| Class | `type` | Status | Meaning |
|
|
545
|
+
| --- | --- | --- | --- |
|
|
546
|
+
| `ValidationError` | `validation_failure` | 400 | A parameter is missing or not valid. `param` names it. |
|
|
547
|
+
| `AuthenticationError` | `authentication_failure` | 401 | No token, or one not valid. (The SDK refreshes expired tokens itself.) |
|
|
548
|
+
| `AuthorizationError` | `authorization_failure` | 403 | The key may not do this, e.g. `test_mode_only`. |
|
|
549
|
+
| `NotFoundError` | `not_found` | 404 | No such object for this key. |
|
|
550
|
+
| `ConflictError` | `conflict` | 409 | Not in a state that allows this, e.g. `intent_state`, `idempotency_key_reused`. |
|
|
551
|
+
| `InProgressError` | `timeout_or_in_progress` | 409 | A duplicate still running, or `refund_in_progress`. Retry later. |
|
|
552
|
+
| `PolicyRejectionError` | `policy_rejection` | 422 | Your account may not do this now: `code` says why. |
|
|
553
|
+
| `InvariantViolationError` | `invariant_violation` | 422 | E.g. `amount_exceeds_refundable`. |
|
|
554
|
+
| `RateLimitError` | `rate_limited` | 429 | Too many requests. `retryAfter` is in seconds. |
|
|
555
|
+
| `DependencyFailureError` | `dependency_failure` | 503 | Failure on the platform's side. See below. |
|
|
556
|
+
|
|
557
|
+
Other errors: `OAuthError` (the token endpoint refused your key: `error` is `invalid_client`,
|
|
558
|
+
`invalid_request`, `unsupported_grant_type` or `rate_limited`), `ConnectionError` and
|
|
559
|
+
`TimeoutError` (no answer received), `WebhookSignatureError`.
|
|
560
|
+
|
|
561
|
+
```ts
|
|
562
|
+
import { ApiError, PolicyRejectionError } from "@domdanao/finfactory-payments";
|
|
563
|
+
|
|
564
|
+
try {
|
|
565
|
+
await finfactory.refunds.create({ payment_intent: id }, { idempotencyKey: `refund-${id}` });
|
|
566
|
+
} catch (e) {
|
|
567
|
+
if (e instanceof PolicyRejectionError && e.code === "refund_not_yet_available") {
|
|
568
|
+
// Partial card refunds open tomorrow.
|
|
569
|
+
} else if (e instanceof ApiError) {
|
|
570
|
+
log.error({ type: e.type, code: e.code, param: e.param, requestId: e.requestId }, e.message);
|
|
571
|
+
throw e;
|
|
572
|
+
} else {
|
|
573
|
+
throw e;
|
|
574
|
+
}
|
|
575
|
+
}
|
|
576
|
+
```
|
|
577
|
+
|
|
578
|
+
Branch on `type` or `code`. Never on `message`: it is for the developer reading a log and may be
|
|
579
|
+
reworded. Quote `requestId` when you contact support.
|
|
580
|
+
|
|
581
|
+
## Idempotency and retries
|
|
582
|
+
|
|
583
|
+
Creating, confirming and cancelling a payment intent, simulating an outcome, and creating a
|
|
584
|
+
refund require an `Idempotency-Key`. Pass your own, unique to the operation:
|
|
585
|
+
|
|
586
|
+
```ts
|
|
587
|
+
await finfactory.paymentIntents.create(params, { idempotencyKey: `order-${order.id}-attempt-${order.attempt}` });
|
|
588
|
+
```
|
|
589
|
+
|
|
590
|
+
If you leave it out, the SDK generates a random UUID. That makes the SDK's own retries safe, but
|
|
591
|
+
not a retry your code makes later (for example after a crash): only a key derived from your own
|
|
592
|
+
data does that. Keys are remembered for 7 days.
|
|
593
|
+
|
|
594
|
+
**What the SDK retries, `maxRetries` times (default 2), with exponential backoff:**
|
|
595
|
+
|
|
596
|
+
| Failure | Reads | Keyed writes | Webhook endpoint update, disable, rotate | Webhook endpoint create |
|
|
597
|
+
| --- | --- | --- | --- | --- |
|
|
598
|
+
| Network error, timeout | ✓ | ✓ same key | ✓ | ✗ |
|
|
599
|
+
| 5xx (`dependency_failure`) | ✓ | ✓ same key | ✓ | ✗ |
|
|
600
|
+
| 429 `rate_limited` | ✓ honours `Retry-After` (up to 60 s) | ✓ | ✓ | ✓ |
|
|
601
|
+
| 409 `idempotency_key_in_use` | | ✓ | | |
|
|
602
|
+
| 401 `invalid_access_token` | ✓ once, with a new token | ✓ | ✓ | ✓ |
|
|
603
|
+
| anything else | ✗ | ✗ | ✗ | ✗ |
|
|
604
|
+
|
|
605
|
+
**When a write still fails with `DependencyFailureError` or `ConnectionError`, whether it took
|
|
606
|
+
effect is not known.** Retry it later with the **same** idempotency key, never a new one: a new
|
|
607
|
+
key is a new request, and can pay or refund twice. If that retry answers `ConflictError` with code
|
|
608
|
+
`intent_state`, retrieve the intent rather than send it again.
|
|
609
|
+
|
|
610
|
+
`intent.lastResponse.idempotentReplayed` is `true` when the answer is a replay of an earlier
|
|
611
|
+
success with the same key.
|
|
612
|
+
|
|
613
|
+
## Pagination
|
|
614
|
+
|
|
615
|
+
Lists are paged by cursor. `list()` returns one page:
|
|
616
|
+
|
|
617
|
+
```ts
|
|
618
|
+
const page = await finfactory.paymentIntents.list({ limit: 100 });
|
|
619
|
+
page.data; // PaymentIntent[]
|
|
620
|
+
page.has_more; // boolean
|
|
621
|
+
page.next_cursor; // pass as `cursor` for the next page
|
|
622
|
+
|
|
623
|
+
const next = await finfactory.paymentIntents.list({ limit: 100, cursor: page.next_cursor! });
|
|
624
|
+
```
|
|
625
|
+
|
|
626
|
+
`all()` goes through every page for you:
|
|
627
|
+
|
|
628
|
+
```ts
|
|
629
|
+
for await (const intent of finfactory.paymentIntents.all({ limit: 100 })) {
|
|
630
|
+
console.log(intent.id, intent.status);
|
|
631
|
+
}
|
|
632
|
+
|
|
633
|
+
// or, on Node.js 22+:
|
|
634
|
+
const refunds = await Array.fromAsync(finfactory.refunds.all({ payment_intent: "pi_..." }));
|
|
635
|
+
```
|
|
636
|
+
|
|
637
|
+
`list` and `all` exist on `paymentIntents`, `paymentMethods`, `refunds`, `disputes` and
|
|
638
|
+
`webhookEndpoints`.
|
|
639
|
+
|
|
640
|
+
## Test mode
|
|
641
|
+
|
|
642
|
+
Test keys (`ci_test_...`, `sk_test_...`) never move money. `finfactory.livemode` tells you which
|
|
643
|
+
kind of key the client has.
|
|
644
|
+
|
|
645
|
+
In test mode, give a payment its outcome with the test helper:
|
|
646
|
+
|
|
647
|
+
```ts
|
|
648
|
+
const intent = await finfactory.paymentIntents.create(
|
|
649
|
+
{ amount: 10000, currency: "php", payment_method_data: { type: "qrph" }, confirm: true },
|
|
650
|
+
{ idempotencyKey: "test-1" },
|
|
651
|
+
);
|
|
652
|
+
|
|
653
|
+
const paid = await finfactory.testHelpers.paymentIntents.simulate(intent.id, { outcome: "paid" });
|
|
654
|
+
paid.status; // "succeeded"
|
|
655
|
+
```
|
|
656
|
+
|
|
657
|
+
| Method | Outcomes |
|
|
658
|
+
| --- | --- |
|
|
659
|
+
| QR Ph, cash | `paid`, `expired` |
|
|
660
|
+
| Card | `approved`, `declined` (with an optional `decline_reason`: `insufficient_funds`, `do_not_honor`, `expired_card`), `three_d_secure_passed`, `three_d_secure_failed`, `abandoned` |
|
|
661
|
+
|
|
662
|
+
A live key is refused with `AuthorizationError`, code `test_mode_only`. A test card payment of
|
|
663
|
+
**PHP 404.00** (`amount: 40400`) is charged back once it succeeds, opening a test dispute. See
|
|
664
|
+
[Testing your integration](https://docs.payments.finfactory.dev/merchant/guides/testing-your-integration/).
|
|
665
|
+
|
|
666
|
+
A runnable end-to-end example is in [`examples/quickstart.mjs`](examples/quickstart.mjs):
|
|
667
|
+
|
|
668
|
+
```sh
|
|
669
|
+
FINFACTORY_CLIENT_ID=ci_test_... FINFACTORY_CLIENT_SECRET=sk_test_... node examples/quickstart.mjs
|
|
670
|
+
```
|
|
671
|
+
|
|
672
|
+
## Helpers
|
|
673
|
+
|
|
674
|
+
Results are plain objects, so the SDK gives you functions to read them. The PHP SDK has the same
|
|
675
|
+
ones, as methods (`$intent->redirectUrl()`):
|
|
676
|
+
|
|
677
|
+
```ts
|
|
678
|
+
import { redirectUrl, clientToken, qrphData, qrphExpiresAt, isSucceeded, hasMore, nextCursor, dataObject } from "@domdanao/finfactory-payments";
|
|
679
|
+
|
|
680
|
+
isSucceeded(intent);
|
|
681
|
+
redirectUrl(intent); // hosted checkout / card page URL, or null
|
|
682
|
+
clientToken(intent); // embedded checkout client token, or null
|
|
683
|
+
qrphData(intent); // QR Ph payload to show, or null
|
|
684
|
+
qrphExpiresAt(intent); // when the QR code stops being payable, or null
|
|
685
|
+
hasMore(page); // on a list page; and nextCursor(page)
|
|
686
|
+
dataObject(event); // the PaymentIntent, Refund or Dispute a webhook event is about
|
|
687
|
+
```
|
|
688
|
+
|
|
689
|
+
## Response metadata
|
|
690
|
+
|
|
691
|
+
Every object a call returns has a non-enumerable `lastResponse` (it does not appear in
|
|
692
|
+
`JSON.stringify` or `Object.keys`):
|
|
693
|
+
|
|
694
|
+
```ts
|
|
695
|
+
const intent = await finfactory.paymentIntents.retrieve("pi_...");
|
|
696
|
+
intent.lastResponse.requestId; // X-Request-ID, for support
|
|
697
|
+
intent.lastResponse.statusCode; // 200
|
|
698
|
+
intent.lastResponse.idempotentReplayed; // true on a replay
|
|
699
|
+
intent.lastResponse.idempotencyKey; // the key sent, if any
|
|
700
|
+
intent.lastResponse.headers; // Headers
|
|
701
|
+
```
|
|
702
|
+
|
|
703
|
+
## Calling an endpoint the SDK does not have yet
|
|
704
|
+
|
|
705
|
+
The API adds resources inside `/v1`. Until the SDK has a method for one, call it with the same
|
|
706
|
+
authentication, retries and errors:
|
|
707
|
+
|
|
708
|
+
```ts
|
|
709
|
+
const result = await finfactory.request<{ id: string }>(
|
|
710
|
+
{ method: "POST", path: "/v1/new_things", body: { name: "x" }, idempotent: true },
|
|
711
|
+
{ idempotencyKey: "new-thing-1" },
|
|
712
|
+
);
|
|
713
|
+
```
|
|
714
|
+
|
|
715
|
+
## TypeScript
|
|
716
|
+
|
|
717
|
+
Types are included. Useful ones:
|
|
718
|
+
|
|
719
|
+
```ts
|
|
720
|
+
import type {
|
|
721
|
+
PaymentIntent, PaymentIntentCreateParams, NextAction,
|
|
722
|
+
Refund, Dispute, PaymentMethod, WebhookEndpoint,
|
|
723
|
+
WebhookEvent, KnownWebhookEventType, List, ResponseInfo,
|
|
724
|
+
} from "@domdanao/finfactory-payments";
|
|
725
|
+
```
|
|
726
|
+
|
|
727
|
+
String enums (`status`, `type`, `code`, ...) list the known values and still accept any string,
|
|
728
|
+
because the API adds values inside `v1`. Handle the values you know and ignore the rest.
|
|
729
|
+
|
|
730
|
+
## API reference
|
|
731
|
+
|
|
732
|
+
| Call | HTTP |
|
|
733
|
+
| --- | --- |
|
|
734
|
+
| `paymentIntents.create(params, options?)` | `POST /v1/payment_intents` |
|
|
735
|
+
| `paymentIntents.retrieve(id, options?)` | `GET /v1/payment_intents/{id}` |
|
|
736
|
+
| `paymentIntents.confirm(id, params?, options?)` | `POST /v1/payment_intents/{id}/confirm` |
|
|
737
|
+
| `paymentIntents.cancel(id, params?, options?)` | `POST /v1/payment_intents/{id}/cancel` |
|
|
738
|
+
| `paymentIntents.list(params?, options?)` / `.all()` | `GET /v1/payment_intents` |
|
|
739
|
+
| `paymentMethods.list(params?, options?)` / `.all()` | `GET /v1/payment_methods` |
|
|
740
|
+
| `paymentMethods.retrieve(id, options?)` | `GET /v1/payment_methods/{id}` |
|
|
741
|
+
| `refunds.create(params, options?)` | `POST /v1/refunds` |
|
|
742
|
+
| `refunds.retrieve(id, options?)` | `GET /v1/refunds/{id}` |
|
|
743
|
+
| `refunds.list(params?, options?)` / `.all()` | `GET /v1/refunds` |
|
|
744
|
+
| `disputes.retrieve(id, options?)` | `GET /v1/disputes/{id}` |
|
|
745
|
+
| `disputes.list(params?, options?)` / `.all()` | `GET /v1/disputes` |
|
|
746
|
+
| `webhookEndpoints.create(params, options?)` | `POST /v1/webhook_endpoints` |
|
|
747
|
+
| `webhookEndpoints.list(params?, options?)` / `.all()` | `GET /v1/webhook_endpoints` |
|
|
748
|
+
| `webhookEndpoints.update(id, params, options?)` | `POST /v1/webhook_endpoints/{id}` |
|
|
749
|
+
| `webhookEndpoints.disable(id, options?)` | `POST /v1/webhook_endpoints/{id}/disable` |
|
|
750
|
+
| `webhookEndpoints.rotateSecret(id, options?)` | `POST /v1/webhook_endpoints/{id}/rotate_secret` |
|
|
751
|
+
| `testHelpers.paymentIntents.simulate(id, params, options?)` | `POST /v1/test_helpers/payment_intents/{id}/simulate` |
|
|
752
|
+
| `accessTokens.create(options?)` | `POST /oauth/token` |
|
|
753
|
+
| `Webhooks.constructEvent / verify / isValid / generateTestHeader` | — |
|
|
754
|
+
| `redirectUrl`, `clientToken`, `qrphData`, `qrphExpiresAt`, `isSucceeded`, `hasMore`, `nextCursor`, `dataObject` | — (read a result) |
|
|
755
|
+
|
|
756
|
+
Every parameter and field is described in the
|
|
757
|
+
[Merchant API reference](https://docs.payments.finfactory.dev/merchant/reference/).
|
|
758
|
+
|
|
759
|
+
## Support
|
|
760
|
+
|
|
761
|
+
- Guides and reference: <https://docs.payments.finfactory.dev/merchant/guides/overview/>
|
|
762
|
+
- Bugs in this SDK: open an issue on this repository.
|
|
763
|
+
- Questions about a payment: contact your platform operator, quoting the `requestId`.
|
|
764
|
+
|
|
765
|
+
## License
|
|
766
|
+
|
|
767
|
+
MIT. See [LICENSE](LICENSE).
|