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 = '
'; let paypalOption = ''; let applepayOption = ''; let gpayOption = ''; let venmoOption = ''; let optionsClose = '
'; let paymentInfo = '
'; let paymentMethodSelected = '

Payment Information

'; let successPaymentType = ''; let ccFormMain = creditCard.getElementHTML(); let billingFormMain = ''; if (this.payRequest.isBillingInfoRequired) { billingFormMain = billingInfo.getElementHTML(); } let endTags = '
'; if (this.payRequest.isBillingInfoRequired) { html = mainDiv + creditOption; if (settings.enableWallets && settings.enableWallets.length > 0 && isWalletsExist) { //paypal if (settings.enableWallets.indexOf("paypal") > -1) { html += paypalOption; } if (settings.enableWallets.indexOf("applePay") > -1) { html += applepayOption; } if (settings.enableWallets.indexOf("gpay") > -1) { html += gpayOption; } if (settings.enableWallets.indexOf("venmo") > -1) { html += venmoOption; } } html += optionsClose + paymentInfo + paymentMethodSelected + successPaymentType + ccFormMain + billingFormMain + endTags; } else { html = mainDiv + creditOption; if (settings.enableWallets && settings.enableWallets.length > 0 && isWalletsExist) { //paypal if (settings.enableWallets.indexOf("paypal") > -1) { html += paypalOption; } if (settings.enableWallets.indexOf("applePay") > -1) { html += applepayOption; } if (settings.enableWallets.indexOf("gpay") > -1) { html += gpayOption; } if (settings.enableWallets.indexOf("venmo") > -1) { html += venmoOption; } } html += optionsClose + paymentInfo + paymentMethodSelected + successPaymentType + ccFormMain + endTags; } } //trip pro else { var className = settings.styleId == "horizontal" ? '' : 'widgetVerticle' let mainDiv = '
'; let payomoWidgetMain = ''; if (this.payRequest.isBillingInfoRequired && settings.styleId != 'clubWidget') { payomoWidgetMain = '
'; }else if (settings && settings.styleId && settings.styleId == 'clubWidget'){ payomoWidgetMain = '
'; }else { payomoWidgetMain = '
'; } let applyCoupon = ''; let price = '
' + '' + currencySymbol + parseFloat(finalAmount).toFixed(2) + '
'; let mainTabs = '
' + '
Confirm & Pay
'; let clearfix = '
'; let ccFormMain = ''; if (!this.payRequest.hideCreditCardDetails) { ccFormMain = creditCard.getElementHTML(); } let billingFormMain = ''; if (this.payRequest.isBillingInfoRequired) { billingFormMain = billingInfo.getElementHTML(); } let payWith = '
Or Pay With
'; if (this.payRequest.hideCreditCardDetails) { payWith = ''; } let otherPaymentMethods = '
'; let payWithPayPal = '
'; let payWithVenmo = '
'; let payWithApplePay = '
'; let payWithGooglePay = '
'; let otherPaymentMethodsClose = '
'; let paymentMethodSelected = '
'; let successPaymentType = ''; let elementId=this.payRequest.payElementId; let themeClr="#ff563c" if(this.payRequest !=null && this.payRequest.themeColor != null && this.payRequest.themeColor != ""){ themeClr=this.payRequest.themeColor } let payButton = '
' + ' Pay '+'' + '
'; if (this.payRequest.isBillingInfoRequired && settings.styleId != 'clubWidget') { html = mainDiv + payomoWidgetMain + applyCoupon + price + clearfix; //ccFormMain + billingFormMain; //Removed other payments //ccFormMain + billingFormMain + payButton + otherPaymentMethodsClose; //Removed other payments //ccFormMain + billingFormMain + payWith + otherPaymentMethods + payWithPayPal + payWithApplePay + payWithGooglePay + paymentMethodSelected + successPaymentType + divClose + payButton + otherPaymentMethodsClose; if (settings.enableWallets && settings.enableWallets.length > 0 && isWalletsExist) { //paypal html += otherPaymentMethods; if (settings.enableWallets.indexOf("paypal") > -1) { html += payWithPayPal; } if (settings.enableWallets.indexOf("applePay") > -1) { html += payWithApplePay; } if (settings.enableWallets.indexOf("gpay") > -1) { html += payWithGooglePay; } html += paymentMethodSelected + successPaymentType + divClose; html += payWith + ccFormMain + billingFormMain; html += payButton + otherPaymentMethodsClose; }else{ html += ccFormMain + billingFormMain; html += payButton + otherPaymentMethodsClose; } }else if (settings && settings.styleId && settings.styleId == 'clubWidget'){ html = mainDiv + payomoWidgetMain + applyCoupon + clearfix; //ccFormMain + billingFormMain; //ccFormMain + billingFormMain + paymentMethodSelected + payButton + otherPaymentMethodsClose; //ccFormMain + billingFormMain + payWith + otherPaymentMethods + payWithPayPal + payWithApplePay + payWithGooglePay + paymentMethodSelected + successPaymentType + divClose + otherPaymentMethodsClose; if (settings.enableWallets && settings.enableWallets.length > 0 && isWalletsExist) { //paypal html += otherPaymentMethods; if (settings.enableWallets.indexOf("paypal") > -1) { html += payWithPayPal; } if (settings.enableWallets.indexOf("applePay") > -1) { html += payWithApplePay; } if (settings.enableWallets.indexOf("gpay") > -1) { html += payWithGooglePay; } html += paymentMethodSelected + successPaymentType + divClose; html += payWith + ccFormMain + billingFormMain; html += otherPaymentMethodsClose; }else{ html += ccFormMain + billingFormMain; html += otherPaymentMethodsClose; } } //trip pro horizontal else { html = self.getHTMLForTripproHorizontal(creditCard,settings); } } $("#" + self.payRequest.selector).html(html); //bind on blur event to credit card number creditCard.bindEventsToCreditCradFields(); if (settings && settings.styleId && settings.styleId == 'widgetVerticle') { creditCard.selectCardType(); } if (this.payRequest.isBillingInfoRequired) { billingInfo.bindEventsToBillingInfoFields(); } if (settings && settings.styleId && settings.styleId == 'innerWidget') { self.loadCCClickEvent(); } if (settings.enableWallets && settings.enableWallets.length > 0 && isWalletsExist) { //paypal if (settings.enableWallets.indexOf("paypal") > -1) { $("#payPalDivMain").show(); let environment = 'production'; if (self.payRequest.paypalEnvironment) { environment = self.payRequest.paypalEnvironment; } let paypalRequest = { selector: '#payPalDiv', finalAmount: self.payRequest.finalAmount, countryCode: self.payRequest.countryCode, currencyCode: self.payRequest.currencyCode, paypalEnvironment: environment, styleId:self.payRequest.styleId }; let ccFormMain = PayPal.create(paypalRequest); } //venmo if (settings.enableWallets.indexOf("venmo") > -1) { $("#venmoDivMain").show(); let venmoRequest = { selector: '#venmoDiv', finalAmount: self.payRequest.finalAmount, countryCode: self.payRequest.countryCode, currencyCode: self.payRequest.currencyCode, styleId:self.payRequest.styleId }; Venmo.create(venmoRequest); } //apple pay if (settings.enableWallets.indexOf("applePay") > -1) { // $("#applePayDivMain").show(); //apple pay var applePayObj = { selector: "applePayDiv", finalAmount: self.payRequest.finalAmount, countryCode: self.payRequest.countryCode, currencyCode: self.payRequest.currencyCode, styleId:self.payRequest.styleId, } if(self.payRequest.applePay && self.payRequest.applePay.domainName){ applePayObj.domainName=self.payRequest.applePay.domainName; } let applePay = ApplePay.create(applePayObj); } if (settings.enableWallets.indexOf("gpay") > -1) { $("#googlePayDivMain").show(); let gPayEnvironment = 'production'; if (self.payRequest.googlePayEnvironment) { gPayEnvironment = self.payRequest.googlePayEnvironment; } var googlePayObj = { selector: "googlePayDiv", finalAmount: self.payRequest.finalAmount, countryCode: self.payRequest.countryCode, currencyCode: self.payRequest.currencyCode, googlePayEnvironment: gPayEnvironment, styleId:self.payRequest.styleId } let googlePay = GooglePay.create(googlePayObj); } } //call i18n api var languageCode ="en-US"; if(self.payRequest!= null && self.payRequest.i18n != null && self.payRequest.i18n.url != null && self.payRequest.i18n.lang != null){ self.languageCode =self.payRequest.i18n.lang; this.setI18ndata(self.languageCode,self.payRequest.i18n.url); } } catch (e) { console.log(e); } } getHTMLForTripproHorizontal(creditCardObj,settings) { let mainDiv = '
'; let mainDivClose = '
'; let payomoWidgetMain = '
'; let payomoWidgetMainClose = '
'; let applyCoupon = ''; let clearfix = '
'; let ccFormMain = creditCardObj.getElementHTML(); let payWith = '
Or Pay With
'; if(settings.enableWallets && settings.enableWallets.length == 0){ payWith = ''; } let otherPaymentMethods = '
' let otherPaymentMethodsClose = '
'; let paypalOption = ''; let applepayOption = ''; let gpayOption = ''; let venmoOption = ''; let optionsClose = '
'; let paymentMethodSelected = '
'; let successPaymentType = ''; let html = mainDiv + payomoWidgetMain + applyCoupon + clearfix + ccFormMain + payWith + otherPaymentMethods + paypalOption + applepayOption + gpayOption + venmoOption + otherPaymentMethodsClose + optionsClose + paymentMethodSelected + successPaymentType + payomoWidgetMainClose + mainDivClose; return html; } setPayResponse(paymentTypeObj, payload) { $("#payPalDiv,#venmoDiv,#applePayDiv,#googlePayDiv").removeClass("selected"); var self = this; //console.log("payload=" + self.getEncryptedtext(JSON.stringify(payload))); //reset values for (var key in Widget.payResponse) { Widget.payResponse[key] = ""; } let paymentType = paymentTypeObj.paymentType; Widget.payResponse.selectedPaymentMethod = paymentType; if (paymentType == 'PAYPAL') { Widget.payResponse.paymentToken = payload.nonce; if (payload.details) { Widget.payResponse.email = payload.details.email; Widget.payResponse.firstName = payload.details.firstName; Widget.payResponse.lastName = payload.details.lastName; Widget.payResponse.phoneNumber = payload.details.phone; /*if(payload.details.billingAddress){ Widget.payResponse['street1']=payload.details.billingAddress.line1; Widget.payResponse['city']=payload.details.billingAddress.city; Widget.payResponse['state']=payload.details.billingAddress.state; Widget.payResponse['countryCode']=payload.details.billingAddress.countryCode; Widget.payResponse['zipCode']=payload.details.billingAddress.postalCode.substring(0,5); }*/ } $("#" + paymentTypeObj.containerId).addClass("selected"); self.setPaymentSuccessDetails(paymentType, payload); } else if (paymentType == 'GOOGLE_PAY') { let token = payload.paymentMethodData.tokenizationData.token; Widget.payResponse.paymentToken = btoa(token); Widget.payResponse.cardNumber = payload.paymentMethodData.info.cardDetails; Widget.payResponse.cardType = payload.paymentMethodData.info.cardNetwork; Widget.payResponse.selectedPaymentMethod = self.paymentType; $("#" + paymentTypeObj.containerId).addClass("selected"); self.setPaymentSuccessDetails(paymentType, payload); } else if (paymentType == 'APPLE_PAY') { Widget.payResponse.cardNumber = payload.cardNumber; Widget.payResponse.cardType = payload.cardType; Widget.payResponse.tokenizedCardNumber = payload.applicationPrimaryAccountNumber; if (payload.applicationExpirationDate) { let year = payload.applicationExpirationDate.substring(0, 2); let month = payload.applicationExpirationDate.substring(2, 4); var date = new Date(); var fullYear = date.getFullYear().toString(); year = fullYear.substring(0, 2) + year; Widget.payResponse.tokenizedExpiryDate = month + "/" + year; } if (payload.paymentData) { Widget.payResponse.cryptogram = payload.paymentData.onlinePaymentCryptogram; Widget.payResponse.securityCode = payload.paymentData.eciIndicator; } Widget.payResponse.selectedPaymentMethod = self.paymentType; $("#" + paymentTypeObj.containerId).addClass("selected"); self.setPaymentSuccessDetails(paymentType, payload); } else if (paymentType == 'CREDIT_CARD') { } console.log("payload=" + JSON.stringify(Widget.payResponse)); } setPaymentSuccessDetails(paymentType, payload) { var self = this; if (paymentType == 'PAYPAL' && payload && payload.details) { $(".pmRadio").removeClass("active"); $("#payPalDivMain").addClass("active"); $("#payment-success-div-image").attr("src", "https://images.trippro.com/payomo/widget/PayPal.svg"); $("#payment-success-div-name").text(payload.details.firstName + ' ' + payload.details.lastName); $("#payment-success-div-email").text(payload.details.email); $(".pmCCformMain").hide(); $("#successPaymentDiv").show(); if ($("#verticleCreditCard").length > 0 && self.payRequest && (self.payRequest.styleId=="widgetVerticle" || self.payRequest.styleId=="clubWidget")) { $("#verticleCreditCard").hide(); if ($("#divBilingInfo").length > 0) { $("#divBilingInfo").hide(); } if ($("#divCardPopulation").length > 0) { $("#divCardPopulation").hide(); } if ($("#divPayWith").length > 0) { $("#divPayWith").hide(); } } } else if (paymentType == 'GOOGLE_PAY' && payload) { $(".pmRadio").removeClass("active"); $("#googlePayDivMain").addClass("active"); $("#payment-success-div-image").attr("src", "https://images.trippro.com/payomo/widget/google-pay-logo.svg"); $("#payment-success-div-name").text((payload.paymentMethodData && payload.paymentMethodData.info) ? payload.paymentMethodData.info.cardNetwork : ""); $("#payment-success-div-email").text("XXXXXXXXXXXX" + ((payload.paymentMethodData && payload.paymentMethodData.info) ? payload.paymentMethodData.info.cardDetails : "")); $(".pmCCformMain").hide(); $("#successPaymentDiv").show(); if ($("#verticleCreditCard").length > 0 && self.payRequest && (self.payRequest.styleId=="widgetVerticle" || self.payRequest.styleId=="clubWidget")) { $("#verticleCreditCard").hide(); if ($("#divBilingInfo").length > 0) { $("#divBilingInfo").hide(); } if ($("#divCardPopulation").length > 0) { $("#divCardPopulation").hide(); } if ($("#divPayWith").length > 0) { $("#divPayWith").hide(); } } } else if (paymentType == 'APPLE_PAY' && payload) { $(".pmRadio").removeClass("active"); $("#applePayDivMain").addClass("active"); $("#payment-success-div-image").attr("src", "https://images.trippro.com/payomo/widget/apple-pay-logo.svg"); $("#payment-success-div-name").text(payload.cardType); $("#payment-success-div-email").text("XXXXXXXXXXXX" + payload.cardNumber); $(".pmCCformMain").hide(); $("#successPaymentDiv").show(); if ($("#verticleCreditCard").length > 0 && self.payRequest && (self.payRequest.styleId=="widgetVerticle" || self.payRequest.styleId=="clubWidget")) { $("#verticleCreditCard").hide(); if ($("#divBilingInfo").length > 0) { $("#divBilingInfo").hide(); } if ($("#divCardPopulation").length > 0) { $("#divCardPopulation").hide(); } if ($("#divPayWith").length > 0) { $("#divPayWith").hide(); } } } $("#successPaymentDiv").click(function () { if(self.payRequest && (self.payRequest.styleId=="widgetVerticle" || self.payRequest.styleId=="clubWidget")){ $("#successPaymentDiv").hide(); Widget.payResponse.selectedPaymentMethod = null; if ($("#verticleCreditCard").length > 0) { $("#verticleCreditCard").show(); } if ($("#divBilingInfo").length > 0) { $("#divBilingInfo").show(); } if ($("#divCardPopulation").length > 0) { $("#divCardPopulation").show(); } if ($("#divPayWith").length > 0) { $("#divPayWith").show(); } } }); } loadCCClickEvent() { $("#creditCardDivMain").click(function () { $("#successPaymentDiv").hide(); $(".pmRadio").removeClass("active"); $("#creditCardDivMain").addClass("active"); $(".pmCCformMain").show(); Widget.payResponse.selectedPaymentMethod = null; }); } //deviceDataCollection iframe deviceDataCollection(){ var div = document.createElement("div"); div.innerHTML ='
\n'+ '\n'+ '
\n'+ '\n'+ '
\n'+ '
' document.body.appendChild(div); } //step-up iframe steupIframe(){ var div = document.createElement("div"); div.innerHTML ='
\n'+ '\n'+ '
' document.body.appendChild(div); /*var addedElt = document.getElementById("close-addpr"); addedElt.addEventListener("click", function(){ document.getElementById("travelerOverlayBGMain").style.display = 'none'; window.location.reload(); });*/ var iframe1 = document.getElementById('step-up-iframe'); //this is check the return URL loaded into iframe or not,, if loaded then return reload iframe1.addEventListener("load", function(){ var url = document.location.href; var href = iframe1.contentWindow.location.href; console.log("href: ", href); if (href.indexOf("stepUpReturnUrl") > -1) { window.parent.postMessage("reload", "*"); } }); } //braintree hosted-fields div braintreeHostedFields(){ var div = document.createElement("div"); div.innerHTML ='' document.body.appendChild(div); var brainTreesubmitButton = document.getElementById("brainTreesubmitButton"); } certificateOfCompletionDetails(){ //completed on const d = new Date(); let currentDateTime = d.toUTCString(); let themeClr="#ff563c" if(this.payRequest != null && this.payRequest.themeColor != null && this.payRequest.themeColor != ""){ themeClr=this.payRequest.themeColor } var div = document.createElement("div"); div.setAttribute("id","templateModal"); div.setAttribute("class","ctemplateModal"); div.innerHTML ='\n'+ '
' document.body.appendChild(div); var certificateOfCompletionButton = document.getElementById("certificateOfCompletionButton"); } generateUUID() { // Public Domain/MIT var d = new Date().getTime();//Timestamp var d2 = ((typeof performance !== 'undefined') && performance.now && (performance.now()*1000)) || 0;//Time in microseconds since page-load or 0 if unsupported return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) { var r = Math.random() * 16;//random number between 0 and 16 if(d > 0){//Use timestamp until depleted r = (d + r)%16 | 0; d = Math.floor(d/16); } else {//Use microseconds since page-load if supported r = (d2 + r)%16 | 0; d2 = Math.floor(d2/16); } return (c === 'x' ? r : (r & 0x3 | 0x8)).toString(16); }); } } /* * ApplePay */ class ApplePay extends Widget{ constructor(payRequest, payResponse) { super() this.payRequest=payRequest; this.paymentType="APPLE_PAY" this.containerId="applePayDiv"; } static create(payObj,callback) { let instance=new ApplePay(payObj) instance._createElement(); if(callback){ callback(instance); } } _createElement() { var self = this; if (window.ApplePaySession && ApplePaySession.canMakePayments()) { var ele = document.getElementById(this.payRequest.selector); console.log(" Apple pay available.....") var applePayHTML = '' + '
' + //'Buy with' + '' + '
' $("#applePayDivMain").show(); ele.innerHTML = applePayHTML; self.applePayEle = document.getElementById(this.payRequest.selector); self.applePayEle.style.display = 'block'; console.log(self.applePayEle.style.display); self.applePayEle.addEventListener("click", function (e) { self._startApplePaySession(); }); SmartScript.auditObject.performAudit("APPLE_PAY_ELEMENT_SETUP", {}, {}, self.getDecryptedtext(self.payomoAccountId), self.getDecryptedtext(self.sessionId)); } else { document.getElementById(this.containerId).style.display='none'; console.log("Apple pay not available...") } } _applePaymentUpdate(event) { var self = this; event["accountId"]=self.getDecryptedtext(self.payomoAccountId); if(self.payRequest.domainName){ event["domainName"]=self.payRequest.domainName; } $.ajax({ url: self.getDecryptedtext(self.payomoServer) + "/api/v1/wallet/applePay/payment", method: "POST", contentType: "application/json; charset=utf-8", dataType: "json", data: JSON.stringify(event) }).then(function (payload) { // Complete validation by passing the merchant session to the Apple Pay session. if(event.token && event.token.paymentMethod && event.token.paymentMethod.displayName){ let displayName=event.token.paymentMethod.displayName; let displayNameArr=displayName.split(" "); payload["cardNumber"]=displayNameArr[1]; payload["cardType"] =displayNameArr[0] } self.setPayResponse(self,payload); }); } _startApplePaySession() { var self = this; console.log("_startApplePaySession started"); var request = { "countryCode": self.payRequest.countryCode, "currencyCode": self.payRequest.currencyCode, "merchantCapabilities": [ "supports3DS" ], "supportedNetworks": [ "visa", "masterCard", "amex", "discover" ], "total": { "label": "", "type": "final", "amount": self.payRequest.finalAmount } }; SmartScript.auditObject.performAudit("APPLE_PAY_SETUP", request, {}, self.getDecryptedtext(self.payomoAccountId), self.getDecryptedtext(self.sessionId)); var session = new ApplePaySession(1, request); window.session = session; session.onpaymentauthorized = function (event) { console.log("Validate payment authorized Callback"); console.log(event); session.completePayment(ApplePaySession.STATUS_SUCCESS); SmartScript.auditObject.performAudit("APPLE_PAY_PAYMANT_INFO_COLLECTED", {}, event.payment, self.getDecryptedtext(self.payomoAccountId), self.getDecryptedtext(self.sessionId)); self._applePaymentUpdate(event.payment); } session.onpaymentmethodselected = function (event) { console.log(" apple pay - onpaymentmethodselected ") // make sure we use new items if it exists var update = { newTotal: request["total"] }; session.completePaymentMethodSelection(update); console.log(' after - completePaymentMethodSelection') console.log(event); } session.onshippingmethodselected = function (event) { console.log(" apple pay - onshippingmethodselected ") console.log(event); } session.onshippingcontactselected = function (event) { console.log(" apple pay - onshippingcontactselected "); console.log(event); } session.oncancel = function (event) { console.log(" Apple oncancel"); console.log(event); }; session.onvalidatemerchant = function (event) { const validationURL = event.validationURL; var data = { validationUrl: event.validationURL, accountId: self.getDecryptedtext(self.payomoAccountId), sessionId: self.getDecryptedtext(self.payomoAccountId)// need to create }; if(self.payRequest.domainName){ data["domainName"]=self.payRequest.domainName; } console.log("Validate Marchent Callback -- " + validationURL +" "+ payomo.payomoServer); $.ajax({ url: self.getDecryptedtext(payomo.payomoServer) + "/api/v1/wallet/applePay/createSession", method: "POST", contentType: "application/json; charset=utf-8", // "application/json; charset=utf-8", dataType: "json", data: JSON.stringify(data) // headers: headers }).then(function (merchantSession) { // Complete validation by passing the merchant session to the Apple Pay session. console.log(" -- Marchant Session -- " + merchantSession); console.log(session); var jsonMarchangSession = merchantSession; // JSON.parse(merchantSession); session.completeMerchantValidation(jsonMarchangSession); console.log(" -- completeMerchantValidation with Session -- "); }); console.log(event); } session.begin(); } } /* * GooglePay */ class GooglePay extends Widget { constructor(payRequest, payResponse) { super() this.payRequest=payRequest; this.paymentType="GOOGLE_PAY"; this.containerId="googlePayDiv"; GooglePay.baseRequest={ apiVersion: 2, apiVersionMinor: 0 }; GooglePay.allowedCardNetworks = ["AMEX", "DISCOVER", "INTERAC", "JCB", "MASTERCARD", "VISA"]; GooglePay.allowedCardAuthMethods = ["PAN_ONLY", "CRYPTOGRAM_3DS"]; GooglePay.tokenizationSpecification = { type: 'PAYMENT_GATEWAY', parameters: { 'gateway': this.getDecryptedtext(payomo.gateway).toLowerCase(), 'gatewayMerchantId': this.getDecryptedtext(payomo.gpayGatewayMerchantId) } }; GooglePay.baseCardPaymentMethod = { type: 'CARD', parameters: { allowedAuthMethods: GooglePay.allowedCardAuthMethods, allowedCardNetworks: GooglePay.allowedCardNetworks } }; GooglePay.cardPaymentMethod = Object.assign({}, GooglePay.baseCardPaymentMethod, { tokenizationSpecification: GooglePay.tokenizationSpecification } ); GooglePay.paymentsClient = null; } _getGoogleIsReadyToPayRequest() { return Object.assign({}, GooglePay.baseRequest, { allowedPaymentMethods: [GooglePay.baseCardPaymentMethod] } ); } _getGooglePaymentDataRequest() { var self = this; const paymentDataRequest = Object.assign({}, GooglePay.baseRequest); paymentDataRequest.allowedPaymentMethods = [GooglePay.cardPaymentMethod]; paymentDataRequest.transactionInfo = self._getGoogleTransactionInfo(); paymentDataRequest.merchantInfo = { merchantId:self.getDecryptedtext(self.gPayMerchantId), merchantName: 'Example Merchant' }; return paymentDataRequest; } _getGooglePaymentsClient() { var self = this; var environment='PRODUCTION'//'PRODUCTION'//'TEST' if(self.payRequest && self.payRequest.googlePayEnvironment && self.payRequest.googlePayEnvironment==='sandbox'){ environment='TEST'; } console.log("Google pay environment="+environment); if (GooglePay.paymentsClient === null) { GooglePay.paymentsClient = new google.payments.api.PaymentsClient({ environment:environment }); } return GooglePay.paymentsClient; } _onGooglePayLoaded() { var self = this; const paymentsClient = self._getGooglePaymentsClient(); paymentsClient.isReadyToPay(self._getGoogleIsReadyToPayRequest()) .then(function (response) { if (response.result) { self._addGooglePayButton(); } }) .catch(function (err) { // show error in developer console for debugging console.log(err); }); } _addGooglePayButton () { var self = this; const paymentsClient = self._getGooglePaymentsClient(); const button = paymentsClient.createButton({ onClick: function (event) { event.preventDefault(); self._onGooglePaymentButtonClicked(self) }, buttonColor : 'white', buttonType : 'short' }); //button.innerHTML = button.innerHTML.replace("black","white"); document.getElementById(this.payRequest.selector).appendChild(button); } _getGoogleTransactionInfo() { var self=this; var amount = self.payRequest.finalAmount; return { countryCode: self.payRequest.countryCode, currencyCode: self.payRequest.currencyCode, totalPriceStatus: 'FINAL', // set to cart total totalPrice: amount + '' }; } _onGooglePaymentButtonClicked(googlePayObj) { var self = this; const paymentDataRequest = googlePayObj._getGooglePaymentDataRequest(); paymentDataRequest.transactionInfo = googlePayObj._getGoogleTransactionInfo(); const paymentsClient = googlePayObj._getGooglePaymentsClient(); paymentsClient.loadPaymentData(paymentDataRequest) .then(function (payload) { // handle the response self.setPayResponse(self,payload); //self._setPayResponse(token); //self._setSelectedPaymentType(self.paymentType); }) .catch(function (err) { // show error in developer console for debugging console.error(err); }); } static create(payRequest,callback) { let googlePayObj=new GooglePay(payRequest); googlePayObj._onGooglePayLoaded(); if(callback){ callback(googlePayObj); } } submitPayment (callback) { callback(this.payResponse); } getPaymentResponse () { return this.payResponse; } } /* * PayPal */ class PayPal extends Widget{ constructor(payRequest, payResponse) { super(payRequest) this.paymentType="PAYPAL"; this.containerId="payPalDiv"; } _addBraintreeDropin(){ var s = document.createElement('script'); s.type = 'text/javascript'; //s.async = true; s.src = "https://js.braintreegateway.com/web/dropin/1.22.1/js/dropin.min.js"; var x = document.getElementsByTagName('script')[0]; x.parentNode.insertBefore(s, x); console.log("added Braintree Dropin successfully"); } static create(payRequest) { var self=new PayPal(payRequest); var environment='production'; var authKey=self.getDecryptedtext(self.braintreeProductionAuthKey); if(self.payRequest.paypalEnvironment && self.payRequest.paypalEnvironment==='sandbox'){ environment=self.payRequest.paypalEnvironment; authKey=self.getDecryptedtext(self.braintreeSandBoxAuthKey); } braintree.client.create({ authorization:authKey }).then(function (clientInstance) { // Create a PayPal Checkout component. return braintree.paypalCheckout.create({ client: clientInstance }); }).then(function (paypalCheckoutInstance) { // Set up PayPal with the checkout.js library console.log("paypal environment="+environment); paypal.Button.render({ env:environment, // Or 'sandbox' 'production' commit: true, // This will add the transaction amount to the PayPal button style: { size: 'responsive', color: 'white', shape: 'rect', label: 'paypal', tagline: 'false', height : 40 }, payment: function () { return paypalCheckoutInstance.createPayment({ flow: 'vault', // Required amount: self.payRequest.finalAmount, // Required currency: self.payRequest.currencyCode// Required }); }, onAuthorize: function (data, actions) { console.log("data="+JSON.stringify(data)); return paypalCheckoutInstance.tokenizePayment(data) .then(function (payload) { // Submit `payload.nonce` to your server self.setPayResponse(self,payload); }); }, onCancel: function (data) { console.log('checkout.js payment cancelled', JSON.stringify(data, 0, 2)); }, onError: function (err) { console.error('checkout.js error', err); } }, self.payRequest.selector); }).then(function () { console.log("paypal button created"); }).catch(function (err) { console.log("Exception while creating paypal button ="+err); });} } /* * Venmo */ class Venmo extends Widget{ constructor(payRequest, payResponse) { super(payRequest) this.paymentType="VENMO"; this.containerId="venmoDiv"; } static create(payRequest) { var self=new Venmo(payRequest); var venmoButton = document.getElementById(self.containerId); // Create a client. braintree.client.create({ authorization:"production_v2dzkt2m_yr9w369mv92mbg3c"//"sandbox_tv8rz5k8_m77f6k54g7wpqz9f" //"production_v2dzkt2m_yr9w369mv92mbg3c" }).then(function (clientInstance) { // You may need to polyfill Promise // if used on older browsers that // do not natively support it. return Promise.all([ braintree.dataCollector.create({ client: clientInstance, paypal: true }), braintree.venmo.create({ client: clientInstance, // Add allowNewBrowserTab: false if your checkout page does not support // relaunching in a new tab when returning from the Venmo app. This can // be omitted otherwise. // allowNewBrowserTab: false }) ]); }).then(function (results) { var dataCollectorInstance = results[0]; var venmoInstance = results[1]; // At this point, you should access the deviceData value and provide it // to your server, e.g. by injecting it into your form as a hidden input. console.log('Got device data:', dataCollectorInstance.deviceData); // Verify browser support before proceeding. if (!venmoInstance.isBrowserSupported()) { console.log('Browser does not support Venmo'); return; } displayVenmoButton(venmoInstance); // Check if tokenization results already exist. This occurs when your // checkout page is relaunched in a new tab. This step can be omitted // if allowNewBrowserTab is false. if (venmoInstance.hasTokenizationResult()) { venmoInstance.tokenize().then(handleVenmoSuccess).catch(handleVenmoError); } }); function displayVenmoButton(venmoInstance) { // Assumes that venmoButton is initially display: none. venmoButton.style.display = 'block'; venmoButton.addEventListener('click', function () { venmoButton.disabled = true; venmoInstance.tokenize().then(handleVenmoSuccess).catch(handleVenmoError).then(function () { venmoButton.removeAttribute('disabled'); }); }); } function handleVenmoError(err) { if (err.code === 'VENMO_CANCELED') { console.log('App is not available or user aborted payment flow'); } else if (err.code === 'VENMO_APP_CANCELED') { console.log('User canceled payment flow'); } else { console.error('An error occurred:', err.message); } } function handleVenmoSuccess(payload) { // Send the payment method nonce to your server, e.g. by injecting // it into your form as a hidden input. //console.log('Got a payment method nonce:', payload.nonce); // Display the Venmo username in your checkout UI. console.log('Venmo user:', payload.details.username); // Submit `payload.nonce` to your server console.log("payload.nonce="+payload.nonce); Widget.payResponse.paymentToken=payload.nonce; Widget.payResponse.selectedPaymentMethod=self.paymentType; $("#"+self.containerId).addClass("selected"); } } } /* * credit card */ class CreditCard extends Widget{ constructor(payRequest) { super(payRequest) this.paymentType="CREDIT_CARD"; CreditCard.CARD_TYPES=[ { id : "VI", name : "VISA", start : 4, length : 16, prefixes : "4" }, { id : "CA", name : "MASTERCARD", start : 5, length : 16, prefixes : "51,52,53,54,55,56,57,58" }, { id : "AX", name : "AMERICAN EXPRESS", start : 3, length : 15, prefixes : "34,35,36,37" }, { id : "DS", name : "DISCOVER", start : "6", length : 16, prefixes : "6011,650" }, { id : "MI", name : "MISC", start : 0, length : 16 } ], CreditCard.ExpiryMonths = [ 'MM', 'JAN(01)', 'FEB(02)', 'MAR(03)', 'APR(04)', 'MAY(05)', 'JUN(06)', 'JUL(07)', 'AUG(08)', 'SEP(09)', 'OCT(10)', 'NOV(11)', 'DEC(12)' ]; } static create(payRequest,callback) { //credit card HTML let instance=new CreditCard(payRequest) let ccFormMain =instance._getElementHTML(); document.querySelector('#cardDiv').innerHTML= ccFormMain; callback(); return ccFormMain; } //select allowedCardTypes selectCardType(){ if(this.allowedCardTypes.length >=1){ if(this.allowedCardTypes.includes('VI')){ document.getElementById("checkboxVI").checked= true; } if(this.allowedCardTypes.includes('CA')){ document.getElementById("checkboxCA").checked= true; } if(this.allowedCardTypes.includes('AX')){ document.getElementById("checkboxAX").checked= true; } if(this.allowedCardTypes.includes('DS')){ document.getElementById("checkboxDS").checked= true; } } else { document.getElementById("allowedCardTypes").style.display = 'none'; } } bindEventsToCreditCradFields(){ var self=this; $("#widget-card-number").blur(function(){ $("#widget-card-number").removeClass("border-red"); var cardNumber=document.getElementById("widget-card-number").value; if(!cardNumber.includes('XXXX')){ self.validateCardNumber(cardNumber); } return self.validateAllowedCards(); }); $("#widget-expiry-month,#widget-expiry-year").change(function(){ $("#widget-expiry-month").removeClass("border-red"); $("#widget-expiry-year").removeClass("border-red"); let expiryMonth = document.getElementById("widget-expiry-month").value; let expiryYear = document.getElementById("widget-expiry-year").value; document.getElementById("widget-expiry-month-error").style.display='none'; document.getElementById("widget-expiry-year-error").style.display='none'; document.getElementById("widget-expiry-date-error").style.display='none'; if(expiryMonth == "0" && expiryYear == "0"){ $("#widget-expiry-month").removeClass("border-red"); $("#widget-expiry-year").removeClass("border-red"); document.getElementById("widget-expiry-date-error").style.display='block'; return false; } if(expiryMonth == "0"){ $("#widget-expiry-month").addClass("border-red"); document.getElementById("widget-expiry-month-error").style.display='block'; //$("#widget-expiry-date-error").text("Please select card expiry month"); return false; }else if(expiryYear == "0"){ $("#widget-expiry-year").addClass("border-red"); document.getElementById("widget-expiry-year-error").style.display='block'; //$("#widget-expiry-date-error").text("Please select card expiry year"); return false; } if(expiryMonth.length == 1){ expiryMonth = "0"+expiryMonth; } let expiryDate = expiryMonth+'/'+expiryYear; self.validateExpiryDate(expiryDate); }); $("#widget-cvv").blur(function(){ $("#widget-cvv").removeClass("border-red"); var cvv=document.getElementById("widget-cvv").value; self.validateCardCVV(cvv); }); $("#widget-card-holder").blur(function(){ $("#widget-card-holder").removeClass("border-red"); if(self.validateCardHolderName()){ $("#widget-card-holder-error").hide(); }else{ //$("#widget-card-holder-error").text("Please enter a valid card holder name. It must be atleast 3 letters long"); $("#widget-card-holder").addClass("border-red"); $("#widget-card-holder-error").show(); if($("#bilingErrorInfo").length > 0){ $("#bilingErrorInfo").hide(); } return false; } }); //validation when property change $("#widget-card-number").bind('input propertychange', function (e){ var cardNumber=document.getElementById("widget-card-number").value; if(self.validateCardNumber(cardNumber)){ $("#widget-card-number").removeClass("border-red"); $("#widget-card-number-invalid-error").hide(); }else{ $("#widget-card-number").addClass("border-red"); $("#widget-card-number-invalid-error").show(); return false; } }); $("#widget-card-holder").bind('input propertychange', function (e){ if(self.validateCardHolderName()){ $("#widget-card-holder").removeClass("border-red"); $("#widget-card-holder-error").hide(); }else{ $("#widget-card-holder").addClass("border-red"); $("#widget-card-holder-error").show(); return false; } }); $("#widget-card-number").bind('input propertychange', function (e){ var cardNumber=document.getElementById("widget-card-number").value; if(self.validateCardNumber(cardNumber)){ $("#widget-card-number").removeClass("border-red"); $("#widget-card-number-invalid-error").hide(); }else{ $("#widget-card-number").addClass("border-red"); $("#widget-card-number-invalid-error").show(); return false; } }); $("#widget-cvv").bind('input propertychange', function (e){ if(self.validateCardCVV()){ $("#idget-cvv").removeClass("border-red"); $("#widget-cvv-error").hide(); }else{ $("#idget-cvv").addClass("border-red"); $("#widget-cvv-error").show(); return false; } }); $("#widget-card-holder").on('keyup touchend', function(){ $(this).val(function (index, value) { return value.replace(/\W\s\b/gi, '').replace(/[^a-z^A-Z\s\b]+/g, ''); }); }); $("#widget-card-number").on('keyup touchend', function(){ const key = event.key; if (key === "Backspace" || key === "Delete") { return; } $(this).val(function (index, value) { // var start = this.selectionStart, // end = this.selectionEnd; this.value = value.replace(/\W/gi, '').replace(/\D/gi, '').replace(/(.{4})/g, '$1-').substring(0, 19); // if(start == 5 || start == 10 || start == 15){ // end = document.getElementById("widget-card-number").value.length; // this.setSelectionRange(end, end); // $("#widget-card-number").addClass("border-red"); // document.getElementById("widget-card-number").focus(); // }else{ // $("#widget-card-number").addClass("border-red"); // this.setSelectionRange(start, end); // document.getElementById("widget-card-number").focus(); // } return this.value; }); var ccnum=document.getElementById("widget-card-number").value; if (ccnum.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 (ccnum.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 (ccnum.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 (ccnum.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'); } let count = ccnum.split('-').length-1; if (ccnum == null || ccnum == '') { $("#widget-card-number").prop('maxLength', 22); } if (ccnum.includes('-')) { ccnum = ccnum.split('--').join('-'); if (ccnum && ccnum.charAt(0) === '3') { $("#widget-card-number").prop('maxLength', 15+count); } else { $("#widget-card-number").prop('maxLength', 16+count); } }else if (ccnum.includes(' ')) { ccnum = ccnum.split(' ').join(' '); count = ccnum.split(' ').length-1; if (ccnum && ccnum.charAt(0) === '3') { $("#widget-card-number").prop('maxLength', 15+count); } else { $("#widget-card-number").prop('maxLength', 16+count); } }else { if (ccnum && ccnum.charAt(0) === '3') { $("#widget-card-number").prop('maxLength', 15+count); } else { if(count == 0){ if (ccnum == null || ccnum == '') { $("#widget-card-number").prop('maxLength', 22); }else{ $("#widget-card-number").prop('maxLength', 16); } }else{ $("#widget-card-number").prop('maxLength', 16+count); } } } }); $("#widget-card-population").change(function(){ var cardNumber = $('#widget-card-population').val(); self.populateCardInformation(cardNumber); }); } //values print according to cardType validateAllowedCards(){ var ccnum=document.getElementById("widget-card-number").value; if((ccnum != null || cardNumber != '') && document.getElementById("checkboxVI")!= null) { var chkVI= document.getElementById("checkboxVI").checked; var chkCA= document.getElementById("checkboxCA").checked; var chkAX= document.getElementById("checkboxAX").checked; var chkDS= document.getElementById("checkboxDS").checked; var cardTypeStatus= true; $("#widget-card-number-invalid-error").text("Please enter a valid card number"); var arr=[ {CARDTYPE : "VI", "ACTIVE" : chkVI, "STARTWITH" : "4"}, {CARDTYPE : "CA", "ACTIVE" : chkCA, "STARTWITH" : "5"}, {CARDTYPE : "AX", "ACTIVE" : chkAX, "STARTWITH" : "3"}, {CARDTYPE : "DS", "ACTIVE" : chkDS, "STARTWITH" : "6"} ]; let validCard = arr.find(c=> c.ACTIVE && ccnum.startsWith(c.STARTWITH)); if(validCard){ cardTypeStatus= false; } else{ cardTypeStatus= true; } if(chkVI && chkCA && chkAX && chkDS){ cardTypeStatus= false; } if(!chkVI && !chkCA && !chkAX && !chkDS){ cardTypeStatus= false; } if(cardTypeStatus){ $("#widget-card-number").addClass("border-red"); $("#widget-card-number-invalid-error").text("Enter only allowed card").show(); return true; } else{ $("#widget-card-number").removeClass("border-red"); $("#widget-card-number-invalid-error").hide(); this.validateCardNumber(ccnum); return false; } } else{ return true; } } populateCardInformation(cardNumber){ let cardProfile = JSON.parse(this.getDecryptedtext(this.cardProfile)); let cardsList = cardProfile.creditCards; if(cardNumber == "0"){ $('#widget-card-number').val(''); $('#widget-card-holder').val(''); $('#widget-cvv').val(''); $('#widget-billingInfo-address1').val(''); $('#widget-billingInfo-city').val(''); $('#widget-billingInfo-zipcode').val(''); $('#widget-contactInfo-email').val(''); $('#widget-contactInfo-confirmEmail').val(''); $('#widget-contactInfo-phone1').val('1'); $('#widget-contactInfo-phone2').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; } try{ for (var key in cardsList) { if(this.getDecryptedtext(cardsList[key].cardNumber) == cardNumber){ var actualCC = this.getDecryptedtext(cardsList[key].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-holder').val(this.getDecryptedtext(cardsList[key].cardHolderName)); $('#widget-cvv').val(''); //not populating for security reasons document.getElementById("widget-expiry-month").selectedIndex = this.getDecryptedtext(cardsList[key].expiryDate).substring(0,2); var currentYear = new Date().getFullYear(); var yearValue = currentYear.toString().substring(0,2)+this.getDecryptedtext(cardsList[key].expiryDate).substring(2,4); var ind = $("#widget-expiry-year option[value="+ yearValue+"]").index(); document.getElementById("widget-expiry-year").selectedIndex = ind.toString(); $('#widget-billingInfo-address1').val(this.getDecryptedtext(cardsList[key].street1)); ind = $("#widget-billingInfo-country option[code="+ this.getDecryptedtext(cardsList[key].countryCode)+"]").index(); document.getElementById("widget-billingInfo-country").selectedIndex = ind.toString(); var billingObj = new BillingInfo(); billingObj.appendCountryStateList($('#widget-billingInfo-country').val()); setTimeout(function() { ind = $("#widget-billingInfo-state option[code="+ this.getDecryptedtext(cardsList[key].state)+"]").index(); document.getElementById("widget-billingInfo-state").selectedIndex = ind.toString(); }, 2000);//Wait for 2secs to load the states of the selected country $('#widget-billingInfo-city').val(this.getDecryptedtext(cardsList[key].city)); $('#widget-billingInfo-zipcode').val(this.getDecryptedtext(cardsList[key].zipCode)); $('#widget-contactInfo-email').val(this.getDecryptedtext(cardsList[key].email)); $('#widget-contactInfo-confirmEmail').val(this.getDecryptedtext(cardsList[key].email)); $('#widget-contactInfo-phone2').val(this.getDecryptedtext(cardsList[key].phoneNumber)); break; } } }catch (e) { var json={"eventName":"credit_card_image_exception","eventCategory":"credit_card_image_exception","message":"credit card image exception","data":e}; SmartScript.auditObject.sendDataToElk(json); } } addCreditCardInfoToPayResponse(){ var cardNumber=document.getElementById("widget-card-number").value; if(cardNumber.includes('XXXX')){ cardNumber=document.getElementById("actualcc").value; } var cardHolderName=document.getElementById("widget-card-holder").value; var settings = JSON.parse(payomo.checkoutReplyJson); var expiryDate=''; if(settings.styleId == 'innerWidget') { let expiryMonth = document.getElementById("widget-expiry-month").value; let expiryYear = document.getElementById("widget-expiry-year").value; expiryDate = expiryMonth+'/'+expiryYear; } else { //expiryDate = document.getElementById("widget-expiry-date").value; let expiryMonth = document.getElementById("widget-expiry-month").value; let expiryYear = document.getElementById("widget-expiry-year").value; if(expiryMonth.length == 1){ expiryMonth = "0"+expiryMonth; } expiryDate = expiryMonth+'/'+expiryYear; } var cvv=document.getElementById("widget-cvv").value; Widget.payResponse['cardNumber']=cardNumber; Widget.payResponse['cardHolderName']=cardHolderName; Widget.payResponse['expiryDate']=expiryDate; Widget.payResponse['cvv']=cvv; Widget.payResponse['cardType']=this.getCardType(cardNumber); Widget.payResponse.selectedPaymentMethod=this.paymentType; } isCreditCardDetailsValid(){ let isValid=false; let isValidCard=true; let isCardAllowed= false; var settings = JSON.parse(payomo.checkoutReplyJson); //check all the card filed entered or not //let cardNumber=document.getElementById(CreditCard.fieldIdMap.get("cardNumber")).value; var cardNumber=document.getElementById("widget-card-number").value; var cardHolderName=document.getElementById("widget-card-holder").value; if(!cardNumber.includes('XXXX')){ // skipping validation for masking card if(!this.validateCardNumber(cardNumber)){ //$('#widget-card-number').focus(); $("#widget-card-number").addClass("border-red"); isValidCard=false; } }else{ $("#widget-card-number").removeClass("border-red"); document.getElementById("widget-card-number-invalid-error").style.display='none'; } //check allowed valid cards if(settings.styleId === 'widgetVerticle' && this.allowedCardTypes.length >=1) { if(this.validateAllowedCards()){ // if error then -> return true isCardAllowed=false; }else{ isCardAllowed=true; } } // var expiryDate=document.getElementById("widget-expiry-date").value; var cardType = this.getCardType(cardNumber); var expiryDate=''; let expiryMonth = ''; let expiryYear = ''; if(settings.styleId == 'innerWidget') { expiryMonth = document.getElementById("widget-expiry-month").value; expiryYear = document.getElementById("widget-expiry-year").value; $("#widget-expiry-month").removeClass("border-red"); $("#widget-expiry-year").removeClass("border-red"); if(expiryMonth == "0" || expiryYear == "0"){ $("#widget-expiry-month").addClass("border-red"); $("#widget-expiry-year").addClass("border-red"); isValid=false; }else{ $("#widget-expiry-month").removeClass("border-red"); $("#widget-expiry-year").removeClass("border-red"); if(expiryMonth.length == 1){ expiryMonth = "0"+expiryMonth; } expiryDate = expiryMonth+'/'+expiryYear; isValid = this.validateExpiryDate(expiryDate); } } else { //expiryDate = document.getElementById("widget-expiry-date").value; expiryMonth = document.getElementById("widget-expiry-month").value; expiryYear = document.getElementById("widget-expiry-year").value; $("#widget-expiry-month").removeClass("border-red"); $("#widget-expiry-year").removeClass("border-red"); if(expiryMonth == "0" || expiryYear == "0"){ isValid=false; $("#widget-expiry-month").addClass("border-red"); $("#widget-expiry-year").addClass("border-red"); }else{ $("#widget-expiry-month").removeClass("border-red"); $("#widget-expiry-year").removeClass("border-red"); if(expiryMonth.length == 1){ expiryMonth = "0"+expiryMonth; } expiryDate = expiryMonth+'/'+expiryYear; isValid = this.validateExpiryDate(expiryDate); } } var cvv=document.getElementById("widget-cvv").value; if(!cardNumber && settings.styleId == 'innerWidget' && document.getElementById("widget-credit-error")) { $("#widget-credit-error").show(); isValidCard=false; }else{ let invalidCreditCardErrorEle=$("#widget-credit-error"); if(invalidCreditCardErrorEle){ invalidCreditCardErrorEle.hide(); } } if(!cardHolderName && document.getElementById("widget-card-holder-error")){ document.getElementById("widget-card-holder-error").style.display='block'; $("#widget-card-holder").addClass("border-red"); isValidCard=false; }else{ $("#widget-card-holder").removeClass("border-red"); if(this.validateCardHolderName()){ $("#widget-card-holder-error").hide(); }else{ $("#widget-card-holder").addClass("border-red"); //$("#widget-card-holder-error").text("Please enter a valid card holder name. It must be atleast 3 letters long"); $("#widget-card-holder-error").show(); if($("#bilingErrorInfo").length > 0){ $("#bilingErrorInfo").hide(); } return false; } } if(!cardHolderName && settings.styleId == 'innerWidget' && document.getElementById("widget-credit-error")) { $("#widget-credit-error").show(); isValidCard=false; }else{ $("#widget-credit-error").hide(); } if(!isValid && document.getElementById("widget-expiry-date-error")){ $("#widget-expiry-month").removeClass("border-red"); $("#widget-expiry-year").removeClass("border-red"); document.getElementById("widget-expiry-date-error").style.display='block'; document.getElementById("widget-expiry-month-error").style.display='none'; document.getElementById("widget-expiry-year-error").style.display='none'; $("#widget-expiry-date-error").show(); if(expiryMonth == "0" && expiryYear == "0"){ // $("#widget-expiry-date-error").text("Please select card expiry month and year"); document.getElementById("widget-expiry-date-error").style.display='block'; $("#widget-expiry-month").removeClass("border-red"); $("#widget-expiry-year").removeClass("border-red"); }else if(expiryMonth == "0"){ // $("#widget-expiry-date-error").text("Please select card expiry month"); document.getElementById("widget-expiry-month-error").style.display='block'; $("#widget-expiry-month").addClass("border-red"); }else if(expiryYear == "0"){ // $("#widget-expiry-date-error").text("Please select card expiry year"); document.getElementById("widget-expiry-year-error").style.display='block'; $("#widget-expiry-year").addClass("border-red"); } }else{ $("#widget-expiry-month").removeClass("border-red"); $("#widget-expiry-year").removeClass("border-red"); document.getElementById("widget-expiry-date-error").style.display='none'; document.getElementById("widget-expiry-month-error").style.display='none'; document.getElementById("widget-expiry-year-error").style.display='none'; } if(!expiryDate && settings.styleId == 'innerWidget' && document.getElementById("widget-credit-error")) { $("#widget-credit-error").show(); isValidCard=false; }else{ $("#widget-credit-error").hide(); } if(!cvv && document.getElementById("widget-cvv-error")){ $("#widget-cvv").addClass("border-red"); document.getElementById("widget-cvv-error").style.display='block'; isValidCard=false; }else{ $("#widget-cvv").removeClass("border-red"); document.getElementById("widget-cvv-error").style.display='none'; if(cardType == 'AX'){ if((/^\d{4}$/).test(cvv)){ if(cvv === "0000"){//all zeroes not allowed document.getElementById("widget-cvv-error").style.display='block'; $("#widget-cvv-error").show(); $("#widget-cvv").addClass("border-red"); isValidCard=false; } }else{ document.getElementById("widget-cvv-error").style.display='block'; $("#widget-cvv-error").show(); $("#widget-cvv").addClass("border-red"); isValidCard=false; } }else{ if((/^\d{3}$/).test(cvv)){ if(cvv === "000"){//all zeroes not allowed document.getElementById("widget-cvv-error").style.display='block'; $("#widget-cvv-error").show(); $("#widget-cvv").addClass("border-red"); isValidCard=false; } }else{ document.getElementById("widget-cvv-error").style.display='block'; $("#widget-cvv-error").show(); $("#widget-cvv").addClass("border-red"); isValidCard=false; } } } if(!cvv && settings.styleId == 'innerWidget' && document.getElementById("widget-credit-error")) { $("#widget-credit-error").show(); isValidCard=false; }else{ $("#widget-credit-error").hide(); } if(!cardNumber || !cardHolderName || !expiryDate || !cvv || !isValid || !isValidCard || (!isCardAllowed && this.allowedCardTypes.length >=1)){ return false; } return true; } getCardType(cardNumber){ if(cardNumber.length>0){ let masterCardPrefixes=[51,52,53,54,55,56,57,58]; let discoverPrefixes=[60,65]; let amexPrefixes=[34,35,36,37]; if(cardNumber.startsWith("4")){ return 'VI'; } if(cardNumber.length>2){ let prefix=cardNumber.substring(0, 2); if(masterCardPrefixes.indexOf(parseInt(prefix))!=-1 && cardNumber.length==16){ return 'CA'; } if((discoverPrefixes.indexOf(parseInt(prefix))!=-1 && cardNumber.length==15) || (discoverPrefixes.indexOf(parseInt(prefix))!=-1 && cardNumber.length==16)){ return 'DS'; } if((amexPrefixes.indexOf(parseInt(prefix))!=-1 && cardNumber.length==15)||(amexPrefixes.indexOf(parseInt(prefix))!=-1 && cardNumber.length==16)||(amexPrefixes.indexOf(parseInt(prefix))!=-1 && cardNumber.length==14)){ return 'AX'; } } if(cardNumber.startsWith("3")){ return 'AX'; } if(cardNumber.startsWith("6")){ return 'DS'; } if(cardNumber.startsWith("5")){ return 'CA'; } return 'MI'; } } splitCardNumber(){ var self=this; var cardNumber=document.getElementById("widget-card-number").value; if (cardNumber == null || cardNumber == '') { $("#widget-card-number").prop('maxLength', 22); } if(cardNumber.includes(' ')){ cardNumber = cardNumber.split(' ').join('').trim(); $("#widget-card-number").prop('maxLength', 16); } if(cardNumber.includes('-')){ cardNumber = cardNumber.split('-').join('').trim(); $("#widget-card-number").prop('maxLength', 16); } let cardNum = ''; let cNum = cardNumber.split('-').join(''); if (cNum) { for (var i = 0; i < cNum.length; i++) { cardNum += cNum.charAt(i); if (cardNum.length == 4 || cardNum.length == 9 || cardNum.length == 14) { cardNum += '-'; } } let count = cardNum.split('-').length-1; if (cardNum && cardNum.charAt(0) === '3') { $("#widget-card-number").prop('maxLength', 15+count); } else { $("#widget-card-number").prop('maxLength', 16+count); } } self.validateCardNumber(cNum); document.getElementById("widget-card-number").value = cardNum; }; validateCardNumber(ccNum){ ccNum = ccNum.split('-').join(''); var settings = JSON.parse(payomo.checkoutReplyJson); var pattern = new RegExp("^[0-9-\b]+$"); $("#widget-card-number").removeClass("border-red"); if(typeof ccNum == 'undefined'){ $("#widget-card-number").addClass("border-red"); return false; } if (!pattern.test(ccNum)){ $("#widget-card-number").addClass("border-red"); document.getElementById("widget-card-number-invalid-error").style.display='block'; return false; } var nCheck = 0, nDigit = 0, bEven = false; ccNum = ccNum.replace(/\D/g, ""); for (var n = ccNum.length - 1; n >= 0; n--) { var cDigit = ccNum.charAt(n), nDigit = parseInt(cDigit, 10); if (bEven) { if ((nDigit *= 2) > 9) nDigit -= 9; } nCheck += nDigit; bEven = !bEven; } let isValid = (nCheck % 10) == 0; if(!isValid && ccNum.startsWith("60") && ccNum.length == 15){ isValid = true; } var cardType = this.getCardType(ccNum); var cardnoReg = ''; /*if(isValid && cardType=='VI'){ cardnoReg = /^(?:4[0-9]{12}(?:[0-9]{3})?)$/; if(!ccNum.match(cardno)){ isValid = false; } }else if(isValid && cardType=='CA'){ cardnoReg = /^(?:5[1-5][0-9]{14})$/; if(!ccNum.match(cardno)){ isValid = false; } }else if(isValid && cardType=='AX'){ cardnoReg = /^(?:3[47][0-9]{13})$/; if(!ccNum.match(cardno)){ isValid = false; } }*/ if(isValid && cardType=='MI'){ isValid = false; } if(isValid && cardType=='DS'){ cardnoReg = /^(?:6(?:011|5[0-9][0-9])[0-9]{12})$/; if(!ccNum.match(cardnoReg)){ isValid = false; } } if(isValid && cardType=='AX' && (ccNum.length < 15 || ccNum.length > 15)){ isValid = false; }/*else if(isValid && cardType=='DS' && (ccNum.length <= 14 || ccNum.length > 16)){ isValid = false; }*/else if(isValid && (cardType=='CA'||cardType=='VI'||cardType=='DS') && (ccNum.length < 16 || ccNum.length > 16)){ isValid = false; }else if(!isValid){ $("#widget-card-number").addClass("border-red"); document.getElementById("widget-card-number-invalid-error").style.display='block'; return false; } if(isValid && document.getElementById("widget-card-number-invalid-error")){ document.getElementById("widget-card-number-invalid-error").style.display='none'; /*let errorEle=document.getElementById("widget-card-number-error"); if(errorEle){ errorEle.style.display='none'; }*/ }else if(document.getElementById("widget-card-number-invalid-error")) { document.getElementById("widget-card-number-invalid-error").style.display='block'; } if(isValid && settings.styleId == 'innerWidget' && document.getElementById("widget-credit-error")) { $("#widget-credit-error").text("").hide(); } else { $("#widget-credit-error").show(); if($("#bilingErrorInfo").length > 0){ $("#bilingErrorInfo").hide(); } } return isValid; } onlyNumberKey(evt) { var iKeyCode = (evt.which) ? evt.which : evt.keyCode; if (iKeyCode != 46 && iKeyCode > 31 && (iKeyCode < 48 || iKeyCode > 57)) return false; return true; } onlyCCVNumberKey(evt) { var cvv = document.getElementById("widget-cvv"); var style = window.getComputedStyle(cvv); if (style.webkitTextSecurity) { // Do nothing } else { cvv.setAttribute("type", "password"); } var iKeyCode = (evt.which) ? evt.which : evt.keyCode; if (iKeyCode != 46 && iKeyCode > 31 && (iKeyCode < 48 || iKeyCode > 57)) return false; return true; } onlyAlphaNumericWithSpaceBackspace(evt) { var regex = new RegExp("^[a-zA-Z\b\\s0-9]+$"); var key = String.fromCharCode(!event.charCode ? event.which : event.charCode); if (!regex.test(key)) { event.preventDefault(); return false; } return true; } onlyAlphaNumericWithSomeKeys(evt) { var regex = new RegExp("^[a-zA-Z0-9\b\\s_,-.\u{0023}]+$"); var key = String.fromCharCode(!event.charCode ? event.which : event.charCode); if (!regex.test(key)) { event.preventDefault(); return false; } } onlyAlphabetsWithSomeKeys(evt) { var regex = new RegExp("^[a-zA-Z\b\\s_,-]+$"); var key = String.fromCharCode(!event.charCode ? event.which : event.charCode); if (!regex.test(key)) { event.preventDefault(); return false; } } onlyAlphabetsWithSpaceBackspace(evt) { var regex = new RegExp("^[a-zA-Z\b\\s]+$"); var key = String.fromCharCode(!event.charCode ? event.which : event.charCode); if (!regex.test(key)) { event.preventDefault(); return false; } } validateCardHolderName(){ try{ var cardHolderName=document.getElementById("widget-card-holder").value; $("#widget-card-holder").removeClass("border-red"); if(cardHolderName.length < 3 || cardHolderName.trim().length == 0){ $("#widget-card-holder").addClass("border-red"); return false; } var pattern = new RegExp("^[a-zA-Z\b\\s]+$"); if (pattern.test(cardHolderName)){ $("#widget-card-holder").removeClass("border-red"); return true; }else{ $("#widget-card-holder").addClass("border-red"); return false; } }catch (e) { } } validateCardCVV(){ try{ var cardNumber=document.getElementById("widget-card-number").value; var cvv=document.getElementById("widget-cvv").value; $("#widget-cvv").removeClass("border-red"); var cardType = this.getCardType(cardNumber); document.getElementById("widget-cvv-error").style.display='none'; if(cardType && cardType == 'AX' && cvv && cvv.length > 0){ if((/^\d{4}$/).test(cvv)){ if(cvv === "0000"){//all zeroes not allowed document.getElementById("widget-cvv-error").style.display='block'; $("#widget-cvv").addClass("border-red"); $("#widget-cvv-error").show(); return false; } return true; }else{ document.getElementById("widget-cvv-error").style.display='block'; $("#widget-cvv").addClass("border-red"); $("#widget-cvv-error").show(); return false; } return true; }else{ if((/^\d{3}$/).test(cvv)){ if(cvv === "000"){//all zeroes not allowed document.getElementById("widget-cvv-error").style.display='block'; $("#widget-cvv").addClass("border-red"); $("#widget-cvv-error").show(); return false; } return true; }else{ if(cvv!=null && cvv.trim().length == 0){ document.getElementById("widget-cvv-error").style.display='block'; $("#widget-cvv").addClass("border-red"); $("#widget-cvv-error").show(); return false; }else{ document.getElementById("widget-cvv-error").style.display='block'; $("#widget-cvv").addClass("border-red"); $("#widget-cvv-error").show(); return false; } return true; } } }catch (e) { } } validateExpiryDate(expiryDate){ let isValid=false; try{ var pattern = /(0|1)[0-9]\/(19|20)[0-9]{2}/; if (pattern.test(expiryDate)) { var date_array = expiryDate.split('/'); var month = date_array[0] - 1; var year = date_array[1]; var source_date = new Date(); if (year > source_date.getFullYear()) { isValid=true; } else if(year == source_date.getFullYear()){ if (month >= source_date.getMonth()) { isValid=true; } } } if(isValid){ document.getElementById("widget-expiry-date-error").style.display='none'; return true; }else{ if(!isValid && document.getElementById("widget-expiry-date-error")){ $("#widget-expiry-month").removeClass("border-red"); $("#widget-expiry-year").removeClass("border-red"); let expiryMonth = document.getElementById("widget-expiry-month").value; let expiryYear = document.getElementById("widget-expiry-year").value; document.getElementById("widget-expiry-date-error").style.display='block'; document.getElementById("widget-expiry-month-error").style.display='none'; document.getElementById("widget-expiry-year-error").style.display='none'; $("#widget-expiry-date-error").show(); if(expiryMonth == "0" && expiryYear == "0"){ // $("#widget-expiry-date-error").text("Please select card expiry month and year"); $("#widget-expiry-month").addClass("border-red"); $("#widget-expiry-year").addClass("border-red"); document.getElementById("widget-expiry-date-error").style.display='block'; }else if(expiryMonth == "0"){ // $("#widget-expiry-date-error").text("Please select card expiry month"); document.getElementById("widget-expiry-month-error").style.display='block'; $("#widget-expiry-month").addClass("border-red"); }else if(expiryYear == "0"){ // $("#widget-expiry-date-error").text("Please select card expiry year"); document.getElementById("widget-expiry-year-error").style.display='block'; $("#widget-expiry-year").addClass("border-red"); } }else{ $("#widget-expiry-month").removeClass("border-red"); $("#widget-expiry-year").removeClass("border-red"); document.getElementById("widget-expiry-date-error").style.display='none'; document.getElementById("widget-expiry-month-error").style.display='none'; document.getElementById("widget-expiry-year-error").style.display='none'; } return false; } }catch (e) { } } getElementHTML(payRequest){ let instance=this; let cardPopulationHTML= ''; var settings = JSON.parse(payomo.checkoutReplyJson); if (this.payRequest && this.payRequest.styleId=="widgetVerticle") { cardPopulationHTML=instance._getCardPopulationHTML(settings); settings.styleId = 'widgetVerticle'; } if (this.payRequest && this.payRequest.styleId=="clubWidget") { settings.styleId = 'clubWidget'; } let cardNumberHTML=instance._getCardNumberHTML(settings); let cardHolderHTML=instance._getCardHolderHTML(settings); let expiryDateHTML=instance._getExpiryDateHTML(settings); let payButton=''; let ccvHTML=instance._getCCVHTML(settings); if(settings && settings.isPayButtonRequired && !this.payRequest.isBillingInfoRequired && !this.payRequest.hidePayElement) { payButton = instance._getPayButtonHTML(settings); } let ccFormMain = ''; if(settings.styleId == 'innerWidget') { payButton = ''; ccFormMain = '
'; ccFormMain += cardNumberHTML + cardHolderHTML +expiryDateHTML +ccvHTML +payButton + '
'; } else { ccFormMain += '
'; if (this.payRequest && this.payRequest.styleId=="widgetVerticle") { ccFormMain += cardPopulationHTML; } ccFormMain += '
Credit Card
' + '
' + '
'; ccFormMain += cardNumberHTML + cardHolderHTML +expiryDateHTML +ccvHTML +payButton + '
'; } return ccFormMain; } _getCardPopulationHTML(settings){ let returnHtml = ''; if (this.payRequest && this.payRequest.styleId=="widgetVerticle") { returnHtml = '
' +'
' returnHtml +='
'+ '
Visa
'+ '
Master Card
'+ '
Amex
'+ '
Discover
'+ '
'; } return returnHtml; } _getPayButtonHTML(settings){ let elementId=this.payRequest.payElementId; return '
' + ' Pay '+'' + '
'; } _getCCVHTML(settings){ if(settings && settings.styleId == 'innerWidget') { return '
' + '
' + '
'; } var className=""; if(!this.payRequest.hidePayElement){ className="halfBox"; } return '
' + '' +'

