@bytegigs/daraja 0.0.0-stage → 0.3.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/LICENSE +202 -0
- package/NOTICE +14 -0
- package/README.md +76 -2
- package/dist/async-result.d.ts +47 -0
- package/dist/async-result.js +70 -0
- package/dist/callback.d.ts +26 -0
- package/dist/callback.js +44 -0
- package/dist/client.d.ts +219 -0
- package/dist/client.js +389 -0
- package/dist/credential.d.ts +7 -0
- package/dist/credential.js +20 -0
- package/dist/errors.d.ts +28 -0
- package/dist/errors.js +42 -0
- package/dist/generated/schema.d.ts +1049 -0
- package/dist/generated/schema.js +5 -0
- package/dist/helpers.d.ts +24 -0
- package/dist/helpers.js +100 -0
- package/dist/index.d.ts +11 -0
- package/dist/index.js +7 -0
- package/dist/results.d.ts +3 -0
- package/dist/results.js +15 -0
- package/package.json +39 -4
package/dist/client.d.ts
ADDED
|
@@ -0,0 +1,219 @@
|
|
|
1
|
+
import type { components } from "./generated/schema.js";
|
|
2
|
+
type Schemas = components["schemas"];
|
|
3
|
+
export type StkPushRequest = Schemas["StkPushRequest"];
|
|
4
|
+
export type StkPushResponse = Schemas["StkPushResponse"];
|
|
5
|
+
export type StkPushQueryResponse = Schemas["StkPushQueryResponse"];
|
|
6
|
+
export type AsyncAccepted = Schemas["AsyncAccepted"];
|
|
7
|
+
export type C2bRegisterUrlResponse = Schemas["C2bRegisterUrlResponse"];
|
|
8
|
+
export type DynamicQrResponse = Schemas["DynamicQrResponse"];
|
|
9
|
+
export declare const BASE_URLS: {
|
|
10
|
+
readonly sandbox: "https://sandbox.safaricom.co.ke";
|
|
11
|
+
readonly production: "https://api.safaricom.co.ke";
|
|
12
|
+
};
|
|
13
|
+
export interface DarajaOptions {
|
|
14
|
+
consumerKey: string;
|
|
15
|
+
consumerSecret: string;
|
|
16
|
+
environment?: keyof typeof BASE_URLS;
|
|
17
|
+
/** Overrides `environment`, e.g. the URL of @bytegigs/daraja-mock in tests. */
|
|
18
|
+
baseUrl?: string;
|
|
19
|
+
/** Default paybill or till and its Lipa na M-PESA passkey. Can be overridden per call. */
|
|
20
|
+
shortCode?: string;
|
|
21
|
+
passkey?: string;
|
|
22
|
+
/**
|
|
23
|
+
* For B2C, B2B, reversal, transaction status and account balance: the API
|
|
24
|
+
* initiator and either its password plus Safaricom's certificate, or a
|
|
25
|
+
* `securityCredential` you computed already.
|
|
26
|
+
*/
|
|
27
|
+
initiatorName?: string;
|
|
28
|
+
initiatorPassword?: string;
|
|
29
|
+
certificate?: string | Buffer;
|
|
30
|
+
securityCredential?: string;
|
|
31
|
+
/** Milliseconds before a request is abandoned. Default 30 seconds. */
|
|
32
|
+
timeoutMs?: number;
|
|
33
|
+
fetch?: typeof fetch;
|
|
34
|
+
}
|
|
35
|
+
export interface StkPushInput {
|
|
36
|
+
amount: number;
|
|
37
|
+
phone: string;
|
|
38
|
+
callbackUrl: string;
|
|
39
|
+
/** Shown to the customer as the account number. Up to 12 characters. */
|
|
40
|
+
accountReference: string;
|
|
41
|
+
/** Up to 13 characters. */
|
|
42
|
+
description: string;
|
|
43
|
+
/** "paybill" (default) or "till". */
|
|
44
|
+
type?: "paybill" | "till";
|
|
45
|
+
/** The paybill or till that receives the money. Defaults to `shortCode`. Tills use a separate store number. */
|
|
46
|
+
partyB?: string;
|
|
47
|
+
shortCode?: string;
|
|
48
|
+
passkey?: string;
|
|
49
|
+
}
|
|
50
|
+
export interface StkQueryInput {
|
|
51
|
+
checkoutRequestId: string;
|
|
52
|
+
shortCode?: string;
|
|
53
|
+
passkey?: string;
|
|
54
|
+
}
|
|
55
|
+
export type StkStatus = {
|
|
56
|
+
state: "pending";
|
|
57
|
+
} | {
|
|
58
|
+
state: "paid";
|
|
59
|
+
resultCode: 0;
|
|
60
|
+
resultDesc: string;
|
|
61
|
+
raw: StkPushQueryResponse;
|
|
62
|
+
} | {
|
|
63
|
+
state: "failed";
|
|
64
|
+
resultCode: number;
|
|
65
|
+
resultDesc: string;
|
|
66
|
+
meaning: string;
|
|
67
|
+
raw: StkPushQueryResponse;
|
|
68
|
+
};
|
|
69
|
+
/** Where Daraja sends the outcome of an asynchronous request. */
|
|
70
|
+
export interface ResultUrls {
|
|
71
|
+
resultUrl: string;
|
|
72
|
+
/** Where M-PESA reports a request that timed out in its queue. */
|
|
73
|
+
timeoutUrl: string;
|
|
74
|
+
}
|
|
75
|
+
export interface B2cInput extends ResultUrls {
|
|
76
|
+
/** Your unique ID for this payment. Reuse it when retrying, so you never pay twice. */
|
|
77
|
+
originatorConversationId: string;
|
|
78
|
+
amount: number;
|
|
79
|
+
phone: string;
|
|
80
|
+
remarks: string;
|
|
81
|
+
/** Default "BusinessPayment". */
|
|
82
|
+
commandId?: "SalaryPayment" | "BusinessPayment" | "PromotionPayment";
|
|
83
|
+
occasion?: string;
|
|
84
|
+
shortCode?: string;
|
|
85
|
+
}
|
|
86
|
+
export interface B2bInput extends ResultUrls {
|
|
87
|
+
amount: number;
|
|
88
|
+
/** The paybill or till you are paying. */
|
|
89
|
+
to: string;
|
|
90
|
+
/** "paybill" (default) or "till". */
|
|
91
|
+
type?: "paybill" | "till";
|
|
92
|
+
accountReference: string;
|
|
93
|
+
remarks: string;
|
|
94
|
+
/** The customer on whose behalf you pay, if any. */
|
|
95
|
+
requester?: string;
|
|
96
|
+
shortCode?: string;
|
|
97
|
+
}
|
|
98
|
+
export interface ReversalInput extends ResultUrls {
|
|
99
|
+
/** The M-PESA receipt of the payment to reverse. */
|
|
100
|
+
transactionId: string;
|
|
101
|
+
amount: number;
|
|
102
|
+
remarks: string;
|
|
103
|
+
occasion?: string;
|
|
104
|
+
shortCode?: string;
|
|
105
|
+
}
|
|
106
|
+
export type TransactionStatusInput = ResultUrls & {
|
|
107
|
+
remarks: string;
|
|
108
|
+
shortCode?: string;
|
|
109
|
+
occasion?: string;
|
|
110
|
+
} & ({
|
|
111
|
+
transactionId: string;
|
|
112
|
+
originatorConversationId?: undefined;
|
|
113
|
+
} | {
|
|
114
|
+
originatorConversationId: string;
|
|
115
|
+
transactionId?: undefined;
|
|
116
|
+
});
|
|
117
|
+
export interface AccountBalanceInput extends ResultUrls {
|
|
118
|
+
remarks: string;
|
|
119
|
+
shortCode?: string;
|
|
120
|
+
/** "shortcode" (default) or "till". */
|
|
121
|
+
type?: "shortcode" | "till";
|
|
122
|
+
}
|
|
123
|
+
export interface C2bRegisterInput {
|
|
124
|
+
confirmationUrl: string;
|
|
125
|
+
validationUrl: string;
|
|
126
|
+
/** What M-PESA does if your validation URL doesn't answer in time. Default "Completed". */
|
|
127
|
+
onValidationTimeout?: "Completed" | "Cancelled";
|
|
128
|
+
shortCode?: string;
|
|
129
|
+
}
|
|
130
|
+
export interface C2bSimulateInput {
|
|
131
|
+
amount: number;
|
|
132
|
+
phone: string;
|
|
133
|
+
/** The account number for a paybill. Leave out for a till. */
|
|
134
|
+
accountReference?: string;
|
|
135
|
+
type?: "paybill" | "till";
|
|
136
|
+
shortCode?: string;
|
|
137
|
+
}
|
|
138
|
+
export interface DynamicQrInput {
|
|
139
|
+
merchantName: string;
|
|
140
|
+
reference: string;
|
|
141
|
+
amount: number;
|
|
142
|
+
/** What the QR pays: a till, agent, paybill, phone number or business. */
|
|
143
|
+
type: "till" | "agent" | "paybill" | "phone" | "business";
|
|
144
|
+
/** The till, agent, paybill or phone number to pay. */
|
|
145
|
+
to: string;
|
|
146
|
+
/** Pixels. Default 300. */
|
|
147
|
+
size?: number;
|
|
148
|
+
}
|
|
149
|
+
/**
|
|
150
|
+
* A small, typed client for Daraja. Request and response types come from the
|
|
151
|
+
* generated OpenAPI schema; this layer adds the parts a spec cannot express:
|
|
152
|
+
* token caching, the STK password, EAT timestamps and phone formats.
|
|
153
|
+
*
|
|
154
|
+
* STK Push is never retried automatically: a retry would send the customer a
|
|
155
|
+
* second payment prompt.
|
|
156
|
+
*/
|
|
157
|
+
export declare class Daraja {
|
|
158
|
+
readonly baseUrl: string;
|
|
159
|
+
private readonly options;
|
|
160
|
+
private readonly fetchImpl;
|
|
161
|
+
private token;
|
|
162
|
+
private pendingToken;
|
|
163
|
+
constructor(options: DarajaOptions);
|
|
164
|
+
/** Never print credentials, even by accident: JSON.stringify, console.log and util.inspect all see this. */
|
|
165
|
+
toJSON(): {
|
|
166
|
+
baseUrl: string;
|
|
167
|
+
shortCode: string | null;
|
|
168
|
+
initiatorName: string | null;
|
|
169
|
+
};
|
|
170
|
+
toString(): string;
|
|
171
|
+
/** A cached access token, refreshed a minute before it expires. Concurrent callers share one request. */
|
|
172
|
+
accessToken(): Promise<string>;
|
|
173
|
+
private fetchToken;
|
|
174
|
+
/** Sends an M-PESA Express (STK Push) prompt to the customer's phone. */
|
|
175
|
+
stkPush(input: StkPushInput): Promise<StkPushResponse>;
|
|
176
|
+
/** Reads the result of an STK Push. "pending" means the customer has not answered yet. */
|
|
177
|
+
stkQuery(input: StkQueryInput): Promise<StkStatus>;
|
|
178
|
+
/**
|
|
179
|
+
* Polls `stkQuery` until the customer answers or `timeoutMs` passes. Use it to
|
|
180
|
+
* confirm a payment, or to recover one whose callback never arrived.
|
|
181
|
+
*/
|
|
182
|
+
waitForStkResult(input: StkQueryInput & {
|
|
183
|
+
timeoutMs?: number;
|
|
184
|
+
intervalMs?: number;
|
|
185
|
+
initialDelayMs?: number;
|
|
186
|
+
}): Promise<StkStatus>;
|
|
187
|
+
/** Registers where M-PESA sends customer payments made to your shortcode. */
|
|
188
|
+
c2bRegisterUrls(input: C2bRegisterInput): Promise<C2bRegisterUrlResponse>;
|
|
189
|
+
/** Sandbox only: makes Daraja send your C2B callbacks as if a customer paid. */
|
|
190
|
+
c2bSimulate(input: C2bSimulateInput): Promise<C2bRegisterUrlResponse>;
|
|
191
|
+
/**
|
|
192
|
+
* Pays a customer from your B2C shortcode. The outcome arrives at `resultUrl`:
|
|
193
|
+
* read it with `parseAsyncResult`. Not retried automatically.
|
|
194
|
+
*/
|
|
195
|
+
b2cPayment(input: B2cInput): Promise<AsyncAccepted>;
|
|
196
|
+
/** Pays another business's paybill or till from your shortcode. */
|
|
197
|
+
b2bPayment(input: B2bInput): Promise<AsyncAccepted>;
|
|
198
|
+
/** Reverses a payment your shortcode received, by its M-PESA receipt. */
|
|
199
|
+
reversal(input: ReversalInput): Promise<AsyncAccepted>;
|
|
200
|
+
/** Looks up a transaction by receipt, or a B2C payment by your OriginatorConversationID. */
|
|
201
|
+
transactionStatus(input: TransactionStatusInput): Promise<AsyncAccepted>;
|
|
202
|
+
/** Requests your shortcode's balances. Read them with `parseAccountBalance`. */
|
|
203
|
+
accountBalance(input: AccountBalanceInput): Promise<AsyncAccepted>;
|
|
204
|
+
/** Generates a QR code customers scan in the M-PESA app. `QRCode` is a base64 PNG. */
|
|
205
|
+
dynamicQr(input: DynamicQrInput): Promise<DynamicQrResponse>;
|
|
206
|
+
private post;
|
|
207
|
+
private shortCode;
|
|
208
|
+
private amount;
|
|
209
|
+
private remarks;
|
|
210
|
+
private url;
|
|
211
|
+
private resultUrls;
|
|
212
|
+
private initiatorName;
|
|
213
|
+
private cachedCredential;
|
|
214
|
+
private securityCredential;
|
|
215
|
+
private credentials;
|
|
216
|
+
private allowsHttpCallbacks;
|
|
217
|
+
private request;
|
|
218
|
+
}
|
|
219
|
+
export {};
|
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
|
+
}
|
package/dist/errors.d.ts
ADDED
|
@@ -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
|
+
}
|