@clikgate/node 0.0.0-stage → 2.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +136 -0
- package/LICENSE +21 -0
- package/README.md +311 -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 +191 -0
- package/dist/cjs/client.js +291 -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/customer-id.d.ts +26 -0
- package/dist/cjs/customer-id.js +52 -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 +17793 -0
- package/dist/cjs/generated/index.js +8896 -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 +42 -0
- package/dist/cjs/identity.js +133 -0
- package/dist/cjs/index.d.ts +34 -0
- package/dist/cjs/index.js +70 -0
- package/dist/cjs/known-customers.d.ts +45 -0
- package/dist/cjs/known-customers.js +95 -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 +191 -0
- package/dist/esm/client.js +287 -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/customer-id.d.ts +26 -0
- package/dist/esm/customer-id.js +47 -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 +17793 -0
- package/dist/esm/generated/index.js +8833 -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 +42 -0
- package/dist/esm/identity.js +125 -0
- package/dist/esm/index.d.ts +34 -0
- package/dist/esm/index.js +23 -0
- package/dist/esm/known-customers.d.ts +45 -0
- package/dist/esm/known-customers.js +90 -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,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;
|
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
import { type RequestOptions } from './http.js';
|
|
2
|
+
import type { Click, Conversion, GoalEvent, Link, LinkUpdateResult, ListPage, QrCode } from './types.js';
|
|
3
|
+
type Params = Record<string, unknown>;
|
|
4
|
+
/** Conversions: the older API. New integrations should use goals. */
|
|
5
|
+
export declare class Conversions {
|
|
6
|
+
private readonly core;
|
|
7
|
+
/**
|
|
8
|
+
* Report a conversion (`POST /v1/conversions`). `params` uses the API's field names.
|
|
9
|
+
* In private mode only `external_id`, `goal`, `click_id`, `code`, `reference`, `value`, `currency`,
|
|
10
|
+
* `provider`, `is_first`, `occurred_at`, `consent`, `kept_by`, `browser_engine`, `platform` and the hashed
|
|
11
|
+
* identifiers `hashed_email`, `hashed_phone_e164`, `hashed_phone_digits` (64 lowercase hex; `hashForAds`) are allowed.
|
|
12
|
+
*
|
|
13
|
+
* With `goal` set to a Payment goal this is a trusted payment confirmation: send `provider` and the payment
|
|
14
|
+
* reference (`external_id`), and the answer is the goal event (`object: 'goal_event'`) instead of a conversion.
|
|
15
|
+
* Tell them apart by `object`.
|
|
16
|
+
*
|
|
17
|
+
* @example
|
|
18
|
+
* await clikgate.conversions.create({ external_id: 'ORD-1001', click_id: clickId, goal: 'order_paid', value: '1500.50', currency: 'NGN' });
|
|
19
|
+
*/
|
|
20
|
+
create(params: Params, requestOptions?: RequestOptions): Promise<Conversion | GoalEvent>;
|
|
21
|
+
/**
|
|
22
|
+
* Reverse a conversion, fully or partly (`amount_minor`).
|
|
23
|
+
*
|
|
24
|
+
* @example
|
|
25
|
+
* await clikgate.conversions.reverse('cnv_01J…', { amount_minor: 200000, reason: 'partial refund' });
|
|
26
|
+
*/
|
|
27
|
+
reverse(id: string, params?: Params, requestOptions?: RequestOptions): Promise<Conversion>;
|
|
28
|
+
}
|
|
29
|
+
/** Options for `links.qr`. */
|
|
30
|
+
export interface QrOptions {
|
|
31
|
+
format?: 'svg' | 'png';
|
|
32
|
+
/** 256–2048 pixels. */
|
|
33
|
+
size?: number;
|
|
34
|
+
margin?: number;
|
|
35
|
+
/** Hex colour without `#`, e.g. `000000`. */
|
|
36
|
+
dark?: string;
|
|
37
|
+
light?: string;
|
|
38
|
+
}
|
|
39
|
+
/** An async iterator over every link that also exposes the first page. */
|
|
40
|
+
export interface LinkIterator extends AsyncIterable<Link> {
|
|
41
|
+
/** Collect up to `max` links (default: all). */
|
|
42
|
+
toArray(max?: number): Promise<Link[]>;
|
|
43
|
+
}
|
|
44
|
+
/** Links: create, read, update (with approvals and locks), list and QR codes. */
|
|
45
|
+
export declare class Links {
|
|
46
|
+
private readonly core;
|
|
47
|
+
/**
|
|
48
|
+
* Create a link. The result's `warnings` include `no_preview` when there is no preview title and image.
|
|
49
|
+
*
|
|
50
|
+
* @example
|
|
51
|
+
* const link = await clikgate.links.create({ destination_url: 'https://example.com/spring', og_title: 'Spring sale', og_image_url: 'https://example.com/og.png' });
|
|
52
|
+
* console.log(link.short_url, link.warnings);
|
|
53
|
+
*/
|
|
54
|
+
create(params: Params, requestOptions?: RequestOptions): Promise<Link>;
|
|
55
|
+
/**
|
|
56
|
+
* Fetch a link by ID.
|
|
57
|
+
*
|
|
58
|
+
* @example
|
|
59
|
+
* const link = await clikgate.links.get('lnk_01J…');
|
|
60
|
+
*/
|
|
61
|
+
get(id: string, requestOptions?: RequestOptions): Promise<Link>;
|
|
62
|
+
/**
|
|
63
|
+
* Update a link. With two-person approval on, a destination change answers `202` and waits for a
|
|
64
|
+
* second person: the result is `{ applied: false, change_request }`. A locked link throws {@link LinkLockedError}.
|
|
65
|
+
* An explicit `null` clears a field.
|
|
66
|
+
*
|
|
67
|
+
* @example
|
|
68
|
+
* const result = await clikgate.links.update('lnk_01J…', { destination_url: 'https://example.com/summer' });
|
|
69
|
+
* if (!result.applied) console.log('waiting for approval:', result.change_request.id);
|
|
70
|
+
*/
|
|
71
|
+
update(id: string, params: Params, requestOptions?: RequestOptions): Promise<LinkUpdateResult>;
|
|
72
|
+
/**
|
|
73
|
+
* Fetch one page of links (`limit` 1–100, `starting_after`, `ending_before`, filters such as `status`, `tag`, `campaign_id`).
|
|
74
|
+
*
|
|
75
|
+
* @example
|
|
76
|
+
* const page = await clikgate.links.listPage({ limit: 100, tag: 'promo' });
|
|
77
|
+
*/
|
|
78
|
+
listPage(params?: Params, requestOptions?: RequestOptions): Promise<ListPage<Link>>;
|
|
79
|
+
/**
|
|
80
|
+
* Iterate over every link, fetching pages lazily.
|
|
81
|
+
*
|
|
82
|
+
* @example
|
|
83
|
+
* for await (const link of clikgate.links.list({ status: 'active', limit: 100 })) {
|
|
84
|
+
* console.log(link.short_url);
|
|
85
|
+
* }
|
|
86
|
+
*/
|
|
87
|
+
list(params?: Params, requestOptions?: RequestOptions): LinkIterator;
|
|
88
|
+
/**
|
|
89
|
+
* Download the link's QR code.
|
|
90
|
+
*
|
|
91
|
+
* @example
|
|
92
|
+
* const qr = await clikgate.links.qr('lnk_01J…', { format: 'png', size: 1024 });
|
|
93
|
+
* await fs.promises.writeFile('qr.png', qr.data);
|
|
94
|
+
*/
|
|
95
|
+
qr(id: string, options?: QrOptions, requestOptions?: RequestOptions): Promise<QrCode>;
|
|
96
|
+
}
|
|
97
|
+
/** Clicks. */
|
|
98
|
+
export declare class Clicks {
|
|
99
|
+
private readonly core;
|
|
100
|
+
/**
|
|
101
|
+
* Fetch a click by its ID (`clk_…`).
|
|
102
|
+
*
|
|
103
|
+
* @example
|
|
104
|
+
* const click = await clikgate.clicks.get(clickId);
|
|
105
|
+
* console.log(click.country, click.link?.id);
|
|
106
|
+
*/
|
|
107
|
+
get(clickId: string, requestOptions?: RequestOptions): Promise<Click>;
|
|
108
|
+
}
|
|
109
|
+
export {};
|