@yabetoo/mtn-momo-js
Version:
MTN Mobile Money API Client for NodeJS written in TypeScript
2 lines (1 loc) • 10.5 kB
JavaScript
import{v4 as e}from"uuid";import{strictEqual as r}from"assert";import t from"axios";function n(){return n=Object.assign?Object.assign.bind():function(e){for(var r=1;r<arguments.length;r++){var t=arguments[r];for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n])}return e},n.apply(this,arguments)}function s(e,r){if(null==e)return{};var t,n,s={},a=Object.keys(e);for(n=0;n<a.length;n++)r.indexOf(t=a[n])>=0||(s[t]=e[t]);return s}var a,c,o,i;!function(e){e.MSISDN="MSISDN",e.EMAIL="EMAIL",e.PARTY_CODE="PARTY_CODE"}(a||(a={})),function(e){e.SANDBOX="sandbox",e.PRODUCTION="production"}(c||(c={})),function(e){e.SUCCESSFUL="SUCCESSFUL",e.PENDING="PENDING",e.FAILED="FAILED"}(o||(o={})),function(e){e.PAYEE_NOT_FOUND="PAYEE_NOT_FOUND",e.PAYER_NOT_FOUND="PAYER_NOT_FOUND",e.NOT_ALLOWED="NOT_ALLOWED",e.NOT_ALLOWED_TARGET_ENVIRONMENT="NOT_ALLOWED_TARGET_ENVIRONMENT",e.INVALID_CALLBACK_URL_HOST="INVALID_CALLBACK_URL_HOST",e.INVALID_CURRENCY="INVALID_CURRENCY",e.SERVICE_UNAVAILABLE="SERVICE_UNAVAILABLE",e.INTERNAL_PROCESSING_ERROR="INTERNAL_PROCESSING_ERROR",e.NOT_ENOUGH_FUNDS="NOT_ENOUGH_FUNDS",e.PAYER_LIMIT_REACHED="PAYER_LIMIT_REACHED",e.PAYEE_NOT_ALLOWED_TO_RECEIVE="PAYEE_NOT_ALLOWED_TO_RECEIVE",e.PAYMENT_NOT_APPROVED="PAYMENT_NOT_APPROVED",e.RESOURCE_NOT_FOUND="RESOURCE_NOT_FOUND",e.APPROVAL_REJECTED="APPROVAL_REJECTED",e.EXPIRED="EXPIRED",e.TRANSACTION_CANCELED="TRANSACTION_CANCELED",e.RESOURCE_ALREADY_EXIST="RESOURCE_ALREADY_EXIST"}(i||(i={}));class u extends Error{constructor(e){super(e),Object.setPrototypeOf(this,new.target.prototype)}}class E extends u{constructor(){super(...arguments),this.name="ApprovalRejectedError"}}class l extends u{constructor(){super(...arguments),this.name="ExpiredError"}}class d extends u{constructor(){super(...arguments),this.name="InternalProcessingError"}}class _ extends u{constructor(){super(...arguments),this.name="InvalidCallbackUrlHostError"}}class A extends u{constructor(){super(...arguments),this.name="InvalidCurrencyError"}}class N extends u{constructor(){super(...arguments),this.name="NotAllowedTargetEnvironmentError"}}class p extends u{constructor(){super(...arguments),this.name="NotAllowedError"}}class I extends u{constructor(){super(...arguments),this.name="NotEnoughFundsError"}}class m extends u{constructor(){super(...arguments),this.name="PayeeNotFoundError"}}class h extends u{constructor(){super(...arguments),this.name="PayeeNotAllowedToReceiveError"}}class O extends u{constructor(){super(...arguments),this.name="PayerLimitReachedError"}}class R extends u{constructor(){super(...arguments),this.name="PayerNotFoundError"}}class T extends u{constructor(){super(...arguments),this.name="PaymentNotApprovedError"}}class f extends u{constructor(){super(...arguments),this.name="ResourceAlreadyExistError"}}class y extends u{constructor(){super(...arguments),this.name="ResourceNotFoundError"}}class L extends u{constructor(){super(...arguments),this.name="ServiceUnavailableError"}}class D extends u{constructor(){super(...arguments),this.name="TransactionCancelledError"}}class P extends u{constructor(){super(...arguments),this.name="UnspecifiedError"}}function C(e){if(!e.response)return e;const{code:r,message:t}=e.response.data||{};return b(r,t)}function b(e,r){return e===i.APPROVAL_REJECTED?new E(r):e===i.EXPIRED?new l(r):e===i.INTERNAL_PROCESSING_ERROR?new d(r):e===i.INVALID_CALLBACK_URL_HOST?new _(r):e===i.INVALID_CURRENCY?new A(r):e===i.NOT_ALLOWED?new p(r):e===i.NOT_ALLOWED_TARGET_ENVIRONMENT?new N(r):e===i.NOT_ENOUGH_FUNDS?new I(r):e===i.PAYEE_NOT_FOUND?new m(r):e===i.PAYEE_NOT_ALLOWED_TO_RECEIVE?new h(r):e===i.PAYER_LIMIT_REACHED?new O(r):e===i.PAYER_NOT_FOUND?new R(r):e===i.PAYMENT_NOT_APPROVED?new T(r):e===i.RESOURCE_ALREADY_EXIST?new f(r):e===i.RESOURCE_NOT_FOUND?new y(r):e===i.SERVICE_UNAVAILABLE?new L(r):e===i.TRANSACTION_CANCELED?new D(r):new P(r)}function S(e){const r=b(e.reason);return r.transaction=e,r}function U(e){const{primaryKey:t}=e;r(g(t),!0,"primaryKey is required"),r(x(t),!0,"primaryKey must be a string")}function v(e){return!isNaN(parseInt(e,10))}function g(e){return!!e}function x(e){return"string"==typeof e}function w(e){return/^[0-9A-F]{8}-[0-9A-F]{4}-4[0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$/i.test(e)}const F=["callbackUrl"];class q{constructor(e){this.client=e}requestToPay(t){let{callbackUrl:a}=t,c=s(t,F);return function(e){const{amount:t,currency:n,payer:s}=e||{};return Promise.resolve().then(()=>{r(g(t),!0,"amount is required"),r(v(t),!0,"amount must be a number"),r(g(n),!0,"currency is required"),r(g(s),!0,"payer is required"),r(g(s.partyId),!0,"payer.partyId is required"),r(g(s.partyIdType),!0,"payer.partyIdType is required"),r(x(n),!0,"amount must be a string")})}(c).then(()=>{const r=e();return this.client.post("/collection/v1_0/requesttopay",c,{headers:n({"X-Reference-Id":r},a?{"X-Callback-Url":a}:{})}).then(()=>r)})}getTransaction(e){return this.client.get(`/collection/v1_0/requesttopay/${e}`).then(e=>e.data).then(e=>e.status===o.FAILED?Promise.reject(S(e)):Promise.resolve(e))}getBalance(){return this.client.get("/collection/v1_0/account/balance").then(e=>e.data)}isPayerActive(e,r=a.MSISDN){return this.client.get(`/collection/v1_0/accountholder/${r}/${e}/active`).then(e=>e.data)}}const V=["callbackUrl","referenceId"];class Y{constructor(e){this.client=e}transfer(t){let{callbackUrl:a,referenceId:c=e()}=t,o=s(t,V);return function(e){const{amount:t,currency:n,payee:s,referenceId:a}=e||{};return Promise.resolve().then(()=>{r(g(a),!0,"referenceId is required"),r(w(a),!0,"referenceId must be a valid uuid v4"),r(g(t),!0,"amount is required"),r(v(t),!0,"amount must be a number"),r(g(n),!0,"currency is required"),r(g(s),!0,"payee is required"),r(g(s.partyId),!0,"payee.partyId is required"),r(g(s.partyIdType),!0,"payee.partyIdType is required"),r(x(n),!0,"amount must be a string")})}(n({referenceId:c},o)).then(()=>this.client.post("/disbursement/v1_0/transfer",o,{headers:n({"X-Reference-Id":c},a?{"X-Callback-Url":a}:{})}).then(()=>c))}getTransaction(e){return this.client.get(`/disbursement/v1_0/transfer/${e}`).then(e=>e.data).then(e=>e.status===o.FAILED?Promise.reject(S(e)):Promise.resolve(e))}getBalance(){return this.client.get("/disbursement/v1_0/account/balance").then(e=>e.data)}isPayerActive(e,r=a.MSISDN){return this.client.get(`/disbursement/v1_0/accountholder/${String(r).toLowerCase()}/${e}/active`).then(e=>e.data).then(e=>!!e.result&&e.result)}}const k=["callbackUrl","referenceId"];class B{constructor(e){this.client=e}remit(t){let{callbackUrl:a,referenceId:c=e()}=t,o=s(t,k);return function(e){const{amount:t,currency:n,payee:s,referenceId:a}=e||{};return Promise.resolve().then(()=>{r(g(a),!0,"referenceId is required"),r(w(a),!0,"referenceId must be a valid uuid v4"),r(g(t),!0,"amount is required"),r(v(t),!0,"amount must be a number"),r(g(n),!0,"currency is required"),r(g(s),!0,"payee is required"),r(g(s.partyId),!0,"payee.partyId is required"),r(g(s.partyIdType),!0,"payee.partyIdType is required"),r(x(n),!0,"amount must be a string")})}(n({referenceId:c},o)).then(()=>this.client.post("/remittance/v1_0/transfer",o,{headers:n({"X-Reference-Id":c},a?{"X-Callback-Url":a}:{})}).then(()=>c))}getTransaction(e){return this.client.get(`/remittance/v1_0/transfer/${e}`).then(e=>e.data).then(e=>e.status===o.FAILED?Promise.reject(S(e)):Promise.resolve(e))}getBalance(){return this.client.get("/remittance/v1_0/account/balance").then(e=>e.data)}isPayerActive(e,r=a.MSISDN){return this.client.get(`/remittance/v1_0/accountholder/${String(r).toLowerCase()}/${e}/active`).then(e=>e.data).then(e=>!!e.result&&e.result)}}class X{constructor(e){this.client=e}create(r){const t=e();return this.client.post("/v1_0/apiuser",{providerCallbackHost:r},{headers:{"X-Reference-Id":t}}).then(()=>t)}login(e){return this.client.post(`/v1_0/apiuser/${e}/apikey`).then(e=>e.data)}}function $(e,r=t.create()){return r.defaults.baseURL=e.baseUrl,r.defaults.headers={"Ocp-Apim-Subscription-Key":e.primaryKey,"X-Target-Environment":e.environment||"sandbox"},function(e){return e.interceptors.response.use(e=>e,e=>Promise.reject(C(e))),e}(r)}function M(e,r){return r.interceptors.request.use(r=>e().then(e=>n({},r,{headers:n({},r.headers,{Authorization:`Bearer ${e}`})}))),r}function H(e,r){let t;return()=>function(e){return!e||!e.expires||Date.now()>e.expires}(t)?e(r).then(e=>{const{access_token:r,expires_in:t}=e;return{accessToken:r,expires:Date.now()+1e3*t-6e4}}).then(e=>(t=e,t.accessToken)):Promise.resolve(t.accessToken)}const G=function(e,r=$(e)){const t=K(e);return r.post("/collection/token/",null,{headers:{Authorization:`Basic ${t}`}}).then(e=>e.data)},j=function(e,r=$(e)){const t=K(e);return r.post("/disbursement/token/",null,{headers:{Authorization:`Basic ${t}`}}).then(e=>e.data)},W=function(e,r=$(e)){const t=K(e);return r.post("/remittance/token/",null,{headers:{Authorization:`Basic ${t}`}}).then(e=>e.data)};function K(e){return Buffer.from(`${e.userId}:${e.userSecret}`).toString("base64")}const z={baseUrl:"https://sandbox.momodeveloper.mtn.com",environment:c.SANDBOX};function J(e){return function(e){const{callbackHost:t,baseUrl:n,environment:s}=e;r(g(t),!0,"callbackHost is required"),s&&s!==c.SANDBOX&&(r(g(n),!0,"baseUrl is required if environment is not sandbox"),r(x(n),!0,"baseUrl must be a string"))}(e),{Collections(t){!function(e){U(e),function({userId:e,userSecret:t}){r(g(e),!0,"userId is required"),r(x(e),!0,"userId must be a string"),r(g(t),!0,"userSecret is required"),r(x(t),!0,"userSecret must be a string"),r(w(e),!0,"userId must be a valid uuid v4")}(e)}(t);const s=n({},z,e,t),a=M(H(G,s),$(s));return new q(a)},Disbursements(r){const t=n({},z,e,r),s=M(H(j,t),$(t));return new Y(s)},Remittances(r){const t=n({},z,e,r),s=M(H(W,t),$(t));return new B(s)},Users(r){U(r);const t=$(n({},z,e,r));return new X(t)}}}export{E as ApprovalRejectedError,c as Environment,l as ExpiredError,i as FailureReason,d as InternalProcessingError,_ as InvalidCallbackUrlHostError,A as InvalidCurrencyError,u as MtnMoMoError,p as NotAllowedError,N as NotAllowedTargetEnvironmentError,I as NotEnoughFundsError,h as PayeeNotAllowedToReceiveError,m as PayeeNotFoundError,O as PayerLimitReachedError,R as PayerNotFoundError,a as PayerType,T as PaymentNotApprovedError,f as ResourceAlreadyExistError,y as ResourceNotFoundError,L as ServiceUnavailableError,o as Status,D as TransactionCancelledError,P as UnspecifiedError,J as create,b as getError,S as getTransactionError,C as handleError};