Why do we need this?

For your protection, we require that you enter a credit card verification number.

For Visa, MasterCard, Discover, Diners Club, and Carte Blanche:

The Verification number is the final 3-digit number located on the back of the credit card.

For American Express

The Verification number is the 4-digit number located on the front of the credit card.

' +'' +'
'; } _getExpiryDateHTML(settings){ let returnHtml = ''; if(settings && settings.styleId == 'innerWidget') { returnHtml = '
' + '
' return returnHtml; } var className=""; if(!this.payRequest.hidePayElement){ className="halfBox"; } returnHtml = '
' returnHtml += '' returnHtml += '
' return returnHtml; /*+'' +'
Please fill out Expiry Date
' +'
Please enter valid Expiry Date
' +'
';*/ } _getCardHolderHTML(settings){ if(settings && settings.styleId == 'innerWidget') { return '
' + '
' + '
'; } return '
' +'' +'' + '
'; } _getCardNumberHTML(settings){ if(settings && settings.styleId == 'innerWidget') { return '
' + '
' + '
'; } let samsclubImagesDiv = '
' + '' + '' + '' + '' + '' + '
' if(this.getDecryptedtext(this.payomoAccountId) == '2D5C96DD-F018-4119-9648-2FFD28FE2FE8'){ return '
'+ samsclubImagesDiv + '' + '' +'' +'
'; }else{ return '
' + '' + '' //+'' +'' +'
'; } } }/** * Billing Information */ class BillingInfo extends Widget{ constructor(payRequest) { super(payRequest) this.countryList=[], this.statesList=[] } static create(payRequest,callback) { //BillingInfo HTML let instance=new BillingInfo(payRequest) let billingFormMain =instance._getElementHTML(); document.querySelector('#cardDiv').innerHTML= billingFormMain; callback(); return ccFormMain; } bindEventsToBillingInfoFields(){ var self=this; $("#widget-billingInfo-country").change(function(){ $("#widget-billingInfo-zipcode").removeClass("border-red"); var countryId = $('#widget-billingInfo-country').val(); self.appendCountryStateList(countryId); if(self.validateZipCode()){ $("#widget-billingInfo-zipcode-invalid-error").hide(); }else{ $("#widget-billingInfo-zipcode").addClass("border-red"); $("#widget-billingInfo-zipcode-invalid-error").show(); } }); $("#widget-billingInfo-country").change(function(){ var countryId = $('#widget-billingInfo-country').val(); if(countryId == 0){ $("#widget-billingInfo-country").addClass("border-red"); $("#widget-billingInfo-country-invalid-error").show(); isValidBillingInfo=false; } else{ $("#widget-billingInfo-country").removeClass("border-red"); self.appendCountryStateList(countryId); $("#widget-billingInfo-country-invalid-error").hide(); } }); $("#widget-billingInfo-state").change(function(){ var stateId = $('#widget-billingInfo-state').val(); if(stateId == 0){ $("#widget-billingInfo-state").addClass("border-red"); //$("#widget-billingInfo-state-invalid-error").text("Please select State"); $("#widget-billingInfo-state-invalid-error").show(); isValidBillingInfo=false; }else{ $("#widget-billingInfo-state").removeClass("border-red"); $("#widget-billingInfo-state-invalid-error").hide(); } }); //contact info $("#widget-contactInfo-phone1").bind('input propertychange', function (e){ $("#widget-contactInfo-phone1").removeClass("border-red"); if(self.validatePhone2()){ $("#widget-contactInfo-phone-invalid-error").hide(); }else{ $("#widget-contactInfo-phone1").addClass("border-red"); $("#widget-contactInfo-phone-invalid-error").show(); return false; } }); $("#widget-contactInfo-phone2").bind('input propertychange', function (e){ if(self.validatePhone2()){ $("#widget-contactInfo-phone2").removeClass("border-red"); $("#widget-contactInfo-phone-invalid-error").hide(); }else{ $("#widget-contactInfo-phone2").addClass("border-red"); $("#widget-contactInfo-phone-invalid-error").show(); return false; } }); $("#widget-contactInfo-email").bind('input propertychange', function (e){ $("#widget-contactInfo-email").removeClass("border-red"); if(self.validateEmail()){ $("#widget-contactInfo-email-invalid-error").hide(); }else{ $("#widget-contactInfo-email").addClass("border-red"); $("#widget-contactInfo-email-invalid-error").show(); return false; } }); $("#widget-contactInfo-confirmEmail").bind('input propertychange', function (e){ $("#widget-contactInfo-confirmEmail").removeClass("border-red"); if(self.validateConfirmEmail()){ $("#widget-contactInfo-confirmEmail-invalid-error").hide(); }else{ $("#widget-contactInfo-confirmEmail").addClass("border-red"); $("#widget-contactInfo-confirmEmail-invalid-error").show(); return false; } }); $("#widget-billingInfo-address1").bind('input propertychange', function (e){ if(self.validateBillingAddress()){ $("#widget-billingInfo-address1-invalid-error").hide(); $("#widget-billingInfo-address1").removeClass("border-red"); }else{ $("#widget-billingInfo-address1").addClass("border-red"); $("#widget-billingInfo-address1-invalid-error").show(); return false; } }); $("#widget-billingInfo-address2").bind('input propertychange', function (e){ if(self.validateBillingAddress2()){ $("#widget-billingInfo-address2").removeClass("border-red"); $("#widget-billingInfo-address2-invalid-error").hide(); }else{ $("#widget-billingInfo-address2").addClass("border-red"); $("#widget-billingInfo-address2-invalid-error").show(); return false; } }); $("#widget-billingInfo-city").bind('input propertychange', function (e){ if(self.validateBillingCity()){ $("#widget-billingInfo-city").removeClass("border-red"); $("#widget-billingInfo-city-invalid-error").hide(); }else{ $("#widget-billingInfo-city").addClass("border-red"); $("#widget-billingInfo-city-invalid-error").show(); return false; } }); $("#widget-billingInfo-zipcode").bind('input propertychange', function (e){ if(self.validateZipCode()){ $("#widget-billingInfo-zipcode").removeClass("border-red"); $("#widget-billingInfo-zipcode-invalid-error").hide(); }else{ $("#widget-billingInfo-zipcode").addClass("border-red"); $("#widget-billingInfo-zipcode-invalid-error").show(); return false; } }); $("#widget-billingInfo-address1").blur(function(){ if(self.validateBillingAddress()){ $("#widget-billingInfo-address1-invalid-error").hide(); $("#widget-billingInfo-address1").removeClass("border-red"); //$("#bilingErrorInfo").hide(); }else{ //$("#bilingErrorInfo").text("Please enter valid Address1"); $("#widget-billingInfo-address1").addClass("border-red"); $("#widget-billingInfo-address1-invalid-error").show(); //$("#bilingErrorInfo").show(); return false; } }); $("#widget-billingInfo-address2").blur(function(){ if(self.validateBillingAddress2()){ $("#widget-billingInfo-address2").removeClass("border-red"); $("#widget-billingInfo-address2-invalid-error").hide(); $("#bilingErrorInfo").hide(); }else{ //$("#bilingErrorInfo").text("Please enter valid Address2"); //$("#bilingErrorInfo").show(); $("#widget-billingInfo-address2").addClass("border-red"); $("#widget-billingInfo-address2-invalid-error").show(); return false; } }); $("#widget-billingInfo-city").blur(function(){ if(self.validateBillingCity()){ $("#widget-billingInfo-city").removeClass("border-red"); $("#widget-billingInfo-city-invalid-error").hide(); //$("#bilingErrorInfo").hide(); }else{ //$("#bilingErrorInfo").text("Please enter valid City"); //$("#bilingErrorInfo").show(); $("#widget-billingInfo-city").addClass("border-red"); $("#widget-billingInfo-city-invalid-error").show(); return false; } }); $("#widget-billingInfo-zipcode").blur(function(){ if(self.validateZipCode()){ $("#widget-billingInfo-zipcode").removeClass("border-red"); $("#widget-billingInfo-zipcode-invalid-error").hide(); //$("#bilingErrorInfo").hide(); }else{ //$("#bilingErrorInfo").text("Please enter valid ZipCode"); //$("#bilingErrorInfo").show(); $("#widget-billingInfo-zipcode").addClass("border-red"); $("#widget-billingInfo-zipcode-invalid-error").show(); return false; } }); } appendCountryStateList(countryId) { var self=this; try{ $.ajax({ url: self.getDecryptedtext(self.payomoServer) +"/api/v1/utility/stateCountry/list?countryId="+countryId, method : "GET", contentType : "application/json", dataType : "json", data : "" // headers: headers }).then(function(res) { //console.log("appendCountryStateList success= "+self.getEncryptedtext(res)); var returnHtml = ''; $("#widget-billingInfo-state").html(''); BillingInfo.statesList = res.countryState.results; if(window.i18Data !== undefined && window.i18Data !== null){ returnHtml += ''; }else{ returnHtml += ''; } for (var key in BillingInfo.statesList) { returnHtml += '' } $("#widget-billingInfo-state").html(returnHtml); }); }catch(e) { console.log(e); } } appendCountryList(countryId) { var self=this; try{ $.ajax({ url: self.getDecryptedtext(self.payomoServer) +"/api/v1/utility/stateCountry/list", method : "GET", contentType : "application/json", dataType : "json", data : "" // headers: headers }).then(function(res) { //console.log("appendCountryList success= "+self.getEncryptedtext(res)); BillingInfo.countryList = res.countryState.results; var html = "", topHtml = ''; $("#widget-billingInfo-country").html(''); if(window.i18Data !== undefined && window.i18Data !== null ){ topHtml += ''; }else{ topHtml += ''; } for (var key in BillingInfo.countryList) { if (BillingInfo.countryList[key].countryCode && BillingInfo.countryList[key].countryCode == "US") { topHtml += '' } else { html += '' } } $("#widget-billingInfo-country").html(topHtml+html); }); }catch(e) { console.log(e); } } getElementHTML(payRequest){ let instance=this; var settings = JSON.parse(payomo.checkoutReplyJson); let adress1HTML=instance._getAdress1HTML(settings); let adress2HTML=instance._getAdress2HTML(settings); let countryHTML=instance._getCountryHTML(settings); let stateHTML=instance._getStateHTML(settings); let cityHTML=instance._getCityHTML(settings); let zipCodeHTML=instance._getZipCodeHTML(settings); let phoneNumberHTML = instance._getContactPhoneNumber(settings); let emailHTML = instance._getContactEmail(settings); let confirmEmailHTML = instance._getContactConfirmEmail(settings); let termsandCondition=instance._getTermsCheckboxHTML(settings); instance.appendCountryList(null); instance.appendCountryStateList(231); let payButton=''; if(settings && settings.isPayButtonRequired && !this.payRequest.hidePayElement) { payButton = instance._getPayButtonHTML(settings); } if (this.payRequest && this.payRequest.styleId == "clubWidget") { settings.styleId = 'clubWidget'; } if (this.payRequest && this.payRequest.styleId=="widgetVerticle") { settings.styleId = 'widgetVerticle'; } let ccFormMain = ''; if(settings.styleId == 'innerWidget') { payButton = ''; ccFormMain = '
'; ccFormMain += adress1HTML + adress2HTML + countryHTML +stateHTML +cityHTML +zipCodeHTML +termsandCondition +payButton +'
'; } else { if(settings.styleId != 'clubWidget') { ccFormMain = '
' + '
'; ccFormMain += adress1HTML + adress2HTML + countryHTML +stateHTML +cityHTML +zipCodeHTML + '
'; }else{ ccFormMain = '

