UNPKG

cloud-sdk-js

Version:
2 lines (1 loc) 17.1 kB
!function(){"use strict";const e=function(){this.jsApiVersion="2.0",this.serverDomain="xpayments.com",this.messageNamespace="xpayments.widget.",this.receiverNamespace="xpayments.checkout.",this.widgetId=this.generateId(),this.previousHeight=-1,this.applePayData={session:null,supportedNetworks:[],merchantCapabilities:[],merchantId:""},this.googlePayData={client:null,libUrl:"https://pay.google.com/gp/p/js/pay.js",libLoaded:!1,paymentMethods:{},merchantInfo:{},tokenizationSpecification:{}},this.paymentMethod=null,this.config={debug:!1,account:"",widgetKey:"",container:"",form:"",language:"",customerId:"",tokenName:"xpaymentsToken",showSaveCard:!0,enableWallets:!0,applePay:{enabled:!1,shippingMethods:[],requiredShippingFields:[],requiredBillingFields:[]},googlePay:{enabled:!1,shippingMethods:[],requiredShippingFields:[],requiredBillingFields:[]},walletMode:"",company:{name:"",domain:document.location.hostname,countryCode:""},order:{tokenizeCard:!1,total:-1,currency:""}},this.handlers={},this.bindedListener=!1,this.bindedSubmit=!1};e.prototype.on=function(e,t,i){if(void 0===i&&(i=this),"formSubmit"!==e)this.handlers[e]=t.bind(i);else{var o=this.getFormElm();o&&(this.bindedSubmit&&o.removeEventListener("submit",this.bindedSubmit),this.bindedSubmit=t.bind(i),o.addEventListener("submit",this.bindedSubmit))}return this},e.prototype.trigger=function(e,t){var i=null;return"function"==typeof this.handlers[e]&&(i=this.handlers[e](t)),this._log("X-Payments widget triggered: "+e,t),i},e.prototype.init=function(e){for(var t in e)if(void 0!==this.config[t])if("object"==typeof this.config[t])for(var i in e[t])void 0!==this.config[t][i]&&(this.config[t][i]=e[t][i]);else this.config[t]=e[t];return this.config.order.tokenizeCard&&(this.config.showSaveCard=!1),this.on("formSubmit",(function(e){this.isValid()&&(this.submit(),e.preventDefault())})).on("success",this._defaultSuccessHandler).on("applepay.paymentauthorized",this._applePayAuthorized).on("applepay.buttonclick",(function(){this.isValid()&&this.submit()})).on("googlepay.paymentauthorized",this._googlePayAuthorized).on("googlepay.buttonclick",(function(){this.isValid()&&this.submit()})).on("alert",(function(e){window.alert(e.message)})),this.bindedListener=this.messageListener.bind(this),window.addEventListener("message",this.bindedListener),void 0!==e.autoload&&e.autoload&&this.load(),this},e.prototype.generateId=function(){return Math.random().toString(36).substring(2,15)+Math.random().toString(36).substring(2,15)},e.prototype.getIframeId=function(){return"xpayments-"+this.widgetId},e.prototype.getIframeElm=function(){return document.getElementById(this.getIframeId())},e.prototype.getContainerElm=function(){return this.safeQuerySelector(this.config.container)},e.prototype.getFormElm=function(){return this.safeQuerySelector(this.config.form)},e.prototype.isValid=function(){return this.getIframeElm()&&this.getFormElm()},e.prototype.safeQuerySelector=function(e){var t=!1;return e&&(t=document.querySelector(e)),t},e.prototype.loadAsyncJS=function(e,t){var i=document.createElement("script");i.type="text/javascript",i.async=!0,i.onload=t,i.src=e,document.getElementsByTagName("head")[0].appendChild(i)},e.prototype.load=function(){var e=this.getContainerElm();if(!e)return this;var t=this.getIframeElm();t||((t=document.createElement("iframe")).id=this.getIframeId(),t.style.width="100%",t.style.height="0",t.style.overflow="hidden",t.style.border="none",this.config.walletMode&&(t.style.display="none"),t.setAttribute("scrolling","no"),e.appendChild(t));var i=this.getServerUrl()+"/payment.php?widget_key="+encodeURIComponent(this.config.widgetKey)+"&widget_id="+encodeURIComponent(this.widgetId)+"&shop="+encodeURIComponent(this.config.company.domain)+"&api_version="+encodeURIComponent(this.jsApiVersion);return this.config.customerId&&(i+="&customer_id="+encodeURIComponent(this.config.customerId)),this.config.language&&(i+="&language="+encodeURIComponent(this.config.language)),this.config.walletMode&&(i+="&target=wallet&mode="+encodeURIComponent(this.config.walletMode)),t.src=i,this._isGooglePayEnabled()&&this.loadAsyncJS(this.googlePayData.libUrl,function(){this.googlePayData.libLoaded=!0}.bind(this)),this},e.prototype.getServerHost=function(){return this.config.account+"."+this.serverDomain},e.prototype.getServerUrl=function(){return"https://"+this.getServerHost()},e.prototype.submit=function(){if(this.config.walletMode)switch(this.getPaymentMethod()){case"applePay":this.trigger("applepay.start"),this._applePayStart();break;case"googlePay":this.trigger("googlepay.start"),this._googlePayStart()}else this._sendEvent("submit")},e.prototype.beginCheckoutWithWallet=function(){this.submit()},e.prototype._afterLoad=function(e){this.showSaveCard(),this._isApplePayAvailable()&&this._sendEvent("applepay.enable"),this._isGooglePayEnabled()&&this._sendGooglePayLoaded(),this.setOrder(),this.resize(e.height)},e.prototype._defaultSuccessHandler=function(e){var t=this.getFormElm();if(t){var i=document.getElementById(this.config.tokenName);i||((i=document.createElement("input")).type="hidden",i.name=i.id=this.config.tokenName,t.appendChild(i)),i.value=e.token,t.submit()}},e.prototype.getPaymentMethod=function(){return this.config.walletMode||this.paymentMethod},e.prototype._paymentMethodChange=function(e){this.paymentMethod=e.newId},e.prototype._applePayValidated=function(e){try{this.applePayData.session.completeMerchantValidation(e.data)}catch(e){}},e.prototype._applePayAuthorized=function(e){this.succeedApplePayPayment(e)},e.prototype._applePayCompleted=function(e){this.completeApplePayPayment({status:ApplePaySession.STATUS_SUCCESS,errors:[]})},e.prototype._applePayError=function(e){try{this.applePayData.session.abort()}catch(e){}},e.prototype._applePayStart=function(){if(this.applePayData.merchantCapabilities.length){var e={countryCode:this.config.company.countryCode,currencyCode:this.config.order.currency,supportedNetworks:this.applePayData.supportedNetworks,merchantCapabilities:this.applePayData.merchantCapabilities,total:{label:this.config.company.name,amount:this.config.order.total}};this.applePayCustomerAddress=null,this.config.walletMode&&(this.config.applePay.shippingMethods.length&&(e.shippingMethods=this.config.applePay.shippingMethods),this.config.applePay.requiredShippingFields.length&&(e.requiredShippingContactFields=this.config.applePay.requiredShippingFields),this.config.applePay.requiredBillingFields.length&&(e.requiredBillingContactFields=this.config.applePay.requiredBillingFields)),this.applePayData.session=new ApplePaySession(3,e),this.applePayData.session.onvalidatemerchant=function(e){this._sendEvent("applepay.validatemerchant",{validationURL:e.validationURL,displayName:this.config.company.name,context:this.config.company.domain})}.bind(this),this.applePayData.session.onpaymentauthorized=function(e){this.trigger("applepay.paymentauthorized",e.payment)}.bind(this),this.applePayData.session.oncancel=function(e){var t={};void 0!==e.sessionError&&(t.error=e.sessionError),this._sendEvent("applepay.cancel",t),this.trigger("applepay.cancel",t)}.bind(this),this.config.walletMode&&(this.applePayData.session.onshippingcontactselected=function(e){this.trigger("applepay.shippingcontactselected",e.shippingContact)}.bind(this),this.applePayData.session.onshippingmethodselected=function(e){this.trigger("applepay.shippingmethodselected",e.shippingMethod)}.bind(this)),this.applePayData.session.begin()}else this._sendEvent("applepay.cancel",{alert:!0})},e.prototype._parseApplePayNewTotal=function(e){return this.setOrder(e.newTotal.amount),void 0!==e.newTotal&&void 0===e.newTotal.label&&(e.newTotal.label=this.config.company.name),e},e.prototype.completeApplePayShippingContactSelection=function(e){this.applePayData.session.completeShippingContactSelection(this._parseApplePayNewTotal(e))},e.prototype.completeApplePayShippingMethodSelection=function(e){this.applePayData.session.completeShippingMethodSelection(this._parseApplePayNewTotal(e))},e.prototype.completeApplePayPayment=function(e){this.applePayData.session.completePayment(e)},e.prototype.succeedApplePayPayment=function(e){this._sendEvent("applepay.paymentauthorized",{payment:e})},e.prototype.isApplePaySupportedByDevice=function(){return window.ApplePaySession&&ApplePaySession.canMakePayments()},e.prototype._isApplePayAvailable=function(){return this.isApplePaySupportedByDevice()&&(this.config.enableWallets&&this.config.applePay.enabled||"applePay"===this.config.walletMode)},e.prototype._checkApplePayActiveCard=function(){ApplePaySession.canMakePaymentsWithActiveCard(this.applePayData.merchantId).then(function(e){e&&(this.trigger("applepay.forceselect"),this._sendEvent("applepay.select"))}.bind(this))},e.prototype._applePayInit=function(e){this.applePayData.supportedNetworks=e.supportedNetworks,this.applePayData.merchantCapabilities=e.merchantCapabilities,this.applePayData.merchantId=e.merchantId,this.config.walletMode||this._checkApplePayActiveCard()},e.prototype._isGooglePayEnabled=function(){return this.config.enableWallets&&this.config.googlePay.enabled||"googlePay"===this.config.walletMode},e.prototype._sendGooglePayLoaded=function(){new Promise(function(e,t){var i=0,o=function(){i++,this.googlePayData.libLoaded?e():i<300?setTimeout(o,100):this._log("Error! Failed to load Google Pay library.")}.bind(this);o()}.bind(this)).then(function(){this._sendEvent("googlepay.loaded",{origin:this.config.company.domain})}.bind(this))},e.prototype._googlePayPrepareBaseRequest=function(){return{apiVersion:2,apiVersionMinor:0,allowedPaymentMethods:this.googlePayData.paymentMethods}},e.prototype._googlePayPrepareReadyToPay=function(e){var t={};return void 0!==e&&e&&(t.existingPaymentMethodRequired=e),Object.assign({},this._googlePayPrepareBaseRequest(),t)},e.prototype._googlePayPrepareLoadPayment=function(e){var t=this._googlePayPrepareBaseRequest();for(var i in t.allowedPaymentMethods)t.allowedPaymentMethods[i].tokenizationSpecification=this.googlePayData.tokenizationSpecification,this.config.walletMode&&this.config.googlePay.requiredBillingFields.length&&(t.allowedPaymentMethods[i].parameters.billingAddressRequired=!0,t.allowedPaymentMethods[i].parameters.billingAddressParameters={format:-1!==this.config.googlePay.requiredBillingFields.indexOf("full")?"FULL":"MIN",phoneNumberRequired:-1!==this.config.googlePay.requiredBillingFields.indexOf("phone")});return Object.assign({},t,e)},e.prototype._googlePayInit=function(e){this.googlePayData.merchantInfo={merchantName:this.config.company.name,merchantOrigin:this.config.company.domain,merchantId:e.businessId},e.authJwt&&(this.googlePayData.merchantInfo.authJwt=e.authJwt),this.googlePayData.tokenizationSpecification={type:"PAYMENT_GATEWAY",parameters:{gateway:e.gatewayId,gatewayMerchantId:e.merchantId}};var t={environment:e.environment,merchantInfo:this.googlePayData.merchantInfo,paymentDataCallbacks:{onPaymentAuthorized:function(e){return this.trigger("googlepay.paymentauthorized",e,!0)}.bind(this)}};for(var i in this.config.walletMode&&this.config.googlePay.requiredShippingFields.length&&(t.paymentDataCallbacks.onPaymentDataChanged=function(e){return this.trigger("googlepay.paymentdatachanged",e)}.bind(this)),this.googlePayData.client=new google.payments.api.PaymentsClient(t),this.googlePayData.paymentMethods=[],e.paymentMethods)this.googlePayData.paymentMethods.push({type:e.paymentMethods[i],parameters:{allowedAuthMethods:e.authMethods,allowedCardNetworks:e.supportedNetworks}});var o=this._googlePayPrepareReadyToPay();this.googlePayData.client.isReadyToPay(o).then(function(e){e.result?(this._sendEvent("googlepay.enable"),this.trigger("googlepay.ready")):this.trigger("googlepay.nonready")}.bind(this)).catch(function(e){this._log(e)}.bind(this))},e.prototype._googlePayStart=function(e){if(this.googlePayData.client){var t={merchantInfo:this.googlePayData.merchantInfo,transactionInfo:{totalPriceStatus:"FINAL",totalPrice:this.config.order.total.toString(),currencyCode:this.config.order.currency,countryCode:this.config.company.countryCode},callbackIntents:["PAYMENT_AUTHORIZATION"]};this.config.walletMode&&this.config.googlePay.requiredShippingFields.length&&(t.transactionInfo.displayItems=[{label:"Subtotal",type:"SUBTOTAL",price:this.config.order.total.toString()}],t.transactionInfo.totalPriceStatus="ESTIMATED",t.transactionInfo.totalPriceLabel="Total",t.callbackIntents.push("SHIPPING_ADDRESS"),t.shippingAddressRequired=!0,t.shippingAddressParameters={phoneNumberRequired:-1!==this.config.googlePay.requiredShippingFields.indexOf("phone")},t.emailRequired=-1!==this.config.googlePay.requiredShippingFields.indexOf("email"),this.config.googlePay.shippingMethods.length&&(t.callbackIntents.push("SHIPPING_OPTION"),t.shippingOptionRequired=!0)),t=this._googlePayPrepareLoadPayment(t),this.googlePayData.client.loadPaymentData(t).then(function(e){}.bind(this)).catch(function(e){this._sendEvent("googlepay.cancel",{error:e}),this.trigger("googlepay.cancel")}.bind(this))}else this._sendEvent("googlepay.cancel",{alert:!0})},e.prototype._googlePayAuthorized=function(e){return new Promise(function(t,i){t(this.succeedGooglePayPayment(e))}.bind(this))},e.prototype._googlePayError=function(e){},e.prototype.succeedGooglePayPayment=function(e){return this._sendEvent("googlepay.paymentauthorized",{payment:e.paymentMethodData}),{transactionState:"SUCCESS"}},e.prototype.isGooglePayInitialized=function(e){return null!==this.googlePayData.client},e.prototype.createApplePayButton=function(e){if(!this.isApplePaySupportedByDevice())return console.error("Apple Pay is not supported by the device"),null;var t={onClick:function(){this.trigger("applepay.buttonclick")}.bind(this),wrapperClass:"apple-pay-button-wrapper",buttonClass:"apple-pay-button",buttonContent:""};void 0!==e&&(t=Object.assign({},t,e));var i=document.createElement("div");i.className=t.wrapperClass;var o=document.createElement("button");return o.className=t.buttonClass,o.type="button",o.innerHTML=t.buttonContent,o.addEventListener("click",t.onClick),i.appendChild(o),i},e.prototype.createGooglePayButton=function(e){if(!this.isGooglePayInitialized())return console.error("Google Pay not initalized"),null;var t={onClick:function(){this.trigger("googlepay.buttonclick")}.bind(this)};return void 0!==e&&(t=Object.assign({},t,e)),this.googlePayData.client.createButton(t)},e.prototype.setWalletMode=function(e){this.config.walletMode=e},e.prototype.showSaveCard=function(e){void 0===e?e=this.config.showSaveCard:this.config.showSaveCard=!0===e,this._sendEvent("savecard",{show:e})},e.prototype.refresh=function(){this._sendEvent("refresh")},e.prototype.resize=function(e){var t=this.getIframeElm();t&&(this.previousHeight=t.style.height,t.style.height=e+"px")},e.prototype.setOrder=function(e,t){void 0!==e&&(this.config.order.total=e),void 0!==t&&(this.config.order.currency=t),this._sendEvent("details",{tokenizeCard:this.config.order.tokenizeCard,total:this.config.order.total,currency:this.config.order.currency})},e.prototype.destroy=function(){this.bindedListener&&window.removeEventListener("message",this.bindedListener);var e=this.getFormElm();this.bindedSubmit&&e&&e.removeEventListener("submit",this.bindedSubmit);var t=this.getContainerElm();if(t){var i=this.getIframeElm();i&&t.contains(i)&&t.removeChild(i)}},e.prototype.messageListener=function(e){if(window.JSON){var t=!1;if(-1!==this.getServerUrl().toLowerCase().indexOf(e.origin.toLowerCase()))try{t=window.JSON.parse(e.data)}catch(e){}if(t&&t.event&&0===t.event.indexOf(this.messageNamespace)&&(!t.widgetId||t.widgetId===this.widgetId)){this._log("Received from X-Payments: "+t.event,t.params);var i=t.event.substr(this.messageNamespace.length);"loaded"===i?this._afterLoad(t.params):"applepay.start"===i?this._applePayStart(t.params):"applepay.init"===i?this._applePayInit(t.params):"applepay.merchantvalidated"===i?this._applePayValidated(t.params):"applepay.completed"===i?this._applePayCompleted(t.params):"applepay.error"===i?this._applePayError(t.params):"googlepay.init"===i?this._googlePayInit(t.params):"googlepay.start"===i?this._googlePayStart(t.params):"googlepay.error"===i?this._googlePayError(t.params):"paymentmethod.change"===i?this._paymentMethodChange(t.params):"resize"===i?this.resize(t.params.height):"alert"===i&&(t.params.message="string"==typeof t.params.message?t.params.message.replace(/<\/?[^>]+>/gi,""):""),this.trigger(i,t.params)}}},e.prototype._isDebugMode=function(){return this.config.debug},e.prototype._log=function(e,t){this._isDebugMode()&&(console.groupCollapsed(e),void 0!==t&&console.log(JSON.stringify(t)),console.trace(),console.groupEnd())},e.prototype._sendEvent=function(e,t){void 0===t&&(t={}),this._postMessage({event:this.receiverNamespace+e,params:t})},e.prototype._postMessage=function(e){var t=this.getIframeElm();window.postMessage&&window.JSON&&t&&t.contentWindow?(this._log("Sent to X-Payments: "+e.event,e.params),t.contentWindow.postMessage(window.JSON.stringify(e),"*")):this._log("Error sending message - iframe wasn't initialized!")}}();