@bytegigs/daraja 0.0.0-stage → 0.2.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/dist/client.js ADDED
@@ -0,0 +1,389 @@
1
+ import { DarajaError, DarajaValidationError } from "./errors.js";
2
+ import { darajaTimestamp, isLocalBaseUrl, normalizePhone, requireBaseUrl, requireCallbackUrl, requireLength, requireShortCode, stkPassword, } from "./helpers.js";
3
+ import { describeStkResult } from "./results.js";
4
+ import { securityCredential } from "./credential.js";
5
+ export const BASE_URLS = {
6
+ sandbox: "https://sandbox.safaricom.co.ke",
7
+ production: "https://api.safaricom.co.ke",
8
+ };
9
+ const QR_CODES = { till: "BG", agent: "WA", paybill: "PB", phone: "SM", business: "SB" };
10
+ const REFRESH_MARGIN_MS = 60_000;
11
+ const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
12
+ /** Retry-After may be seconds or an HTTP date. */
13
+ function retryAfter(value) {
14
+ if (!value)
15
+ return null;
16
+ const seconds = Number(value);
17
+ if (Number.isFinite(seconds))
18
+ return Math.max(0, seconds * 1000);
19
+ const date = Date.parse(value);
20
+ return Number.isNaN(date) ? null : Math.max(0, date - Date.now());
21
+ }
22
+ /**
23
+ * A small, typed client for Daraja. Request and response types come from the
24
+ * generated OpenAPI schema; this layer adds the parts a spec cannot express:
25
+ * token caching, the STK password, EAT timestamps and phone formats.
26
+ *
27
+ * STK Push is never retried automatically: a retry would send the customer a
28
+ * second payment prompt.
29
+ */
30
+ export class Daraja {
31
+ baseUrl;
32
+ options;
33
+ fetchImpl;
34
+ token = null;
35
+ pendingToken = null;
36
+ constructor(options) {
37
+ if (!options?.consumerKey || !options?.consumerSecret) {
38
+ throw new DarajaValidationError("consumerKey", "consumerKey and consumerSecret are required");
39
+ }
40
+ this.options = options;
41
+ const environment = options.environment ?? "sandbox";
42
+ if (!options.baseUrl && !(environment in BASE_URLS)) {
43
+ throw new DarajaValidationError("environment", 'must be "sandbox" or "production"');
44
+ }
45
+ this.baseUrl = requireBaseUrl(options.baseUrl ?? BASE_URLS[environment]);
46
+ this.fetchImpl = options.fetch ?? globalThis.fetch;
47
+ }
48
+ /** Never print credentials, even by accident: JSON.stringify, console.log and util.inspect all see this. */
49
+ toJSON() {
50
+ return {
51
+ baseUrl: this.baseUrl,
52
+ shortCode: this.options.shortCode ?? null,
53
+ initiatorName: this.options.initiatorName ?? null,
54
+ };
55
+ }
56
+ [Symbol.for("nodejs.util.inspect.custom")]() {
57
+ return { Daraja: this.toJSON() };
58
+ }
59
+ toString() {
60
+ return `Daraja(${this.baseUrl})`;
61
+ }
62
+ /** A cached access token, refreshed a minute before it expires. Concurrent callers share one request. */
63
+ async accessToken() {
64
+ if (this.token && this.token.expiresAt - REFRESH_MARGIN_MS > Date.now())
65
+ return this.token.value;
66
+ this.pendingToken ??= this.fetchToken().finally(() => {
67
+ this.pendingToken = null;
68
+ });
69
+ return this.pendingToken;
70
+ }
71
+ async fetchToken() {
72
+ const basic = Buffer.from(`${this.options.consumerKey}:${this.options.consumerSecret}`).toString("base64");
73
+ const body = await this.request("GET", "/oauth/v1/generate?grant_type=client_credentials", {
74
+ authorization: `Basic ${basic}`,
75
+ });
76
+ const seconds = Number(body.expires_in);
77
+ if (!body.access_token || !Number.isFinite(seconds)) {
78
+ throw new DarajaError("Daraja returned an unreadable access token", 200, null, null);
79
+ }
80
+ this.token = { value: body.access_token, expiresAt: Date.now() + seconds * 1000 };
81
+ return body.access_token;
82
+ }
83
+ /** Sends an M-PESA Express (STK Push) prompt to the customer's phone. */
84
+ async stkPush(input) {
85
+ const { shortCode, passkey } = this.credentials(input.shortCode, input.passkey);
86
+ if (!Number.isInteger(input.amount) || input.amount < 1) {
87
+ throw new DarajaValidationError("amount", "must be a whole number of shillings, at least 1");
88
+ }
89
+ const phone = normalizePhone(input.phone);
90
+ const timestamp = darajaTimestamp();
91
+ const body = {
92
+ BusinessShortCode: shortCode,
93
+ Password: stkPassword(shortCode, passkey, timestamp),
94
+ Timestamp: timestamp,
95
+ TransactionType: input.type === "till" ? "CustomerBuyGoodsOnline" : "CustomerPayBillOnline",
96
+ Amount: input.amount,
97
+ PartyA: phone,
98
+ PartyB: requireShortCode("partyB", input.partyB ?? shortCode),
99
+ PhoneNumber: phone,
100
+ CallBackURL: requireCallbackUrl(input.callbackUrl, this.allowsHttpCallbacks()),
101
+ AccountReference: requireLength("accountReference", input.accountReference, 12),
102
+ TransactionDesc: requireLength("description", input.description, 13),
103
+ };
104
+ return this.request("POST", "/mpesa/stkpush/v1/processrequest", {
105
+ authorization: `Bearer ${await this.accessToken()}`,
106
+ body,
107
+ });
108
+ }
109
+ /** Reads the result of an STK Push. "pending" means the customer has not answered yet. */
110
+ async stkQuery(input) {
111
+ const { shortCode, passkey } = this.credentials(input.shortCode, input.passkey);
112
+ const checkoutRequestId = requireLength("checkoutRequestId", input.checkoutRequestId, 64);
113
+ const timestamp = darajaTimestamp();
114
+ let raw;
115
+ try {
116
+ raw = await this.request("POST", "/mpesa/stkpushquery/v1/query", {
117
+ authorization: `Bearer ${await this.accessToken()}`,
118
+ body: {
119
+ BusinessShortCode: shortCode,
120
+ Password: stkPassword(shortCode, passkey, timestamp),
121
+ Timestamp: timestamp,
122
+ CheckoutRequestID: checkoutRequestId,
123
+ },
124
+ });
125
+ }
126
+ catch (error) {
127
+ if (error instanceof DarajaError && error.isPending)
128
+ return { state: "pending" };
129
+ throw error;
130
+ }
131
+ const code = Number(raw.ResultCode);
132
+ if (code === 0)
133
+ return { state: "paid", resultCode: 0, resultDesc: raw.ResultDesc, raw };
134
+ return { state: "failed", resultCode: code, resultDesc: raw.ResultDesc, meaning: describeStkResult(code), raw };
135
+ }
136
+ /**
137
+ * Polls `stkQuery` until the customer answers or `timeoutMs` passes. Use it to
138
+ * confirm a payment, or to recover one whose callback never arrived.
139
+ */
140
+ async waitForStkResult(input) {
141
+ const deadline = Date.now() + (input.timeoutMs ?? 90_000);
142
+ const base = Math.max(1000, input.intervalMs ?? 5000);
143
+ let wait = base;
144
+ // Daraja rate-limits a query sent right after the push, so give it a moment first.
145
+ await sleep(Math.min(input.initialDelayMs ?? 3000, Math.max(0, deadline - Date.now())));
146
+ for (;;) {
147
+ let status;
148
+ try {
149
+ status = await this.stkQuery(input);
150
+ wait = base;
151
+ }
152
+ catch (error) {
153
+ if (!(error instanceof DarajaError && error.isRateLimited))
154
+ throw error;
155
+ // Back off: honour Retry-After, otherwise double the wait, up to 30 seconds.
156
+ wait = Math.min(30_000, Math.max(error.retryAfterMs ?? 0, wait * 2));
157
+ status = { state: "pending" };
158
+ }
159
+ if (status.state !== "pending" || Date.now() + wait > deadline)
160
+ return status;
161
+ await sleep(wait);
162
+ }
163
+ }
164
+ /** Registers where M-PESA sends customer payments made to your shortcode. */
165
+ async c2bRegisterUrls(input) {
166
+ const shortCode = this.shortCode(input.shortCode);
167
+ return this.post("/mpesa/c2b/v2/registerurl", {
168
+ ShortCode: shortCode,
169
+ ResponseType: input.onValidationTimeout ?? "Completed",
170
+ ConfirmationURL: this.url("confirmationUrl", input.confirmationUrl),
171
+ ValidationURL: this.url("validationUrl", input.validationUrl),
172
+ });
173
+ }
174
+ /** Sandbox only: makes Daraja send your C2B callbacks as if a customer paid. */
175
+ async c2bSimulate(input) {
176
+ if (new URL(this.baseUrl).hostname === new URL(BASE_URLS.production).hostname) {
177
+ throw new DarajaValidationError("environment", "C2B simulate works only in the sandbox");
178
+ }
179
+ const body = {
180
+ ShortCode: this.shortCode(input.shortCode),
181
+ CommandID: input.type === "till" ? "CustomerBuyGoodsOnline" : "CustomerPayBillOnline",
182
+ Amount: this.amount(input.amount),
183
+ Msisdn: normalizePhone(input.phone),
184
+ };
185
+ if (input.accountReference)
186
+ body.BillRefNumber = requireLength("accountReference", input.accountReference, 20);
187
+ return this.post("/mpesa/c2b/v2/simulate", body);
188
+ }
189
+ /**
190
+ * Pays a customer from your B2C shortcode. The outcome arrives at `resultUrl`:
191
+ * read it with `parseAsyncResult`. Not retried automatically.
192
+ */
193
+ async b2cPayment(input) {
194
+ const body = {
195
+ OriginatorConversationID: requireLength("originatorConversationId", input.originatorConversationId, 64),
196
+ InitiatorName: this.initiatorName(),
197
+ SecurityCredential: this.securityCredential(),
198
+ CommandID: input.commandId ?? "BusinessPayment",
199
+ Amount: this.amount(input.amount, 10),
200
+ PartyA: this.shortCode(input.shortCode),
201
+ PartyB: normalizePhone(input.phone),
202
+ Remarks: this.remarks(input.remarks),
203
+ ...this.resultUrls(input),
204
+ };
205
+ if (input.occasion)
206
+ body.Occassion = requireLength("occasion", input.occasion, 100);
207
+ return this.post("/mpesa/b2c/v3/paymentrequest", body);
208
+ }
209
+ /** Pays another business's paybill or till from your shortcode. */
210
+ async b2bPayment(input) {
211
+ const body = {
212
+ Initiator: this.initiatorName(),
213
+ SecurityCredential: this.securityCredential(),
214
+ CommandID: input.type === "till" ? "BusinessBuyGoods" : "BusinessPayBill",
215
+ SenderIdentifierType: "4",
216
+ RecieverIdentifierType: "4",
217
+ Amount: this.amount(input.amount),
218
+ PartyA: this.shortCode(input.shortCode),
219
+ PartyB: requireShortCode("to", input.to),
220
+ AccountReference: requireLength("accountReference", input.accountReference, 13),
221
+ Remarks: this.remarks(input.remarks),
222
+ ...this.resultUrls(input),
223
+ };
224
+ if (input.requester)
225
+ body.Requester = normalizePhone(input.requester);
226
+ return this.post("/mpesa/b2b/v1/paymentrequest", body);
227
+ }
228
+ /** Reverses a payment your shortcode received, by its M-PESA receipt. */
229
+ async reversal(input) {
230
+ const body = {
231
+ Initiator: this.initiatorName(),
232
+ SecurityCredential: this.securityCredential(),
233
+ CommandID: "TransactionReversal",
234
+ TransactionID: requireLength("transactionId", input.transactionId, 20),
235
+ Amount: this.amount(input.amount),
236
+ ReceiverParty: this.shortCode(input.shortCode),
237
+ RecieverIdentifierType: "11",
238
+ Remarks: this.remarks(input.remarks),
239
+ ResultURL: this.resultUrls(input).ResultURL,
240
+ QueueTimeOutURL: this.resultUrls(input).QueueTimeOutURL,
241
+ };
242
+ if (input.occasion)
243
+ body.Occasion = requireLength("occasion", input.occasion, 100);
244
+ return this.post("/mpesa/reversal/v1/request", body);
245
+ }
246
+ /** Looks up a transaction by receipt, or a B2C payment by your OriginatorConversationID. */
247
+ async transactionStatus(input) {
248
+ const body = {
249
+ Initiator: this.initiatorName(),
250
+ SecurityCredential: this.securityCredential(),
251
+ CommandID: "TransactionStatusQuery",
252
+ PartyA: this.shortCode(input.shortCode),
253
+ IdentifierType: "4",
254
+ Remarks: this.remarks(input.remarks),
255
+ ...this.resultUrls(input),
256
+ };
257
+ if (input.transactionId)
258
+ body.TransactionID = requireLength("transactionId", input.transactionId, 20);
259
+ else if (input.originatorConversationId) {
260
+ body.OriginatorConversationID = requireLength("originatorConversationId", input.originatorConversationId, 64);
261
+ }
262
+ else
263
+ throw new DarajaValidationError("transactionId", "or originatorConversationId is required");
264
+ if (input.occasion)
265
+ body.Occasion = requireLength("occasion", input.occasion, 100);
266
+ return this.post("/mpesa/transactionstatus/v1/query", body);
267
+ }
268
+ /** Requests your shortcode's balances. Read them with `parseAccountBalance`. */
269
+ async accountBalance(input) {
270
+ return this.post("/mpesa/accountbalance/v1/query", {
271
+ Initiator: this.initiatorName(),
272
+ SecurityCredential: this.securityCredential(),
273
+ CommandID: "AccountBalance",
274
+ PartyA: this.shortCode(input.shortCode),
275
+ IdentifierType: input.type === "till" ? "2" : "4",
276
+ Remarks: this.remarks(input.remarks),
277
+ ...this.resultUrls(input),
278
+ });
279
+ }
280
+ /** Generates a QR code customers scan in the M-PESA app. `QRCode` is a base64 PNG. */
281
+ async dynamicQr(input) {
282
+ const code = QR_CODES[input.type];
283
+ if (!code)
284
+ throw new DarajaValidationError("type", "must be till, agent, paybill, phone or business");
285
+ const size = input.size ?? 300;
286
+ if (!Number.isInteger(size) || size < 100 || size > 2000) {
287
+ throw new DarajaValidationError("size", "must be a whole number of pixels between 100 and 2000");
288
+ }
289
+ return this.post("/mpesa/qrcode/v1/generate", {
290
+ MerchantName: requireLength("merchantName", input.merchantName, 50),
291
+ RefNo: requireLength("reference", input.reference, 20),
292
+ Amount: this.amount(input.amount),
293
+ TrxCode: code,
294
+ CPI: input.type === "phone" ? normalizePhone(input.to) : requireShortCode("to", input.to),
295
+ Size: String(size),
296
+ });
297
+ }
298
+ async post(path, body) {
299
+ return this.request("POST", path, { authorization: `Bearer ${await this.accessToken()}`, body });
300
+ }
301
+ shortCode(value) {
302
+ return requireShortCode("shortCode", value ?? this.options.shortCode ?? "");
303
+ }
304
+ amount(value, minimum = 1) {
305
+ if (!Number.isInteger(value) || value < minimum) {
306
+ throw new DarajaValidationError("amount", `must be a whole number of shillings, at least ${minimum}`);
307
+ }
308
+ return value;
309
+ }
310
+ remarks(value) {
311
+ const text = requireLength("remarks", value, 100);
312
+ if (text.length < 2)
313
+ throw new DarajaValidationError("remarks", "must be at least 2 characters");
314
+ return text;
315
+ }
316
+ url(field, value) {
317
+ return requireCallbackUrl(value, this.allowsHttpCallbacks(), field);
318
+ }
319
+ resultUrls(input) {
320
+ return { ResultURL: this.url("resultUrl", input.resultUrl), QueueTimeOutURL: this.url("timeoutUrl", input.timeoutUrl) };
321
+ }
322
+ initiatorName() {
323
+ if (!this.options.initiatorName)
324
+ throw new DarajaValidationError("initiatorName", "is required for this API");
325
+ return this.options.initiatorName;
326
+ }
327
+ cachedCredential = null;
328
+ securityCredential() {
329
+ if (this.options.securityCredential)
330
+ return this.options.securityCredential;
331
+ if (!this.options.initiatorPassword || !this.options.certificate) {
332
+ throw new DarajaValidationError("securityCredential", "set securityCredential, or initiatorPassword and Safaricom's certificate, on the client");
333
+ }
334
+ this.cachedCredential ??= securityCredential(this.options.initiatorPassword, this.options.certificate);
335
+ return this.cachedCredential;
336
+ }
337
+ credentials(shortCode, passkey) {
338
+ const code = requireShortCode("shortCode", shortCode ?? this.options.shortCode ?? "");
339
+ const key = passkey ?? this.options.passkey;
340
+ if (!key)
341
+ throw new DarajaValidationError("passkey", "is required (set it on the client or per call)");
342
+ return { shortCode: code, passkey: key };
343
+ }
344
+ allowsHttpCallbacks() {
345
+ // Only a local mock can call back over http; real Daraja requires https.
346
+ return isLocalBaseUrl(this.baseUrl);
347
+ }
348
+ async request(method, path, init) {
349
+ let response;
350
+ try {
351
+ response = await this.fetchImpl(`${this.baseUrl}${path}`, {
352
+ method,
353
+ headers: {
354
+ Authorization: init.authorization,
355
+ Accept: "application/json",
356
+ ...(init.body ? { "Content-Type": "application/json" } : {}),
357
+ },
358
+ body: init.body ? JSON.stringify(init.body) : undefined,
359
+ // Daraja never redirects. Following one would send the bearer token or
360
+ // Basic credentials to wherever it pointed.
361
+ redirect: "error",
362
+ signal: AbortSignal.timeout(this.options.timeoutMs ?? 30_000),
363
+ });
364
+ }
365
+ catch (error) {
366
+ throw new DarajaError(`Could not reach Daraja: ${error.message}`, null, null, null);
367
+ }
368
+ const text = await response.text();
369
+ let parsed = null;
370
+ try {
371
+ parsed = text ? JSON.parse(text) : null;
372
+ }
373
+ catch {
374
+ parsed = null;
375
+ }
376
+ if (!response.ok) {
377
+ const error = (parsed ?? {});
378
+ if (response.status === 401)
379
+ this.token = null;
380
+ const fallback = response.status === 429
381
+ ? "Daraja is rate-limiting requests (HTTP 429). Wait, then retry with backoff."
382
+ : `Daraja returned HTTP ${response.status}`;
383
+ throw new DarajaError(error.errorMessage ?? fallback, response.status, error.errorCode ?? null, error.requestId ?? null, retryAfter(response.headers.get("retry-after")), text ? text.slice(0, 500) : null);
384
+ }
385
+ if (parsed === null)
386
+ throw new DarajaError("Daraja returned an empty or non-JSON response", response.status, null, null);
387
+ return parsed;
388
+ }
389
+ }
@@ -0,0 +1,7 @@
1
+ /**
2
+ * Encrypts the initiator password into Daraja's `SecurityCredential`:
3
+ * RSA with PKCS #1 v1.5 padding, using the public key in Safaricom's certificate,
4
+ * then base64. Download the sandbox or production certificate from the Daraja
5
+ * portal; they differ. The password itself never leaves your server.
6
+ */
7
+ export declare function securityCredential(initiatorPassword: string, certificatePem: string | Buffer): string;
@@ -0,0 +1,20 @@
1
+ import { constants, publicEncrypt, X509Certificate } from "node:crypto";
2
+ import { DarajaValidationError } from "./errors.js";
3
+ /**
4
+ * Encrypts the initiator password into Daraja's `SecurityCredential`:
5
+ * RSA with PKCS #1 v1.5 padding, using the public key in Safaricom's certificate,
6
+ * then base64. Download the sandbox or production certificate from the Daraja
7
+ * portal; they differ. The password itself never leaves your server.
8
+ */
9
+ export function securityCredential(initiatorPassword, certificatePem) {
10
+ if (!initiatorPassword)
11
+ throw new DarajaValidationError("initiatorPassword", "is required");
12
+ let publicKey;
13
+ try {
14
+ publicKey = new X509Certificate(certificatePem).publicKey;
15
+ }
16
+ catch {
17
+ throw new DarajaValidationError("certificate", "is not a PEM or DER X.509 certificate");
18
+ }
19
+ return publicEncrypt({ key: publicKey, padding: constants.RSA_PKCS1_PADDING }, Buffer.from(initiatorPassword, "utf8")).toString("base64");
20
+ }
@@ -0,0 +1,28 @@
1
+ /** Daraja answered with an error, or could not be reached. */
2
+ export declare class DarajaError extends Error {
3
+ readonly status: number | null;
4
+ readonly errorCode: string | null;
5
+ readonly requestId: string | null;
6
+ /** From Daraja's Retry-After header, when it sends one. */
7
+ readonly retryAfterMs: number | null;
8
+ /** The start of Daraja's response body, for errors that don't follow its usual shape. */
9
+ readonly responseBody: string | null;
10
+ readonly name = "DarajaError";
11
+ constructor(message: string, status: number | null, errorCode: string | null, requestId: string | null,
12
+ /** From Daraja's Retry-After header, when it sends one. */
13
+ retryAfterMs?: number | null,
14
+ /** The start of Daraja's response body, for errors that don't follow its usual shape. */
15
+ responseBody?: string | null);
16
+ /** Daraja's gateway is rate-limiting this app (HTTP 429): wait and retry with backoff. */
17
+ get isRateLimited(): boolean;
18
+ /** Your Daraja app doesn't include this API product (HTTP 401 "no apiproduct match found"). */
19
+ get isProductMissing(): boolean;
20
+ /** True while a customer is still answering an STK prompt (`500.001.1001`). */
21
+ get isPending(): boolean;
22
+ }
23
+ /** The request was rejected before it was sent, because Daraja would reject it too. */
24
+ export declare class DarajaValidationError extends Error {
25
+ readonly field: string;
26
+ readonly name = "DarajaValidationError";
27
+ constructor(field: string, message: string);
28
+ }
package/dist/errors.js ADDED
@@ -0,0 +1,42 @@
1
+ /** Daraja answered with an error, or could not be reached. */
2
+ export class DarajaError extends Error {
3
+ status;
4
+ errorCode;
5
+ requestId;
6
+ retryAfterMs;
7
+ responseBody;
8
+ name = "DarajaError";
9
+ constructor(message, status, errorCode, requestId,
10
+ /** From Daraja's Retry-After header, when it sends one. */
11
+ retryAfterMs = null,
12
+ /** The start of Daraja's response body, for errors that don't follow its usual shape. */
13
+ responseBody = null) {
14
+ super(message);
15
+ this.status = status;
16
+ this.errorCode = errorCode;
17
+ this.requestId = requestId;
18
+ this.retryAfterMs = retryAfterMs;
19
+ this.responseBody = responseBody;
20
+ }
21
+ /** Daraja's gateway is rate-limiting this app (HTTP 429): wait and retry with backoff. */
22
+ get isRateLimited() {
23
+ return this.status === 429;
24
+ }
25
+ /** Your Daraja app doesn't include this API product (HTTP 401 "no apiproduct match found"). */
26
+ get isProductMissing() {
27
+ return this.status === 401 && /no apiproduct match/i.test(this.message);
28
+ }
29
+ /** True while a customer is still answering an STK prompt (`500.001.1001`). */
30
+ get isPending() {
31
+ return this.errorCode === "500.001.1001";
32
+ }
33
+ }
34
+ /** The request was rejected before it was sent, because Daraja would reject it too. */
35
+ export class DarajaValidationError extends Error {
36
+ field;
37
+ name = "DarajaValidationError";
38
+ constructor(field, message) {
39
+ super(`${field}: ${message}`);
40
+ this.field = field;
41
+ }
42
+ }