var SmartScriptFunction = (function() {
this.ssInstance = null;
/*
* SmartScript
*/
class SmartScript {
constructor(config){
this.fraudType='DIm+10GJZaDU7NkOZSmQwA==';
this.cardinalOrgUnitId = '17ZpV6vsgIOAeNsFTpFXrpGtFX6q+jqMUGn/PJ+r3x8=';
this.cardinalApiIdentifier = 'EBBxA3ADrHTVh2LowQiX9ha23fcKSo1z/r+ldlx2Pmo=';
this.cardinalApiKey = 'p5h4zwlIVajqIMUra/196DQmHdphnqCkjeYhOCgX3VC5mjsbuqMD7fUx/XNeUfhY';
this.cybersourceServerJwtString = 'UgOQf1UQBaz3PfSUccEXH0s9cYRnESloOEXwWq8lWkFqGNxfS/BDNdQ4DCLAuuLgYDLfEa9TgoRYnAX9Pbp/R3lsvBNOV7veA89TEL5zNHlROGRfd9x+DsHVLEkgZVFMOSu8b+f+VE2MK2Mfu+Q/kKJSR5/5x5frLfIPSBdqpGYfOyNHbr+0079yWQWX63k49kG37I16SXNMM6SGuoq84qiloDZ+m3yTykKkV5XPrQbm3OlbrCIYUUMCy1B+pZKkD1irJJCzPNZ6Dzq2RjsiT+AQOJWnCT9pgfd+lAqYVTbGk2dkSrYp+gayM3Kg9to72/2zAtxDK5tj0erVW7s7LYpaWQMyhrBlC9l9EvpNY51Qg9ypTR4HkYQWdF4yPzJl5aYxe+YPqinawt9fITdRRMfTIK2CW/9a5lY6w5aoDhSkN9QpTjwqDcyY8sTU617yRYNN999FJJS0LdXKdvwzsM3yzTzvJ2AFl1N7Xsxc3N28UE/r8Q8RGIaMmW9zsXGhZT2JHF4kkL5gCJpIM7Cbsx7Ox7XyUJtPaxbdml+jAnL5ID1OZSUnSLsY05xyTz/W7PBk6tMy/NmRdRgQ1DF1qarJedGj5DkRNh4nuFFFiEW2cY87hlQqF8rT5YGSfbu0/a2+tQBbGID5ukOvGkdRsoJL463uTBrCOH/EZb+1xNuI1zLbu//urqFyhAeJOY3R+GTUL8PeyanMsIWGWjrCU3cU5H1KphRVbeCBp4VajlDu9DnesywIUr29vrRYMpH+';
this.secure3dCardTypes = "";
this.cnalScript = 'https://songbird.cardinalcommerce.com/cardinalcruise/v1/songbird.js';
this.enc_base64 = 'https://cdnjs.cloudflare.com/ajax/libs/crypto-js/3.1.2/components/enc-base64-min.js';
this.hamc_sha256 = 'https://cdnjs.cloudflare.com/ajax/libs/crypto-js/3.1.2/rollups/hmac-sha256.js';
this.dm_script = 'MVLNPU5TTxQXSAEViuMehg==';
this.dm_mid_id = 'XzeKFCk3RUVf4gfxouov5w==';
this.dm_uuid = 'sg24Ox4JLjwurFzhbuucUUcCm/yNxJSh4dWFlGZ9QCvNCvdldTh7I0GblVo19gC+';
this.riskified_uuid = '6SIiezcaxF/9Y6EPHMic5w5iPjJLcHwhbKPi2z0B3dBsUy6tn2xX1PsnbEp3IUlj';
this.payomoAccountId = 'cxOqmpMfqhZMeDYpELBf4Oc+8yzTXOVM3n5iq1GyVSRtFjby1NcZSOCWAu+k9Zde';
this.config = config;
this.jwt = this.cybersourceServerJwtString;
this.payomoServer ='do7xf8YSUtcl+au7bTyOaf3T02pPi2C2wmH+yZ6Hk88=';//"https://api.payomo.com"; //"http://localhost:8020";// ;
this.payomoStylesUrl ='https://dfpscript.payomo.com/css/ss.min.css';
this.payementReqButtonEle = "payment-request-button";
this.sessionId = 'OyCXX6Xn/NJCHGk+w9deNOmsYEYciwk+nt80d3+IsuE7JrKWTn7lD2hi1eM3x5l7';
this.sessionIdd = 'OyCXX6Xn/NJCHGk+w9deNOmsYEYciwk+nt80d3+IsuE7JrKWTn7lD2hi1eM3x5l7';
this.logSessionId='6oW6FCrvzJbXbvcCU1qD6T/bYUGY5Yk9OiBAoU65HUQ=';
this.braintreeInstance=null;
this.paymentMethodInfo=null;
this.enableRiskCheck= 'yes';
this.paymentOptions = ['cc'];
this.currencyJson = {'USD' : '$', 'INR' : 'rs'};
this.gPayMerchantId='c3TgA478J54EQUE3sSnW7ijO1TjaWRpbuQrlD4fv81c=';
this.braintreeSandBoxAuthKey='VvfkfTHla9gqNH8GDvsrVu7bmFkeo//Wb60zQ/76+soaMnVFn8oWrP8Wd4WlcNYR';
this.braintreeProductionAuthKey='DGAjfkQH+l/olLTnidmDewM71F2sOTJwXmH4JPAcDIj5h5ef1dVz5UiiFNYgsYhw';
this.brainTreeClientToken='eyJ2ZXJzaW9uIjoyLCJhdXRob3JpemF0aW9uRmluZ2VycHJpbnQiOiJleUowZVhBaU9pSktWMVFpTENKaGJHY2lPaUpGVXpJMU5pSXNJbXRwWkNJNklqSXdNVGd3TkRJMk1UWXRjSEp2WkhWamRHbHZiaUlzSW1semN5STZJbWgwZEhCek9pOHZZWEJwTG1KeVlXbHVkSEpsWldkaGRHVjNZWGt1WTI5dEluMC5leUpsZUhBaU9qRTNNalU1TWpjM01qa3NJbXAwYVNJNklqUTFZalppTkRSaExUVmtabVF0TkdGaU9DMDVaVEpsTFRGaU5XVTBNell6TmpaaVpDSXNJbk4xWWlJNkltYzNhM0J4WnpWeVkzWnRlRzFyYUdzaUxDSnBjM01pT2lKb2RIUndjem92TDJGd2FTNWljbUZwYm5SeVpXVm5ZWFJsZDJGNUxtTnZiU0lzSW0xbGNtTm9ZVzUwSWpwN0luQjFZbXhwWTE5cFpDSTZJbWMzYTNCeFp6VnlZM1p0ZUcxcmFHc2lMQ0oyWlhKcFpubGZZMkZ5WkY5aWVWOWtaV1poZFd4MElqcG1ZV3h6Wlgwc0luSnBaMmgwY3lJNld5SnRZVzVoWjJWZmRtRjFiSFFpWFN3aWMyTnZjR1VpT2xzaVFuSmhhVzUwY21WbE9sWmhkV3gwSWwwc0ltOXdkR2x2Ym5NaU9uc2liV1Z5WTJoaGJuUmZZV05qYjNWdWRGOXBaQ0k2SW5SeVlYWmxiRUZuWlc1amVWOXBibk4wWVc1MEluMTkuTUlGdTZmRHROT1NwWDJEeDllcmlzbGtWejZBZlViQUFZeEphQWlJOXNyX1J1djV6djdSejNXM0N5NVJ1XzNGb0JjOENoWVVmc2t1QURKN3NMT0drSlEiLCJjb25maWdVcmwiOiJodHRwczovL2FwaS5icmFpbnRyZWVnYXRld2F5LmNvbTo0NDMvbWVyY2hhbnRzL2c3a3BxZzVyY3ZteG1raGsvY2xpZW50X2FwaS92MS9jb25maWd1cmF0aW9uIiwibWVyY2hhbnRBY2NvdW50SWQiOiJ0cmF2ZWxBZ2VuY3lfaW5zdGFudCIsImdyYXBoUUwiOnsidXJsIjoiaHR0cHM6Ly9wYXltZW50cy5icmFpbnRyZWUtYXBpLmNvbS9ncmFwaHFsIiwiZGF0ZSI6IjIwMTgtMDUtMDgiLCJmZWF0dXJlcyI6WyJ0b2tlbml6ZV9jcmVkaXRfY2FyZHMiXX0sImNsaWVudEFwaVVybCI6Imh0dHBzOi8vYXBpLmJyYWludHJlZWdhdGV3YXkuY29tOjQ0My9tZXJjaGFudHMvZzdrcHFnNXJjdm14bWtoay9jbGllbnRfYXBpIiwiZW52aXJvbm1lbnQiOiJwcm9kdWN0aW9uIiwibWVyY2hhbnRJZCI6Imc3a3BxZzVyY3ZteG1raGsiLCJhc3NldHNVcmwiOiJodHRwczovL2Fzc2V0cy5icmFpbnRyZWVnYXRld2F5LmNvbSIsImF1dGhVcmwiOiJodHRwczovL2F1dGgudmVubW8uY29tIiwidmVubW8iOiJvZmYiLCJjaGFsbGVuZ2VzIjpbXSwidGhyZWVEU2VjdXJlRW5hYmxlZCI6dHJ1ZSwiYW5hbHl0aWNzIjp7InVybCI6Imh0dHBzOi8vY2xpZW50LWFuYWx5dGljcy5icmFpbnRyZWVnYXRld2F5LmNvbS9nN2twcWc1cmN2bXhta2hrIn0sInBheXBhbEVuYWJsZWQiOnRydWUsInBheXBhbCI6eyJiaWxsaW5nQWdyZWVtZW50c0VuYWJsZWQiOnRydWUsImVudmlyb25tZW50Tm9OZXR3b3JrIjpmYWxzZSwidW52ZXR0ZWRNZXJjaGFudCI6ZmFsc2UsImFsbG93SHR0cCI6ZmFsc2UsImRpc3BsYXlOYW1lIjoiVHJpcFBybyIsImNsaWVudElkIjoiQVJZcDBpWVBDNHNRY2RtTVM4YWVOc0lFckFZRlZ1NGpVVEtlb2Q0cEU5ZmJOOTk0S2N4TzNUdmR0am81OHZBUXdOZHlsdE9TZk5Qd0cxLUgiLCJiYXNlVXJsIjoiaHR0cHM6Ly9hc3NldHMuYnJhaW50cmVlZ2F0ZXdheS5jb20iLCJhc3NldHNVcmwiOiJodHRwczovL2NoZWNrb3V0LnBheXBhbC5jb20iLCJkaXJlY3RCYXNlVXJsIjpudWxsLCJlbnZpcm9ubWVudCI6ImxpdmUiLCJicmFpbnRyZWVDbGllbnRJZCI6IkFSS3JZUkRoM0FHWER6VzdzT18zYlNrcS1VMUM3SEdfdVdOQy16NTdMallTRE5VT1NhT3RJYTlxNlZwVyIsIm1lcmNoYW50QWNjb3VudElkIjoidHJhdmVsYWdlbmN5X2luc3RhbnQiLCJjdXJyZW5jeUlzb0NvZGUiOiJVU0QifX0=';
this.smartScriptEnvironment='gPkBSqQ4ALjG0OWdXf37zA==';
this.elkServer ='/DlvddnTkSaXqPxiDRrfh+9FQcchdw6u9ARZfkENbSCf/6hjgV0r8m+zzpD8Arbb';
this.enableElkLogging='yes';
this.count=100000;
this.threedsSource = 'IlP8+KkpnxUDAO+x5ViM9g==';
this.encryptionKey = 'V1VYOHNqeFplOFA4ZXJORUxFUkk2Q1Q0Z3RqZWRSSjk=,2e13c4a4-f9ca-4cc1-8b1e-8f18fdbf8dfe';
this.allowedCardTypes = '';
this.logJson={
"type": "SiteInteractLog",
"message": "",
"eventCategory": "",
"eventName": "",
"sessionId": "",
"userId": "",
"siteId": "",
"pageName": "",
"pageUrl": "",
"siteUrl": "",
"timestamp": "",
"level": "DEBUG",
"browserInfo": {},
"customer": {},
"httpStatusCode": "",
"logId": "",
"httpElapseTime": "",
"httpUrl": "",
"httpRequestType": "",
"httpResultType": "",
"pageSequence": 0,
"tpDeepLink": "direct",
"tpDeepLinkParam": {},
"httpServerAddress": "",
"itineraryGuid": "",
"pageload": {
"type": null,
"time": 0
},
"count": 0,
"queryParam": {},
"component": "",
"reprice": {},
"pageInfo": {},
"data":{"content":null}
};
if(this.widget == null || typeof this.widget == "undefined"){
this.widget=Widget;
}
this.filesLoaded = {
"songbird" : false,
"enc-base64-min" : false,
"hamc_sha256" : false,
"dm" : false
};
this.cardinalSetupCB = {
"setupComplete" : false,
"validated" : false
};
this.checkoutReplyJson= '{"accountId":"673F1FE9-CE9A-4DFA-A9BC-13CDCDE3BF25","pageId":"w7u4d8ukjhg","productId":"","logoUrl":"","iconUrl":"","isPayButtonRequired":true,"favIconUrl":"","path":"","enableWallets":["paypal","gpay"],"enableCards":["visa","masterCard","amex","discover"],"enableTransfers":[],"domain":"Trippro","subdomain":"","successUrl":"","failureUrl":"","cancelUrl":"","webhookUrl":"","templateId":"","templatePath":"","templateType":"","lineItemTemplateMapping":"","styleId":"widgetVerticle","threedsSource":"braintree"}';
this.gpayGatewayMerchantId= 'KDlm532kuLQtYAUAytmS4w==';
this.gateway= 'oGJwhDTcleEly8JRbz8Hpg==';
this.cardProfile='KM7VONpZGlu5CuUPh+/zVw==';
this.elkLogParam ='UGFoZDNXVFM4M1dmY2dPa3V5UjlpZz09'
console.log("called SmartScript constructor");
}
init(callback,logJsonVal) {
if(this.smartScriptEnvironment!="dev"){
console.log = function(){};
}
this.loadLibraries();
if(logJsonVal){
this.logJson=logJsonVal;
}
SmartScript.auditObject=new Audit(this.logJson);
var loader = new Loader();
this.creditCard=new CreditCard();
this.widget=Widget;
Widget.payResponse={};
Widget.paymentMethodType=null;
var widgetObj=new Widget();
widgetObj.loadWidgetStyles();
widgetObj.loadWidgetScripts();
widgetObj.braintreeHostedFields(); // braintree hosted fields for 3ds
//widgetObj.certificateOfCompletionDetails();
this.riskcheck=RiskManagement;
this.loadCrypto().then(res => {
console.log(res);
var riskObj=new RiskManagement(null);
riskObj.loadScripts();
}).catch(error => console.log(error));
//added Ifrmae code
widgetObj.deviceDataCollection();
widgetObj.steupIframe();
var interval = setInterval(function() {
//console.log(" file loaded checks.....");
if (widgetObj.isAllLoaded()) {
var json={"eventName":"risk_check_isAllLoaded_success","eventCategory":"app_user_interaction","message":"smart script class all scripts loaded success","data":null};
SmartScript.auditObject.sendDataToElk(json);
if(callback){
callback();
}
clearInterval(interval);
console.log("Clear Interval - " + interval)
}
}, 500)
/*var intval = setInterval(function() {
console.log(" cardinal token verification.....");
riskObj.cardinalTokenRefreshment();
}, 100*60*1000)*/
var langCode="es-US"; //es-US
var i18nbaseUrl="http://api-platform-prod2.prodservicesmd.rt"; //"http://10.11.3.89:8080";
//this.setI18ndata(langCode,i18nbaseUrl);
}
//load Crypto
loadCrypto(){
return new Promise(function(resolve, reject){
try{
var head = document.getElementsByTagName('head')[0];
var jScript = document.createElement('script');
jScript.src = "https://cdnjs.cloudflare.com/ajax/libs/crypto-js/3.1.9-1/crypto-js.min.js";
jScript.type = 'text/javascript';
jScript.addEventListener("load", (ev) => {
resolve("cryptoLoaded");
});
document.body.appendChild(jScript);
}catch(e){
console.log(e);
var json={"eventName":"load_crypto_js_exception","eventCategory":"load_crypto_js_exception","message":"load crypto-js failed","data":null};
SmartScript.auditObject.sendDataToElk(json);
reject("cryptoFailed");
}
})
}
//load Jquery
loadJquery(){
return new Promise(function(resolve, reject){
try{
var head = document.getElementsByTagName('head')[0];
var jScript = document.createElement('script');
jScript.src = "https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js";
jScript.type = 'text/javascript';
head.appendChild(jScript);
resolve("JqueryLoaded");
}catch(e){
console.log(e);
var json={"eventName":"load_Jquery_exception","eventCategory":"load_Jquery_exception","message":"load Jquery failed","data":e};
SmartScript.auditObject.sendDataToElk(json);
reject("JqueryFailed");
}
})
}
//load jquery then load boorstrap
loadLibraries() {
try {
if(typeof jQuery === 'undefined' || !jQuery) {
this.loadJquery().then(res => {
console.log(res);
var head = document.getElementsByTagName('head')[0];
var bScript = document.createElement('script');
bScript.src = "https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js";
bScript.type = 'text/javascript';
head.appendChild(bScript);
var bCss = document.createElement('link');
bCss.href = "https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css";
bCss.rel = 'stylesheet';
head.appendChild(bCss);
}).catch(error => console.log(error));
}
} catch (e) {
console.log("error while loading jquery lib :: " , e);
var json={"eventName":"load_bootstrap_exception","eventCategory":"load_bootstrap_exception","message":"load bootstrap failed","data":e};
SmartScript.auditObject.sendDataToElk(json);
}
}
// i18n library
setI18ndata(langCode,i18nbaseUrl){
if(langCode != null && langCode != undefined && langCode != ""){
langCode = langCode
} else{
langCode = "en-US";
}
if(i18nbaseUrl != null && i18nbaseUrl != undefined && i18nbaseUrl != ""){
i18nbaseUrl=i18nbaseUrl
} else{
i18nbaseUrl="http://api-platform-prod2.prodservicesmd.rt"; // "http://10.11.3.89:8080";
}
this.geti18nlib(langCode,i18nbaseUrl); // call API
}
// calling API to get i18n data
geti18nlib(langCode,i18nbaseUrl){
var self=this;
const i18nUrl = i18nbaseUrl+"/v2/i18n/commonlist/"+langCode+"/tripsClbRtl/tripsClbRtl/9173/siteClbRtl,menu?platform=TripPro&distribution=TripPro%20US";
//console.log("i18URL : ", self.getEncryptedtext(i18nUrl));
var json={"eventName":"load_i18n_lib","eventCategory":"load_i18n_lib","message":"load i18n lib Url ","data":i18nUrl};
SmartScript.auditObject.sendDataToElk(json);
const headers = {
"Content-Type": "application/json"
};
fetch(i18nUrl, {
method: "GET",
headers : headers
})
.then((response) => {
if (response.ok) {
return response.json();
} else{
//console.log("i18Data response failed",self.getEncryptedtext(response))
var json={"eventName":"load_i18n_lib_failed","eventCategory":"load_i18n_lib_failed","message":"load i18n lib failed ","data":response};
SmartScript.auditObject.sendDataToElk(json);
}
})
.then((json) => {
self.i18Data=json.data.keyDetails;
window.i18Data=json.data.keyDetails; // for globle declaration
//console.log("i18Data response : ", self.getEncryptedtext(json.data.keyDetails));
if(json.data != null && self.i18Data != null){
if(document.getElementById('billingInfo')){
document.getElementById('billingInfo').innerHTML = self.i18Data.Billing_Information;
}
if(document.getElementById('contactInfo')){
document.getElementById('contactInfo').innerHTML = self.i18Data.contact_info;
}
if(document.getElementById('cardnumberlbl') && document.getElementById("widget-card-number")){
document.getElementById('cardnumberlbl').innerHTML = self.i18Data.Card_Number+"*";
document.getElementById("widget-card-number").placeholder = self.i18Data.Card_Number;
}
if(document.getElementById('cardholderlbl') && document.getElementById("widget-card-holder")){
document.getElementById('cardholderlbl').innerHTML = self.i18Data.Card_Holder+"*";
document.getElementById("widget-card-holder").placeholder = self.i18Data.Card_Holder;
}
if(document.getElementById('cvv')){
document.getElementById('cvv').innerHTML = self.i18Data.CVV+"*";
}
if(document.getElementById('expireDate')){
document.getElementById('expireDate').innerHTML = self.i18Data.Expiry_Date+"*";
}
if(document.getElementById('divPayWithspn')){
document.getElementById('divPayWithspn').innerHTML = self.i18Data.or_pay_with;
}
if(document.getElementById('billingInfo')){
document.getElementById('billingInfo').innerHTML = self.i18Data.Billing_Information;
}
if(document.getElementById('email') && document.getElementById("widget-contactInfo-email")){
document.getElementById('email').innerHTML = self.i18Data.email+"*";
document.getElementById("widget-contactInfo-email").placeholder = self.i18Data.email;
}
if(document.getElementById('confirmEmail') && document.getElementById("widget-contactInfo-confirmEmail")){
document.getElementById('confirmEmail').innerHTML = self.i18Data.confirm_email+"*";
document.getElementById("widget-contactInfo-confirmEmail").placeholder = self.i18Data.confirm_email;
}
if(document.getElementById('phoneNumber') && document.getElementById("widget-contactInfo-phone2")){
document.getElementById('phoneNumber').innerHTML = self.i18Data.phone_number+"*";
document.getElementById("widget-contactInfo-phone2").placeholder = "1234567890";
}
if(document.getElementById('zipCode') && document.getElementById("widget-billingInfo-zipcode")){
document.getElementById('zipCode').innerHTML = self.i18Data.zip_code+"*";
document.getElementById("widget-billingInfo-zipcode").placeholder = self.i18Data.zip_code;
}
if(document.getElementById('city') && document.getElementById("widget-billingInfo-city")){
document.getElementById('city').innerHTML = self.i18Data.city+"*";
document.getElementById("widget-billingInfo-city").placeholder = self.i18Data.city;
}
if(document.getElementById('state')){
document.getElementById('state').innerHTML = self.i18Data.state+"*";
}
if(document.getElementById('country')){
document.getElementById('country').innerHTML = self.i18Data.Country+"*";
}
if(document.getElementById('address_2')){
document.getElementById('address_2').innerHTML = self.i18Data.Address_line +" 2";
document.getElementById("widget-billingInfo-address2").placeholder = self.i18Data.Address_line +" 2";
}
if(document.getElementById('address_1') && document.getElementById("widget-billingInfo-address1")){
document.getElementById('address_1').innerHTML = self.i18Data.Address_line +" 1*";
document.getElementById("widget-billingInfo-address1").placeholder = self.i18Data.Address_line +" 1";
}
if(document.getElementById('widget-billingInfo-state')){
$('#widget-billingInfo-state option[value="0"]').text(self.i18Data.Select);
}
if(document.getElementById('widget-billingInfo-country')){
$('#widget-billingInfo-country option[value="0"]').text(self.i18Data.Select);
}
// validation Error message
if(document.getElementById('widget-card-number-invalid-error')){
document.getElementById('widget-card-number-invalid-error').innerHTML = self.i18Data.enter_valid_cardnumber;
}
if(document.getElementById('widget-card-holder-error')){
document.getElementById('widget-card-holder-error').innerHTML = self.i18Data.please_enter_valid_msg;
}
if(document.getElementById('widget-expiry-date-error')){
document.getElementById('widget-expiry-date-error').innerHTML = self.i18Data.plese_select_valid_expirydate;
}
if(document.getElementById('widget-expiry-month-error')){
document.getElementById('widget-expiry-month-error').innerHTML = self.i18Data.please_select_card_expiry_month;
}
if(document.getElementById('widget-expiry-year-error')){
document.getElementById('widget-expiry-year-error').innerHTML = self.i18Data.please_select_card_expiry_year;
}
if(document.getElementById('widget-cvv-error')){
document.getElementById('widget-cvv-error').innerHTML = self.i18Data.please_enter_valid_securitycode+"."+self.i18Data.digit_number;
}
if(document.getElementById('widget-contactInfo-confirmEmail-invalid-error')){
document.getElementById('widget-contactInfo-confirmEmail-invalid-error').innerHTML = self.i18Data.confirmation_email_same;
}
if(document.getElementById('widget-contactInfo-email-invalid-error')){
document.getElementById('widget-contactInfo-email-invalid-error').innerHTML = self.i18Data.please_enter_validtripemail;
}
if(document.getElementById('widget-contactInfo-phone-invalid-error')){
document.getElementById('widget-contactInfo-phone-invalid-error').innerHTML = self.i18Data.please_enter_valid_phone_number;
}
if(document.getElementById('widget-billingInfo-zipcode-invalid-error')){
document.getElementById('widget-billingInfo-zipcode-invalid-error').innerHTML = self.i18Data.enter_zipcode;
}
if(document.getElementById('widget-billingInfo-city-invalid-error')){
document.getElementById('widget-billingInfo-city-invalid-error').innerHTML = self.i18Data.enter_validcity;
}
if(document.getElementById('widget-billingInfo-state-invalid-error')){
document.getElementById('widget-billingInfo-state-invalid-error').innerHTML = self.i18Data.select_state;
}
if(document.getElementById('widget-billingInfo-country-invalid-error')){
document.getElementById('widget-billingInfo-country-invalid-error').innerHTML = self.i18Data.select_country;
}
if(document.getElementById('widget-billingInfo-address2-invalid-error')){
document.getElementById('widget-billingInfo-address2-invalid-error').innerHTML = self.i18Data.enter_address2;
}
if(document.getElementById('widget-billingInfo-address1-invalid-error')){
document.getElementById('widget-billingInfo-address1-invalid-error').innerHTML = self.i18Data.enter_address1;
}
} else{
// console.log("i18n response json null : ", response);
var json={"eventName":"i18n_response_json_null","eventCategory":"i18n_response_json_null","message":"i18n response json null","data":response};
SmartScript.auditObject.sendDataToElk(json);
}
})
.catch((response) => {
//console.log("i18n catch block : ", response);
var json={"eventName":"i18n_exception","eventCategory":"i18n_exception","message":"i18n exception","data":response};
SmartScript.auditObject.sendDataToElk(json);
});
}
//if click on terms and condition check box if check box checked then only open popup
clickTermsCheckbox(){
var self=this;
var termsCondition2=document.querySelector('#widget-contactInfo-termsCondition2').checked;
var termsCondition=document.querySelector('#widget-contactInfo-termsCondition').checked;
var url= self.getDecryptedtext(self.payomoServer) + "/api/v1/fraud/paymentLinkModalTemplate/eb7bb456-1973-4ab4-97d9-4d3d0ed66b63";
if(termsCondition){
$.ajax({
url: url,
method: "GET",
contentType: "application/json",
headers: { "Access-Control-Allow-Origin": "*" },
success: function (data) {
console.log("PaymentLink template : ", data);
const d = new Date();
let currentDateTime = d.toUTCString();
if(data.documenent != null){
var setTemplate=document.querySelector('#paymentLinkModalBody');
setTemplate.innerHTML="";
setTemplate.innerHTML=data.documenent;
document.querySelector('#sent_on').innerHTML=currentDateTime;
document.querySelector('#signers').innerHTML=2;
document.querySelector('#completed_on').innerHTML=currentDateTime;
document.querySelector('#receives_a_copy').innerHTML=2;
document.querySelector('#approvers').innerHTML=1;
document.querySelector('#no_of_documents').innerHTML=2;
document.querySelector('#emailed_on').innerHTML=currentDateTime;
document.querySelector('#viewed_on').innerHTML=currentDateTime;
document.querySelector('#terms_agreed_on').innerHTML=currentDateTime;
document.querySelector('#signed_on').innerHTML=currentDateTime;
document.querySelector('#organization').innerHTML="MONDEE CO.";
document.querySelector('#emailed_on_reservation').innerHTML=currentDateTime;
document.querySelector('#viewed_on_reservation').innerHTML=currentDateTime;
document.querySelector('#emailed_on_Esign').innerHTML=currentDateTime;
document.querySelector('#viewed_on_Esign').innerHTML=currentDateTime;
document.querySelector('#emailed_on_all').innerHTML=currentDateTime;
document.querySelector('#viewed_on_all').innerHTML=currentDateTime;
//document.body.appendChild(setTemplate);
//console.log("setTemplate : ", data.documenent);
}
},
error: function (error) {
console.log("PaymentLink template failed: ", error);
},
})
}
if(termsCondition2){
$('#paymentLinkModal').modal('show');
$("#checkbox1").show();
$("#checkbox2").hide();
}else{
$("#checkbox1").hide();
$("#checkbox2").show();
}
}
//validate Terms and Condition Form
save_termAndCondition(){
var self=this;
var fname=document.getElementById("widget-contactInfo-fname").value;
var lname=document.getElementById("widget-contactInfo-lname").value;
var isvalid=false;
if(fname.trim().length == 0){
$("#widget-contactInfo-fname-invalid-error").show();
isvalid=false;
} else{
$("#widget-contactInfo-fname-invalid-error").hide();
isvalid=true;
}
if(lname.trim().length == 0){
$("#widget-contactInfo-lname-invalid-error").show();
isvalid=false;
} else{
$("#widget-contactInfo-lname-invalid-error").hide();
isvalid=true;
}
if(isvalid){
$("#closeModal").click();
self.saveTermsandConditionForm();
}
}
//API for save terms and condition
saveTermsandConditionForm(){
var self=this;
var fname=document.getElementById("widget-contactInfo-fname").value;
var lname=document.getElementById("widget-contactInfo-lname").value;
var documentId = document.getElementById("terms_document_id").innerText;
let certificate_of_completion_modal = document.querySelector(".ctemplateModal");
var paymentLinkCodeValidator = window.location.pathname.split("/").pop();
var deviceType= self.getDeviceType();
self.getIpAddress().then(res => {
var termsPayloadData={
"documenent": certificate_of_completion_modal.innerHTML,
"documentId": documentId,
"firstName": fname,
"lastName": lname,
"paymentLinkCodeValidator": paymentLinkCodeValidator!= null ?paymentLinkCodeValidator:"",
"ipAddress":res != null? res : "127.0.0.1",
"deviceType": deviceType != null ? deviceType : "Web"
};
$.ajax({
url: self.getDecryptedtext(self.payomoServer) + "/api/v1/fraud/savePaymentLinkCertificate",
method: "POST",
contentType: "application/json",
data: JSON.stringify(termsPayloadData),
headers: { "Access-Control-Allow-Origin": "*" },
success: function (data) {
console.log("Saved Payment Link Certificate response success : ", data);
},
error: function (error) {
console.log("Payment Link Certificate response failed: ", error);
},
})
}).catch(error => console.log(error));
}
getDecryptedtext(encrypteddata){
var self = this;
const myArray = self.encryptionKey.split(",");
let text = myArray[0];
var encryptedBase64Key = text;
var parsedBase64Key = CryptoJS.enc.Base64.parse(encryptedBase64Key);
// Decryption process
var encryptedCipherText = encrypteddata ; // or encryptedData;
var decryptedData = CryptoJS.AES.decrypt( encryptedCipherText, parsedBase64Key, {
mode: CryptoJS.mode.ECB,
padding: CryptoJS.pad.Pkcs7
});
var decryptedText = decryptedData.toString(CryptoJS.enc.Utf8);
return decryptedText;
}
getEncryptedtext(data){
var self = this;
const myArray = self.encryptionKey.split(",");
let text = myArray[0];
var encryptedBase64Key = text;
//console.log("encryptedBase64Key : " , encryptedBase64Key);
var parsedBase64Key = CryptoJS.enc.Base64.parse(encryptedBase64Key);
var encryptedData = null;
// this is Base64-encoded encrypted data
encryptedData = CryptoJS.AES.encrypt(data, parsedBase64Key, {
mode: CryptoJS.mode.ECB,
padding: CryptoJS.pad.Pkcs7
}).toString();
return encryptedData;
}
getEncryptedElktext(data){
var self = this;
var encryptedBase64Key = self.elkLogParam;
//console.log("encryptedBase64Key : " , encryptedBase64Key);
var parsedBase64Key = CryptoJS.enc.Base64.parse(encryptedBase64Key);
var encryptedData = null;
// this is Base64-encoded encrypted data
encryptedData = CryptoJS.AES.encrypt(data, parsedBase64Key, {
mode: CryptoJS.mode.ECB,
padding: CryptoJS.pad.Pkcs7
}).toString();
return encryptedData;
}
getIpAddress(){
return new Promise(function(resolve, reject){
fetch('https://api.ipify.org?format=json')
.then(response => response.json())
.then(data => {
console.log("IP Address:", data.ip);
resolve(data.ip)
})
.catch(error => {
console.error("Error fetching IP address:", error);
reject();
});
})
}
getDeviceType(){
const ua = navigator.userAgent;
if (/(tablet|ipad|playbook|silk)|(android(?!.*mobi))/i.test(ua)) {
return 'Tablet';
}
if (/Mobile|iP(hone|od)|Android|BlackBerry|IEMobile|Kindle|Silk-Accelerated|(hpw|web)OS|Opera M(obi|ini)/.test(ua)) {
return 'Mobile';
}
return 'Web';
}
}
/*
* Loader
*/
class Loader extends SmartScript
{
constructor() {
super();
Loader.failedFiles = {};
console.log("called Loader constructor");
}
static appendScript(filename, scriptFile, callback) {
try{
var self = this;
var scriptTag = document.createElement('script');
scriptTag.setAttribute('src', scriptFile);
if(filename=='payPalCheckout'){
scriptTag.setAttribute('data-version-4','');
scriptTag.setAttribute('log-level','warn');
}
scriptTag.onload = callback;
scriptTag.onreadystatechange = callback;
scriptTag.async = true;
scriptTag.addEventListener('error', function () {
Loader.updateFailedFiles(filename, scriptFile, 'error');
});
scriptTag.addEventListener('abort', function () {
Loader.updateFailedFiles(filename, scriptFile, 'abort');
});
console.log("scriptFile = "+scriptFile);
document.head.appendChild(scriptTag);
}
catch(e){
console.log("Exception while appending script to html="+e);
}
}
static loadScriptCallback(e, filename,filesLoadedMap) {
console.log(" file loaded callback for the file - " + filename);
Loader.markFileLoaded(filename,filesLoadedMap);
}
static markFileLoaded(fileName,filesLoadedMap) {
if (!filesLoadedMap.get(fileName)) {
filesLoadedMap.set(fileName, true);
} else {
console.log("File . " + fileName + " does not exist")
}
}
static isAllLoaded(filesLoadedMap) {
let isFailed = Loader.isFilesFailed(filesLoadedMap);
if(isFailed) {
return false;
}
for (let value of filesLoadedMap.values()) {
if(!value) {
return false;
}
}
return true;
}
static updateFailedFiles(filename, scriptFile, failedFrom) {
try {
console.log(" filename :: " + filename + " is failed to load " + failedFrom);
if(Loader.failedFiles && Loader.failedFiles[filename]) {
let fileJson = Loader.failedFiles[filename];
let count = fileJson.count;
fileJson.count = count + 1;
console.log(filename + " failed to load for " + count + " time(s) ");
} else {
Loader.failedFiles[filename] = {file : scriptFile, count : 1};
}
} catch (e) {
console.log(" error in reload files " + e);
}
}
static isFilesFailed(filesLoadedMap) {
let failed = false;
try {
if(Loader.failedFiles && Object.entries(Loader.failedFiles).length > 0) {
for (let fileName of filesLoadedMap.keys()) {
if(Loader.failedFiles[fileName]) {
failed = true;
let json = Loader.failedFiles[fileName];
if(json.count <= 3) {
Loader.appendScript(fileName, json.file, function(e) {
Loader.loadScriptCallback(e, fileName,filesLoadedMap);
});
}
break;
}
}
} else {
return false;
}
} catch (e) {
console.log(" error in reload files " + e);
}
return failed;
}
}/*
* Audit
*/
class Audit extends SmartScript
{
constructor(logJsonVal) {
super(logJsonVal);
this.logJson=logJsonVal;
}
static getAuditObject(){
}
static pushSmartscriptLog(data) {
var self = this;
$.ajax({
url : self.getDecryptedtext(self.payomoServer) + "/api/v1.1/UILogger/saveSmartScirptLog",
type : "POST",
contentType : "application/json",
data : data,
async : false,
success : function() {
}
});
}
performAudit(key, reqest, response, accountId, sessionId){
var self = this;
var data = {
auditKey : key,
reqest : reqest,
response : response,
accountId : accountId,
sessionId : sessionId
}
$.ajax({
url : self.getDecryptedtext(self.payomoServer) + "/api/v1/audit/ss",
method : "POST",
contentType : "application/x-www-form-urlencoded", // "application/json; charset=utf-8",//, //
dataType : "json",
data : "{}",
data : JSON.stringify(data)
// headers: headers
}).then(function(e) {
// Complete validation by passing the merchant session to the Apple Pay session.
console.log(" -- Audit response -- ");
console.log(e)
});
}
logData(logRequest){
try{
var self = this;
logRequest['sessionId']=self.getDecryptedtext(this.logSessionId);
logRequest['accountId']=self.getDecryptedtext(this.payomoAccountId);
logRequest['type']="smartScript";
$.ajax({
url : self.getDecryptedtext(self.payomoServer) + "/api/v1/smartScript/logEncrypted",
method : "POST",
contentType : "application/json", // "application/json; charset=utf-8",//, //
dataType : "json",
data : self.getEncryptedtext(JSON.stringify(logRequest))
}).then(function(e) {
// Complete validation by passing the merchant session to the Apple Pay session.
console.log(" -- Audit response -- ");
console.log(e)
});
}catch(e){
}
}
log(className,methodName,message){
try{
var self = this;
var logRequest={};
logRequest['className']=className;
logRequest['methodName']=methodName;
logRequest['message']=message;
logRequest['sessionId']=self.getDecryptedtext(this.logSessionId);
logRequest['accountId']=self.getDecryptedtext(this.payomoAccountId);
logRequest['type']="smartScript";
$.ajax({
url : self.getDecryptedtext(self.payomoServer) + "/api/v1/smartScript/logEncrypted",
method : "POST",
contentType : "application/json", // "application/json; charset=utf-8",//, //
dataType : "json",
data : self.getEncryptedtext(JSON.stringify(logRequest))
}).then(function(e) {
// Complete validation by passing the merchant session to the Apple Pay session.
console.log(" -- Audit response -- ");
console.log(e)
});
}catch(e){
}
}
sendDataToElk(json){
var requestPayload ={};
try{
if(this.enableElkLogging==='no'){
return;
}
var self = this;
this.logJson["eventName"]=json.eventName;
this.logJson["eventCategory"]=json.eventCategory;
this.count=this.count+1;
this.logJson["count"]=this.count;
this.logJson.data={};
if(json.data && this.logJson.data){
var dataStr=JSON.stringify(json.data)
this.logJson.data["content"]=dataStr;
}
this.logJson["message"]=json.message;
this.logJson['sessionId']=self.getDecryptedtext(this.logSessionId);
this.logJson['accountId']=self.getDecryptedtext(this.payomoAccountId);
var request={"type": "SiteInteractLog","records":[this.logJson]};
var encryptData = self.getEncryptedElktext(JSON.stringify(request));
requestPayload= {"request" : encryptData } ;
$.ajax({
url : self.getDecryptedtext(self.elkServer) + "/api/v1/tomato/producer/tracking/0",
method : "POST",
contentType : "application/json",
dataType : "json",
data : JSON.stringify(requestPayload)
}).then(function(e) {
// Complete validation by passing the merchant session to the Apple Pay session.
console.log("sendDataToElk response");
console.log(e)
});
}catch(e){
}
}
}
/*
* RiskManagement
*/
class RiskManagement extends SmartScript
{
constructor(payRequest) {
super(payRequest);
let urlMap=new Map();
urlMap.set('cardinalCommerce', 'https://songbird.cardinalcommerce.com/cardinalcruise/v1/songbird.js');
urlMap.set("decisionManager", 'https://h.online-metrix.net/fp/tags.js?org_id=k8vif92e&session_id='+this.getDecryptedtext(this.gpayGatewayMerchantId)+this.getDecryptedtext(this.dm_uuid));
urlMap.set("riskified", "https://beacon.riskified.com?shop=lbftravel.com&sid="+this.getDecryptedtext(this.riskified_uuid));
this.filesUrlMap=urlMap;
this.payRequest = payRequest;
let map = new Map();
map.set('cardinalCommerce', false);
map.set("decisionManager", false);
map.set("riskified", false);
map.set("cardinalSetupSuccess", true);
map.set("BraintreeThreeDS", false);
this.filesLoadedMap=map;
this.payomoAccountId=this.getDecryptedtext(this.payomoAccountId);
this.sessionId=this.getDecryptedtext(this.sessionId);
this.braintreeClientToken=this.brainTreeClientToken;
this.submitRiskcheckStartTime = 0;
RiskManagement.response={"score":"",
transactionRefNumber:""};
console.log("called RiskManagement constructor");
}
static submit(authRequest, callback){
let obj = new SmartScript();
obj.loadCrypto().then(res => {
let self =new RiskManagement();
let fraudTp=self.getDecryptedtext(self.fraudType);
if("identityCheck"===fraudTp){
self.submitIdentityCheck(authRequest,callback);
}else {
self.submitRiskCheck(authRequest, callback);
}
}).catch(error => console.log(error));
}
submitIdentityCheck(authRequest,callback){
var self=this;
var logRequest={};
var data={};
try{
$.ajax({
// url : "https://www.exploretrip1.com:8443/payment/api/v1/apple/createSession", "http://localhost:8080/payment/api/v1/payment/fraud/basic"
url : self.getDecryptedtext(self.payomoServer) + "/api/v1/fraud/identityCheck",
method : "POST",
contentType : "application/json", // "application/json; // application/x-www-form-urlencoded",//, // //
dataType : "json",
data : "{}",
data : JSON.stringify(authRequest),
error: function(returnval) {
callback(returnval.responseJSON);
}
// headers: headers
}).then(function(res) {
// Complete validation by passing the merchant session to the Apple Pay session.
//console.log("risk check success= "+res);
RiskManagement.response.transactionRefNumber=res.identityCheckId;
RiskManagement.response.status=res.message;
RiskManagement.response.transactionDate=res.transactionDate;
RiskManagement.response.transactionTime=res.transactionTime;
RiskManagement.response.rawResponse=JSON.stringify(res);
if(callback){
logRequest['eventName']="identity_check_invokeIdentityCheck";
logRequest['eventCategory']="app_user_interaction";
logRequest['message']="risk manament class invokeIdentityCheck method callback called";
data['IdentityCheckResponse']=JSON.stringify(res);
data['riskManagementResponse']=JSON.stringify(RiskManagement.response);
logRequest['data']=data;
if(authRequest && authRequest.transaction){
logRequest["merchantRefNum"]=authRequest.merchantRef;
}
SmartScript.auditObject.logData(logRequest);
console.log("After risk check success callback called");
callback(RiskManagement.response);
}
});
}catch(ex){
logRequest['eventName']="identity_check_submit_exception",
logRequest['eventCategory']="app_user_interaction",
logRequest['message']="identity manament class invokeIdentityCheck method exception= "+ex,
logRequest['data']=data;
if(authRequest && authRequest.transaction){
logRequest["merchantRefNum"]=authRequest.merchantRef;
}
SmartScript.auditObject.logData(logRequest);
}
}
submitRiskCheck(authRequest, callback){
var self=this;
var logRequest={};
var data={};
try{
self.submitRiskcheckStartTime = new Date().getTime();
logRequest["className"]="riskManagement";
logRequest["methodName"]="submitRiskCheck";
logRequest['eventName']="risk_check_submitRiskCheck_start",
logRequest['eventCategory']="app_user_interaction",
logRequest['message']="risk manament class submit Risk Check method start",
data['paymentRequest']=JSON.stringify(authRequest)
logRequest['data']=data;
if(authRequest && authRequest.transaction){
logRequest["merchantRefNum"]=authRequest.transaction.merchantReference;
}
SmartScript.auditObject.logData(logRequest);
SmartScript.auditObject.sendDataToElk(logRequest);
//let self =new RiskManagement();
let phoneNumber=null;
let email=null;
let cardNumber=null;
let accountId='';
if(authRequest){
if(authRequest.creditCard!=null){
phoneNumber=authRequest.creditCard.phoneNumber;
email=authRequest.creditCard.email;;
cardNumber=authRequest.creditCard.cardNumber;
}
if(authRequest.customer!=null && authRequest.customer.customerId){
accountId=authRequest.customer.customerId;
}
}
if(authRequest.creditCard!=null){
//console.log("threedsSource " + self.threedsSource);
if(authRequest.isInternalAgent || cardNumber == ''){
console.log("skipped cardinal call");
self.invokeRiskCheck(authRequest,callback);
var json={"eventName":"cardinal-commerce_skipped","eventCategory":"cardinal-commerce-scan","message":"skipped cardinal call","data":authRequest};
SmartScript.auditObject.sendDataToElk(json);
}else{
var cardinal=new CardinalCommerce();
var braintreeThreeDS= new BraintreeThreeDS();
console.log("calling cardinal api");
var isScanFailExec = false;
var json={"eventName":"cardinal-commerce_start","eventCategory":"cardinal-commerce-scan","message":"cardinal call starttime","data":authRequest};
SmartScript.auditObject.sendDataToElk(json);
console.log("cardinal-commerce_start");
// if Cardinal response not getting in 2 min , automatically call the basic api
var timeoutHandle = setTimeout(function() {
self.isScanFailExec = true;
self.invokeRiskCheck(authRequest,callback);
var json={"eventName":"cardinal-commerce_longtime","eventCategory":"cardinal-commerce-scan","message":"cardinal call taking longtime","data":authRequest};
SmartScript.auditObject.sendDataToElk(json);
console.log("cardinal-commerce_longtime");
clearTimeout(timeoutHandle);
}, 120000); // set timeout to 2 min
var json={"eventName":"cardinal-commerce_threedsSource","eventCategory":"cardinal-commerce-scan","message":"cardinal threedsSource ","data": self.getDecryptedtext(self.threedsSource)};
SmartScript.auditObject.sendDataToElk(json);
//if threedssource is cybersource
if(self.getDecryptedtext(self.threedsSource) === "cybersource"){
cardinal.scan(authRequest,function(cardinalResponse, responseJWT){
clearTimeout(timeoutHandle);
if(!self.isScanFailExec){
self.invokeRiskCheck(authRequest,callback,cardinalResponse);
}
var json={"eventName":"cardinal-commerce_success","eventCategory":"cardinal-commerce-scan","message":"cardinal success response","data":cardinalResponse};
SmartScript.auditObject.sendDataToElk(json);
console.log("cardinal-commerce_success");
});
} else {
var paymoCustomerId= authRequest.customer.customerId != null ? authRequest.customer.customerId : self.payomoAccountId;
var currency= authRequest.transaction.currency != null ? authRequest.transaction.currency : "USD";
//console.log("paymoCustomerId :", paymoCustomerId);
var submitRiskcheckEndTime = new Date().getTime();
var submitRiskcheckReponseTime = submitRiskcheckEndTime - self.submitRiskcheckStartTime;
var json={"eventName":"BTBefore_getbraintreeToken","eventCategory":"brainTree_getbraintreeToken","message":"braintree before Token " + submitRiskcheckReponseTime,"data":null};
SmartScript.auditObject.sendDataToElk(json);
var braintreeTokenStartTime = new Date().getTime();
self.getbraintreeToken(paymoCustomerId, currency).then(res => {
//console.log("token",res.messageDesc);
//if threedssource is braintree
var submitRiskcheckEndTime = new Date().getTime();
var submitRiskcheckReponseTime = submitRiskcheckEndTime - braintreeTokenStartTime;
console.log("getbraintreeToken ", submitRiskcheckReponseTime);
var json={"eventName":"BTAfter_getbraintreeToken","eventCategory":"brainTree_getAfterbraintreeToken","message":"braintree getAfterbraintreeToken success response " + submitRiskcheckReponseTime,"data":res};
SmartScript.auditObject.sendDataToElk(json);
let resp = {};
try{
let braintreeToken= self.getDecryptedtext(res.data);
resp = JSON.parse(braintreeToken);
}catch(e){
resp.token = self.getDecryptedtext(res.data);
}
braintreeTokenStartTime = new Date().getTime();
braintreeThreeDS.threeDsecureCheck(resp.token,authRequest,function(brainTreeResponse){
clearTimeout(timeoutHandle);
var submitRiskcheckEndTime = new Date().getTime();
var submitRiskcheckReponseTime = submitRiskcheckEndTime - braintreeTokenStartTime;
console.log("threeDsecureCheck ", submitRiskcheckReponseTime);
var json={"eventName":"BTThreeDsecureCheck_success","eventCategory":"BTThreeDsecureCheck_success","message":"braintree threeDsecureCheck success response " + submitRiskcheckReponseTime,"data":brainTreeResponse};
SmartScript.auditObject.sendDataToElk(json);
if(!self.isScanFailExec){
self.invokeRiskCheck(authRequest,callback,brainTreeResponse);
}
//console.log("brainTreeResponse_success",brainTreeResponse);
submitRiskcheckEndTime = new Date().getTime();
submitRiskcheckReponseTime = submitRiskcheckEndTime - self.submitRiskcheckStartTime;
var json={"eventName":"brainTreeResponse_success","eventCategory":"brainTreeResponse-success","message":"braintree success response " + submitRiskcheckReponseTime,"data":brainTreeResponse};
SmartScript.auditObject.sendDataToElk(json);
});
}).catch(err =>{
clearTimeout(timeoutHandle);
console.log("token erro",err);
var json={"eventName":"braintreeToken_exception","eventCategory":"braintreeToken_exception","message":"braintree Token exception","data":err};
SmartScript.auditObject.sendDataToElk(json);
})
}
}
} else{
if(authRequest.paymentMethod!=null){
self.invokeRiskCheck(authRequest,callback);
var json={"eventName":"cardinal-commerce_skipped_wallet","eventCategory":"cardinal-commerce-scan","message":"skipped cardinal call wallet","data":authRequest};
SmartScript.auditObject.sendDataToElk(json);
//console.log("wallet request call : ", json);
}
}
SmartScript.auditObject.log("riskManagement","submitRiskCheck","method end");
var json={"eventName":"risk_check_submitRiskCheck_end","eventCategory":"app_user_interaction","message":"risk manament class submit method start","data":null};
SmartScript.auditObject.sendDataToElk(json);
var submitRiskcheckEndTime = new Date().getTime();
var submitRiskcheckReponseTime = submitRiskcheckEndTime - self.submitRiskcheckStartTime;
var json={"eventName":"submitRiskCheck_responseTime","eventCategory":"submitRiskCheck_responseTime","message":"risk manament class submit method responseTime " + submitRiskcheckReponseTime,"data":null};
SmartScript.auditObject.sendDataToElk(json);
}catch(ex){
consoleo.log("exception : ", ex);
logRequest['eventName']="risk_check_submitRiskCheck_exception",
logRequest['eventCategory']="app_user_interaction",
logRequest['message']="risk manament class submit method exception= "+ex,
logRequest['data']=data;
if(authRequest && authRequest.transaction){
logRequest["merchantRefNum"]=authRequest.transaction.merchantReference;
}
SmartScript.auditObject.logData(logRequest);
SmartScript.auditObject.sendDataToElk(logRequest);
}
}
invokeRiskCheck(authRequest,callback,cardinalResponse){
var logRequest={};
var data={};
try{
logRequest['eventName']="risk_check_invokeRiskCheck_start";
logRequest['eventCategory']="app_user_interaction";
logRequest['message']="risk manament class invokeRiskCheck method started";
data['cardinalResponse']=JSON.stringify(cardinalResponse);
logRequest['data']=data;
if(authRequest && authRequest.transaction){
logRequest["merchantRefNum"]=authRequest.transaction.merchantReference;
}
SmartScript.auditObject.logData(logRequest);
SmartScript.auditObject.sendDataToElk(logRequest);
var self = this;
//console.log("cardinalResponse = " +JSON.stringify(cardinalResponse));
if(authRequest.hasOwnProperty("isInternalAgent")){
delete authRequest.isInternalAgent; // remove the property before
// sending it to fraud check
}
// call service here
if(authRequest.creditCard != null){
var expiryDate = authRequest.creditCard.expiryDate;
var expiryDateSplit = expiryDate.split("/");
var expiryMonth = expiryDateSplit[0];
if (expiryMonth.length == 1) {
expiryMonth = "0" + expiryMonth;
}
var expiryYear = expiryDateSplit[1];
if(expiryYear){
expiryYear=expiryYear.substring(expiryYear.length-2, expiryYear.length);
}
authRequest.creditCard.expiryDate=expiryMonth+expiryYear;
}
try{
if(cardinalResponse){
var json={"eventName":"invokeRiskCheck_cardinalResponse_not_empty","eventCategory":"invokeRiskCheck_cardinalResponse_not_empty","message":"cardinalResponse ","data":cardinalResponse};
SmartScript.auditObject.sendDataToElk(json);
//if threedssource is cybersource
if(self.getDecryptedtext(self.threedsSource) === "cybersource"){
var errorDetails = "Success";
var errorCode = 0;
if (cardinalResponse != null && cardinalResponse.consumerAuthenticationInformation.errorInformation != null) {
errorDetails = cardinalResponse.consumerAuthenticationInformation.errorInformation.message != null ? cardinalResponse.consumerAuthenticationInformation.errorInformation.message : null;
errorCode = cardinalResponse.consumerAuthenticationInformation.errorInformation.code;
}
if(cardinalResponse != null &&cardinalResponse.consumerAuthenticationInformation!= null){
var cardinalResponseData = {
"Validated": "true",
"Provider": "Cybersource",
"ActionCode": cardinalResponse.status === "AUTHENTICATION_SUCCESSFUL" ? "SUCCESS" : "FAILED",
"ErrorNumber": errorCode,
"ErrorDescription": errorDetails,
"ThreeDSResponse":cardinalResponse!= null ? self.getEncryptedtext(JSON.stringify(cardinalResponse)): null,
"Payment": {
"Type": "CCA",
"ProcessorTransactionId": cardinalResponse.consumerAuthenticationInformation.authenticationTransactionId != null ? cardinalResponse.consumerAuthenticationInformation.authenticationTransactionId : null,
"ExtendedData": {
"CAVV": cardinalResponse.consumerAuthenticationInformation.cavv != null ? cardinalResponse.consumerAuthenticationInformation.cavv : null,
"ECIFlag": cardinalResponse.consumerAuthenticationInformation.eci != null ? cardinalResponse.consumerAuthenticationInformation.eci : cardinalResponse.consumerAuthenticationInformation.eciRaw != null ? cardinalResponse.consumerAuthenticationInformation.eciRaw : null,
"ThreeDSVersion": cardinalResponse.consumerAuthenticationInformation.specificationVersion != null ? cardinalResponse.consumerAuthenticationInformation.specificationVersion : null,
"Enrolled": cardinalResponse.consumerAuthenticationInformation.veresEnrolled != null ? cardinalResponse.consumerAuthenticationInformation.veresEnrolled : null,
"PAResStatus": cardinalResponse.consumerAuthenticationInformation.paresStatus != null ? cardinalResponse.consumerAuthenticationInformation.paresStatus : null,
"SignatureVerification": "Y",
"XID":cardinalResponse.consumerAuthenticationInformation.xid != null ? cardinalResponse.consumerAuthenticationInformation.xid : null,
"ACSTransactionId" :cardinalResponse.consumerAuthenticationInformation.acsTransactionId != null ? cardinalResponse.consumerAuthenticationInformation.acsTransactionId : null,
"ThreeDSServerTransactionId" : cardinalResponse.consumerAuthenticationInformation.threeDSServerTransactionId != null ? cardinalResponse.consumerAuthenticationInformation.threeDSServerTransactionId : null,
"DSTransactionId": cardinalResponse.consumerAuthenticationInformation.directoryServerTransactionId != null ? cardinalResponse.consumerAuthenticationInformation.directoryServerTransactionId : null,
"UcafCollectionIndicator" : cardinalResponse.consumerAuthenticationInformation.ucafCollectionIndicator != null ? cardinalResponse.consumerAuthenticationInformation.ucafCollectionIndicator : null,
"UcafAuthenticationData": cardinalResponse.consumerAuthenticationInformation.ucafAuthenticationData != null ? cardinalResponse.consumerAuthenticationInformation.ucafAuthenticationData : null,
"AuthenticationTransactionId": cardinalResponse.consumerAuthenticationInformation.authenticationTransactionId != null ? cardinalResponse.consumerAuthenticationInformation.authenticationTransactionId : null
}
}
}
}
//console.log("cardinal Response Data :", cardinalResponseData)
authRequest["threeDSData"]=cardinalResponseData;
} else{
var errorDetails = "Success";
var errorCode = 0;
if (cardinalResponse != null && (cardinalResponse.threeDSecureInfo.status !== "authenticate_successful" || cardinalResponse.threeDSecureInfo.status !== "authenticate_attempt_successful")) {
errorDetails = cardinalResponse.threeDSecureInfo.status !=null ? cardinalResponse.threeDSecureInfo.status : null;
errorCode = 1;
}
if(cardinalResponse != null){
var braintreeResponseData = {
"Validated": "true",
"Provider": "Braintree",
"Nonce":cardinalResponse.nonce != null ? cardinalResponse.nonce: null,
"ActionCode": (cardinalResponse.threeDSecureInfo.status == "authenticate_successful" || cardinalResponse.threeDSecureInfo.status == "authenticate_attempt_successful") ? "SUCCESS" : "FAILED",
"ClientToken":self.braintreeClientToken!= null ? self.braintreeClientToken: null,
"ThreeDSResponse":cardinalResponse!= null ? self.getEncryptedtext(JSON.stringify(cardinalResponse)): null,
"ErrorNumber": cardinalResponse.rawCardinalSDKVerificationData && cardinalResponse.rawCardinalSDKVerificationData.ErrorNumber !=null ? cardinalResponse.rawCardinalSDKVerificationData.ErrorNumber : errorCode,
"ErrorDescription": cardinalResponse.rawCardinalSDKVerificationData && cardinalResponse.rawCardinalSDKVerificationData.ErrorDescription !=null ? cardinalResponse.rawCardinalSDKVerificationData.ErrorDescription : errorDetails,
"Payment": {
"Type": cardinalResponse.rawCardinalSDKVerificationData && cardinalResponse.rawCardinalSDKVerificationData.Payment.Type !=null ? cardinalResponse.rawCardinalSDKVerificationData.Payment.Type : "CCA",
"ProcessorTransactionId": cardinalResponse.rawCardinalSDKVerificationData && cardinalResponse.rawCardinalSDKVerificationData.ProcessorTransactionId !=null ?cardinalResponse.rawCardinalSDKVerificationData.ProcessorTransactionId: null,
"ExtendedData": {
"CAVV": cardinalResponse.threeDSecureInfo && cardinalResponse.threeDSecureInfo.cavv !=null ? cardinalResponse.threeDSecureInfo.cavv : "",
"ECIFlag": cardinalResponse.threeDSecureInfo && cardinalResponse.threeDSecureInfo.eciFlag !=null ? cardinalResponse.threeDSecureInfo.eciFlag : null,
"ThreeDSVersion": cardinalResponse.threeDSecureInfo && cardinalResponse.threeDSecureInfo.threeDSecureVersion !=null ? cardinalResponse.threeDSecureInfo.threeDSecureVersion :null,
"Enrolled": cardinalResponse.threeDSecureInfo.enrolled != null ? cardinalResponse.threeDSecureInfo.enrolled : null,
"PAResStatus": cardinalResponse.threeDSecureInfo && cardinalResponse.threeDSecureInfo.paresStatus !=null ? cardinalResponse.threeDSecureInfo.paresStatus : null,
"SignatureVerification": cardinalResponse.rawCardinalSDKVerificationData && cardinalResponse.rawCardinalSDKVerificationData.Payment.ExtendedData.SignatureVerification != null ? cardinalResponse.rawCardinalSDKVerificationData.Payment.ExtendedData.SignatureVerification : "Y",
"XID":cardinalResponse.threeDSecureInfo && cardinalResponse.threeDSecureInfo.xid != null ? cardinalResponse.threeDSecureInfo.xid : null,
"ACSTransactionId" :cardinalResponse.threeDSecureInfo && cardinalResponse.threeDSecureInfo.acsTransactionId != null ? cardinalResponse.threeDSecureInfo.acsTransactionId : null,
"ThreeDSServerTransactionId" : cardinalResponse.threeDSecureInfo && cardinalResponse.threeDSecureInfo.threeDSecureServerTransactionId != null ?cardinalResponse.threeDSecureInfo.threeDSecureServerTransactionId : null,
"DSTransactionId": cardinalResponse.threeDSecureInfo && cardinalResponse.threeDSecureInfo.dsTransactionId !=null ?cardinalResponse.threeDSecureInfo.dsTransactionId : null
}
}
}
}
//console.log("braintree Response Data :", braintreeResponseData);
authRequest["threeDSData"]=braintreeResponseData; //assign braintree Response
}
}else{
console.log("cardinal response Empty");
var json={"eventName":"cardinal_response_empty","eventCategory":"cardinal_response_empty","message":"cardinal response empty","data":null};
SmartScript.auditObject.sendDataToElk(json);
}
}catch(ex){
console.log("exception : ", ex);
var json={"eventName":"threeDSResponse_exception","eventCategory":"threeDSResponse_exception","message":"threeDSResponse exception","data":ex};
SmartScript.auditObject.sendDataToElk(json);
}
authRequest['dmClientToken']=self.getDecryptedtext(self.dm_uuid);
authRequest['rkClientToken']=self.getDecryptedtext(self.riskified_uuid);
authRequest['fraudChecks']= [
"threeDS",
"decisionManager",
"riskified"
];
var BTEndTime = new Date().getTime();
var BTReponseTime = BTEndTime - self.submitRiskcheckStartTime;
try{
if( authRequest!=null && authRequest.threeDSData != null){
authRequest.threeDSData.responseTimeTaken = BTReponseTime
}
}catch(ex){}
//encryption payload
var requestPayloadBasic ={};
try{
const myArray = self.encryptionKey.split(",");
let encKey = myArray[0];
let encryptedBase64Key = encKey;
//console.log("encryptedBase64Key : " , encryptedBase64Key);
var parsedBase64Key = CryptoJS.enc.Base64.parse(encryptedBase64Key);
var encryptedData = null;
// Encryption process
var plaintText = JSON.stringify(authRequest);
// this is Base64-encoded encrypted data
encryptedData = CryptoJS.AES.encrypt(plaintText, parsedBase64Key, {
mode: CryptoJS.mode.ECB,
padding: CryptoJS.pad.Pkcs7
}).toString();
//console.log("encryptedData = " + encryptedData);
requestPayloadBasic= {"request" : encryptedData } ;
}catch(ex){
console.log("encryptedData exception : ", ex);
var json={"eventName":"encryptedData_exception","eventCategory":"encryptedData_exception","message":"encryptedData exception","data":ex};
SmartScript.auditObject.sendDataToElk(json);
}
//store braintree 3ds response
if(authRequest.creditCard!=null){
if(self.getDecryptedtext(self.threedsSource) === "braintree"){
var json={"eventName":"BT_responseTime","eventCategory":"BT_responseTime","message":"braintree responseTime " + BTReponseTime,"data":null};
SmartScript.auditObject.sendDataToElk(json);
try{
$.ajax({
url : self.getDecryptedtext(self.payomoServer) + "/api/v1/braintree/saveEncryptedResponse",
method : "POST",
contentType : "application/json",
dataType : "json",
data : "{}",
data : JSON.stringify(requestPayloadBasic),
error: function(error) {
console.log("save braintree error : ", error);
var json={"eventName":"saved_braintree_error","eventCategory":"saved_braintree_error","message":"saved braintree error","data":error};
SmartScript.auditObject.sendDataToElk(json);
}
}).then(function(res) {
//console.log("save braintree res : ", res);
var json={"eventName":"saved_braintree_response","eventCategory":"saved_braintree_response","message":"saved braintree response","data":self.getDecryptedtext(res)};
SmartScript.auditObject.sendDataToElk(json);
});
}catch(ex){
console.log("exception : ", ex);
var json={"eventName":"save_braintree_res_exception","eventCategory":"save_braintree_res_exception","message":"save braintree res exception","data":ex};
SmartScript.auditObject.sendDataToElk(json);
}
}
}
$.ajax({
// url :"https://www.exploretrip1.com:8443/payment/api/v1/apple/createSession", "http://localhost:8080/payment/api/v1/payment/fraud/basic"
url : self.getDecryptedtext(self.payomoServer) + "/api/v1/fraud/basicEncrypted",
method : "POST",
contentType : "application/json", // "application/json; application/x-www-form-urlencoded",//,
dataType : "json",
data : "{}",
data : encryptedData,
error: function(returnval) {
var json={"eventName":"risk_check_fraudbasic_call_failure","eventCategory":"app_user_interaction","message":"risk manament class fraud basic call failure","data":returnval.responseJSON};
SmartScript.auditObject.sendDataToElk(json);
callback(returnval.responseJSON);
}
// headers: headers
}).then(function(res) {
// Complete validation by passing the merchant session to the Apple Pay session.
var json={"eventName":"risk_check_fraudbasic_call_success","eventCategory":"app_user_interaction","message":"risk manament class fraud basic call success","data":res};
SmartScript.auditObject.sendDataToElk(json);
//console.log("risk check success= ", res);
RiskManagement.response.score=res.score;
RiskManagement.response.transactionRefNumber=res.pmTransactionReference;
RiskManagement.response.status=res.message;
RiskManagement.response.transactionType=res.transactionType;
RiskManagement.response.trustedCustomer=res.trustedCustomer;
RiskManagement.response.transactionDate=res.transactionDate;
RiskManagement.response.transactionTime=res.transactionTime;
RiskManagement.response.partial=res.partial;
RiskManagement.response.code=res.code;
if(authRequest.creditCard != null){
RiskManagement.response.cardNumber=authRequest.creditCard.cardNumber;
RiskManagement.response.cardType=authRequest.creditCard.cardType;
}
RiskManagement.response.rawResponse=JSON.stringify(res);
RiskManagement.response.historyTransactions=res.historyTransactions;
RiskManagement.response.chargebackHistory=res.chargebackHistory;
if(callback){
logRequest['eventName']="risk_check_invokeRiskCheck_callback";
logRequest['eventCategory']="app_user_interaction";
logRequest['message']="risk manament class invokeRiskCheck method callback called";
data['riskCheckResponse']=JSON.stringify(res);
data['riskManagementResponse']=JSON.stringify(RiskManagement.response);
logRequest['data']=data;
if(authRequest && authRequest.transaction){
logRequest["merchantRefNum"]=authRequest.transaction.merchantReference;
}
SmartScript.auditObject.logData(logRequest);
SmartScript.auditObject.sendDataToElk(logRequest);
console.log("After risk check success callback called");
callback(RiskManagement.response);
}
});
var json={"eventName":"risk_check_invokeRiskCheck_end","eventCategory":"app_user_interaction","message":"risk manament class invoke risk check method end","data":null};
SmartScript.auditObject.sendDataToElk(json);
}catch(ex){
logRequest['eventName']="risk_check_invokeRiskCheck_exception",
logRequest['eventCategory']="app_user_interaction",
logRequest['message']="risk manament class invokeRiskCheck method exception= "+ex,
data['cardinalResponse']=JSON.stringify(cardinalResponse);
logRequest['data']=data;
if(authRequest && authRequest.transaction){
logRequest["merchantRefNum"]=authRequest.transaction.merchantReference;
}
SmartScript.auditObject.logData(logRequest);
SmartScript.auditObject.sendDataToElk(logRequest);
}
}
cardinalTokenRefreshment(){
var self =this;
$.ajax({
url : self.getDecryptedtext(self.payomoServer) + "/api/v1/"+ self.getDecryptedtext(self.cardinalOrgUnitId) +"/"+self.getDecryptedtext(self.cardinalApiIdentifier)+"/"+self.getDecryptedtext(self.cardinalApiKey),
method : "GET",
contentType : "application/json", // "application/json;
dataType : "json",
data : "",
error: function(jqXHR, textStatus, errorThrown) {
//console.log("cardinalTokenRefreshment generateJWT servcie error= "+jqXHR.responseText);
var json={"eventName":"generateJWT_call_failure","eventCategory":"app_user_interaction","message":"generateJWT API call failed","data":jqXHR.responseText};
// SmartScript.auditObject.sendDataToElk(json);
console.log("whiteListCustomer servcie error= "+errorThrown);
callback(jqXHR.responseText);
},
success:function(res, textStatus, jqXHR) {
//console.log("cardinalTokenRefreshment success response= "+JSON.stringify(res));
var json={"eventName":"generateJWT_call_success","eventCategory":"app_user_interaction","message":"generateJWT API call success","data":JSON.stringify(res)};
// SmartScript.auditObject.sendDataToElk(json);
console.log(" cardinal token refreshed.....")
//var cardinal=new CardinalCommerce();
self.jwt = res.messageDesc;
// Cardinal.setup('init', {
// jwt : self.jwt
// });
}
})
}
loadScripts(){
var self =this;
var logRequest={};
logRequest['eventName']="risk_management_load_scripts_start";
logRequest['eventCategory']="app_user_interaction";
logRequest['message']="risk management load scripts called";
SmartScript.auditObject.logData(logRequest);
SmartScript.auditObject.sendDataToElk(logRequest);
if(!self.filesLoadedMap.get('cardinalCommerce')){
Loader.appendScript("cardinalCommerce", self.filesUrlMap.get('cardinalCommerce'), function(e) {
var cardinal=new CardinalCommerce();
// cardinal.setup(self.jwt);
Loader.loadScriptCallback(e, "cardinalCommerce",self.filesLoadedMap)
});
}
if(!self.filesLoadedMap.get('decisionManager')){
Loader.appendScript("decisionManager", self.filesUrlMap.get('decisionManager'), function(e) {
Loader.loadScriptCallback(e, "decisionManager",self.filesLoadedMap)
});
}
if(!self.filesLoadedMap.get('riskified')){
Loader.appendScript("riskified", self.filesUrlMap.get('riskified'), function(e) {
Loader.loadScriptCallback(e, "riskified",self.filesLoadedMap)
});
}
}
isAllLoaded(){
return Loader.isAllLoaded(this.filesLoadedMap)
}
//get braintree token
getbraintreeToken(paymoAccountId, currency){
var self =this;
var requestPayload ={};
//console.log("braintree token call");
var brainTreeTokenReq={
"accountId": paymoAccountId,
"currency": currency
};
const brainTreeTokenRequest= self.getEncryptedtext(JSON.stringify(brainTreeTokenReq));
requestPayload= {"request" : brainTreeTokenRequest } ;
return new Promise(function(resolve,reject){
try{
$.ajax({
url : self.getDecryptedtext(self.payomoServer) + "/api/v1/braintree/getClientToken",
method : "POST",
contentType : "application/json",
dataType : "json",
data : "{}",
data : JSON.stringify(requestPayload),
error: function(error) {
console.log("braintree token error : ", error);
var json={"eventName":"braintree_token_api_failed","eventCategory":"braintree_token_api_failed","message":"braintree token api failed","data":error};
SmartScript.auditObject.sendDataToElk(json);
reject(error);
}
}).then(function(res) {
//console.log("braintree token response : ", self.getEncryptedtext(res));
var submitRiskcheckEndTime = new Date().getTime();
var submitRiskcheckReponseTime = submitRiskcheckEndTime - self.submitRiskcheckStartTime;
var json={"eventName":"braintree_token_api_success","eventCategory":"braintree_token_api_success","message":"braintree token api success "+submitRiskcheckReponseTime,"data":null};
SmartScript.auditObject.sendDataToElk(json);
resolve(res);
});
}catch(ex){
console.log("exception : ", ex);
var json={"eventName":"braintree_token_api_exception","eventCategory":"braintree_token_api_exception","message":"braintree token api exception","data":ex};
SmartScript.auditObject.sendDataToElk(json);
reject(ex);
}
})
}
}/*
* CardinalCommerce
*/
class CardinalCommerce extends RiskManagement {
constructor() {
super();
this.deviceDataCollectionURL = "";
this.referenceId = "";
this.accessToken = "";
this.retry = 2;
// payer setup request payload structure
this.payerSetupRequest = {
"clientReferenceInformation": {
"code": ""
},
"paymentInformation": {
"card": {
"type": "",
"expirationMonth": "",
"expirationYear": "",
"number": ""
}
}
}
// payer enroll request payload structure
this.payerEnrollRequest = {
"clientReferenceInformation": {
"code": ""
},
"orderInformation": {
"amountDetails": {
"currency": "",
"totalAmount": 0
},
"billTo": {
"address1": "",
"address2":"",
"city": "",
"country": "",
"administrativeArea": "",
"locality": "",
"firstName": "",
"lastName": "",
"phoneNumber": "",
"email": "",
"postalCode": ""
}
},
"paymentInformation": {
"card": {
"type": "",
"expirationMonth": "",
"expirationYear": "",
"number": ""
}
},
"buyerInformation": {
"mobilePhone": ""
},
"consumerAuthenticationInformation": {
"referenceId": "",
"transactionMode": "",
"specificationVersion": "",
"returnUrl": ""
},
"processingInformation": {
"commerceIndicator": "internet",
"authorizationOptions": {
"initiator": {
"credentialStoredOnFile": true
}
},
"actionList": [
"CONSUMER_AUTHENTICATION"
]
}
}
// payer result request payload structure
this.payerResultRequest = {
"clientReferenceInformation": {
"code": ""
},
"orderInformation": {
"amountDetails": {
"currency": "",
"totalAmount": 0
},
"billTo": {
"address1": "",
"address2":"",
"city": "",
"country": "",
"administrativeArea": "",
"locality": "",
"firstName": "",
"lastName": "",
"phoneNumber": "",
"email": "",
"postalCode": ""
}
},
"paymentInformation": {
"card": {
"type": "",
"expirationMonth": "",
"expirationYear": "",
"number": ""
}
},
"buyerInformation": {
"mobilePhone": ""
},
"consumerAuthenticationInformation": {
"authenticationTransactionId":""
},
"processingInformation": {
"actionList": [
"VALIDATE_CONSUMER_AUTHENTICATION"
],
"commerceIndicator": "internet",
"authorizationOptions": {
"initiator": {
"credentialStoredOnFile": true
}
}
}
}
//payment request payload structure
this.paymentRequest = {
"clientReferenceInformation": {
"code": ""
},
"processingInformation": {
"commerceIndicator": "internet",
"authorizationOptions": {
"initiator": {
"credentialStoredOnFile": true
}
}
},
"paymentInformation": {
"card": {
"number": "",
"expirationMonth": "",
"expirationYear": ""
}
},
"orderInformation": {
"amountDetails": {
"totalAmount": 0,
"currency": "USD"
},
"billTo": {
"firstName": "",
"lastName": "",
"address1": "",
"address2":"",
"locality": "",
"administrativeArea": "",
"postalCode": "",
"country": "",
"email": "",
"phoneNumber": ""
}
}
}
}
//payer setup request
prepareSetupauthenticationRequestData(authRequest) {
var self = this;
var cardinalOrder = Object.assign({}, self.payerSetupRequest);
self.setClientReferenceInformation(authRequest, cardinalOrder);
self.setPaymentInformation(authRequest, cardinalOrder);
return cardinalOrder;
}
//payer enroll request
prepareauthenticationRequestData(authRequest) {
var self = this;
var cardinalOrder = Object.assign({}, self.payerEnrollRequest);
self.setClientReferenceInformation(authRequest, cardinalOrder);
self.setOrderInformation(authRequest, cardinalOrder);
self.setPaymentInformation(authRequest, cardinalOrder);
self.setBuyerInformation(authRequest, cardinalOrder);
self.setConsumerAuthenticationInformation(authRequest, cardinalOrder);
return cardinalOrder;
}
//Prepare payer result data
prepareResultRequestData(authRequest) {
var self = this;
var cardinalOrder = Object.assign({}, self.payerResultRequest);
self.setClientReferenceInformation(authRequest, cardinalOrder);
self.setOrderInformation(authRequest, cardinalOrder);
self.setPaymentInformation(authRequest, cardinalOrder);
self.setBuyerInformation(authRequest, cardinalOrder);
self.setConsumerAuthenticationInformationResult(authRequest, cardinalOrder);
// cardinalOrder.orderInformation.amountDetails.totalAmount=0;
return cardinalOrder;
}
//Prepare Payment request data
preparePaymentRequestData(authRequest) {
var self = this;
var cardinalOrder = Object.assign({}, self.paymentRequest);
self.setClientReferenceInformation(authRequest, cardinalOrder);
self.setProcessingInformation(authRequest, cardinalOrder);
self.setPaymentInformation(authRequest, cardinalOrder);
self.setOrderInformation(authRequest, cardinalOrder);
//for the 0 amount checke
// cardinalOrder.orderInformation.amountDetails.totalAmount=0;
return cardinalOrder;
}
//1
setClientReferenceInformation(authRequest, cardinalOrder) {
let self = this;
var transactionData = authRequest.transaction;
if (transactionData) {
cardinalOrder.clientReferenceInformation.code = transactionData.merchantReference;
}
}
//2
setOrderInformation(authRequest, cardinalOrder) {
var self = this;
var name = null, firstName = "", lastName = "";
if (authRequest) {
//amountDetails
var transactionData = authRequest.transaction;
if (transactionData) {
cardinalOrder.orderInformation.amountDetails.currency = transactionData.currency;
cardinalOrder.orderInformation.amountDetails.totalAmount = transactionData.amount;
}
if(cardinalOrder.orderInformation != null && cardinalOrder.orderInformation.amountDetails != null && cardinalOrder.orderInformation.amountDetails.totalAmount == 0){
cardinalOrder.orderInformation.amountDetails.totalAmount = transactionData.amount;
}
//billTo
var creditCard = authRequest.creditCard;
if (creditCard) {
var name = creditCard.cardHolderName;
if (name.includes(" ")) {
var nameArr = name.split(" ");
firstName = nameArr[0];
lastName = nameArr[1];
if(lastName.trim().length == 0){
lastName = firstName;
}
} else {
firstName = name;
lastName = name;
}
const billTo = {
"address1": creditCard.street1,
"address2": "",
"city": creditCard.city,
"country": creditCard.countryCode,
"administrativeArea": creditCard.state,
"locality": creditCard.city,
"firstName": firstName,
"lastName": lastName,
"phoneNumber": creditCard.phoneNumber,
"email": creditCard.email,
"postalCode": creditCard.zipCode
}
cardinalOrder.orderInformation.billTo = billTo;
}
}
}
//3
setPaymentInformation(authRequest, cardinalOrder) {
var self = this;
if (authRequest) {
//paymentInformation
var creditCard = authRequest.creditCard;
var expiryDate = creditCard.expiryDate;
var expiryDateSplit = expiryDate.split("/");
var expiryMonth = expiryDateSplit[0];
if (expiryMonth.length == 1) {
expiryMonth = "0" + expiryMonth;
}
var expiryYear = expiryDateSplit[1];
if (creditCard) {
let cardType = "";
if (creditCard.cardType == "VI") {
cardType = "001";
} else if (creditCard.cardType == "CA") {
cardType = "002";
} else if (creditCard.cardType == "AX") {
cardType = "003";
} else if (creditCard.cardType == "DS") {
cardType = "004";
} else {
cardType = "0";
}
const cardData = {
"type": cardType, //creditCard.cardType,
"expirationMonth": expiryMonth,
"expirationYear": expiryYear,
"number": creditCard.cardNumber
}
cardinalOrder.paymentInformation.card = cardData;
}
}
}
//4
setBuyerInformation(authRequest, cardinalOrder) {
var creditCard = authRequest.creditCard;
cardinalOrder.buyerInformation.mobilePhone = creditCard.phoneNumber;
}
//5
setConsumerAuthenticationInformation(authRequest, cardinalOrder) {
let self = this;
const consumerAuthenticationInformationData = {
"referenceId": "",
"transactionMode": "S",
"challengeCode":"04",
"returnUrl": window.location.href + "/stepUpReturnUrl",
}
cardinalOrder.consumerAuthenticationInformation = consumerAuthenticationInformationData;
}
//6
setProcessingInformation(authRequest, cardinalOrder) {
let self = this;
const processingInformation = {
"commerceIndicator": "internet",
"authorizationOptions": {
"initiator": {
"credentialStoredOnFile": true
}
}
}
cardinalOrder.processingInformation = processingInformation;
}
//7 only for result
setConsumerAuthenticationInformationResult(authRequest, cardinalOrder) {
let self = this;
const consumerAuthenticationInformationResultData = {
"authenticationTransactionId": ""
}
cardinalOrder.consumerAuthenticationInformation = consumerAuthenticationInformationResultData;
}
//Starting
scan(authRequest, callback) {
//console.log("authRequest : ", authRequest);
var paymoAccountId = authRequest.customer.customerId; //paymo account id
let self = this;
var setupAuthenticationEncryptedRequestData1;
let step3Result = "";
let authenticationRequestData = self.prepareauthenticationRequestData(authRequest); //enroll payload
let setupAuthenticationRequestData = self.prepareSetupauthenticationRequestData(authRequest); //setup payload
let paymentRequestData = self.preparePaymentRequestData(authRequest); //payment payload
let payerResultData= self.prepareResultRequestData(authRequest) // payer result
//encryption payload
try{
const myArray = self.encryptionKey.split(",");
let text = myArray[0];
let encryptedBase64Key = text;
let parsedBase64Key = CryptoJS.enc.Base64.parse(encryptedBase64Key);
let encryptedData = null;
// Encryption process
let plaintText = JSON.stringify(setupAuthenticationRequestData);
// this is Base64-encoded encrypted data
setupAuthenticationEncryptedRequestData1 = CryptoJS.AES.encrypt(plaintText, parsedBase64Key, {
mode: CryptoJS.mode.ECB,
padding: CryptoJS.pad.Pkcs7
}).toString();
//console.log("setupAuthenticationEncryptedRequestData1 = " + setupAuthenticationEncryptedRequestData1);
}catch(ex){
console.log("setupAuthenticationEncryptedRequestData1 exception : ", ex);
var jsonLog={"eventName":"setupAuthenticationEncryptedRequestData_exception","eventCategory":"setupAuthenticationEncryptedRequestData_exception","message":"setupAuthentication Encrypted RequestData exception","data":ex};
SmartScript.auditObject.sendDataToElk(jsonLog);
}
//for getting session id : Step 1
var json={"eventName":"cardinal-submitPayerSetup","eventCategory":"cardinal-commerce-scan","message":"cardinal call submitPayerSetup","data":setupAuthenticationEncryptedRequestData1};
SmartScript.auditObject.sendDataToElk(json);
self.submitPayerSetup(setupAuthenticationRequestData, paymoAccountId)
.then((result) => {
if (result.status === "COMPLETED") {
authenticationRequestData.consumerAuthenticationInformation.referenceId = result.consumerAuthenticationInformation.referenceId;
document.getElementById("cardinal_collection_form").action = result.consumerAuthenticationInformation.deviceDataCollectionUrl;
document.getElementById("cardinal_collection_form_input").value = result.consumerAuthenticationInformation.accessToken;
//calling device Data collection : Step 2
return self.deviceDataCollection(result);
} else{
var errorObj={ "consumerAuthenticationInformation":{
"errorInformation" : {
"message":result.errorInformation.message,
"code": result.errorInformation.code
}
}
};
var json={"eventName":"cardinal-submitPayerSetup_errorObj","eventCategory":"cardinal-commerce-scan","message":"cardinal call submitPayerSetup errorObj","data":errorObj};
SmartScript.auditObject.sendDataToElk(json);
}
}).then((result) => {
//result of the device data
//call enroll service Step 3
return self.submitPayerAuthentication(authenticationRequestData,paymoAccountId)
}).then((result) => {
// result of step 3
//assign to global variable
if(!self.isEmptyObject(result)){
step3Result = result;
}else{
step3Result={"errorInformation":"INVALID REQUEST","message":1};
}
// if status not successful then call step 4 else callback
if (!self.isEmptyObject(result) && result.status === "PENDING_AUTHENTICATION") {
return self.submitSetupIframe(step3Result);
var json={"eventName":"cardinal_otp_case","eventCategory":"cardinal_otp_case","message":"cardinal otp case","data":result.status};
SmartScript.auditObject.sendDataToElk(json);
}
}).then((result) => {
//result of step 4 .. ie stepUpDone
if (result && result === "stepUpDone") {
return self.submitPayerAuthenticationResult(step3Result,paymoAccountId, payerResultData)
}
}).then((result) => {
//result of step 5
//add Extra parameters to response
if (result && step3Result.status !== "AUTHENTICATION_SUCCESSFUL") {
var res = step3Result;
step3Result = result;
step3Result["eci"] = result.consumerAuthenticationInformation.eci;
step3Result["indicator"] = result.consumerAuthenticationInformation.indicator;
step3Result["specificationVersion"] = result.consumerAuthenticationInformation.specificationVersion;
step3Result.consumerAuthenticationInformation.paresStatus = result.consumerAuthenticationInformation.paresStatus;
step3Result.consumerAuthenticationInformation.authenticationTransactionId = res.consumerAuthenticationInformation.authenticationTransactionId;
step3Result.consumerAuthenticationInformation.veresEnrolled = res.consumerAuthenticationInformation.veresEnrolled;
}
// console.log("Console step3 Output : ", step3Result);
console.log("final Output : ", step3Result);
var json={"eventName":"cardinal_final_output","eventCategory":"cardinal_final_output","message":"cardinal final_output","data":step3Result};
SmartScript.auditObject.sendDataToElk(json);
//callback response
callback(step3Result);
}).catch((error) => {
var json={"eventName":"cardinal_promise_error","eventCategory":"cardinal-commerce-scan","message":"cardinal promise error","data":error};
SmartScript.auditObject.sendDataToElk(json);
})
}
// Step 1 : Payer Authentication Setup Service
submitPayerSetup(setupAuthenticationRequestData, paymoAccountId) {
let self = this;
var setupAuthenticationEncryptedRequestData;
//encryption payload
try{
const myArray = self.encryptionKey.split(",");
let encKey = myArray[0];
let encryptedBase64Key = encKey;
let parsedBase64Key = CryptoJS.enc.Base64.parse(encryptedBase64Key);
let encryptedData = null;
// Encryption process
let plaintText = JSON.stringify(setupAuthenticationRequestData);
// this is Base64-encoded encrypted data
setupAuthenticationEncryptedRequestData = CryptoJS.AES.encrypt(plaintText, parsedBase64Key, {
mode: CryptoJS.mode.ECB,
padding: CryptoJS.pad.Pkcs7
}).toString();
//console.log("setupAuthenticationEncryptedRequestData = " + setupAuthenticationEncryptedRequestData);
}catch(ex){
console.log("setupAuthenticationEncryptedRequestData exception : ", ex);
}
var jsonLog={"eventName":"cardinal-step1_request_data","eventCategory":"cardinal-commerce-scan","message":"cardinal step1 request data","data":setupAuthenticationEncryptedRequestData};
SmartScript.auditObject.sendDataToElk(jsonLog);
//console.log("cardinal-step1_request_data : ", setupAuthenticationEncryptedRequestData);
var url1= self.getDecryptedtext(self.payomoServer) + "/v2/risk/"+paymoAccountId+"/payersetupEncryption";
var jsonLog={"eventName":"cardinal-step1_payersetup_url","eventCategory":"cardinal-commerce-scan","message":"cardinal step1 payer setup url","data":url1};
SmartScript.auditObject.sendDataToElk(jsonLog);
return new Promise((resolve, reject) => {
const url = self.getDecryptedtext(self.payomoServer) + "/v2/risk/"+paymoAccountId+"/payersetupEncryption";
const headers = {
Accept: "application/json",
"Content-Type": "application/json",
"Access-Control-Allow-Origin": "*"
};
fetch(url, {
method: "POST",
mode:"cors",
headers,
body: setupAuthenticationEncryptedRequestData,
})
.then((response) => {
if (response.ok) {
return response.json();
} else{
var jsonLog={"eventName":"cardinal-step1_result_error","eventCategory":"cardinal-commerce-scan","message":"cardinal step1_result_error","data":response};
SmartScript.auditObject.sendDataToElk(jsonLog);
reject(response);
}
})
.then((json) => {
//console.log("Payer Step 1 response : ", json);
var jsonLog={"eventName":"cardinal-step1_result","eventCategory":"cardinal-commerce-scan","message":"cardinal step1_result","data":json};
SmartScript.auditObject.sendDataToElk(jsonLog);
resolve(json);
})
.catch((response) => {
var jsonLog={"eventName":"cardinal-step1_result_exception","eventCategory":"cardinal-commerce-scan","message":"cardinal step1_result_exception","data":response};
SmartScript.auditObject.sendDataToElk(jsonLog);
//console.log("cardinal-step1_result_exception : ", response.status, response.statusText);
response.json().then(json => {
//console.log(json);
});
reject(response);
});
});
}
// Step 2 : Device Data Collection Iframe
deviceDataCollection(setupResponse) {
let self = this;
return new Promise((resolve, reject) => {
var cardinalCollectionForm = document.querySelector('#cardinal_collection_form');
if (cardinalCollectionForm) {
cardinalCollectionForm.submit();
try{
if (window.addEventListener) {
var json={"eventName":"cardinal-addEventListener","eventCategory":"cardinal-commerce-scan","message":"cardinal addEventListener_error","data":null};
SmartScript.auditObject.sendDataToElk(json);
window.addEventListener("message", onThreeDSMessage);
}else if (window.attachEvent) {
var json={"eventName":"cardinal-attachEvent_addEventListener","eventCategory":"cardinal-commerce-scan","message":"cardinal addEventListener_error","data":null};
SmartScript.auditObject.sendDataToElk(json);
window.attachEvent("onmessage", onThreeDSMessage, false);
}else if(cardinalCollectionForm.addEventListener){
var json={"eventName":"cardinal-cardinalCollectionForm_addEventListener","eventCategory":"cardinal-commerce-scan","message":"cardinal addEventListener_error","data":null};
SmartScript.auditObject.sendDataToElk(json);
cardinalCollectionForm.addEventListener("message", onThreeDSMessage);
}else if(document.addEventListener){
var json={"eventName":"cardinal-document_addEventListener","eventCategory":"cardinal-commerce-scan","message":"cardinal addEventListener_error","data":null};
SmartScript.auditObject.sendDataToElk(json);
document.addEventListener("message", onThreeDSMessage);
}else{
var json={"eventName":"cardinal-addEventListener_error","eventCategory":"cardinal-commerce-scan","message":"cardinal addEventListener_error","data":null};
SmartScript.auditObject.sendDataToElk(json);
}
}catch(ex){
var json={"eventName":"cardinal-addEventListener_error1","eventCategory":"cardinal-commerce-scan","message":"cardinal addEventListener_error","data":ex};
SmartScript.auditObject.sendDataToElk(json);
}
}else{
var json={"eventName":"cardinal-cardinalCollectionForm_error","eventCategory":"cardinal-commerce-scan","message":"cardinal addEventListener_error","data":null};
SmartScript.auditObject.sendDataToElk(json);
}
function onThreeDSMessage(event) {
if (event.origin === "https://centinelapi.cardinalcommerce.com" || event.origin === "https://centinelapistag.cardinalcommerce.com") {
//console.log("data collect response : ", event.data);
var json={"eventName":"cardinal-step2_result","eventCategory":"cardinal-commerce-scan","message":"cardinal step2_result","data":event.data};
SmartScript.auditObject.sendDataToElk(json);
//document.getElementById("dataCollection").innerHTML = event.data;
// console.log("Payer Step 2 response : ", event);
resolve(event.data);
} else {
var json={"eventName":"cardinal-step2_result_error","eventCategory":"cardinal-commerce-scan","message":"cardinal step2_result_error","data":event};
SmartScript.auditObject.sendDataToElk(json);
reject(event)
}
};
})
}
// Step 3 : Payer Authentication Check Enrollment Service Request Fields
submitPayerAuthentication(authenticationRequestData, paymoAccountId) {
let self = this;
var authenticationEncryptedRequestData;
//encryption payload
try{
const myArray = self.encryptionKey.split(",");
let text = myArray[0];
let encryptedBase64Key = text;
let parsedBase64Key = CryptoJS.enc.Base64.parse(encryptedBase64Key);
let encryptedData = null;
// Encryption process
let plaintText = JSON.stringify(authenticationRequestData);
// this is Base64-encoded encrypted data
authenticationEncryptedRequestData = CryptoJS.AES.encrypt(plaintText, parsedBase64Key, {
mode: CryptoJS.mode.ECB,
padding: CryptoJS.pad.Pkcs7
}).toString();
//console.log("authenticationEncryptedRequestData = " + authenticationEncryptedRequestData);
}catch(ex){
console.log("setupAuthenticationEncryptedRequestData exception : ", ex);
}
var jsonLog={"eventName":"cardinal-step2_request_data","eventCategory":"cardinal-commerce-scan","message":"cardinal step2 request data","data":authenticationEncryptedRequestData};
SmartScript.auditObject.sendDataToElk(jsonLog);
//console.log("cardinal-step2_request_data: ",jsonLog);
return new Promise((resolve, reject) => {
const url = self.getDecryptedtext(self.payomoServer) + "/v2/risk/"+paymoAccountId+"/payerenrollEncryption";
const headers = {
Accept: "application/json",
"Content-Type": "application/json",
"Access-Control-Allow-Origin": "*"
};
fetch(url, {
method: "POST",
mode:"cors",
headers,
body: authenticationEncryptedRequestData,
})
.then((response) => {
if (response.ok) {
return response.json();
} else {
var jsonLog={"eventName":"cardinal-step3_result_error","eventCategory":"cardinal-commerce-scan","message":"cardinal step3_result_error","data":error};
SmartScript.auditObject.sendDataToElk(jsonLog);
reject(response);
}
})
.then((json) => {
//console.log("Payer Step 3 response : ", json);
var jsonLog={"eventName":"cardinal-step3_result","eventCategory":"cardinal-commerce-scan","message":"cardinal step3_result","data":json};
SmartScript.auditObject.sendDataToElk(jsonLog);
resolve(json);
})
.catch((response) => {
var jsonLog={"eventName":"cardinal-step3_result_exception","eventCategory":"cardinal-commerce-scan","message":"cardinal step3_result_exception","data":response};
SmartScript.auditObject.sendDataToElk(jsonLog);
//console.log("cardinal-step3_result_exception", response.status, response.statusText);
response.json().then(json => {
//console.log(json);
});
reject(response);
});
});
}
// Step 4 : Step-Up IFrame
submitSetupIframe(res) {
let self = this;
return new Promise((resolve, reject) => {
document.getElementById("setup_iframe_input").value = res.consumerAuthenticationInformation.accessToken;
document.getElementById("step-up-form").action = res.consumerAuthenticationInformation.stepUpUrl;
var stepUpForm = document.querySelector('#step-up-form');
if (stepUpForm) {
console.log("Payer Step 4 ");
var json={"eventName":"cardinal-step4_otp","eventCategory":"cardinal-commerce-scan","message":"cardinal step4_otp","data":"cardinal step4_otp"};
SmartScript.auditObject.sendDataToElk(json);
document.getElementById("travelerOverlayBGMain").style.display = 'flex';
stepUpForm.submit();
if (window.addEventListener) {
window.addEventListener('message', function(event) {
//console.log("Message received from the parent: " + event.data); // Message received from parent
if(event.data === "reload"){
var json={"eventName":"cardinal-step4_otp_result","eventCategory":"cardinal-commerce-scan","message":"cardinal step4_otp_result","data":event.data};
SmartScript.auditObject.sendDataToElk(json);
resolve("stepUpDone");
}
});
}
}else{
var json={"eventName":"cardinal-step4_No-otp","eventCategory":"cardinal-commerce-scan","message":"cardinal step4_No-otp","data":event.data};
SmartScript.auditObject.sendDataToElk(json);
}
})
}
// Step 5 : Payer Authentication Validation Service
submitPayerAuthenticationResult(authenticationResponse, paymoAccountId, payerResultData) {
//console.log(" in Step 5 request ", payerResultData);
document.getElementById("travelerOverlayBGMain").style.display = 'none';
let self = this;
var payerResultEncryptedRequestData;
payerResultData.consumerAuthenticationInformation.authenticationTransactionId = authenticationResponse.consumerAuthenticationInformation.authenticationTransactionId;
//encryption payload
try{
const myArray = self.encryptionKey.split(",");
let text = myArray[0];
let encryptedBase64Key = text;
let parsedBase64Key = CryptoJS.enc.Base64.parse(encryptedBase64Key);
let encryptedData = null;
// Encryption process
let plaintText = JSON.stringify(payerResultData);
// this is Base64-encoded encrypted data
payerResultEncryptedRequestData = CryptoJS.AES.encrypt(plaintText, parsedBase64Key, {
mode: CryptoJS.mode.ECB,
padding: CryptoJS.pad.Pkcs7
}).toString();
//console.log("payerResultEncryptedRequestData = " + payerResultEncryptedRequestData);
}catch(ex){
console.log("payerResultEncryptedRequestData exception : ", ex);
}
var jsonLog={"eventName":"cardinal-step5_request_data","eventCategory":"cardinal-commerce-scan","message":"cardinal step5 request data","data":payerResultEncryptedRequestData};
SmartScript.auditObject.sendDataToElk(jsonLog);
//console.log("cardinal-step5_request_data: ",jsonLog);
return new Promise((resolve, reject) => {
const url = self.getDecryptedtext(self.payomoServer) + "/v2/risk/"+paymoAccountId+"/payerresultEncryption";
const headers = {
Accept: "application/json",
"Content-Type": "application/json",
"Access-Control-Allow-Origin": "*"
};
fetch(url, {
method: "POST",
mode:"cors",
headers,
body: payerResultEncryptedRequestData,
})
.then((response) => {
if (response.ok) {
return response.json();
} else{
//console.log("Payer Step 5 response : : ", response);
var jsonLog={"eventName":"cardinal-step5_error","eventCategory":"cardinal-commerce-scan","message":"cardinal step5_error","data": response};
SmartScript.auditObject.sendDataToElk(jsonLog);
reject(response);
}
})
.then((json) => {
var jsonLog={"eventName":"cardinal-step5_result","eventCategory":"cardinal-commerce-scan","message":"cardinal step5_result","data": json};
SmartScript.auditObject.sendDataToElk(jsonLog);
//console.log("Payer Step 5 response : ", json);
resolve(json);
})
.catch((response) => {
var jsonLog={"eventName":"cardinal-step5_result_exception","eventCategory":"cardinal-commerce-scan","message":"cardinal step3_result_exception","data":response};
SmartScript.auditObject.sendDataToElk(jsonLog);
//console.log(response.status, response.statusText);
response.json().then(json => {
//console.log(json);
});
reject(response);
});
});
}
// Payment service
submitPayment(paymentRequestData, paymoAccountId) {
//console.log(" Payment service request data: ", paymentRequestData);
let self = this;
return new Promise((resolve, reject) => {
$.ajax({
url: self.getDecryptedtext(self.payomoServer) + "/v2/risk/"+paymoAccountId+"/payment",
method: "POST",
contentType: "application/json",
data: JSON.stringify(paymentRequestData),
headers: { "Access-Control-Allow-Origin": "*" },
success: function (data) {
resolve(data)
},
error: function (error) {
console.log("Payment Error : : ", error);
reject(error)
},
})
})
}
//check json object is empty or not
isEmptyObject(obj){
return JSON.stringify(obj) === '{}';
}
}/*
* Riskified
*/
class Riskified extends RiskManagement{
constructor(sessionId){
this.sessionId=sessionId;
}
static loadScript(){
var s = document.createElement('script');
s.type = 'text/javascript';
s.async = true;
s.src = "https://beacon.riskified.com?shop=lbftravel.com&sid="+this.getDecryptedtext(this.sessionId);
var x = document.getElementsByTagName('script')[0];
x.parentNode.insertBefore(s, x);
console.log("added Riskified Beacon successfully");
}
}/*
* DecisionManager
*/
class DecisionManager extends RiskManagement{
static loadScript(filename, scriptFile, callback){
}
}/*
* BraintreeThreeDS
*/
class BraintreeThreeDS extends RiskManagement {
constructor() {
super();
}
threeDsecureCheck(clientToken,authRequest,callback) {
let self=this;
let threeDSecure;
let threeDS;
let hf;
var threeDSResponse;
var dataCollector;
return self.setupComponents(clientToken,authRequest).then(function (instances) {
hf = instances[0];
threeDS = instances[1];
dataCollector = instances[2];
console.log(" 3ds instances : ", instances);
if (hf === null || hf === undefined) {
return null;
}
if (threeDS === null || threeDS === undefined) {
return null;
}
if (dataCollector === null || dataCollector === undefined || dataCollector.deviceData == null) {
return null;
}
threeDSResponse = self.varifyCard(hf,threeDS,authRequest,callback);
}).catch(function (err) {
console.log('component error:', err);
var json={"eventName":"braintree_component_error ","eventCategory":"braintree_component_error","message":"braintree component error","data":err};
SmartScript.auditObject.sendDataToElk(json);
});
}
setupComponents(clientToken,authRequest) {
// re-new braintreeDiv
var widgetObj1=new Widget();
var bt= document.getElementById("braintreeDiv");
if(bt){
bt.remove();
}
widgetObj1.braintreeHostedFields();
return Promise.all([
braintree.hostedFields.create({
authorization: clientToken,
styles: {
input: {
'font-size': '14px',
'font-family': 'monospace'
}
},
fields: {
cardholderName: {
selector: '#hf-cardholdername',
prefill: authRequest.creditCard.cardHolderName
},
number: {
selector: '#hf-number',
prefill: authRequest.creditCard.cardNumber
},
cvv: {
selector: '#hf-cvv',
prefill: authRequest.creditCard.cvv
},
expirationDate: {
selector: '#hf-date',
prefill: authRequest.creditCard.expiryDate
}
}
}),
braintree.threeDSecure.create({
authorization: clientToken,
version: 2
}),
braintree.dataCollector.create({
authorization: clientToken
})
]);
}
varifyCard(hf,threeDS,authRequest,callback) {
var payload;
hf.tokenize().then(function (payload) {
console.log("payload", payload);
//split names to fname and lname
var name = null, firstName = "", lastName = "";
var name = authRequest.creditCard.cardHolderName;
if (name.includes(" ")) {
var nameArr = name.split(" ");
firstName = nameArr[0];
lastName = nameArr[1];
if(lastName.trim().length == 0){
lastName = firstName;
}
} else {
firstName = name;
lastName = name;
}
return threeDS.verifyCard({
onLookupComplete: function (data, next) {
next();
},
amount: authRequest.transaction.amount,
nonce: payload.nonce,
bin: payload.details.bin,
email: authRequest.creditCard.email,
billingAddress: {
givenName: firstName, // ASCII-printable characters required, else will throw a validation error
surname: lastName, // ASCII-printable characters required, else will throw a validation error
phoneNumber: authRequest.creditCard.phoneNumber,
streetAddress: authRequest.creditCard.street1,
extendedAddress: authRequest.creditCard.city,
locality: authRequest.creditCard.state,
region: authRequest.creditCard.countryCode, // ISO-3166-2 code
postalCode: authRequest.creditCard.zipCode,
countryCodeAlpha2: authRequest.creditCard.countryCode
}
})
}).then(function (payloadResp) {
payload = payloadResp;
if (!payload.liabilityShifted) {
console.log('Liability did not shift', payload);
//return;
}
console.log('verification success:', payload);
var json={"eventName":"braintree_verification_success ","eventCategory":"braintree_verification_success","message":"braintree verification success","data":payload};
SmartScript.auditObject.sendDataToElk(json);
// send nonce and verification data to your server
callback(payload);
}).catch(function (err) {
console.log("braintree err ", err);
var json={"eventName":"braintree_exception ","eventCategory":"braintree_exception","message":"braintree exception","data":err};
SmartScript.auditObject.sendDataToElk(json);
var braintreeException={
"threeDSecureInfo": {
"liabilityShifted": false,
"liabilityShiftPossible": false,
"status": "authenticate_rejected",
"enrolled": null,
"cavv": null,
"xid": null,
"acsTransactionId": null,
"dsTransactionId": null,
"eciFlag": null,
"acsUrl": null,
"paresStatus": null,
"threeDSecureAuthenticationId": null,
"threeDSecureServerTransactionId": null,
"threeDSecureVersion": null,
"lookup": {
"transStatus": null,
"transStatusReason": null
},
"authentication": {
"transStatus": null,
"transStatusReason": null
}
},
"verificationDetails": {
"liabilityShifted": false,
"liabilityShiftPossible": false
},
"rawCardinalSDKVerificationData": {
"Validated": false,
"ActionCode": "authenticate_rejected",
"ErrorNumber": 0,
"ErrorDescription": JSON.stringify(err.details),
"Payment": {
"Type": null,
"ExtendedData": {
"Amount": null,
"CAVV": null,
"CurrencyCode": null,
"ECIFlag": null,
"ThreeDSVersion": "2.2.0",
"PAResStatus": null,
"SignatureVerification": null
},
"ProcessorTransactionId": null
}
}
}
console.log("braintree Exception ", braintreeException);
callback(braintreeException);
});
};
}
/*
* Widget
*/
class Widget extends SmartScript {
constructor(payRequest) {
super();
var self = this;
this.payRequest = payRequest;
let urlMap = new Map();
urlMap.set('widgetStyles', self.payomoStylesUrl);
urlMap.set("googlePay", 'https://pay.google.com/gp/p/js/pay.js');
urlMap.set("payPalCheckout", 'https://www.paypalobjects.com/api/checkout.js');
urlMap.set('braintreePayPalCheckout', 'https://js.braintreegateway.com/web/3.88.4/js/paypal-checkout.min.js');
urlMap.set('braintreeClient', 'https://js.braintreegateway.com/web/3.88.4/js/client.js');
//urlMap.set('venmo', 'https://js.braintreegateway.com/web/3.88.4/js/venmo.min.js');
urlMap.set('dataCollector', 'https://js.braintreegateway.com/web/3.88.4/js/data-collector.min.js');
urlMap.set('threeDsJs', 'https://js.braintreegateway.com/web/3.88.4/js/three-d-secure.min.js');
urlMap.set('hostedfields', 'https://js.braintreegateway.com/web/3.88.4/js/hosted-fields.min.js');
urlMap.set('crypto', 'https://cdnjs.cloudflare.com/ajax/libs/crypto-js/3.1.9-1/crypto-js.min.js');
this.filesUrlMap = urlMap;
let map = new Map();
map.set('widgetStyles', false);
map.set("googlePay", false);
map.set("payPalCheckout", false);
map.set("braintreeClient", false);
map.set("braintreePayPalCheckout", false);
//map.set("venmo", false);
map.set("dataCollector", false);
map.set("threeDsJs", false);
map.set("hostedfields", false);
map.set("crypto", false);
// VI, CA, AX, DS;
this.filesLoadedMap = map;
Widget.payResponse = {
paymentToken: "",
selectedPaymentMethod: "",
cardNumber: "",
cardHolderName: "",
expiryDate: "",
cvv: "",
cardType: "",
cryptogram: "",
securityCode: "",
firstName: "",
lastName: "",
email: "",
tokenizedCardNumber: "",
tokenizedCardNumber: ""
};
Widget.finalAmount = 0;
Widget.paymentMethodType = null;
console.log("called Widget constructor");
}
/**
*
*/
_setPayResponse(payload) {
console.log("set pay response")
Widget.payResponse = payload;
}
_setSelectedPaymentType(paymentType) {
Widget.paymentMethodType = paymentType;
}
paymentAuth(authRequest, riskCheckRequired, callback) {
var self = this;
let riskchkResponse = '';
try{
//call risk check service
if (riskCheckRequired) {
payomo.riskcheck.submit(authRequest, function (riskCheckResponse) {
riskchkResponse = riskCheckResponse;
if(authRequest.hasOwnProperty("threeDSData")){
delete authRequest.threeDSData; //remove the property before sending it to Auth
}
if(authRequest.hasOwnProperty("dmClientToken")){
delete authRequest.dmClientToken; //remove the property before sending it to Auth
}
if(authRequest.hasOwnProperty("rkClientToken")){
delete authRequest.rkClientToken; //remove the property before sending it to Auth
}
if(authRequest.hasOwnProperty("fraudChecks")){
delete authRequest.fraudChecks; //remove the property before sending it to Auth
}
if(authRequest.hasOwnProperty("customerCategory")){
delete authRequest.customerCategory; //remove the property before sending it to Auth
}
if(authRequest.hasOwnProperty("customer")){
if(authRequest.customer.hasOwnProperty("action")){
delete authRequest.customer.action;
} //remove the property before sending it to Auth
}
//call auth service
self.callAuthServcie(authRequest, callback, riskchkResponse);
});
}
//call directly auth servcie
else {
self.callAuthServcie(authRequest, callback, riskchkResponse);
}
} catch (e) {
//console.log(e);
var json={"eventName":"payment_auth_exception","eventCategory":"payment_auth_exception","message":"payment auth exception","data":e};
SmartScript.auditObject.sendDataToElk(json);
}
}
callAuthServcie(authRequest, callback, riskCheckResponse) {
var self = this;
//other than credit card request
if (authRequest && authRequest.paymentMethod && authRequest.paymentMethod.tokenizedCard
&& authRequest.paymentMethod.tokenizedCard.expiryDate) {
var expiryDate = authRequest.paymentMethod.tokenizedCard.expiryDate;
expiryDate = expiryDate.substring(0, 2) + expiryDate.substring(expiryDate.length - 2, expiryDate.length);
authRequest.paymentMethod.tokenizedCard.expiryDate = expiryDate;
}
//credit card request
if (authRequest && authRequest.creditCard
&& authRequest.creditCard.expiryDate) {
var expiryDate = authRequest.creditCard.expiryDate;
expiryDate = expiryDate.substring(0, 2) + expiryDate.substring(expiryDate.length - 2, expiryDate.length);
authRequest.creditCard.expiryDate = expiryDate;
}
let request = { "accountId": self.getDecryptedtext(this.payomoAccountId), "request": authRequest }
//call risk check service
$.ajax({
// url : "https://www.exploretrip1.com:8443/payment/api/v1/apple/createSession",
url: self.getDecryptedtext(self.payomoServer) + "/api/v1/payment/card/auth",
method: "POST",
contentType: "application/json", // "application/json; charset=utf-8",//, //
dataType: "json",
data: "{}",
data: JSON.stringify(request)
// headers: headers
}).then(function (res) {
// Complete validation by passing the merchant session to the Apple Pay session.
if (callback) {
if(riskCheckResponse!=null && JSON.stringify(riskCheckResponse).length > 0){
res.riskifiedResponse = riskCheckResponse;
}
callback(res);
}
});
}
paymentSale(authRequest, riskCheckRequired, callback) {
var self = this;
let riskchkResponse = '';
//call risk check service
if (riskCheckRequired) {
payomo.riskcheck.submit(authRequest, function (riskCheckResponse) {
riskchkResponse = riskCheckResponse;
if(authRequest.hasOwnProperty("threeDSData")){
delete authRequest.threeDSData; //remove the property before sending it to Auth
}
if(authRequest.hasOwnProperty("dmClientToken")){
delete authRequest.dmClientToken; //remove the property before sending it to Auth
}
if(authRequest.hasOwnProperty("rkClientToken")){
delete authRequest.rkClientToken; //remove the property before sending it to Auth
}
if(authRequest.hasOwnProperty("fraudChecks")){
delete authRequest.fraudChecks; //remove the property before sending it to Auth
}
if(authRequest.hasOwnProperty("customerCategory")){
delete authRequest.customerCategory; //remove the property before sending it to Auth
}
if(authRequest.hasOwnProperty("customer")){
if(authRequest.customer.hasOwnProperty("action")){
delete authRequest.customer.action;
} //remove the property before sending it to Auth
}
if(authRequest.hasOwnProperty("customer")){
if(authRequest.customer.hasOwnProperty("whiteListed")){
delete authRequest.customer.whiteListed;
} //remove the property before sending it to Auth
}
//call sale service
self.callSaleServcie(authRequest, callback, riskchkResponse);
});
}
//call directly sale servcie
else {
self.callSaleServcie(authRequest, callback, riskchkResponse);
}
}
callSaleServcie(authRequest, callback, riskchkResponse) {
var self = this;
//other than credit card request
if (authRequest && authRequest.paymentMethod && authRequest.paymentMethod.tokenizedCard
&& authRequest.paymentMethod.tokenizedCard.expiryDate) {
var expiryDate = authRequest.paymentMethod.tokenizedCard.expiryDate;
expiryDate = expiryDate.substring(0, 2) + expiryDate.substring(expiryDate.length - 2, expiryDate.length);
authRequest.paymentMethod.tokenizedCard.expiryDate = expiryDate;
}
//credit card request
if (authRequest && authRequest.creditCard
&& authRequest.creditCard.expiryDate) {
var expiryDate = authRequest.creditCard.expiryDate;
expiryDate = expiryDate.substring(0, 2) + expiryDate.substring(expiryDate.length - 2, expiryDate.length);
authRequest.creditCard.expiryDate = expiryDate;
}
let request = { "accountId": self.getDecryptedtext(this.payomoAccountId), "request": authRequest }
//call risk check service
$.ajax({
// url : "https://www.exploretrip1.com:8443/payment/api/v1/apple/createSession", "http://localhost:8080/payment/api/v1/payment/card/sale", //https://api.payomo.com/api/v1/payment/card/sale
url: self.getDecryptedtext(self.payomoServer) + "/api/v1/payment/card/sale",
method: "POST",
contentType: "application/json", // "application/json; charset=utf-8",//, //
dataType: "json",
data: "{}",
data: JSON.stringify(request)
// headers: headers
}).then(function (res) {
// Complete validation by passing the merchant session to the Apple Pay session.
try{
if (callback) {
if(riskchkResponse!=null && JSON.stringify(riskchkResponse).length > 0){
res.riskifiedResponse = riskchkResponse;
}
callback(res);
}
}catch (e) {
console.log(e);
var json={"eventName":"payment_sale_exception","eventCategory":"payment_sale_exception","message":"payment sale exception","data":e};
SmartScript.auditObject.sendDataToElk(json);
}
});
}
submitPayment(callback) {
let resp = '';
if (!Widget.payResponse.selectedPaymentMethod) {
var cardObj = new CreditCard();
var isValid = cardObj.isCreditCardDetailsValid();
if (isValid) {
cardObj.addCreditCardInfoToPayResponse();
resp = Widget.payResponse;
}else{
if (this.payRequest.isBillingInfoRequired) {
var billingObj = new BillingInfo();
var isbillingValid = billingObj.isBillingInfoValid(this.payRequest);
if (isbillingValid && isValid) {
billingObj.addBillingInfoToPayResponse(this.payRequest);
}else{
return;
}
}
}
if (this.payRequest.isBillingInfoRequired && isValid) {
var billingObj = new BillingInfo();
var isbillingValid = billingObj.isBillingInfoValid(this.payRequest);
if (isbillingValid) {
billingObj.addBillingInfoToPayResponse(this.payRequest);
}else{
return;
}
}
Widget.payResponse['cardNumber']=resp.cardNumber.replace(/\D/g, "");
Widget.payResponse['cardHolderName']=resp.cardHolderName;
Widget.payResponse['expiryDate']=resp.expiryDate;
Widget.payResponse['cvv']=resp.cvv;
Widget.payResponse['cardType']=resp.cardType;
Widget.payResponse.selectedPaymentMethod=resp.selectedPaymentMethod;
}else if(Widget.payResponse.selectedPaymentMethod =='CREDIT_CARD'){
var cardObj = new CreditCard();
var isValid = cardObj.isCreditCardDetailsValid();
if (isValid) {
cardObj.addCreditCardInfoToPayResponse();
resp = Widget.payResponse;
}else{
if (this.payRequest.isBillingInfoRequired) {
var billingObj = new BillingInfo();
var isbillingValid = billingObj.isBillingInfoValid(this.payRequest);
if (isbillingValid) {
billingObj.addBillingInfoToPayResponse(this.payRequest);
}else{
return;
}
}
}
if (this.payRequest.isBillingInfoRequired) {
var billingObj = new BillingInfo();
var isbillingValid = billingObj.isBillingInfoValid(this.payRequest);
if (isbillingValid) {
billingObj.addBillingInfoToPayResponse(this.payRequest);
}else{
return;
}
}
Widget.payResponse['cardNumber']=resp.cardNumber.replace(/\D/g, "");
Widget.payResponse['cardHolderName']=resp.cardHolderName;
Widget.payResponse['expiryDate']=resp.expiryDate;
Widget.payResponse['cvv']=resp.cvv;
Widget.payResponse['cardType']=resp.cardType;
Widget.payResponse.selectedPaymentMethod=resp.selectedPaymentMethod;
}else if(Widget.payResponse.selectedPaymentMethod =='PAYPAL'){
resp = Widget.payResponse;
/*if (this.payRequest.isBillingInfoRequired) {
var billingObj = new BillingInfo();
var isbillingValid = billingObj.isBillingInfoValid(this.payRequest);
if (isbillingValid) {
billingObj.addBillingInfoToPayResponse(this.payRequest);
}else{
Widget.payResponse=resp;
return;
}
}*/
/* adding default address*/
Widget.payResponse['street1']="10800 Pecan Park Blvd.#315";
Widget.payResponse['city']="Austin";
Widget.payResponse['state']="TX";
Widget.payResponse['countryCode']="US";
Widget.payResponse['zipCode']="78750";
Widget.payResponse.email = resp.email;
Widget.payResponse.firstName = resp.firstName;
Widget.payResponse.lastName = resp.lastName;
Widget.payResponse.paymentToken =resp.paymentToken;
Widget.payResponse.selectedPaymentMethod=resp.selectedPaymentMethod;
}else if(Widget.payResponse.selectedPaymentMethod =='GOOGLE_PAY'){
resp = Widget.payResponse;
/*if (this.payRequest.isBillingInfoRequired) {
var billingObj = new BillingInfo();
var isbillingValid = billingObj.isBillingInfoValid(this.payRequest);
if (isbillingValid) {
billingObj.addBillingInfoToPayResponse(this.payRequest);
}else{
Widget.payResponse=resp;
return;
}
}*/
/* adding default address*/
Widget.payResponse['street1']="10800 Pecan Park Blvd.#315";
Widget.payResponse['city']="Austin";
Widget.payResponse['state']="TX";
Widget.payResponse['countryCode']="US";
Widget.payResponse['zipCode']="78750";
Widget.payResponse.cardNumber = resp.cardNumber;
Widget.payResponse.cardType = resp.cardType;
Widget.payResponse.paymentToken =resp.paymentToken;
Widget.payResponse.selectedPaymentMethod=resp.selectedPaymentMethod;
}else if(Widget.payResponse.selectedPaymentMethod =='APPLE_PAY'){
resp = Widget.payResponse;
/*if (this.payRequest.isBillingInfoRequired) {
var billingObj = new BillingInfo();
var isbillingValid = billingObj.isBillingInfoValid(this.payRequest);
if (isbillingValid) {
billingObj.addBillingInfoToPayResponse(this.payRequest);
}else{
Widget.payResponse=resp;
return;
}
}*/
/* adding default address*/
Widget.payResponse['street1']="10800 Pecan Park Blvd.#315";
Widget.payResponse['city']="Austin";
Widget.payResponse['state']="TX";
Widget.payResponse['countryCode']="US";
Widget.payResponse['zipCode']="78750";
Widget.payResponse.tokenizedCardNumber = resp.tokenizedCardNumber;
Widget.payResponse.tokenizedExpiryDate = resp.tokenizedExpiryDate;
Widget.payResponse.cryptogram =resp.cryptogram;
Widget.payResponse.securityCode =resp.securityCode;
Widget.payResponse.selectedPaymentMethod=resp.selectedPaymentMethod;
}
//console.log("Widget.payResponse =" + self.getEncryptedtext(JSON.stringify(Widget.payResponse)));
callback(Widget.payResponse);
}
populateCardInformation(request) {
var self = this;
try{
$("#widget-card-holder-error").hide();
$("#bilingErrorInfo").hide();
$("#widget-card-number-error").hide();
$("#widget-credit-error").hide();
$("#widget-expiry-date-error").hide();
$("#widget-cvv-error").hide();
$("#widget-card-number-invalid-error").hide();
if(request.type.toLowerCase() == "add"){
$('#widget-card-number').removeAttr('disabled');
$('#widget-card-holder').removeAttr('disabled');
$('#widget-expiry-year').removeAttr('disabled');
$('#widget-expiry-month').removeAttr('disabled');
$('#widget-card-image').css('display', 'none');
$('#widget-card-number').val('');
$('#widget-card-holder').val('');
$('#widget-cvv').val('');
$('#widget-billingInfo-address1').val('');
$('#widget-billingInfo-city').val('');
$('#widget-billingInfo-zipcode').val('');
document.getElementById("widget-expiry-month").selectedIndex = "0";
document.getElementById("widget-expiry-year").selectedIndex = "0";
document.getElementById("widget-billingInfo-country").selectedIndex = "0";
document.getElementById("widget-billingInfo-state").selectedIndex = "0";
$("#actualcc").val('');
return;
}else{
var actualCC = request.cardNumber;
if (actualCC.startsWith("4")) {
$('#widget-card-image').css('background-image', 'url("https://images.trippro.com/payomo/widget/visa.svg")');
$('#widget-card-image').css('display', 'block');
} else if (actualCC.startsWith("3")) {
$('#widget-card-image').css('background-image', 'url("https://images.trippro.com/payomo/widget/amex.svg")');
$('#widget-card-image').css('display', 'block');
} else if (actualCC.startsWith("5")) {
$('#widget-card-image').css('background-image', 'url("https://images.trippro.com/payomo/widget/mc_vrt_pos.svg")');
$('#widget-card-image').css('display', 'block');
} else if (actualCC.startsWith("6")) {
$('#widget-card-image').css('background-image', 'url("https://images.trippro.com/payomo/widget/discover.svg")');
$('#widget-card-image').css('display', 'block');
} else {
$('#widget-card-image').css('display', 'none');
}
var first6 = actualCC.substring(0,6);
var last4 = actualCC.substring(actualCC.length-4);
$("#actualcc").val(actualCC);
$('#widget-card-number').val(first6 + 'XXXXXX' + last4);
$('#widget-card-number').attr('disabled','disabled');
$('#widget-card-holder').val(request.cardHolderName);
$('#widget-card-holder').attr('disabled','disabled');
$('#widget-cvv').val(''); //not populating for security reasons
document.getElementById("widget-expiry-month").selectedIndex = request.expiryDate.substring(0,2);
var currentYear = new Date().getFullYear();
var yearValue = currentYear.toString().substring(0,2)+request.expiryDate.substring(2,4);
var ind = $("#widget-expiry-year option[value="+ yearValue+"]").index();
document.getElementById("widget-expiry-year").selectedIndex = ind.toString();
$('#widget-expiry-year').attr('disabled','disabled');
$('#widget-expiry-month').attr('disabled','disabled');
$('#widget-billingInfo-address1').val(request.street1);
var billingObj = new BillingInfo();
//billingObj.appendCountryList(null);
setTimeout(function() {
ind = $("#widget-billingInfo-country option[code="+ request.countryCode+"]").index();
document.getElementById("widget-billingInfo-country").selectedIndex = ind.toString();
billingObj.appendCountryStateList($('#widget-billingInfo-country').val());
setTimeout(function() {
ind = $("#widget-billingInfo-state option[code="+ request.state+"]").index();
document.getElementById("widget-billingInfo-state").selectedIndex = ind.toString();
}, 2000);
//Wait for 2secs to load the states of the selected country
}, 2000);
$('#widget-billingInfo-city').val(request.city);
$('#widget-billingInfo-zipcode').val(request.zipCode);
/*$('#widget-contactInfo-email').val(request.email);
$('#widget-contactInfo-confirmEmail').val(request.email);
$('#widget-contactInfo-phone2').val(request.phoneNumber);*/
}
}catch (e) {
var json={"eventName":"populateCardInformation_exception","eventCategory":"populateCardInformation_exception","message":"populateCardInformation exception","data":e};
SmartScript.auditObject.sendDataToElk(json);
}
}
loadWidgetScripts() {
var self = this;
try {
var settings = JSON.parse(payomo.checkoutReplyJson);
if (!self.filesLoadedMap.get('threeDsJs')) {
Loader.appendScript("threeDsJs", self.filesUrlMap.get('threeDsJs'), function (e) {
Loader.loadScriptCallback(e, "threeDsJs", self.filesLoadedMap)
});
}
if (!self.filesLoadedMap.get('hostedfields')) {
Loader.appendScript("hostedfields", self.filesUrlMap.get('hostedfields'), function (e) {
Loader.loadScriptCallback(e, "hostedfields", self.filesLoadedMap)
});
}
//data collector
if (!self.filesLoadedMap.get('dataCollector')) {
Loader.appendScript("dataCollector", self.filesUrlMap.get('dataCollector'), function (e) {
Loader.loadScriptCallback(e, "dataCollector", self.filesLoadedMap)
});
}
//crypto js
if (!self.filesLoadedMap.get('crypto')) {
Loader.appendScript("crypto", self.filesUrlMap.get('crypto'), function (e) {
Loader.loadScriptCallback(e, "crypto", self.filesLoadedMap)
});
}
if (settings.enableWallets && settings.enableWallets.length > 0) {
if (settings.enableWallets.indexOf("gpay") > -1) {
//google pay
if (!self.filesLoadedMap.get('googlePay')) {
Loader.appendScript("googlePay", self.filesUrlMap.get('googlePay'), function (e) {
Loader.loadScriptCallback(e, "googlePay", self.filesLoadedMap)
});
}
}else{
self.filesLoadedMap.delete('googlePay');
}
if (settings.enableWallets.indexOf("paypal") > -1) {
//brain tree client
if (!self.filesLoadedMap.get('braintreeClient')) {
Loader.appendScript("braintreeClient", self.filesUrlMap.get('braintreeClient'), function (e) {
Loader.loadScriptCallback(e, "braintreeClient", self.filesLoadedMap)
});
}
//paypal
if (!self.filesLoadedMap.get('payPalCheckout')) {
Loader.appendScript("payPalCheckout", self.filesUrlMap.get('payPalCheckout'), function (e) {
Loader.loadScriptCallback(e, "payPalCheckout", self.filesLoadedMap)
});
}
//braintreePayPalCheckout
if (!self.filesLoadedMap.get('braintreePayPalCheckout')) {
Loader.appendScript("braintreePayPalCheckout", self.filesUrlMap.get('braintreePayPalCheckout'), function (e) {
Loader.loadScriptCallback(e, "braintreePayPalCheckout", self.filesLoadedMap)
});
}
}else{
self.filesLoadedMap.delete('payPalCheckout');
self.filesLoadedMap.delete('braintreeClient');
self.filesLoadedMap.delete('braintreePayPalCheckout');
//self.filesLoadedMap.delete('dataCollector');
}
/*if ($.inArray('venmo', settings.enableWallets) > -1) {
//venmo
if (!self.filesLoadedMap.get('venmo')) {
Loader.appendScript("venmo", self.filesUrlMap.get('venmo'), function (e) {
Loader.loadScriptCallback(e, "venmo", self.filesLoadedMap)
});
}
}else{
self.filesLoadedMap.delete('venmo');
}*/
}else{
self.filesLoadedMap.delete('googlePay');
self.filesLoadedMap.delete('payPalCheckout');
self.filesLoadedMap.delete('braintreeClient');
self.filesLoadedMap.delete('braintreePayPalCheckout');
//self.filesLoadedMap.delete('dataCollector');
}
}catch (e) {
var json={"eventName":"load_Widget_Scripts_exception","eventCategory":"load_Widget_Scripts_exception","message":"widget scripts exception","data":e};
SmartScript.auditObject.sendDataToElk(json);
}
}
loadWidgetStyles() {
var self = this;
if (!self.filesLoadedMap.get('widgetStyles')) {
var link = document.createElement('link');
link.rel = 'stylesheet';
link.type = 'text/css';
link.href = this.filesUrlMap.get('widgetStyles');
document.getElementsByTagName('HEAD')[0].appendChild(link);
var link1 = document.createElement('link');
link1.rel = 'icon';
link1.type = 'image/png';
link1.href = 'https://www.payomo.com/assets/jsp/Sites/payomo/wp-content/uploads/2018/06/cropped-favicon-32x32.png';
document.getElementsByTagName('HEAD')[0].appendChild(link);
this.filesLoadedMap.set('widgetStyles', true);
}
}
isAllLoaded() {
let obj = {};
this.filesLoadedMap.forEach(function(value, key){
obj[key] = value
});
console.log("isAllLoaded()=" + JSON.stringify(obj));
return Loader.isAllLoaded(this.filesLoadedMap)
}
static create(payRequest, callback) {
//load files
let instance = new Widget(payRequest);
instance.createWidget();
if (callback) {
callback(instance);
}
}
createWidget() {
// create html
var self = this;
var html = '';
var isWalletsExist = false;
self.certificateOfCompletionDetails()
try {
var settings = JSON.parse(payomo.checkoutReplyJson);
if (self.payRequest.styleId && settings && settings.styleId) {
settings.styleId = self.payRequest.styleId;
}
try{
if(settings.enableWalletDomains && settings.enableWalletDomains.length > 0){
if(self.payRequest.applePay && self.payRequest.applePay.domainName){
if(settings.enableWalletDomains.includes(self.payRequest.applePay.domainName)){
isWalletsExist = true;
}
}else{
isWalletsExist = true;
}
}else{
isWalletsExist = true;
}
if(self.payRequest && self.payRequest.hideWalletsForCruise){
isWalletsExist = false;
}else{
isWalletsExist = true;
}
}catch(e){}
var finalAmount = this.payRequest.finalAmount;
var currencySymbol = '$';
try{
currencySymbol = new Intl.NumberFormat('en', {style: 'currency', currency:self.payRequest.currencyCode,}).formatToParts("1").find(part=>part.type="currency").value;
}catch(e){
}
let creditCard = new CreditCard(this.payRequest);
let billingInfo = new BillingInfo(this.payRequest);
if (settings && settings.styleId && settings.styleId == 'innerWidget') {
let mainDiv = 'Payment Method
';
let creditOption = 'Payment Information