Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

MSISDN parsing #4

Closed
wants to merge 4 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
243 changes: 143 additions & 100 deletions index.js
Original file line number Diff line number Diff line change
@@ -1,119 +1,162 @@
require('dotenv').config();
const axios = require('axios').default;
const crypto = require('crypto');
const constants = require('constants');
import { config } from "dotenv";
import axios from "axios";
import { publicEncrypt } from "crypto";
import { RSA_PKCS1_PADDING } from "constants";
import { isValidPhoneNumber, parsePhoneNumber } from "libphonenumber-js";

config();
let mpesaConfig;

function _getBearerToken(mpesa_public_key, mpesa_api_key) {
const publicKey = "-----BEGIN PUBLIC KEY-----\n"+mpesa_public_key+"\n"+"-----END PUBLIC KEY-----";
const buffer = Buffer.from(mpesa_api_key);
const encrypted = crypto.publicEncrypt({
'key': publicKey,
'padding': constants.RSA_PKCS1_PADDING,
}, buffer);
return encrypted.toString("base64");
const publicKey =
"-----BEGIN PUBLIC KEY-----\n" +
mpesa_public_key +
"\n" +
"-----END PUBLIC KEY-----";
const buffer = Buffer.from(mpesa_api_key);
const encrypted = publicEncrypt(
{
key: publicKey,
padding: RSA_PKCS1_PADDING,
},
buffer
);
return encrypted.toString("base64");
}

function initialize_api_from_dotenv() {
if (!mpesaConfig) {
mpesaConfig = {
baseUrl: process.env.MPESA_API_HOST,
apiKey: process.env.MPESA_API_KEY,
publicKey: process.env.MPESA_PUBLIC_KEY,
origin: process.env.MPESA_ORIGIN,
serviceProviderCode: process.env.MPESA_SERVICE_PROVIDER_CODE
};
validateConfig(mpesaConfig);
console.log("Using M-Pesa environment configuration");
} else {
console.log("Using custom M-Pesa configuration");
}
if (!mpesaConfig) {
mpesaConfig = {
baseUrl: process.env.MPESA_API_HOST,
apiKey: process.env.MPESA_API_KEY,
publicKey: process.env.MPESA_PUBLIC_KEY,
origin: process.env.MPESA_ORIGIN,
serviceProviderCode: process.env.MPESA_SERVICE_PROVIDER_CODE,
};
validateConfig(mpesaConfig);
console.log("Using M-Pesa environment configuration");
} else {
console.log("Using custom M-Pesa configuration");
}
}

function required_config_arg(argName) {
return "Please provide a valid " + argName + " in the configuration when calling initializeApi()";
throw new Error(
"Please provide a valid " +
argName +
" in the configuration when calling initializeApi()"
);
}

function validateConfig(configParams) {
if (!configParams.baseUrl) {
throw required_config_arg("baseUrl")
}
if (!configParams.apiKey) {
throw required_config_arg("apiKey")
}
if (!configParams.publicKey) {
throw required_config_arg("publicKey")
}
if (!configParams.origin) {
throw required_config_arg("origin")
}
if (!configParams.serviceProviderCode) {
throw required_config_arg("serviceProviderCode")
}
if (!configParams.baseUrl) {
required_config_arg("baseUrl");
}
if (!configParams.apiKey) {
required_config_arg("apiKey");
}
if (!configParams.publicKey) {
required_config_arg("publicKey");
}
if (!configParams.origin) {
required_config_arg("origin");
}
if (!configParams.serviceProviderCode) {
required_config_arg("serviceProviderCode");
}
}

module.exports.initializeApi = function (configParams) {
validateConfig(configParams);
mpesaConfig = configParams;
};
/**
* Formating phone number to 258 + 84/85 + XXXXXXX
* @param {*} msisdn
* @returns
*/
function parseMsisdn(msisdn) {
if (!isValidPhoneNumber(msisdn, "MZ")) {
throw new Error("Invalid phone number");
} else {
const phoneNumber = parsePhoneNumber(msisdn, "MZ");
return phoneNumber.countryCallingCode + phoneNumber.nationalNumber;
}
}

