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