astrapay
Version:
AstraPay SDK for integrating M-Pesa STK Push in Node.js applications.
57 lines (49 loc) • 1.65 kB
JavaScript
const axios = require("axios");
const base64 = require("base-64");
class AstraPay {
constructor({ consumerKey, consumerSecret, shortcode, passkey, callbackUrl }) {
this.consumerKey = consumerKey;
this.consumerSecret = consumerSecret;
this.shortcode = shortcode;
this.passkey = passkey;
this.callbackUrl = callbackUrl;
}
async getAccessToken() {
const auth = Buffer.from(`${this.consumerKey}:${this.consumerSecret}`).toString("base64");
const res = await axios.get("https://sandbox.safaricom.co.ke/oauth/v1/generate?grant_type=client_credentials", {
headers: {
Authorization: `Basic ${auth}`
}
});
return res.data.access_token;
}
async pay({ phone, amount }) {
const token = await this.getAccessToken();
const timestamp = new Date().toISOString().replace(/[-T:.Z]/g, "").slice(0, 14);
const password = base64.encode(`${this.shortcode}${this.passkey}${timestamp}`);
const payload = {
BusinessShortCode: this.shortcode,
Password: password,
Timestamp: timestamp,
TransactionType: "CustomerPayBillOnline",
Amount: amount,
PartyA: phone,
PartyB: this.shortcode,
PhoneNumber: phone,
CallBackURL: this.callbackUrl,
AccountReference: "AstraPay",
TransactionDesc: "Payment"
};
const res = await axios.post(
"https://sandbox.safaricom.co.ke/mpesa/stkpush/v1/processrequest",
payload,
{
headers: {
Authorization: `Bearer ${token}`
}
}
);
return res.data;
}
}
module.exports = AstraPay;