'; ccFormMain += adress1HTML + adress2HTML +zipCodeHTML +cityHTML +countryHTML +stateHTML+ '
'; //+stateHTML //+ countryHTML + '
'; } if(settings.styleId != 'clubWidget') { ccFormMain += '
' +phoneNumberHTML +emailHTML +confirmEmailHTML + termsandCondition + '
' + '
'; } //+ payButton; } return ccFormMain; } _getAdress1HTML(settings){ if(settings && settings.styleId == 'innerWidget') { } return '
' + '' + '' + '
'; } _getAdress2HTML(settings){ if(settings && settings.styleId == 'innerWidget') { } return '
' + '' + '' + '
'; } _getCountryHTML(settings){ let returnHtml = ''; if(settings && settings.styleId == 'innerWidget') { } returnHtml = '
' +'' + '' returnHtml += '
'; return returnHtml; } _getStateHTML(settings){ let returnHtml = ''; if(settings && settings.styleId == 'innerWidget') { } returnHtml = '
' +'' + '' +'
'; return returnHtml; } _getCityHTML(settings){ if(settings && settings.styleId == 'innerWidget') { } return '
' + '' + '' +'
'; } _getZipCodeHTML(settings){ if(settings && settings.styleId == 'innerWidget') { } return '
' + '' + '' +'
'; } _getContactPhoneNumber(settings){ if(settings && settings.styleId == 'innerWidget') { } return '
+' +'' + '' + '' +'
'; } _getContactEmail(settings){ if(settings && settings.styleId == 'innerWidget') { } return '
' +'' + '' +'
'; } _getContactConfirmEmail(settings){ if(settings && settings.styleId == 'innerWidget') { } return '
' +'' + '' +'
'; } _getTermsCheckboxHTML(settings){ if(settings && settings.styleId == 'innerWidget') { } return '
' +'' +' Please accept the Certificate of Completion ' +'' +'
'; } _getPayButtonHTML(settings){ let elementId=this.payRequest.payElementId; return '
' + ' Pay '+'' + '
'; } isBillingInfoValid(payRequest){ var self=this; let isValid=false; let isValidBillingInfo=true; var add1=document.getElementById("widget-billingInfo-address1").value; var add2=document.getElementById("widget-billingInfo-address2").value; var countryId=$('#widget-billingInfo-country').val(); var stateId=$('#widget-billingInfo-state').val(); var city=document.getElementById("widget-billingInfo-city").value; var zipCode=document.getElementById("widget-billingInfo-zipcode").value; if(document.querySelector('#widget-contactInfo-termsCondition')){ var self=this; var fname=document.getElementById("widget-contactInfo-fname").value; var lname=document.getElementById("widget-contactInfo-lname").value; var termsCondition=document.querySelector('#widget-contactInfo-termsCondition').checked; var termsCondition2=document.querySelector('#widget-contactInfo-termsCondition2').checked; console.log("document.querySelector('#widget-contactInfo-termsCondition2').checked", document.querySelector('#widget-contactInfo-termsCondition2').checked); if(termsCondition&& fname.trim().length != 0 && lname.trim().length != 0){ $("#widget-contactInfo-termsCondition-invalid-error").hide(); } else{ $("#widget-contactInfo-termsCondition-invalid-error").show(); isValidBillingInfo=false; } if ($("#checkbox1").css("display")=='none'){ $("#widget-contactInfo-termsCondition-invalid-error").show(); isValidBillingInfo=false; } else{ $("#widget-contactInfo-termsCondition-invalid-error").hide(); } if(self.isEmptyNullUndefined(fname)){ $("#widget-contactInfo-fname").addClass("border-red"); $("#widget-contactInfo-fname-invalid-error").show(); isValidBillingInfo=false; }else{ $("#widget-contactInfo-fname").removeClass("border-red"); isValid = self.validateFirstName(fname); if(isValid){ $("#widget-contactInfo-fname-invalid-error").hide(); }else{ $("#widget-contactInfo-fname").addClass("border-red"); $("#widget-contactInfo-fname-invalid-error").show(); isValidBillingInfo=false; } } if(self.isEmptyNullUndefined(lname)){ $("#widget-contactInfo-lname").addClass("border-red"); $("#widget-contactInfo-lname-invalid-error").show(); isValidBillingInfo=false; }else{ $("#widget-contactInfo-lname").removeClass("border-red"); isValid = self.validateLastName(lname); if(isValid){ $("#widget-contactInfo-lname-invalid-error").hide(); }else{ $("#widget-contactInfo-lname").addClass("border-red"); $("#widget-contactInfo-lname-invalid-error").show(); isValidBillingInfo=false; } } } if(self.isEmptyNullUndefined(add1)){ $("#widget-billingInfo-address1").addClass("border-red"); //$("#widget-billingInfo-address1-invalid-error").text("Please enter Address line 1"); $("#widget-billingInfo-address1-invalid-error").show(); isValidBillingInfo=false; }else{ $("#widget-billingInfo-address1").removeClass("border-red"); isValid = this.validateBillingAddress(add1); if(isValid){ $("#widget-billingInfo-address1-invalid-error").hide(); $("#widget-billingInfo-address1").removeClass("border-red"); }else{ $("#widget-billingInfo-address1").addClass("border-red"); //$("#widget-billingInfo-address1-invalid-error").text("Please enter a valid Address line 1"); $("#widget-billingInfo-address1-invalid-error").show(); isValidBillingInfo=false; } } if(!self.isEmptyNullUndefined(add2)){ isValid = this.validateBillingAddress2(add2); $("#widget-billingInfo-address2").removeClass("border-red"); if(isValid){ $("#widget-billingInfo-address2-invalid-error").hide(); }else{ $("#widget-billingInfo-address2").addClass("border-red"); //$("#widget-billingInfo-address2-invalid-error").text("Please enter a valid Address line 2"); $("#widget-billingInfo-address2-invalid-error").show(); isValidBillingInfo=false; } } if(countryId == 0){ $("#widget-billingInfo-country").addClass("border-red"); //$("#widget-billingInfo-country-invalid-error").text("Please select Country"); $("#widget-billingInfo-country-invalid-error").show(); isValidBillingInfo=false; }else{ $("#widget-billingInfo-country").removeClass("border-red"); $("#widget-billingInfo-country-invalid-error").hide(); } if(stateId == 0){ $("#widget-billingInfo-state").addClass("border-red"); //$("#widget-billingInfo-state-invalid-error").text("Please select State"); $("#widget-billingInfo-state-invalid-error").show(); isValidBillingInfo=false; }else{ $("#widget-billingInfo-state").removeClass("border-red"); $("#widget-billingInfo-state-invalid-error").hide(); } if(self.isEmptyNullUndefined(city)){ $("#widget-billingInfo-city").addClass("border-red"); //$("#widget-billingInfo-city-invalid-error").text("Please enter City"); $("#widget-billingInfo-city-invalid-error").show(); isValidBillingInfo=false; }else{ $("#widget-billingInfo-city").removeClass("border-red"); isValid = this.validateBillingCity(city); if(isValid){ $("#widget-billingInfo-city-invalid-error").hide(); }else{ $("#widget-billingInfo-city").addClass("border-red"); //$("#widget-billingInfo-city-invalid-error").text("Please enter a valid City"); $("#widget-billingInfo-city-invalid-error").show(); isValidBillingInfo=false; } } if(self.isEmptyNullUndefined(zipCode)){ $("#widget-billingInfo-zipcode").addClass("border-red"); //$("#widget-billingInfo-zipcode-invalid-error").text("Please enter Zipcode"); $("#widget-billingInfo-zipcode-invalid-error").show(); isValidBillingInfo=false; }else{ $("#widget-billingInfo-zipcode").removeClass("border-red"); isValid = this.validateZipCode(zipCode); if(isValid){ $("#widget-billingInfo-zipcode-invalid-error").hide(); }else{ $("#widget-billingInfo-zipcode").addClass("border-red"); //$("#widget-billingInfo-zipcode-invalid-error").text("Please enter a valid Zipcode"); $("#widget-billingInfo-zipcode-invalid-error").show(); isValidBillingInfo=false; } } if(payRequest && payRequest.styleId != 'clubWidget') { var email=document.getElementById("widget-contactInfo-email").value; var confirmEmail=document.getElementById("widget-contactInfo-confirmEmail").value; var phone1=document.getElementById("widget-contactInfo-phone1").value; var phone2 = document.getElementById("widget-contactInfo-phone2").value; $("#widget-contactInfo-phone1").removeClass("border-red"); if(self.isEmptyNullUndefined(phone1)){ $("#widget-contactInfo-phone1").addClass("border-red"); //$("#widget-contactInfo-phone-invalid-error").text("Please enter phone code"); $("#widget-contactInfo-phone-invalid-error").show(); isValidBillingInfo=false; }else{ $("#widget-contactInfo-phone1").removeClass("border-red"); $("#widget-contactInfo-phone-invalid-error").hide(); } $("#widget-contactInfo-phone2").removeClass("border-red"); if(self.isEmptyNullUndefined(phone2)){ $("#widget-contactInfo-phone2").addClass("border-red"); //$("#widget-contactInfo-phone-invalid-error").text("Please enter phone number"); $("#widget-contactInfo-phone-invalid-error").show(); isValidBillingInfo=false; }else{ var filter = /^\d{10}$/; $("#widget-contactInfo-phone2").removeClass("border-red"); if (!filter.test(phone2)) { $("#widget-contactInfo-phone2").addClass("border-red"); //$("#widget-contactInfo-phone-invalid-error").text("Please enter valid phone number"); $("#widget-contactInfo-phone-invalid-error").show(); isValidBillingInfo=false; }else{ $("#widget-contactInfo-phone2").removeClass("border-red"); $("#widget-contactInfo-phone-invalid-error").hide(); } } $("#widget-contactInfo-email").removeClass("border-red"); if(self.isEmptyNullUndefined(email)){ $("#widget-contactInfo-email").addClass("border-red"); //$("#widget-contactInfo-email-invalid-error").text("Please enter email"); $("#widget-contactInfo-email-invalid-error").show(); isValidBillingInfo=false; }else{ var filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/; if (!filter.test(email)) { //$("#widget-contactInfo-email-invalid-error").text("Please enter valid email"); $("#widget-contactInfo-email").addClass("border-red"); $("#widget-contactInfo-email-invalid-error").show(); isValidBillingInfo=false; }else{ $("#widget-contactInfo-email").removeClass("border-red"); $("#widget-contactInfo-email-invalid-error").hide(); } } $("#widget-contactInfo-confirmEmail").removeClass("border-red"); if(self.isEmptyNullUndefined(confirmEmail)){ $("#widget-contactInfo-confirmEmail").addClass("border-red"); //$("#widget-contactInfo-confirmEmail-invalid-error").text("Please enter confirm email"); $("#widget-contactInfo-confirmEmail-invalid-error").show(); isValidBillingInfo=false; }else{ try{ if(confirmEmail){ if(email == confirmEmail){ $("#widget-contactInfo-confirmEmail").removeClass("border-red"); $("#widget-contactInfo-confirmEmail-invalid-error").hide(); }else{ $("#widget-contactInfo-confirmEmail").addClass("border-red"); //$("#widget-contactInfo-confirmEmail-invalid-error").text("Confirmation email and email should be same"); $("#widget-contactInfo-confirmEmail-invalid-error").show(); isValidBillingInfo=false; } }else{ $("#widget-contactInfo-confirmEmail").addClass("border-red"); //$("#widget-contactInfo-confirmEmail-invalid-error").text("Please enter confirm email"); $("#widget-contactInfo-confirmEmail-invalid-error").show(); isValidBillingInfo=false; } }catch (e) { } } } $("#bilingErrorInfo").hide(); if(!isValidBillingInfo){ return false; } return true; } validateBillingAddress(){ var self=this; var address=document.getElementById('widget-billingInfo-address1').value; $("#widget-billingInfo-address1").removeClass("border-red"); if(address.trim().length == 0){ $("#widget-billingInfo-address1").addClass("border-red"); return false; } var pattern = new RegExp("^[a-zA-Z0-9,_-\\s\b\u{0023}]+$"); var afterRemoval = self.removeSpecials(address); if (pattern.test(afterRemoval)){ $("#widget-billingInfo-address1").removeClass("border-red"); $("#widget-billingInfo-address1-invalid-error").hide(); return true; }else{ $("#widget-billingInfo-address1").addClass("border-red"); return false; } } validateFirstName(){ var self=this; var fname=document.getElementById('widget-contactInfo-fname').value; if(fname.trim().length == 0){ return false; } var pattern = new RegExp("^[a-zA-Z0-9,_-\\s\b\u{0023}]+$"); var afterRemoval = self.removeSpecials(fname); if (pattern.test(afterRemoval)){ return true; }else{ return false; } } validateLastName(){ var self=this; var lname=document.getElementById('widget-contactInfo-lname').value; if(lname.trim().length == 0){ return false; } var pattern = new RegExp("^[a-zA-Z0-9,_-\\s\b\u{0023}]+$"); var afterRemoval = self.removeSpecials(lname); if (pattern.test(afterRemoval)){ return true; }else{ return false; } } validatePhone2(){ var self=this; var phone1=document.getElementById('widget-contactInfo-phone1').value; var phone2=document.getElementById('widget-contactInfo-phone2').value; $("#widget-contactInfo-phone1").removeClass("border-red"); $("#widget-contactInfo-phone2").removeClass("border-red"); if(phone1.trim().length == 0){ $("#widget-contactInfo-phone1").addClass("border-red"); return false; } if(phone2.trim().length == 0){ $("#widget-contactInfo-phone2").addClass("border-red"); return false; } var filter = /^\d{10}$/; if (!filter.test(phone2)) { $("#widget-contactInfo-phone2").addClass("border-red"); return false; }else{ $("#widget-contactInfo-phone2").removeClass("border-red"); return true; } } validateEmail(){ var self=this; var email=document.getElementById('widget-contactInfo-email').value; $("#widget-contactInfo-email").removeClass("border-red"); if(email.trim().length == 0){ $("#widget-contactInfo-email").addClass("border-red"); return false; } var filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/; if (!filter.test(email)) { $("#widget-contactInfo-email").addClass("border-red"); return false; }else{ $("#widget-contactInfo-email").removeClass("border-red"); return true; } } validateConfirmEmail(){ var self=this; var email=document.getElementById('widget-contactInfo-email').value; var confirmEmail=document.getElementById('widget-contactInfo-confirmEmail').value; $("#widget-contactInfo-confirmEmail").removeClass("border-red"); if(confirmEmail.trim().length == 0){ $("#widget-contactInfo-confirmEmail").addClass("border-red"); return false; } else{ var filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/; if (!filter.test(confirmEmail)) { $("#widget-contactInfo-confirmEmail").addClass("border-red"); return false; }else{ $("#widget-contactInfo-confirmEmail").removeClass("border-red"); return true; } } try{ if(email == confirmEmail){ $("#widget-contactInfo-confirmEmail").addClass("border-red"); return false; }else{ $("#widget-contactInfo-confirmEmail").removeClass("border-red"); return true; } }catch (e) { } } removeSpecials(str) { var afterRemoval = str.replace(/[&\/\\+()$~%.'":*?<>{}!=]/g,''); return afterRemoval; } validateBillingAddress2(){ var self=this; var address=document.getElementById('widget-billingInfo-address2').value; /*if(address.trim().length == 0){ return false; }*/ if(!self.isEmptyNullUndefined(address)){ var afterRemoval = self.removeSpecials(address); var pattern = new RegExp("^[a-zA-Z0-9,_-\\s\b\u{0023}]+$"); if (pattern.test(afterRemoval)){ return true; }else{ return false; } } return true; } validateBillingCity(address){ var self=this; var city=document.getElementById('widget-billingInfo-city').value; $("#widget-billingInfo-city").removeClass("border-red"); if(city.trim().length == 0){ $("#widget-billingInfo-city").addClass("border-red"); return false; } var pattern = new RegExp("^[a-zA-Z\\s\b]+$"); var afterRemoval = self.removeSpecials(city); if (pattern.test(afterRemoval)){ $("#widget-billingInfo-city").removeClass("border-red"); return true; }else{ $("#widget-billingInfo-city").addClass("border-red"); return false; } } validateZipCode(){ var self=this; var zipCode=document.getElementById("widget-billingInfo-zipcode").value; var afterRemoval = self.removeSpecials(zipCode); $("#widget-billingInfo-zipcode").removeClass("border-red"); if(afterRemoval.trim().length == 0){ $("#widget-billingInfo-zipcode").addClass("border-red"); return false; } //zipCode = zipCode.replace(/\D/g, ""); $('#widget-billingInfo-zipcode').val(afterRemoval); var pattern = new RegExp("^[0-9a-zA-Z\\s\b]+$"); if (pattern.test(afterRemoval)){ if(afterRemoval.length <= 3){ $("#widget-billingInfo-zipcode").addClass("border-red"); return false; } if($('#widget-billingInfo-country').val() != 0){ $("#widget-billingInfo-country").removeClass("border-red"); var countryCode = $('#widget-billingInfo-country').find(":selected").attr('code'); if(countryCode == "US"){ if(afterRemoval.length != 5){ $("#widget-billingInfo-country").addClass("border-red"); return false; } } if(countryCode == "CA"){ if(afterRemoval.length <= 5){ $("#widget-billingInfo-country").addClass("border-red"); return false; } } if(countryCode == "IN"){ if(afterRemoval.length != 6){ $("#widget-billingInfo-country").addClass("border-red"); return false; } } } return true; }else{ return false; } } isEmptyNullUndefined(value) { var self = this; if (self.isNull(value) || self.isEmpty(value) || self.isUndefined(value)) { return true; } else { return false; } } isNull(value) { if (null == value || 'null' == value || 'null' == $.trim(value)) { return true; } else { return false; } } isEmpty(value) { if (value.length == 0) { return true; } else { return false; } } isUndefined(value) { if ('undefined' == value) { return true; } else { return false; } } addBillingInfoToPayResponse(payRequest){ var self = this; var add1=document.getElementById("widget-billingInfo-address1").value; var add2=document.getElementById("widget-billingInfo-address2").value; var countryCode=$('#widget-billingInfo-country').find(':selected').attr('code'); var stateCode=$('#widget-billingInfo-state').find(':selected').attr('code'); var city=document.getElementById("widget-billingInfo-city").value; var zipCode=document.getElementById("widget-billingInfo-zipcode").value; if(stateCode == "null"){ stateCode = "OT"; //OT means others } Widget.payResponse['street1']=self.removeSpecials(add1)+" "+ self.removeSpecials(add2); Widget.payResponse['city']=self.removeSpecials(city); Widget.payResponse['state']=stateCode; Widget.payResponse['countryCode']=countryCode; Widget.payResponse['zipCode']=zipCode; if(payRequest && payRequest.styleId != 'clubWidget') { var email=document.getElementById("widget-contactInfo-email").value; var phone=document.getElementById("widget-contactInfo-phone2").value; Widget.payResponse['email']=email; Widget.payResponse['phoneNumber']=phone; } } } return new function(config) { this.getInstance = function(config) { if (ssInstance == null) { ssInstance = new SmartScript(config); ssInstance.constructor = null; } return ssInstance; }; }; })(); var payomo = SmartScriptFunction.getInstance({});