@byinti/risk-management-js
Version:
Library JS for use in Risk Management
6 lines • 16.5 kB
JavaScript
/**
* # Risk Management Library
*/
/* # global RiskManagement */
/* # eslint-disable */
const DECISION_MANAGER="decision_manager",PAYMENT_AUTHENTICATION_3DS="payment_authentication_3ds",CREDIT_CARD_BILL_CODE="credit_card_bill_code",ADIQ_3DS="adiq_3ds",PASSKEY_C2P="passkey_c2p",STATUS_3DS_ACCEPTED="AUTHENTICATION_SUCCESSFUL",STATUS_3DS_PENDING="PENDING_AUTHENTICATION",STATUS_3DS_REJECTED="AUTHENTICATION_FAILED",RESULT_ACCEPTED="accepted",RESULT_REJECTED="rejected",RESULT_ERROR="error",BEHAVIOUR_NEXT="next",BEHAVIOUR_BREAK="break",BEHAVIOUR_OK="ok",ipifyRequest={url:"https://api.ipify.org/?format=json?",type:"GET"};var requestLib="axios",requestLibObject=null,userIp=null,isProdEnvironment=!0,isMicroformActive=!1,urlsRequests=null,deviceInformation=null,fieldsVariables={totalAmountField:null,installmentsField:null,creditCardNumberField:null,creditCardBrandField:null,creditCardTokenField:null,creditCardExpMonthField:null,creditCardExpYearField:null,creditCardCvv:null,creditCardHolderName:null,checkoutMethodField:null,creditCardPaymentToken:{value:!1}};class RiskManagementHelpers{static log(e,t){isProdEnvironment||console.log("[RiskManagement] "+e,t)}static error(e,t){console.error("[RiskManagement] "+e,t)}static loadAxios(e){var t=document.createElement("script");t.onload=function(){e()},t.src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js",document.head.appendChild(t)}static loadJQuery(e){var t=document.createElement("script");t.onload=function(){e()},t.src="https://code.jquery.com/jquery-3.6.0.slim.min.js",document.head.appendChild(t)}static sendRequest(e,t=null,a,i){"jquery"===requestLib?this.jqueryRequests(e,t,a,i):this.axiosRequests(e,t,a,i)}static axiosRequests(e,t=null,a,i){var r=requestLibObject||axios;"GET"===e.type?r.get(e.url).then(function(e){a(e.data||e)}).catch(function(e){i(e)}):"POST"===e.type?r.post(e.url,t).then(function(e){a(e.data||e)}).catch(function(e){i(e)}):r.put(e.url,t).then(function(e){a(e.data||e)}).catch(function(e){i(e)})}static jqueryRequests(e,t=null,a,i){"GET"===e.type?$.get(e.url,function(e){a(e)}).fail(function(e){i(e)}):"POST"===e.type?$.post(e.url,t,function(e){a(e)}).fail(function(e){i(e)}):$.ajax({type:"PUT",url:e.url,contentType:"application/json",data:t}).done(function(e){a(e)}).fail(function(e){i(e)})}static getField(e){return document.querySelector('input[name="'+fieldsVariables[e]+'"]')||document.getElementById(fieldsVariables[e])||fieldsVariables[e]||null}}class DecisionManager{execute(t){RiskManagementHelpers.log("execute","execute dm is starting...");var e={totalAmount:RiskManagementHelpers.getField("totalAmountField").value,installments:RiskManagementHelpers.getField("installmentsField").value,card_number:RiskManagementHelpers.getField("creditCardNumberField").value,card_exp_month:RiskManagementHelpers.getField("creditCardExpMonthField").value,card_exp_year:RiskManagementHelpers.getField("creditCardExpYearField").value,card_token:RiskManagementHelpers.getField("creditCardTokenField").value,payment_token:RiskManagementHelpers.getField("creditCardPaymentToken").value,device_information:JSON.stringify(deviceInformation)};RiskManagementHelpers.sendRequest(urlsRequests.urlDecisionManagerAnalysis,e,function(e){e.status?(t.executeStackServices(RESULT_REJECTED),RiskManagementHelpers.log("execute","execute dm was rejected!")):(t.executeStackServices(RESULT_ACCEPTED),RiskManagementHelpers.log("execute","execute dm was accepted!"))},function(e){RiskManagementHelpers.error("execute",e),t.executeStackServices(RESULT_ERROR),RiskManagementHelpers.log("execute","execute dm was error!")})}}class PayerAuthentication3DS{constructor(){this.retryStart3DSLimit=3,this.retryStart3DSCounter=0,this.retryStart3DSTimer=null}startCybersource3DS(a){RiskManagementHelpers.log("start","execute 3ds is start...");var i=this;"undefined"==typeof Cardinal&&null===this.retryStart3DSTimer&&this.retryStart3DS(),RiskManagementHelpers.sendRequest(urlsRequests.urlCardinalJwt,null,function(e){e?(Cardinal.off("payments.validated"),Cardinal.configure({timeout:"8000",maxRequestRetries:"10",logging:{level:isProdEnvironment?"off":"verbose"}}),clearInterval(i.retryStart3DSTimer),Cardinal.setup("init",{jwt:e}),Cardinal.on("payments.setupComplete",function(e){}),Cardinal.on("payments.validated",(e,t)=>{i.validateCybersource3DSChallenge(a,t)})):RiskManagementHelpers.error("start",error)},function(e){RiskManagementHelpers.error("start",e)})}retryStart3DS(){var e=this;this.retryStart3DSTimer=setInterval(function(){e.retryStart3DSCounter++,e.retryStart3DSCounter<=e.retryStart3DSLimit?(RiskManagementHelpers.log("retry 3ds","Attempt "+e.retryStart3DSCounter),e.startCybersource3DS()):clearInterval(e.retryStart3DSTimer)},1e3)}sendPanCardCybersource3DS(){var e=RiskManagementHelpers.getField("creditCardNumberField").value;e&&Cardinal.trigger("accountNumber.update",e)}execute(t){RiskManagementHelpers.log("execute","execute 3ds is starting..."),RiskManagementHelpers.sendRequest(urlsRequests.urlPaymentAuthenticationCybersourceAnalysis,{payment_method:RiskManagementHelpers.getField("checkoutMethodField").value,card_number:RiskManagementHelpers.getField("creditCardNumberField").value,card_brand:RiskManagementHelpers.getField("creditCardBrandField").value,card_exp_month:RiskManagementHelpers.getField("creditCardExpMonthField").value,card_exp_year:RiskManagementHelpers.getField("creditCardExpYearField").value,card_token:RiskManagementHelpers.getField("creditCardTokenField").value,totalAmount:RiskManagementHelpers.getField("totalAmountField").value,payment_token:RiskManagementHelpers.getField("creditCardPaymentToken").value,device_information:JSON.stringify(deviceInformation)},function(e){e=e.payment_authentication_3ds||null;e?e.status===STATUS_3DS_ACCEPTED?(t.executeStackServices(RESULT_ACCEPTED),RiskManagementHelpers.log("execute","3ds execution was accepted!")):e.status===STATUS_3DS_PENDING?(RiskManagementHelpers.log("execute","execute 3ds requested challenge"),Cardinal.continue("cca",{AcsUrl:e.consumerAuthenticationInformation.acsUrl,Payload:e.consumerAuthenticationInformation.pareq},{OrderDetails:{TransactionId:e.consumerAuthenticationInformation.authenticationTransactionId}})):(t.executeStackServices(RESULT_REJECTED),RiskManagementHelpers.log("execute","execute 3ds was rejected!")):null!=t.riskManagamentProfilesStack.find(e=>"credit_card_bill_code"===e.service)?(t.executeStackServices(RESULT_REJECTED),RiskManagementHelpers.log("challenge","execute 3ds was error! go to next because is credit card bill code")):(t.executeStackServices(RESULT_ERROR),RiskManagementHelpers.log("execute","execute 3ds was error!"))},function(e){RiskManagementHelpers.error("start 3ds challenge",e)})}validateCybersource3DSChallenge(t,e){RiskManagementHelpers.log("challenge","execute 3ds challenge check..."),RiskManagementHelpers.sendRequest(urlsRequests.urlCheckPaymentAuthenticationCybersourceResult,{payment_method:RiskManagementHelpers.getField("checkoutMethodField").value,card_number:RiskManagementHelpers.getField("creditCardNumberField").value,card_brand:RiskManagementHelpers.getField("creditCardBrandField").value,card_exp_month:RiskManagementHelpers.getField("creditCardExpMonthField").value,card_exp_year:RiskManagementHelpers.getField("creditCardExpYearField").value,card_token:RiskManagementHelpers.getField("creditCardTokenField").value,payment_token:RiskManagementHelpers.getField("creditCardPaymentToken").value,totalAmount:RiskManagementHelpers.getField("totalAmountField").value,jwt:e},function(e){"object"==typeof e&&"result"in e&&!0===e.result||!0===e?(t.executeStackServices(RESULT_ACCEPTED),RiskManagementHelpers.log("challenge","challenge 3ds was accepted!")):null!=t.riskManagamentProfilesStack.find(e=>"credit_card_bill_code"===e.service)?t.callbackBehaviourBreak():(t.executeStackServices(RESULT_REJECTED),RiskManagementHelpers.log("challenge","challenge 3ds was rejected!"))},function(e){RiskManagementHelpers.error("validate 3ds challenge",e),t.executeStackServices(RESULT_ERROR)})}}class CreditCardBillCode{execute(t){var e;t.paymentPayload?((e=t.paymentPayload).payments_data.map(e=>("credit_card"===e.payment_method&&(e=Object.assign(e,{card_number:e.number||"",card_holder_name:e.holderName||"",card_cvv:e.cvc||"",payment_token:e.payment_token||"",validDate:e.validDate||"",installments:e.installments||1,card_expiration_month:e.expiry.month||"",card_expiration_year:e.expiry.year||"",card_hash:e.cardHash||""}),Object.prototype.hasOwnProperty.call(e,"billing"))&&(e.billing={address:e.billing.address,address2:e.billing.address2,address_number:e.billing.number,city:e.billing.city,country:e.billing.country,district:e.billing.district,name:e.billing.name,state:e.billing.state,zipcode:e.billing.zipcode}),e)),RiskManagementHelpers.sendRequest(urlsRequests.urlExecuteCreditCardBillCode,e,function(e){console.log(e),e.payment_status&&"refused"!==e.payment_status?(t.executeStackServices(RESULT_ACCEPTED),RiskManagementHelpers.log("payment","credit card bill code payment success")):(t.executeStackServices(RESULT_ERROR),RiskManagementHelpers.log("payment","credit card bill code payment failed with message: "+e.message))},function(e){t.executeStackServices(RESULT_ERROR),RiskManagementHelpers.log("payment","credit card bill code payment error")})):(t.executeStackServices(RESULT_ERROR),RiskManagementHelpers.log("payment","credit card bill code payment error"))}}class PayerPasskeyC2P{execute(t){RiskManagementHelpers.log("execute","execute passkey c2p is starting..."),RiskManagementHelpers.sendRequest(urlsRequests.urlPaymentPasskeyClickToPayAnalysis,{payment_method:RiskManagementHelpers.getField("checkoutMethodField").value,card_number:RiskManagementHelpers.getField("creditCardNumberField").value,card_brand:RiskManagementHelpers.getField("creditCardBrandField").value,card_exp_month:RiskManagementHelpers.getField("creditCardExpMonthField").value,card_exp_year:RiskManagementHelpers.getField("creditCardExpYearField").value,card_token:RiskManagementHelpers.getField("creditCardTokenField").value,totalAmount:RiskManagementHelpers.getField("totalAmountField").value,payment_token:RiskManagementHelpers.getField("creditCardPaymentToken").value,device_information:JSON.stringify(deviceInformation)},function(e){"object"==typeof e&&"result"in e&&!0===e.result||!0===e?(t.executeStackServices(RESULT_ACCEPTED),RiskManagementHelpers.log("execute","passkey c2p execution was accepted!")):(t.executeStackServices(RESULT_REJECTED),RiskManagementHelpers.log("execute","execute passkey c2p was rejected!"))},function(e){t.executeStackServices(RESULT_ERROR),RiskManagementHelpers.error("error when execute passkey c2p",e)})}}class RiskManagement{constructor(t,e,a,i){urlsRequests=a,Object.keys(fieldsVariables).forEach(function(e){fieldsVariables[e]=t[e]||null}),this.configs=e,this.riskManagamentProfilesStack={},this.currentService=null,this.behavioursService=[],this.callbackBehaviourBreak=null,this.callbackBehaviourOk=null,this.indexStack=null,this.payerAuthentication3DS=null,this.creditCardBillCode=new CreditCardBillCode,this.payerPasskeyC2P=new PayerPasskeyC2P,this.orderCode=i,this.configurationCourse=this.configureRiskManagement()}async configureRiskManagement(){return requestLib=this.configs.hasOwnProperty("requestLib")?this.configs.requestLib:"axios",requestLibObject=this.configs.hasOwnProperty("requestLibObject")?this.configs.requestLibObject:null,userIp=this.configs.userIp||null,isProdEnvironment=!this.configs.hasOwnProperty("isProd")||this.configs.isProd,isMicroformActive=this.configs.isMicroform||!1,this.riskManagamentProfilesStack=this.configs.riskManagamentProfilesStack?JSON.parse(this.configs.riskManagamentProfilesStack):null,RiskManagementHelpers.log("configs",this.configs),RiskManagementHelpers.log("urlsRequests",urlsRequests),RiskManagementHelpers.log("profiles stack",this.riskManagamentProfilesStack),RiskManagementHelpers.log("configure","configure is complete!"),this.checkVariablesAndConfigs()}async checkVariablesAndConfigs(){return new Promise((e,t)=>{let a=()=>{this.configurationCourse=null,e()};var i=()=>{this.configurationCourse=null,t()},r=null;Object.keys(fieldsVariables).forEach(function(e){null!==fieldsVariables[e]&&null!==RiskManagementHelpers.getField(e)||(r=e)}),null!==r?(RiskManagementHelpers.error("configs",'Config field "'+r+'" not found!'),i()):null===typeof this.riskManagamentProfilesStack?(RiskManagementHelpers.error("configs",'Config "riskManagamentProfilesStack" not found!'),i()):"axios"===requestLib&&"undefined"==typeof axios?RiskManagementHelpers.loadAxios(()=>{this.setupRiskManagement(),a()}):"jquery"===requestLib&&"undefined"==typeof jQuery?RiskManagementHelpers.loadJQuery(()=>{this.setupRiskManagement(),a()}):(this.setupRiskManagement(),a())})}setupRiskManagement(){if(RiskManagementHelpers.log("setup","setup is start..."),deviceInformation={ip:userIp,url:window.location.host,acceptContent:this.configs.acceptContent||"",language:navigator.language,javaEnabled:navigator.javaEnabled()||!1,javascriptEnabled:!0,colorDepth:screen.colorDepth.toString(),browserWidth:screen.availWidth.toString(),browserHeight:screen.availHeight.toString(),timeDifferenceUTC:(new Date).getTimezoneOffset().toString(),userAgent:navigator.userAgent},null===userIp?RiskManagementHelpers.sendRequest(ipifyRequest,null,function(e){deviceInformation.ip=e.data||e||"",RiskManagementHelpers.log("setup","get ip and device information save with success...")},function(e){RiskManagementHelpers.error("setup",e)}):RiskManagementHelpers.log("setup","device information save with success..."),this.riskManagamentProfilesStack.map(e=>e.service).includes(PAYMENT_AUTHENTICATION_3DS)){if(this.payerAuthentication3DS=new PayerAuthentication3DS,this.payerAuthentication3DS.startCybersource3DS(this),!isMicroformActive){let a=(t=0)=>{if(3<t)RiskManagementHelpers.log("setup","Error on atach focus out to credit card field. Field not found");else try{RiskManagementHelpers.getField("creditCardNumberField").addEventListener("focusout",this.payerAuthentication3DS.sendPanCardCybersource3DS)}catch(e){setTimeout(()=>{a(t+1)},500)}};a()}RiskManagementHelpers.log("setup","start cybersource 3ds with success...")}RiskManagementHelpers.log("setup","setup is complete!")}execute(e=null,t=null,a=null){let i=()=>{this.callbackBehaviourBreak=e,this.callbackBehaviourOk=t,this.paymentPayload=a,this.indexStack=-1,0<this.riskManagamentProfilesStack.length?this.executeService():this.callbackBehaviourOk()};this.configurationCourse?this.configurationCourse.then(()=>{i()}):i()}executeStackServices(e){switch(this.behavioursService[e]){case BEHAVIOUR_NEXT:this.executeService();break;case BEHAVIOUR_BREAK:this.callbackBehaviourBreak(this.currentService);break;case BEHAVIOUR_OK:this.callbackBehaviourOk(this.currentService)}}getNextService(){this.indexStack<this.riskManagamentProfilesStack.length&&(this.indexStack++,RiskManagementHelpers.log("index stack",this.indexStack)),this.currentService=this.riskManagamentProfilesStack[this.indexStack].service,RiskManagementHelpers.log("current service",this.currentService),this.behavioursService=this.riskManagamentProfilesStack[this.indexStack].behaviours,RiskManagementHelpers.log("behaviours service",this.behavioursService)}executeService(){let t=this;switch(this.getNextService(),this.currentService){case DECISION_MANAGER:let e=new DecisionManager;isMicroformActive?(RiskManagementHelpers.log("execute","execute microform generate hash..."),generateCybersourceCardHash(()=>{e.execute(t)})):e.execute(t);break;case PAYMENT_AUTHENTICATION_3DS:isMicroformActive?(RiskManagementHelpers.log("execute","execute microform generate hash..."),generateCybersourceCardHash(()=>{this.payerAuthentication3DS.execute(t)})):this.payerAuthentication3DS.execute(t);break;case CREDIT_CARD_BILL_CODE:isMicroformActive?(RiskManagementHelpers.log("execute","execute microform generate hash..."),generateCybersourceCardHash(()=>{this.creditCardBillCode.execute(t)})):this.creditCardBillCode.execute(t);break;case PASSKEY_C2P:isMicroformActive?(RiskManagementHelpers.log("execute","execute microform generate hash..."),generateCybersourceCardHash(()=>{this.payerPasskeyC2P.execute(t)})):this.payerPasskeyC2P.execute(t);break;default:RiskManagementHelpers.error("execute","service is not defined!")}}getFirstServiceInStack(){return 0<this.riskManagamentProfilesStack.length?this.riskManagamentProfilesStack[0].service:null}hasServiceInStack(t){return 0<this.riskManagamentProfilesStack.length&&this.riskManagamentProfilesStack.some(e=>e.service===t)}}