module.exports.initiate_c2b = async function (amount, msisdn, transaction_ref, thirdparty_ref) {
initialize_api_from_dotenv();
try {
let response;
response = await axios({
method: 'post',
url: 'https://' + mpesaConfig.baseUrl + ':18352/ipg/v1x/c2bPayment/singleStage/',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + _getBearerToken(mpesaConfig.publicKey, mpesaConfig.apiKey),
'Origin': mpesaConfig.origin
},
data: {
"input_TransactionReference": transaction_ref,
"input_CustomerMSISDN": msisdn + "",
"input_Amount": amount + "",
"input_ThirdPartyReference": thirdparty_ref,
"input_ServiceProviderCode": mpesaConfig.serviceProviderCode + ""
}
});
return response.data;
} catch (e) {
if (e.response.data) {
throw e.response.data;
} else {
throw e;
}
export function initializeApi(configParams) {
validateConfig(configParams);
mpesaConfig = configParams;
}

export async function initiate_c2b(
amount,
msisdn,
transaction_ref,
thirdparty_ref
) {
initialize_api_from_dotenv();

try {
const response = await axios({
method: "post",
url:
"https://" +
mpesaConfig.baseUrl +
":18352/ipg/v1x/c2bPayment/singleStage/",
headers: {
"Content-Type": "application/json",
Authorization:
"Bearer " +
_getBearerToken(mpesaConfig.publicKey, mpesaConfig.apiKey),
Origin: mpesaConfig.origin,
},
data: {
input_TransactionReference: transaction_ref,
input_CustomerMSISDN: parseMsisdn(msisdn) + "",
input_Amount: amount + "",
input_ThirdPartyReference: thirdparty_ref,
input_ServiceProviderCode: mpesaConfig.serviceProviderCode + "",
},
});
return response.data;
} catch (e) {
if (e.response?.data) {
throw e.response.data;
} else {
throw e;
}
};
}
}

module.exports.initiate_b2c = async function (amount, msisdn, transaction_ref, thirdparty_ref) {
initialize_api_from_dotenv();
try {
let response;
response = await axios({
method: 'post',
url: 'https://' + mpesaConfig.baseUrl + ':18345/ipg/v1x/b2cPayment/',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + _getBearerToken(mpesaConfig.publicKey, mpesaConfig.apiKey),
'Origin': mpesaConfig.origin
},
data: {
"input_TransactionReference": transaction_ref,
"input_CustomerMSISDN": msisdn + "",
"input_Amount": amount + "",
"input_ThirdPartyReference": thirdparty_ref,
"input_ServiceProviderCode": mpesaConfig.serviceProviderCode + ""
}
});
return response.data;
} catch (e) {
if (e.response.data) {
throw e.response.data;
} else {
throw e;
}
export async function initiate_b2c(
amount,
msisdn,
transaction_ref,
thirdparty_ref
) {
initialize_api_from_dotenv();
try {
const response = await axios({
method: "post",
url: "https://" + mpesaConfig.baseUrl + ":18345/ipg/v1x/b2cPayment/",
headers: {
"Content-Type": "application/json",
Authorization:
"Bearer " +
_getBearerToken(mpesaConfig.publicKey, mpesaConfig.apiKey),
Origin: mpesaConfig.origin,
},
data: {
input_TransactionReference: transaction_ref,
input_CustomerMSISDN: parseMsisdn(msisdn) + "",
input_Amount: amount + "",
input_ThirdPartyReference: thirdparty_ref,
input_ServiceProviderCode: mpesaConfig.serviceProviderCode + "",
},
});
return response.data;
} catch (e) {
if (e.response?.data) {
throw e.response.data;
} else {
throw e;
}
};
}
}
11 changes: 6 additions & 5 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
"version": "1.1.0",
"description": "Node.js library for M-Pesa API (Mozambique)",
"main": "index.js",
"type": "module",
"scripts": {
"test": "mocha"
},
Expand All @@ -20,13 +21,13 @@
},
"homepage": "https://github.com/rosariopfernandes/mpesa-node-api",
"dependencies": {
"axios": "^0.21.1",
"axios": "^1.5.1",
"constants": "0.0.2",
"crypto": "^1.0.1",
"dotenv": "^8.2.0"
"dotenv": "^16.3.1",
"libphonenumber-js": "^1.10.47"
},
"devDependencies": {
"chai": "^4.2.0",
"mocha": "^8.0.1"
"chai": "^4.3.10",
"mocha": "^10.2.0"
}
}
8 changes: 4 additions & 4 deletions test/test.js
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
const mpesa = require('../index');
const expect = require('chai').expect;
import { initializeApi } from '../index';
import { expect } from 'chai';

describe('config', function () {
it('initializeApi throws an error when required config is missing', function () {
const actualConfig = {
baseUrl: "api.mpesa.co.mz"
};
try {
mpesa.initializeApi(actualConfig)
initializeApi(actualConfig)
} catch (e) {
expect(e).to.equal('Please provide a valid apiKey in the configuration when calling initializeApi()')
}
Expand All @@ -22,7 +22,7 @@ describe('config', function () {
serviceProviderCode: 171717
};
expect(function () {
mpesa.initializeApi(actualConfig)
initializeApi(actualConfig)
}).to.not.throw();
});
});