mpesajs
Version:
A Node.js SDK for seamless integration with M-Pesa payment gateway, providing easy-to-use methods for handling transactions, payments, and API interactions
172 lines • 8.45 kB
JavaScript
;
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
var ownKeys = function(o) {
ownKeys = Object.getOwnPropertyNames || function (o) {
var ar = [];
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
return ar;
};
return ownKeys(o);
};
return function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
__setModuleDefault(result, mod);
return result;
};
})();
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.Auth = void 0;
const axios_1 = __importStar(require("axios"));
const base_64_1 = __importDefault(require("base-64"));
const env_1 = require("./utils/env");
const ErrorHandlers_1 = require("./errors/ErrorHandlers");
const RateLimiter_1 = require("./utils/RateLimiter");
/**
* Auth class handles authentication with the M-Pesa API
* by generating access tokens using consumer credentials.
* This class provides functionality to generate OAuth tokens
* required for authenticating API requests to the M-Pesa system.
*/
class Auth {
/**
* Creates an instance of Auth class
* @param consumerKey - The consumer key obtained from M-Pesa developer portal
* @param consumerSecret - The consumer secret obtained from M-Pesa developer portal
* @param sandbox - Boolean flag to determine environment:
* true for sandbox/testing environment
* false for production environment
*/
constructor(consumerKey = (0, env_1.getEnvVar)('MPESA_CONSUMER_KEY', ''), consumerSecret = (0, env_1.getEnvVar)('MPESA_CONSUMER_SECRET', ''), sandbox = (0, env_1.getEnvVar)('MPESA_SANDBOX', 'true').toLowerCase() === 'true') {
this.consumerKey = consumerKey;
this.consumerSecret = consumerSecret;
this.baseUrl = sandbox
? 'https://apisandbox.safaricom.et/v1/token/generate'
: 'https://api.safaricom.et/v1/token/generate';
this.rateLimiter = RateLimiter_1.RateLimiter.getInstance();
}
/**
* Generates an access token for M-Pesa API authentication.
* The method:
* 1. Combines consumer key and secret
* 2. Base64 encodes the credentials
* 3. Makes HTTP GET request to token endpoint
* 4. Processes the response to extract token
*
* @returns Promise containing an object with:
* - token: The access token string for API authentication
* - expiresIn: Token validity period in seconds
*
* @throws MpesaError with specific error codes and messages based on the API response
* @throws Error for network issues or invalid responses
*
* @example
* ```typescript
* const auth = new Auth('your-key', 'your-secret');
* const {token, expiresIn} = await auth.generateToken();
* ```
*/
/**
* Generates an authentication token for M-Pesa API access.
*
* This method:
* 1. Combines the consumer key and secret
* 2. Base64 encodes the credentials
* 3. Makes an HTTP GET request to the token endpoint
* 4. Returns the access token and expiry time
*
* @returns Promise containing an object with:
* - token: The access token string for API authentication
* - expiresIn: Token validity period in seconds
*
* @throws {Error} If network connection fails or no response received
* @throws {Error} If request setup fails
* @throws {Error} If API returns error response
*/
generateToken() {
return __awaiter(this, void 0, void 0, function* () {
return this.rateLimiter.execute(() => __awaiter(this, void 0, void 0, function* () {
var _a;
try {
// Combine consumer key and secret with colon separator
const credentials = `${this.consumerKey}:${this.consumerSecret}`;
// Base64 encode the credentials for Basic Auth
const encodedCredentials = base_64_1.default.encode(credentials);
// Make GET request to token endpoint with credentials
const response = yield axios_1.default.get(this.baseUrl, {
params: {
grant_type: 'client_credentials', // Required grant type for OAuth 2.0
},
headers: {
Authorization: `Basic ${encodedCredentials}`, // Add encoded credentials to Authorization header
},
});
// Check if response contains valid token data
if (response.data && response.data.access_token) {
// Return token and expiry time if successful
return {
token: response.data.access_token,
tokenType: response.data.token_type,
expiresIn: response.data.expires_in
};
}
else {
// Handle invalid response format
throw new ErrorHandlers_1.AuthenticationError('Unknown authentication error occurred');
}
}
catch (error) {
if (error instanceof axios_1.AxiosError) {
// Handle API response errors
if ((_a = error.response) === null || _a === void 0 ? void 0 : _a.data) {
return ErrorHandlers_1.AuthenticationErrorHandler.handle(error.response.data);
}
// Handle network errors (no response received)
if (error.request || error.code === 'ECONNABORTED') {
throw new ErrorHandlers_1.MpesaError('No response received from the API. Please check your network connection.');
}
// Handle request setup errors
throw new ErrorHandlers_1.MpesaError(`Failed to generate token: ${error.message}`);
}
// If it's an AuthenticationError, rethrow it
if (error instanceof ErrorHandlers_1.AuthenticationError) {
throw error;
}
// For any other error, wrap it in MpesaError
throw new ErrorHandlers_1.MpesaError(`Failed to generate token: ${error instanceof Error ? error.message : 'Unknown error occurred'}`);
}
}));
});
}
}
exports.Auth = Auth;
//# sourceMappingURL=auth.js.map