@clikgate/node 0.0.0-stage → 2.0.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 +126 -0
- package/LICENSE +21 -0
- package/README.md +300 -2
- package/SECURITY.md +34 -0
- package/dist/cjs/ads-hashing.d.ts +37 -0
- package/dist/cjs/ads-hashing.js +67 -0
- package/dist/cjs/click-ids.d.ts +184 -0
- package/dist/cjs/click-ids.js +535 -0
- package/dist/cjs/client.d.ts +175 -0
- package/dist/cjs/client.js +266 -0
- package/dist/cjs/config.d.ts +12 -0
- package/dist/cjs/config.js +87 -0
- package/dist/cjs/core.d.ts +15 -0
- package/dist/cjs/core.js +100 -0
- package/dist/cjs/enums.d.ts +48 -0
- package/dist/cjs/enums.js +47 -0
- package/dist/cjs/errors.d.ts +117 -0
- package/dist/cjs/errors.js +257 -0
- package/dist/cjs/express.d.ts +49 -0
- package/dist/cjs/express.js +44 -0
- package/dist/cjs/fastify.d.ts +47 -0
- package/dist/cjs/fastify.js +35 -0
- package/dist/cjs/generated/index.d.ts +17534 -0
- package/dist/cjs/generated/index.js +8816 -0
- package/dist/cjs/goals.d.ts +116 -0
- package/dist/cjs/goals.js +381 -0
- package/dist/cjs/guard.d.ts +17 -0
- package/dist/cjs/guard.js +40 -0
- package/dist/cjs/http.d.ts +16 -0
- package/dist/cjs/http.js +148 -0
- package/dist/cjs/identity.d.ts +32 -0
- package/dist/cjs/identity.js +99 -0
- package/dist/cjs/index.d.ts +32 -0
- package/dist/cjs/index.js +64 -0
- package/dist/cjs/logger.d.ts +9 -0
- package/dist/cjs/logger.js +8 -0
- package/dist/cjs/money.d.ts +16 -0
- package/dist/cjs/money.js +51 -0
- package/dist/cjs/next.d.ts +81 -0
- package/dist/cjs/next.js +103 -0
- package/dist/cjs/package.json +1 -0
- package/dist/cjs/payments.d.ts +174 -0
- package/dist/cjs/payments.js +485 -0
- package/dist/cjs/resources.d.ts +109 -0
- package/dist/cjs/resources.js +189 -0
- package/dist/cjs/shutdown.d.ts +2 -0
- package/dist/cjs/shutdown.js +51 -0
- package/dist/cjs/transport.d.ts +14 -0
- package/dist/cjs/transport.js +204 -0
- package/dist/cjs/types.d.ts +218 -0
- package/dist/cjs/types.js +2 -0
- package/dist/cjs/user-agent.d.ts +1 -0
- package/dist/cjs/user-agent.js +53 -0
- package/dist/cjs/version.d.ts +2 -0
- package/dist/cjs/version.js +5 -0
- package/dist/cjs/webhooks.d.ts +36 -0
- package/dist/cjs/webhooks.js +108 -0
- package/dist/esm/ads-hashing.d.ts +37 -0
- package/dist/esm/ads-hashing.js +62 -0
- package/dist/esm/click-ids.d.ts +184 -0
- package/dist/esm/click-ids.js +526 -0
- package/dist/esm/client.d.ts +175 -0
- package/dist/esm/client.js +262 -0
- package/dist/esm/config.d.ts +12 -0
- package/dist/esm/config.js +82 -0
- package/dist/esm/core.d.ts +15 -0
- package/dist/esm/core.js +96 -0
- package/dist/esm/enums.d.ts +48 -0
- package/dist/esm/enums.js +44 -0
- package/dist/esm/errors.d.ts +117 -0
- package/dist/esm/errors.js +234 -0
- package/dist/esm/express.d.ts +49 -0
- package/dist/esm/express.js +40 -0
- package/dist/esm/fastify.d.ts +47 -0
- package/dist/esm/fastify.js +32 -0
- package/dist/esm/generated/index.d.ts +17534 -0
- package/dist/esm/generated/index.js +8754 -0
- package/dist/esm/goals.d.ts +116 -0
- package/dist/esm/goals.js +371 -0
- package/dist/esm/guard.d.ts +17 -0
- package/dist/esm/guard.js +36 -0
- package/dist/esm/http.d.ts +16 -0
- package/dist/esm/http.js +138 -0
- package/dist/esm/identity.d.ts +32 -0
- package/dist/esm/identity.js +92 -0
- package/dist/esm/index.d.ts +32 -0
- package/dist/esm/index.js +21 -0
- package/dist/esm/logger.d.ts +9 -0
- package/dist/esm/logger.js +5 -0
- package/dist/esm/money.d.ts +16 -0
- package/dist/esm/money.js +48 -0
- package/dist/esm/next.d.ts +81 -0
- package/dist/esm/next.js +96 -0
- package/dist/esm/package.json +1 -0
- package/dist/esm/payments.d.ts +174 -0
- package/dist/esm/payments.js +476 -0
- package/dist/esm/resources.d.ts +109 -0
- package/dist/esm/resources.js +183 -0
- package/dist/esm/shutdown.d.ts +2 -0
- package/dist/esm/shutdown.js +47 -0
- package/dist/esm/transport.d.ts +14 -0
- package/dist/esm/transport.js +166 -0
- package/dist/esm/types.d.ts +218 -0
- package/dist/esm/types.js +1 -0
- package/dist/esm/user-agent.d.ts +1 -0
- package/dist/esm/user-agent.js +16 -0
- package/dist/esm/version.d.ts +2 -0
- package/dist/esm/version.js +2 -0
- package/dist/esm/webhooks.d.ts +36 -0
- package/dist/esm/webhooks.js +105 -0
- package/package.json +128 -4
|
@@ -0,0 +1,174 @@
|
|
|
1
|
+
import { Provider } from './enums.js';
|
|
2
|
+
import { type RequestOptions } from './http.js';
|
|
3
|
+
import { type MoneyInput } from './money.js';
|
|
4
|
+
/** Normalised payment statuses. */
|
|
5
|
+
export type PaymentStatus = 'success' | 'partial' | 'pending' | 'failed' | 'refunded' | 'reversed';
|
|
6
|
+
/** Parameters of `payments.confirm` (SPEC 22.2): the result of your own server's verification with the gateway. */
|
|
7
|
+
export interface PaymentConfirmParams {
|
|
8
|
+
/**
|
|
9
|
+
* The payment provider, e.g. `Provider.Paystack` (every gateway in `GET /v1/payment-gateways`). A provider key
|
|
10
|
+
* string works too, for a gateway added after this SDK release; the API checks it.
|
|
11
|
+
*/
|
|
12
|
+
provider: Provider | (string & {});
|
|
13
|
+
/** The gateway's canonical payment reference, 1-128 characters. */
|
|
14
|
+
reference: string;
|
|
15
|
+
/** The gateway's verified status, normalised. */
|
|
16
|
+
status: PaymentStatus;
|
|
17
|
+
/** Amount in normal units (`'7500.00'` is ₦7,500). Prefer a decimal string. Not together with `amountMinor`. */
|
|
18
|
+
amount?: MoneyInput | null;
|
|
19
|
+
/** Amount in ISO 4217 minor units, instead of `amount`. */
|
|
20
|
+
amountMinor?: number | bigint | null;
|
|
21
|
+
/** ISO 4217 code (`NGN`, `usd`). */
|
|
22
|
+
currency?: string | null;
|
|
23
|
+
/** When the payment happened (default: now, on the server). */
|
|
24
|
+
occurredAt?: Date | string | null;
|
|
25
|
+
/** Up to 5 other references of the same payment (Stripe `cs_...`, Flutterwave transaction id). */
|
|
26
|
+
aliases?: string[] | null;
|
|
27
|
+
/** The click ID you stored in the gateway metadata (`cg_click_id`), used when no report arrives. */
|
|
28
|
+
clickId?: string | null;
|
|
29
|
+
/** A payment goal key (else the report's goal, else your default payment goal). */
|
|
30
|
+
goal?: string | null;
|
|
31
|
+
/** `true` for a gateway test payment; must match the API key's mode. */
|
|
32
|
+
test?: boolean | null;
|
|
33
|
+
/** Additional wire fields, merged last (forward compatibility). Refused in private mode. */
|
|
34
|
+
extra?: Record<string, unknown>;
|
|
35
|
+
}
|
|
36
|
+
/** Options of the gateway helpers. */
|
|
37
|
+
export interface PaymentHelperOptions {
|
|
38
|
+
/** A payment goal key. */
|
|
39
|
+
goal?: string | null;
|
|
40
|
+
/** A click ID you have yourself; wins over the `cg_click_id` in the gateway metadata. */
|
|
41
|
+
clickId?: string | null;
|
|
42
|
+
}
|
|
43
|
+
/** The wire body of `POST /v1/payments/confirmations`, as the builders return it. */
|
|
44
|
+
export interface PaymentConfirmationBody {
|
|
45
|
+
provider: Provider | (string & {});
|
|
46
|
+
reference: string;
|
|
47
|
+
status: PaymentStatus;
|
|
48
|
+
aliases?: string[];
|
|
49
|
+
amount?: string;
|
|
50
|
+
amount_minor?: number | bigint;
|
|
51
|
+
currency?: string;
|
|
52
|
+
occurred_at?: string;
|
|
53
|
+
test?: boolean;
|
|
54
|
+
click_id?: string;
|
|
55
|
+
goal?: string;
|
|
56
|
+
[key: string]: unknown;
|
|
57
|
+
}
|
|
58
|
+
/** The `payment_confirmation` object. */
|
|
59
|
+
export interface PaymentConfirmation {
|
|
60
|
+
object: 'payment_confirmation';
|
|
61
|
+
id: string;
|
|
62
|
+
/** A `Provider` value (or a newer gateway's key). */
|
|
63
|
+
provider: Provider | (string & {});
|
|
64
|
+
reference: string;
|
|
65
|
+
status: PaymentStatus;
|
|
66
|
+
amount: string | null;
|
|
67
|
+
amount_minor: number | null;
|
|
68
|
+
currency: string | null;
|
|
69
|
+
occurred_at: string;
|
|
70
|
+
route: string;
|
|
71
|
+
match_status: string;
|
|
72
|
+
report_id: string | null;
|
|
73
|
+
goal_event_id: string | null;
|
|
74
|
+
test: boolean;
|
|
75
|
+
duplicate: boolean | null;
|
|
76
|
+
[key: string]: unknown;
|
|
77
|
+
}
|
|
78
|
+
/**
|
|
79
|
+
* Build the confirmation body from a Paystack `GET /transaction/verify/{reference}` response (or its `data`),
|
|
80
|
+
* without sending it. Returns null when there is nothing to send. Reads only the reference, status, amount,
|
|
81
|
+
* currency, time, `domain` and `metadata.cg_click_id`.
|
|
82
|
+
*
|
|
83
|
+
* @example
|
|
84
|
+
* const body = buildFromPaystack(verifyResponse); // { provider: 'paystack', reference, status: 'success', amount: '7500', ... }
|
|
85
|
+
*/
|
|
86
|
+
export declare function buildFromPaystack(response: unknown, options?: PaymentHelperOptions): PaymentConfirmationBody | null;
|
|
87
|
+
/**
|
|
88
|
+
* Build the confirmation body from a Flutterwave v3 verify response (`GET /v3/transactions/{id}/verify` or
|
|
89
|
+
* `verify_by_reference`, or its `data`), without sending it. Returns null when there is nothing to send.
|
|
90
|
+
*
|
|
91
|
+
* @example
|
|
92
|
+
* const body = buildFromFlutterwave(verifyResponse);
|
|
93
|
+
*/
|
|
94
|
+
export declare function buildFromFlutterwave(response: unknown, options?: PaymentHelperOptions): PaymentConfirmationBody | null;
|
|
95
|
+
/**
|
|
96
|
+
* Build the confirmation body from a Monnify transaction status response (`GET /api/v2/transactions/{ref}` or
|
|
97
|
+
* the `query?paymentReference=` call, or its `responseBody`; a webhook's `eventData` works too), without sending it.
|
|
98
|
+
* Returns null when there is nothing to send.
|
|
99
|
+
*
|
|
100
|
+
* @example
|
|
101
|
+
* const body = buildFromMonnify(statusResponse);
|
|
102
|
+
*/
|
|
103
|
+
export declare function buildFromMonnify(response: unknown, options?: PaymentHelperOptions): PaymentConfirmationBody | null;
|
|
104
|
+
/**
|
|
105
|
+
* Build the confirmation body from a Stripe PaymentIntent (`pi_...`) or Checkout Session (`cs_...`) object,
|
|
106
|
+
* without sending it. Returns null when there is nothing to send (for example a session with
|
|
107
|
+
* `payment_status: 'no_payment_required'`).
|
|
108
|
+
*
|
|
109
|
+
* @example
|
|
110
|
+
* const body = buildFromStripe(paymentIntent);
|
|
111
|
+
*/
|
|
112
|
+
export declare function buildFromStripe(object: unknown, options?: PaymentHelperOptions): PaymentConfirmationBody | null;
|
|
113
|
+
/**
|
|
114
|
+
* Payments confirmed by your server. Call these **right after your own server has verified the payment with the
|
|
115
|
+
* gateway**, never with data from the browser or the app. Clikgate matches the confirmation with the Payment goal
|
|
116
|
+
* your website or app reported (`clikgate.goal('order_paid', { provider, reference })`) and counts it with the
|
|
117
|
+
* confirmed amount. Never pass a gateway key: these methods only talk to Clikgate.
|
|
118
|
+
*/
|
|
119
|
+
export declare class Payments {
|
|
120
|
+
private readonly core;
|
|
121
|
+
/**
|
|
122
|
+
* Confirm a payment your server has verified (`POST /v1/payments/confirmations`). Also for refunds
|
|
123
|
+
* (`status: 'refunded'`, `amount` = the refunded amount).
|
|
124
|
+
*
|
|
125
|
+
* @example
|
|
126
|
+
* // after your own verification with the gateway:
|
|
127
|
+
* await clikgate.payments.confirm({ provider: Provider.Paystack, reference: 'T_ref_001', status: 'success', amount: '7500.00', currency: 'NGN' });
|
|
128
|
+
*/
|
|
129
|
+
confirm(params: PaymentConfirmParams, requestOptions?: RequestOptions): Promise<PaymentConfirmation>;
|
|
130
|
+
private send;
|
|
131
|
+
/**
|
|
132
|
+
* Send a Paystack verify response, right after your own `GET /transaction/verify/{reference}` call.
|
|
133
|
+
* Only the reference, status, amount (÷ 100), currency, time, test flag and `metadata.cg_click_id` are sent.
|
|
134
|
+
* Returns null when there is nothing to send.
|
|
135
|
+
*
|
|
136
|
+
* @example
|
|
137
|
+
* const verify = await paystack.get(`/transaction/verify/${reference}`); // your own call, with your key
|
|
138
|
+
* await clikgate.payments.fromPaystack(verify, { goal: 'order_paid' });
|
|
139
|
+
*/
|
|
140
|
+
fromPaystack(response: unknown, options?: PaymentHelperOptions, requestOptions?: RequestOptions): Promise<PaymentConfirmation | null>;
|
|
141
|
+
/**
|
|
142
|
+
* Send a Flutterwave verify response, right after your own `GET /v3/transactions/{id}/verify` call.
|
|
143
|
+
*
|
|
144
|
+
* @example
|
|
145
|
+
* const verify = await flutterwave.get(`/v3/transactions/${id}/verify`);
|
|
146
|
+
* await clikgate.payments.fromFlutterwave(verify);
|
|
147
|
+
*/
|
|
148
|
+
fromFlutterwave(response: unknown, options?: PaymentHelperOptions, requestOptions?: RequestOptions): Promise<PaymentConfirmation | null>;
|
|
149
|
+
/**
|
|
150
|
+
* Send a Monnify transaction status response, right after your own `GET /api/v2/transactions/{ref}` call.
|
|
151
|
+
*
|
|
152
|
+
* @example
|
|
153
|
+
* const status = await monnify.get(`/api/v2/transactions/${encodeURIComponent(transactionReference)}`);
|
|
154
|
+
* await clikgate.payments.fromMonnify(status);
|
|
155
|
+
*/
|
|
156
|
+
fromMonnify(response: unknown, options?: PaymentHelperOptions, requestOptions?: RequestOptions): Promise<PaymentConfirmation | null>;
|
|
157
|
+
/**
|
|
158
|
+
* Send a Stripe PaymentIntent or Checkout Session you have retrieved or received in a webhook you verified.
|
|
159
|
+
* A session with `no_payment_required` sends nothing and returns null.
|
|
160
|
+
*
|
|
161
|
+
* @example
|
|
162
|
+
* const intent = await stripe.paymentIntents.retrieve(id);
|
|
163
|
+
* await clikgate.payments.fromStripe(intent);
|
|
164
|
+
*/
|
|
165
|
+
fromStripe(object: unknown, options?: PaymentHelperOptions, requestOptions?: RequestOptions): Promise<PaymentConfirmation | null>;
|
|
166
|
+
/** {@inheritDoc buildFromPaystack} */
|
|
167
|
+
buildFromPaystack(response: unknown, options?: PaymentHelperOptions): PaymentConfirmationBody | null;
|
|
168
|
+
/** {@inheritDoc buildFromFlutterwave} */
|
|
169
|
+
buildFromFlutterwave(response: unknown, options?: PaymentHelperOptions): PaymentConfirmationBody | null;
|
|
170
|
+
/** {@inheritDoc buildFromMonnify} */
|
|
171
|
+
buildFromMonnify(response: unknown, options?: PaymentHelperOptions): PaymentConfirmationBody | null;
|
|
172
|
+
/** {@inheritDoc buildFromStripe} */
|
|
173
|
+
buildFromStripe(object: unknown, options?: PaymentHelperOptions): PaymentConfirmationBody | null;
|
|
174
|
+
}
|
|
@@ -0,0 +1,485 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.Payments = void 0;
|
|
4
|
+
exports.buildFromPaystack = buildFromPaystack;
|
|
5
|
+
exports.buildFromFlutterwave = buildFromFlutterwave;
|
|
6
|
+
exports.buildFromMonnify = buildFromMonnify;
|
|
7
|
+
exports.buildFromStripe = buildFromStripe;
|
|
8
|
+
exports.buildConfirmWire = buildConfirmWire;
|
|
9
|
+
const click_ids_js_1 = require("./click-ids.js");
|
|
10
|
+
const enums_js_1 = require("./enums.js");
|
|
11
|
+
const errors_js_1 = require("./errors.js");
|
|
12
|
+
const guard_js_1 = require("./guard.js");
|
|
13
|
+
const http_js_1 = require("./http.js");
|
|
14
|
+
const money_js_1 = require("./money.js");
|
|
15
|
+
const PROVIDER = /^[a-z][a-z0-9_]{1,29}$/;
|
|
16
|
+
const GOAL_KEY = /^[a-z][a-z0-9_]{1,39}$/;
|
|
17
|
+
const CURRENCY = /^[A-Za-z]{3}$/;
|
|
18
|
+
const STATUSES = new Set(['success', 'partial', 'pending', 'failed', 'refunded', 'reversed']);
|
|
19
|
+
const STRIPE_ZERO_DECIMAL = new Set(['BIF', 'CLP', 'DJF', 'GNF', 'JPY', 'KMF', 'KRW', 'MGA', 'PYG', 'RWF', 'VND', 'VUV', 'XAF', 'XOF', 'XPF']);
|
|
20
|
+
const PAYSTACK_STATUS = {
|
|
21
|
+
success: 'success',
|
|
22
|
+
failed: 'failed',
|
|
23
|
+
abandoned: 'failed',
|
|
24
|
+
reversed: 'reversed',
|
|
25
|
+
ongoing: 'pending',
|
|
26
|
+
pending: 'pending',
|
|
27
|
+
processing: 'pending',
|
|
28
|
+
queued: 'pending',
|
|
29
|
+
};
|
|
30
|
+
const MONNIFY_STATUS = {
|
|
31
|
+
PAID: 'success',
|
|
32
|
+
OVERPAID: 'success',
|
|
33
|
+
PARTIALLY_PAID: 'partial',
|
|
34
|
+
FAILED: 'failed',
|
|
35
|
+
CANCELLED: 'failed',
|
|
36
|
+
ABANDONED: 'failed',
|
|
37
|
+
EXPIRED: 'failed',
|
|
38
|
+
PENDING: 'pending',
|
|
39
|
+
REVERSED: 'reversed',
|
|
40
|
+
};
|
|
41
|
+
function isObj(v) {
|
|
42
|
+
return typeof v === 'object' && v !== null && !Array.isArray(v);
|
|
43
|
+
}
|
|
44
|
+
/** An object, or JSON text of one; else null. */
|
|
45
|
+
function asObj(v) {
|
|
46
|
+
if (typeof v === 'string') {
|
|
47
|
+
try {
|
|
48
|
+
v = JSON.parse(v);
|
|
49
|
+
}
|
|
50
|
+
catch {
|
|
51
|
+
return null;
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
return isObj(v) ? v : null;
|
|
55
|
+
}
|
|
56
|
+
function unwrap(root, key) {
|
|
57
|
+
const inner = root[key];
|
|
58
|
+
return isObj(inner) ? inner : root;
|
|
59
|
+
}
|
|
60
|
+
/** A trimmed string; numbers as their digits; empty or anything else is null. */
|
|
61
|
+
function str(v) {
|
|
62
|
+
if (typeof v === 'string') {
|
|
63
|
+
const t = v.trim();
|
|
64
|
+
return t === '' ? null : t;
|
|
65
|
+
}
|
|
66
|
+
if (typeof v === 'bigint')
|
|
67
|
+
return v.toString();
|
|
68
|
+
if (typeof v === 'number' && Number.isFinite(v))
|
|
69
|
+
return Number.isInteger(v) ? BigInt(v).toString() : String(v);
|
|
70
|
+
return null;
|
|
71
|
+
}
|
|
72
|
+
function first(...vs) {
|
|
73
|
+
for (const v of vs)
|
|
74
|
+
if (v !== undefined && v !== null && v !== '')
|
|
75
|
+
return v;
|
|
76
|
+
return undefined;
|
|
77
|
+
}
|
|
78
|
+
const DEC_TEXT = /^([+-]?)(\d+\.?\d*|\.\d+)(?:[eE]([+-]?\d+))?$/;
|
|
79
|
+
/** Parse an amount (integer, decimal string, float via its shortest round-trip text). Null when absent, unparsable or negative. */
|
|
80
|
+
function parseDec(v) {
|
|
81
|
+
let text;
|
|
82
|
+
if (typeof v === 'string')
|
|
83
|
+
text = v.trim();
|
|
84
|
+
else if (typeof v === 'bigint')
|
|
85
|
+
text = v.toString();
|
|
86
|
+
else if (typeof v === 'number' && Number.isFinite(v))
|
|
87
|
+
text = String(v);
|
|
88
|
+
else
|
|
89
|
+
return null;
|
|
90
|
+
const m = DEC_TEXT.exec(text);
|
|
91
|
+
if (!m)
|
|
92
|
+
return null;
|
|
93
|
+
const [int = '', frac = ''] = m[2].split('.');
|
|
94
|
+
let digits = `${int}${frac}`.replace(/^0+/, '');
|
|
95
|
+
let scale = frac.length - Number(m[3] ?? 0);
|
|
96
|
+
if (digits === '')
|
|
97
|
+
return { digits: '0', scale: 0 };
|
|
98
|
+
if (m[1] === '-')
|
|
99
|
+
return null;
|
|
100
|
+
if (scale < 0) {
|
|
101
|
+
digits += '0'.repeat(-scale);
|
|
102
|
+
scale = 0;
|
|
103
|
+
}
|
|
104
|
+
return { digits, scale };
|
|
105
|
+
}
|
|
106
|
+
/** The shortest exact decimal text: no exponent, no trailing fractional zeros. */
|
|
107
|
+
function formatDec(d, shift = 0) {
|
|
108
|
+
let { digits } = d;
|
|
109
|
+
let scale = d.scale + shift;
|
|
110
|
+
while (scale > 0 && digits.endsWith('0')) {
|
|
111
|
+
digits = digits.slice(0, -1);
|
|
112
|
+
scale -= 1;
|
|
113
|
+
}
|
|
114
|
+
if (digits === '' || /^0+$/.test(digits))
|
|
115
|
+
return '0';
|
|
116
|
+
if (scale === 0)
|
|
117
|
+
return digits;
|
|
118
|
+
const padded = digits.padStart(scale + 1, '0');
|
|
119
|
+
return `${padded.slice(0, -scale)}.${padded.slice(-scale)}`;
|
|
120
|
+
}
|
|
121
|
+
function amountText(v, shift = 0) {
|
|
122
|
+
const d = parseDec(v);
|
|
123
|
+
return d === null ? undefined : formatDec(d, shift);
|
|
124
|
+
}
|
|
125
|
+
// ---- times ---------------------------------------------------------------------------------------
|
|
126
|
+
const ISO = /^(\d{4})-(\d{2})-(\d{2})[T ](\d{2}):(\d{2})(?::(\d{2})(?:\.(\d+))?)?(Z|[+-]\d{2}:?\d{2})?$/i;
|
|
127
|
+
/** Unix seconds (milliseconds above 10^11) or ISO 8601 text → RFC 3339 UTC; anything else is omitted. */
|
|
128
|
+
function timeText(v) {
|
|
129
|
+
if (typeof v === 'number' && Number.isFinite(v)) {
|
|
130
|
+
const ms = Math.trunc(v > 1e11 ? v : v * 1000);
|
|
131
|
+
return (0, http_js_1.formatDate)(new Date(ms));
|
|
132
|
+
}
|
|
133
|
+
if (typeof v !== 'string')
|
|
134
|
+
return undefined;
|
|
135
|
+
const m = ISO.exec(v.trim());
|
|
136
|
+
if (!m)
|
|
137
|
+
return undefined;
|
|
138
|
+
const [y, mo, d, h, mi, s] = [m[1], m[2], m[3], m[4], m[5], m[6] ?? '0'].map(Number);
|
|
139
|
+
if (mo < 1 || mo > 12 || d < 1 || d > 31 || h > 23 || mi > 59 || s > 59)
|
|
140
|
+
return undefined;
|
|
141
|
+
const ms = Number((m[7] ?? '').slice(0, 3).padEnd(3, '0'));
|
|
142
|
+
let offsetMin = 0;
|
|
143
|
+
const zone = m[8];
|
|
144
|
+
if (zone && zone.toUpperCase() !== 'Z') {
|
|
145
|
+
const z = zone.replace(':', '');
|
|
146
|
+
offsetMin = (z[0] === '-' ? -1 : 1) * (Number(z.slice(1, 3)) * 60 + Number(z.slice(3, 5)));
|
|
147
|
+
}
|
|
148
|
+
const t = Date.UTC(y, mo - 1, d, h, mi, s, ms) - offsetMin * 60_000;
|
|
149
|
+
return Number.isFinite(t) ? (0, http_js_1.formatDate)(new Date(t)) : undefined;
|
|
150
|
+
}
|
|
151
|
+
function metadataClick(meta) {
|
|
152
|
+
const m = asObj(meta);
|
|
153
|
+
const id = m?.cg_click_id;
|
|
154
|
+
return (0, click_ids_js_1.isValid)(id) ? id : undefined;
|
|
155
|
+
}
|
|
156
|
+
function aliasList(reference, ...vs) {
|
|
157
|
+
const out = [];
|
|
158
|
+
for (const v of vs) {
|
|
159
|
+
const a = str(v);
|
|
160
|
+
if (a !== null && a !== reference && !out.includes(a))
|
|
161
|
+
out.push(a);
|
|
162
|
+
}
|
|
163
|
+
return out.length ? out.slice(0, 5) : undefined;
|
|
164
|
+
}
|
|
165
|
+
function finish(body, options) {
|
|
166
|
+
if (options?.clickId != null)
|
|
167
|
+
body.click_id = options.clickId;
|
|
168
|
+
if (options?.goal != null)
|
|
169
|
+
body.goal = options.goal;
|
|
170
|
+
const out = {};
|
|
171
|
+
for (const [k, v] of Object.entries(body))
|
|
172
|
+
if (v !== undefined && v !== null)
|
|
173
|
+
out[k] = v;
|
|
174
|
+
return out;
|
|
175
|
+
}
|
|
176
|
+
function currencyText(v) {
|
|
177
|
+
return str(v)?.toUpperCase() ?? undefined;
|
|
178
|
+
}
|
|
179
|
+
// ---- the builders (pure) -------------------------------------------------------------------------
|
|
180
|
+
/**
|
|
181
|
+
* Build the confirmation body from a Paystack `GET /transaction/verify/{reference}` response (or its `data`),
|
|
182
|
+
* without sending it. Returns null when there is nothing to send. Reads only the reference, status, amount,
|
|
183
|
+
* currency, time, `domain` and `metadata.cg_click_id`.
|
|
184
|
+
*
|
|
185
|
+
* @example
|
|
186
|
+
* const body = buildFromPaystack(verifyResponse); // { provider: 'paystack', reference, status: 'success', amount: '7500', ... }
|
|
187
|
+
*/
|
|
188
|
+
function buildFromPaystack(response, options) {
|
|
189
|
+
const root = asObj(response);
|
|
190
|
+
if (!root)
|
|
191
|
+
return null;
|
|
192
|
+
const d = unwrap(root, 'data');
|
|
193
|
+
const reference = str(d.reference);
|
|
194
|
+
const status = typeof d.status === 'string' ? PAYSTACK_STATUS[d.status.trim().toLowerCase()] : undefined;
|
|
195
|
+
if (reference === null || !status)
|
|
196
|
+
return null;
|
|
197
|
+
const domain = str(d.domain);
|
|
198
|
+
return finish({
|
|
199
|
+
provider: enums_js_1.Provider.Paystack,
|
|
200
|
+
reference,
|
|
201
|
+
status,
|
|
202
|
+
amount: amountText(d.amount, 2),
|
|
203
|
+
currency: currencyText(d.currency),
|
|
204
|
+
occurred_at: timeText(first(d.paid_at, d.paidAt, d.created_at)),
|
|
205
|
+
test: domain === null ? undefined : domain.toLowerCase() === 'test',
|
|
206
|
+
click_id: metadataClick(d.metadata),
|
|
207
|
+
}, options);
|
|
208
|
+
}
|
|
209
|
+
/**
|
|
210
|
+
* Build the confirmation body from a Flutterwave v3 verify response (`GET /v3/transactions/{id}/verify` or
|
|
211
|
+
* `verify_by_reference`, or its `data`), without sending it. Returns null when there is nothing to send.
|
|
212
|
+
*
|
|
213
|
+
* @example
|
|
214
|
+
* const body = buildFromFlutterwave(verifyResponse);
|
|
215
|
+
*/
|
|
216
|
+
function buildFromFlutterwave(response, options) {
|
|
217
|
+
const root = asObj(response);
|
|
218
|
+
if (!root)
|
|
219
|
+
return null;
|
|
220
|
+
const d = unwrap(root, 'data');
|
|
221
|
+
const reference = str(d.tx_ref) ?? str(d.reference);
|
|
222
|
+
if (reference === null)
|
|
223
|
+
return null;
|
|
224
|
+
const raw = typeof d.status === 'string' ? d.status.trim().toLowerCase() : '';
|
|
225
|
+
const status = raw === 'successful' || raw === 'succeeded' ? 'success' : raw === 'failed' || raw === 'voided' ? 'failed' : 'pending';
|
|
226
|
+
return finish({
|
|
227
|
+
provider: enums_js_1.Provider.Flutterwave,
|
|
228
|
+
reference,
|
|
229
|
+
aliases: aliasList(reference, d.id, d.flw_ref),
|
|
230
|
+
status,
|
|
231
|
+
amount: amountText(d.amount),
|
|
232
|
+
currency: currencyText(d.currency),
|
|
233
|
+
occurred_at: timeText(first(d.created_at, d.created_datetime)),
|
|
234
|
+
click_id: metadataClick(d.meta) ?? metadataClick(d.meta_data),
|
|
235
|
+
}, options);
|
|
236
|
+
}
|
|
237
|
+
/**
|
|
238
|
+
* Build the confirmation body from a Monnify transaction status response (`GET /api/v2/transactions/{ref}` or
|
|
239
|
+
* the `query?paymentReference=` call, or its `responseBody`; a webhook's `eventData` works too), without sending it.
|
|
240
|
+
* Returns null when there is nothing to send.
|
|
241
|
+
*
|
|
242
|
+
* @example
|
|
243
|
+
* const body = buildFromMonnify(statusResponse);
|
|
244
|
+
*/
|
|
245
|
+
function buildFromMonnify(response, options) {
|
|
246
|
+
const root = asObj(response);
|
|
247
|
+
if (!root)
|
|
248
|
+
return null;
|
|
249
|
+
const d = unwrap(unwrap(root, 'responseBody'), 'eventData');
|
|
250
|
+
const reference = str(d.paymentReference);
|
|
251
|
+
const status = typeof d.paymentStatus === 'string' ? MONNIFY_STATUS[d.paymentStatus.trim().toUpperCase()] : undefined;
|
|
252
|
+
if (reference === null || !status)
|
|
253
|
+
return null;
|
|
254
|
+
return finish({
|
|
255
|
+
provider: enums_js_1.Provider.Monnify,
|
|
256
|
+
reference,
|
|
257
|
+
aliases: aliasList(reference, d.transactionReference),
|
|
258
|
+
status,
|
|
259
|
+
amount: amountText(d.amountPaid),
|
|
260
|
+
currency: currencyText(first(d.currency, d.currencyCode)),
|
|
261
|
+
occurred_at: timeText(d.paidOn),
|
|
262
|
+
click_id: metadataClick(d.metaData),
|
|
263
|
+
}, options);
|
|
264
|
+
}
|
|
265
|
+
const STRIPE_PI_STATUS = { succeeded: 'success', canceled: 'failed', processing: 'pending' };
|
|
266
|
+
/**
|
|
267
|
+
* Build the confirmation body from a Stripe PaymentIntent (`pi_...`) or Checkout Session (`cs_...`) object,
|
|
268
|
+
* without sending it. Returns null when there is nothing to send (for example a session with
|
|
269
|
+
* `payment_status: 'no_payment_required'`).
|
|
270
|
+
*
|
|
271
|
+
* @example
|
|
272
|
+
* const body = buildFromStripe(paymentIntent);
|
|
273
|
+
*/
|
|
274
|
+
function buildFromStripe(object, options) {
|
|
275
|
+
const o = asObj(object);
|
|
276
|
+
if (!o)
|
|
277
|
+
return null;
|
|
278
|
+
const currency = currencyText(o.currency);
|
|
279
|
+
const shift = currency !== undefined && STRIPE_ZERO_DECIMAL.has(currency) ? 0 : 2;
|
|
280
|
+
const common = {
|
|
281
|
+
currency,
|
|
282
|
+
occurred_at: timeText(o.created),
|
|
283
|
+
test: typeof o.livemode === 'boolean' ? !o.livemode : undefined,
|
|
284
|
+
click_id: metadataClick(o.metadata),
|
|
285
|
+
};
|
|
286
|
+
if (o.object === 'payment_intent') {
|
|
287
|
+
const raw = typeof o.status === 'string' ? o.status.trim().toLowerCase() : '';
|
|
288
|
+
const status = STRIPE_PI_STATUS[raw] ?? (raw.startsWith('requires_') ? 'pending' : undefined);
|
|
289
|
+
const reference = str(o.id);
|
|
290
|
+
if (!status || reference === null)
|
|
291
|
+
return null;
|
|
292
|
+
const received = parseDec(o.amount_received);
|
|
293
|
+
const amount = received !== null && received.digits !== '0' ? o.amount_received : o.amount;
|
|
294
|
+
return finish({ provider: enums_js_1.Provider.Stripe, reference, status, amount: amountText(amount, shift), ...common }, options);
|
|
295
|
+
}
|
|
296
|
+
if (o.object === 'checkout.session') {
|
|
297
|
+
const paymentStatus = typeof o.payment_status === 'string' ? o.payment_status.trim().toLowerCase() : '';
|
|
298
|
+
if (paymentStatus === 'no_payment_required')
|
|
299
|
+
return null;
|
|
300
|
+
const status = paymentStatus === 'paid' ? 'success' : o.status === 'expired' ? 'failed' : 'pending';
|
|
301
|
+
const sessionId = str(o.id);
|
|
302
|
+
const intent = o.payment_intent;
|
|
303
|
+
const reference = str(isObj(intent) ? intent.id : intent) ?? sessionId;
|
|
304
|
+
if (reference === null)
|
|
305
|
+
return null;
|
|
306
|
+
return finish({ provider: enums_js_1.Provider.Stripe, reference, aliases: aliasList(reference, sessionId, o.client_reference_id), status, amount: amountText(o.amount_total, shift), ...common }, options);
|
|
307
|
+
}
|
|
308
|
+
return null;
|
|
309
|
+
}
|
|
310
|
+
// ---- confirm: validation and sending -------------------------------------------------------------
|
|
311
|
+
function isInteger(v) {
|
|
312
|
+
return typeof v === 'bigint' || (typeof v === 'number' && Number.isSafeInteger(v));
|
|
313
|
+
}
|
|
314
|
+
/** @internal Validate `confirm` params and build the wire body (SPEC 22.2). */
|
|
315
|
+
function buildConfirmWire(core, p) {
|
|
316
|
+
const params = (p ?? {});
|
|
317
|
+
if (typeof params.provider !== 'string' || !PROVIDER.test(params.provider)) {
|
|
318
|
+
throw (0, errors_js_1.localError)('invalid_provider', 'provider must be a provider key such as "paystack" or "stripe" (lower case).', 'provider');
|
|
319
|
+
}
|
|
320
|
+
if (typeof params.reference !== 'string' || params.reference.length < 1 || params.reference.length > 128) {
|
|
321
|
+
throw (0, errors_js_1.localError)('invalid_reference', "reference is required: the gateway's payment reference, 1-128 characters.", 'reference');
|
|
322
|
+
}
|
|
323
|
+
if (typeof params.status !== 'string' || !STATUSES.has(params.status)) {
|
|
324
|
+
throw (0, errors_js_1.localError)('invalid_status', 'status must be success, partial, pending, failed, refunded or reversed.', 'status');
|
|
325
|
+
}
|
|
326
|
+
const hasAmount = params.amount !== undefined && params.amount !== null;
|
|
327
|
+
const hasMinor = params.amountMinor !== undefined && params.amountMinor !== null;
|
|
328
|
+
if (hasAmount && hasMinor)
|
|
329
|
+
throw (0, errors_js_1.localError)('amount_and_amount_minor', 'Send either amount or amountMinor, not both.', 'amount');
|
|
330
|
+
let amount;
|
|
331
|
+
if (hasAmount) {
|
|
332
|
+
try {
|
|
333
|
+
amount = (0, money_js_1.formatValue)(params.amount, (m) => core?.warn('inexact_number', m));
|
|
334
|
+
}
|
|
335
|
+
catch (err) {
|
|
336
|
+
if (err instanceof errors_js_1.ClikgateError)
|
|
337
|
+
throw (0, errors_js_1.localError)('invalid_amount', "amount must be a non-negative decimal in normal units, like '7500.00'.", 'amount');
|
|
338
|
+
throw err;
|
|
339
|
+
}
|
|
340
|
+
}
|
|
341
|
+
if (hasMinor && (!isInteger(params.amountMinor) || params.amountMinor < 0)) {
|
|
342
|
+
throw (0, errors_js_1.localError)('invalid_amount', 'amountMinor must be a non-negative integer (ISO 4217 minor units).', 'amount_minor');
|
|
343
|
+
}
|
|
344
|
+
if (params.currency != null && (typeof params.currency !== 'string' || !CURRENCY.test(params.currency))) {
|
|
345
|
+
throw (0, errors_js_1.localError)('invalid_currency', 'currency must be an ISO 4217 code such as NGN or USD.', 'currency');
|
|
346
|
+
}
|
|
347
|
+
if (params.aliases != null && (!Array.isArray(params.aliases) || params.aliases.length > 5 || params.aliases.some((a) => typeof a !== 'string'))) {
|
|
348
|
+
throw (0, errors_js_1.localError)('invalid_aliases', 'aliases must be a list of at most 5 strings.', 'aliases');
|
|
349
|
+
}
|
|
350
|
+
if (params.goal != null && (typeof params.goal !== 'string' || !GOAL_KEY.test(params.goal))) {
|
|
351
|
+
throw (0, errors_js_1.localError)('invalid_goal_key', 'goal must be a goal key: snake_case, 2-40 characters.', 'goal');
|
|
352
|
+
}
|
|
353
|
+
const wire = {
|
|
354
|
+
provider: params.provider,
|
|
355
|
+
reference: params.reference,
|
|
356
|
+
status: params.status,
|
|
357
|
+
amount,
|
|
358
|
+
amount_minor: hasMinor ? params.amountMinor : undefined,
|
|
359
|
+
currency: params.currency,
|
|
360
|
+
occurred_at: params.occurredAt == null ? undefined : (0, http_js_1.formatDate)(params.occurredAt),
|
|
361
|
+
aliases: params.aliases && params.aliases.length > 0 ? params.aliases : undefined,
|
|
362
|
+
click_id: params.clickId,
|
|
363
|
+
goal: params.goal,
|
|
364
|
+
test: params.test,
|
|
365
|
+
...(params.extra ?? {}),
|
|
366
|
+
};
|
|
367
|
+
const out = {};
|
|
368
|
+
for (const [k, v] of Object.entries(wire))
|
|
369
|
+
if (v !== undefined && v !== null)
|
|
370
|
+
out[k] = v;
|
|
371
|
+
return out;
|
|
372
|
+
}
|
|
373
|
+
function bodyToParams(body) {
|
|
374
|
+
return {
|
|
375
|
+
provider: body.provider,
|
|
376
|
+
reference: body.reference,
|
|
377
|
+
status: body.status,
|
|
378
|
+
amount: body.amount,
|
|
379
|
+
currency: body.currency,
|
|
380
|
+
occurredAt: body.occurred_at,
|
|
381
|
+
aliases: body.aliases,
|
|
382
|
+
clickId: body.click_id,
|
|
383
|
+
goal: body.goal,
|
|
384
|
+
test: body.test,
|
|
385
|
+
};
|
|
386
|
+
}
|
|
387
|
+
/**
|
|
388
|
+
* Payments confirmed by your server. Call these **right after your own server has verified the payment with the
|
|
389
|
+
* gateway**, never with data from the browser or the app. Clikgate matches the confirmation with the Payment goal
|
|
390
|
+
* your website or app reported (`clikgate.goal('order_paid', { provider, reference })`) and counts it with the
|
|
391
|
+
* confirmed amount. Never pass a gateway key: these methods only talk to Clikgate.
|
|
392
|
+
*/
|
|
393
|
+
class Payments {
|
|
394
|
+
core;
|
|
395
|
+
/** @internal */
|
|
396
|
+
constructor(core) {
|
|
397
|
+
this.core = core;
|
|
398
|
+
}
|
|
399
|
+
/**
|
|
400
|
+
* Confirm a payment your server has verified (`POST /v1/payments/confirmations`). Also for refunds
|
|
401
|
+
* (`status: 'refunded'`, `amount` = the refunded amount).
|
|
402
|
+
*
|
|
403
|
+
* @example
|
|
404
|
+
* // after your own verification with the gateway:
|
|
405
|
+
* await clikgate.payments.confirm({ provider: Provider.Paystack, reference: 'T_ref_001', status: 'success', amount: '7500.00', currency: 'NGN' });
|
|
406
|
+
*/
|
|
407
|
+
async confirm(params, requestOptions = {}) {
|
|
408
|
+
const body = buildConfirmWire(this.core, params);
|
|
409
|
+
const state = await this.core.guardState();
|
|
410
|
+
if (state.guard)
|
|
411
|
+
(0, guard_js_1.guardPayload)('payment_confirmation', body);
|
|
412
|
+
const { data } = await this.core.requester.request({ method: 'POST', path: '/v1/payments/confirmations', body, ...requestOptions });
|
|
413
|
+
return data;
|
|
414
|
+
}
|
|
415
|
+
async send(body, gateway, quiet = false, requestOptions = {}) {
|
|
416
|
+
if (body === null) {
|
|
417
|
+
if (!quiet)
|
|
418
|
+
this.core.warn('unrecognised_payment_response', `The ${gateway} response has no reference or no status the helper knows; nothing was sent to Clikgate.`);
|
|
419
|
+
return null;
|
|
420
|
+
}
|
|
421
|
+
return this.confirm(bodyToParams(body), requestOptions);
|
|
422
|
+
}
|
|
423
|
+
/**
|
|
424
|
+
* Send a Paystack verify response, right after your own `GET /transaction/verify/{reference}` call.
|
|
425
|
+
* Only the reference, status, amount (÷ 100), currency, time, test flag and `metadata.cg_click_id` are sent.
|
|
426
|
+
* Returns null when there is nothing to send.
|
|
427
|
+
*
|
|
428
|
+
* @example
|
|
429
|
+
* const verify = await paystack.get(`/transaction/verify/${reference}`); // your own call, with your key
|
|
430
|
+
* await clikgate.payments.fromPaystack(verify, { goal: 'order_paid' });
|
|
431
|
+
*/
|
|
432
|
+
fromPaystack(response, options, requestOptions) {
|
|
433
|
+
return this.send(buildFromPaystack(response, options), 'Paystack', false, requestOptions);
|
|
434
|
+
}
|
|
435
|
+
/**
|
|
436
|
+
* Send a Flutterwave verify response, right after your own `GET /v3/transactions/{id}/verify` call.
|
|
437
|
+
*
|
|
438
|
+
* @example
|
|
439
|
+
* const verify = await flutterwave.get(`/v3/transactions/${id}/verify`);
|
|
440
|
+
* await clikgate.payments.fromFlutterwave(verify);
|
|
441
|
+
*/
|
|
442
|
+
fromFlutterwave(response, options, requestOptions) {
|
|
443
|
+
return this.send(buildFromFlutterwave(response, options), 'Flutterwave', false, requestOptions);
|
|
444
|
+
}
|
|
445
|
+
/**
|
|
446
|
+
* Send a Monnify transaction status response, right after your own `GET /api/v2/transactions/{ref}` call.
|
|
447
|
+
*
|
|
448
|
+
* @example
|
|
449
|
+
* const status = await monnify.get(`/api/v2/transactions/${encodeURIComponent(transactionReference)}`);
|
|
450
|
+
* await clikgate.payments.fromMonnify(status);
|
|
451
|
+
*/
|
|
452
|
+
fromMonnify(response, options, requestOptions) {
|
|
453
|
+
return this.send(buildFromMonnify(response, options), 'Monnify', false, requestOptions);
|
|
454
|
+
}
|
|
455
|
+
/**
|
|
456
|
+
* Send a Stripe PaymentIntent or Checkout Session you have retrieved or received in a webhook you verified.
|
|
457
|
+
* A session with `no_payment_required` sends nothing and returns null.
|
|
458
|
+
*
|
|
459
|
+
* @example
|
|
460
|
+
* const intent = await stripe.paymentIntents.retrieve(id);
|
|
461
|
+
* await clikgate.payments.fromStripe(intent);
|
|
462
|
+
*/
|
|
463
|
+
fromStripe(object, options, requestOptions) {
|
|
464
|
+
const o = asObj(object);
|
|
465
|
+
const quiet = o?.object === 'checkout.session' && typeof o.payment_status === 'string' && o.payment_status.trim().toLowerCase() === 'no_payment_required';
|
|
466
|
+
return this.send(buildFromStripe(object, options), 'Stripe', quiet, requestOptions);
|
|
467
|
+
}
|
|
468
|
+
/** {@inheritDoc buildFromPaystack} */
|
|
469
|
+
buildFromPaystack(response, options) {
|
|
470
|
+
return buildFromPaystack(response, options);
|
|
471
|
+
}
|
|
472
|
+
/** {@inheritDoc buildFromFlutterwave} */
|
|
473
|
+
buildFromFlutterwave(response, options) {
|
|
474
|
+
return buildFromFlutterwave(response, options);
|
|
475
|
+
}
|
|
476
|
+
/** {@inheritDoc buildFromMonnify} */
|
|
477
|
+
buildFromMonnify(response, options) {
|
|
478
|
+
return buildFromMonnify(response, options);
|
|
479
|
+
}
|
|
480
|
+
/** {@inheritDoc buildFromStripe} */
|
|
481
|
+
buildFromStripe(object, options) {
|
|
482
|
+
return buildFromStripe(object, options);
|
|
483
|
+
}
|
|
484
|
+
}
|
|
485
|
+
exports.Payments = Payments;
|