Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- let SplitIt;
- SplitIt = {
- styles: {
- modal:
- 'z-index: 9999;' +
- 'display: none;' +
- 'position: fixed;' +
- 'left: 0;top: 0;' +
- 'width: 100%;' +
- 'height: 100%;' +
- 'background-color: rgba(0, 0, 0, 0.5);' +
- 'opacity: 1;' +
- 'visibility: visible;' +
- 'transform: scale(1.0);' +
- 'transition: visibility 0s linear 0s, opacity 0.25s 0s, transform 0.25s;',
- modalContent:
- 'position: absolute;' +
- 'top: 50%;left: 50%;' +
- 'transform: translate(-50%, -50%);' +
- 'background-color: white;' +
- 'padding: 1rem 1.5rem;' +
- 'width: 600;' +
- 'height: 90vh;' +
- 'overflow: scroll;',
- closeButton:
- 'float: right;' +
- 'width: 1.5rem;' +
- 'line-height: 1.5rem;' +
- 'text-align: center;' +
- 'cursor: pointer;' +
- 'border-radius: 0.25rem;' +
- 'background-color: lightgray;',
- learnMoreText:
- 'font-size:14px;' +
- 'margin: 5px 0;' +
- 'text-align: right;',
- learnMore:
- 'font-style: italic; ' +
- 'cursor: pointer'
- },
- init: function () {
- var me = this;
- this.apiKey = '{{ApiKey}}';
- this.appBaseUrl = '{{AppUrl}}';
- this.checkoutMinimumAmount = {{CheckoutMinimumAmount}};
- this.checkoutMaximumAmount = {{CheckoutMaximumAmount}};
- this.logoUrl = this.appBaseUrl + '/images/logo-01.png';
- this.logoText = '{{CheckoutLabel}}';
- this.configNumberOfInstallments = {{ExampleInstallments}};
- this.ccImageBaseUrl = 'https://cdn8.bigcommerce.com/r-c9989feeb90073b5e11876b39360a7e376124460/bower/ng-payments/dist/img';
- this.creditCards = {
- 'visa': {
- 'url': this.appBaseUrl + '/images/visa.svg',
- 'isAllowed': {{1}}
- },
- 'masterCard': {
- 'url': this.appBaseUrl + '/images/mastercard.svg',
- 'isAllowed': {{2}}
- },
- 'amex': {
- 'url': this.appBaseUrl + '/images/amex.svg',
- 'isAllowed': {{3}}
- },
- 'discover': {
- 'url': this.appBaseUrl + '/images/discover.svg',
- 'isAllowed': {{4}}
- },
- 'diners': {
- 'url': this.appBaseUrl + '/images/diners.svg',
- 'isAllowed': 0
- },
- 'paypal': {
- 'url': this.appBaseUrl + '/images/paypal.svg',
- 'isAllowed': 0
- },
- 'paypalCredit': {
- 'url': this.appBaseUrl + '/images/paypalcredit.svg',
- 'isAllowed': 0
- }
- };
- this.cartItems = [];
- this.placeOrderButtonSelector = '#checkout-payment-continue';
- this.paymentHeaderSelector = '.paymentProviderHeader-name';
- this.isLoading = false;
- this.loaderClass = 'js-splitit-loader';
- this.loaderSelector = '.' + this.loaderClass;
- this.ccContainer = '.form-checklist.optimizedCheckout-form-checklist';
- this.itemSelectedSelector = '.form-checklist-item--selected';
- this.checkoutButtonSelector = '.optimizedCheckout-buttonPrimary';
- this.cartPriceSelector = '.cart-priceItem--total';
- this.learnMoreImageClass = 'splitit-learn-more-img';
- this.learnMoreImageUrl = this.appBaseUrl + '/images/English-PNG.png';
- this.installmentPlanClass = 'splitit-installment-plan';
- this.installmentPlanSelector = '.' + this.installmentPlanClass;
- this.learnMoreTextClass = 'splitit-learn-more-text';
- this.learnMoreClass = 'splitit-learn-more';
- this.learnMoreSelector = '.' + this.learnMoreClass;
- this.modalClass = 'splitit-modal';
- this.modalSelector = '.' + this.modalClass;
- this.modalContentClass = 'splitit-modal-content';
- this.closeButtonClass = 'splitit-close-button';
- this.closeButtonSelector = '.' + this.closeButtonClass;
- this.totalString = '';
- this.bindEvents();
- this.observe();
- this.appendLogos();
- },
- bindEvents: function () {
- var me = this;
- $(document).on('click', this.checkoutButtonSelector, function (e) {
- if ($(e.target).attr('id') == 'checkout-payment-continue') {
- return;
- }
- clearInterval(me.logoInterval);
- me.appendLogos();
- });
- $(document).on('click', this.placeOrderButtonSelector, function (e) {
- var ccContainerObj = $(me.ccContainer);
- var selectedMethodObj = ccContainerObj.find(me.itemSelectedSelector);
- var methodName = selectedMethodObj
- .find(me.paymentHeaderSelector)
- .text()
- .trim()
- .toLowerCase();
- if (methodName == 'splitit') {
- e.preventDefault();
- if (!me.isLoading) {
- me.appendLoader(selectedMethodObj);
- me.splititMethodClickEventHandler();
- }
- }
- });
- $(document).on('click', this.learnMoreSelector, function () {
- me.learnMoreClickEventHandler();
- });
- $(document).on('click', this.closeButtonSelector, function () {
- me.closeButtonClickEventHandler();
- });
- },
- observe: function() {
- this.observeTotal();
- },
- observeTotal: function () {
- var me = this;
- setInterval(function() {
- var totalEl = document.querySelector(me.cartPriceSelector + ' [data-test="cart-price-value"]');
- if (!totalEl) {
- return;
- }
- if (me.totalString !== totalEl.textContent) {
- me.totalString = totalEl.textContent;
- me.handleData();
- }
- }, 1000);
- },
- handleData: function() {
- var me = this;
- this.fetchCheckoutData().then(function () {
- if (me.validate() == false) {
- setInterval(function () {
- var label = me.getSplititMethodLabel();
- if (label) {
- label.hide();
- }
- }, 1000);
- } else {
- me.appendInstallmentsExamplePlan();
- me.appendModal();
- }
- });
- },
- splititMethodClickEventHandler: function () {
- const me = this;
- this.fetchCheckoutData()
- .then(function () {
- me.getCheckoutUrl()
- .then(function (apiResponse) {
- if (apiResponse.error) {
- //handle error
- console.log(apiResponse.Error);
- return;
- }
- me.appendIframe();
- loadSplititPaymentForm(apiResponse.Response.CheckoutUrl);
- me.removeLoader();
- });
- });
- },
- learnMoreClickEventHandler: function () {
- this.showModal();
- },
- closeButtonClickEventHandler: function () {
- this.hideModal();
- },
- showModal: function () {
- document.querySelector(this.modalSelector).style.display = "block";
- },
- hideModal: function () {
- document.querySelector(this.modalSelector).style.display = "none";
- },
- appendModal: function () {
- var body, modal, content, img, close;
- var modalEl = document.querySelector(this.modalSelector);
- if (modalEl) {
- return;
- }
- body = document.querySelector("body");
- modal = document.createElement('div');
- content = document.createElement('div');
- img = document.createElement('img');
- close = document.createElement('button');
- modal.className = this.modalClass;
- modal.style.cssText = this.styles.modal;
- content.className = this.modalContentClass;
- content.style.cssText = this.styles.modalContent;
- img.className = this.learnMoreImageClass;
- img.src = this.learnMoreImageUrl;
- close.className = this.closeButtonClass;
- close.style.cssText = this.styles.closeButton;
- close.textContent = 'X';
- content.appendChild(img);
- content.appendChild(close);
- modal.appendChild(content);
- body.appendChild(modal);
- },
- validate: function () {
- if (this.cartAmount < this.checkoutMinimumAmount) {
- return false;
- }
- if (this.cartAmount > this.checkoutMaximumAmount) {
- return false;
- }
- return true;
- },
- getCheckoutUrl: function () {
- const me = this;
- return new Promise(function (resolve, reject) {
- $.ajax({
- url: me.appBaseUrl + '/api/checkout/initiate/' + me.apiKey,
- type: 'POST',
- data: me.getSplitItData(),
- contentType: 'application/json; charset=utf-8',
- dataType: 'json',
- async: false,
- success: function (data) {
- resolve(data);
- },
- error: function (request, error) {
- reject('error: ' + JSON.stringify(request));
- }
- });
- });
- },
- fetchCheckoutData: function () {
- const me = this;
- return new Promise(function (resolve, reject) {
- fetch('/api/storefront/cart', {
- credentials: 'include'
- }).then(function (response) {
- return response.json();
- }).then(function (cartJson) {
- me.cartId = cartJson[0].id;
- me.currencyCode = cartJson[0].currency.code;
- me.convertItems(cartJson[0].lineItems.physicalItems);
- me.convertItems(cartJson[0].lineItems.digitalItems);
- return cartJson[0].id;
- }).catch(function (error) {
- reject(error);
- }).then(function (cartId) {
- fetch('/api/storefront/checkouts/' + cartId, {
- credentials: 'include'
- }).then(function (response) {
- return response.json();
- }).then(function (checkoutJson) {
- me.cartAmount = checkoutJson.grandTotal;
- me.checkoutId = checkoutJson.id;
- me.customerFirstName = checkoutJson.billingAddress.firstName;
- me.customerLastName = checkoutJson.billingAddress.lastName;
- me.customerEmail = checkoutJson.billingAddress.email;
- me.customerPhone = checkoutJson.billingAddress.phone;
- me.customerAddressLine1 = checkoutJson.billingAddress.address1;
- me.customerAddressLine2 = checkoutJson.billingAddress.address2;
- me.customerCity = checkoutJson.billingAddress.city;
- me.customerCountry = checkoutJson.billingAddress.country;
- me.customerState = checkoutJson.billingAddress.stateOrProvince;
- me.customerZip = checkoutJson.billingAddress.postalCode;
- resolve(checkoutJson);
- }).catch(function (error) {
- reject(error);
- })
- });
- });
- },
- convertItems: function (items) {
- for (let key in items) {
- if (items.hasOwnProperty(key)) {
- let item = {
- "Name": items[key].name,
- "SKU": items[key].sku,
- "Price": { "Value": items[key].salePrice, "CurrencyCode": this.currencyCode },
- "Quantity": items[key].quantity
- };
- this.cartItems.push(item);
- }
- }
- },
- getSplitItData: function () {
- const data = {
- "CartId": this.cartId,
- "PlanData": {
- "Amount": { "Value": this.cartAmount, "CurrencyCode": this.currencyCode },
- "PurchaseMethod": "ECommerce",
- "AutoCapture": true
- },
- "BillingAddress": {
- "AddressLine": this.customerAddressLine1,
- "AddressLine2": this.customerAddressLine2,
- "City": this.customerCity,
- "State": this.customerState,
- "Country": this.customerCountry,
- "Zip": this.customerZip
- },
- "ConsumerData": {
- "FullName": this.customerFirstName + ' ' + this.customerLastName,
- "Email": this.customerEmail,
- "PhoneNumber": this.customerPhone
- },
- "CartData": {
- "Items": this.cartItems,
- "AmountDetails": {}
- },
- "RedirectUrls": {
- "Succeeded": this.appBaseUrl + "/api/checkout/confirm-order?ApiKey=" + this.apiKey,
- "Failed": this.appBaseUrl + "/api/checkout/payment-failed?ApiKey=" + this.apiKey,
- "Canceled": this.appBaseUrl + "/api/checkout/payment-canceled?ApiKey=" + this.apiKey
- },
- "EventsEndpoints": {
- "CreateSucceeded": this.appBaseUrl + "/api/events/create-succeeded"
- }
- };
- return JSON.stringify(data);
- },
- appendIframe: function () {
- $('<div id="splitit-payment-form" class="iframe-container"></div>').appendTo('body');
- },
- appendLoader: function (methodObj) {
- let loader = $('<span class="' + this.loaderClass + '"></span>').css({
- 'border': '2px solid transparen',
- 'border-radius': '50%',
- 'border-top': '2px solid #4496f6',
- 'border-bottom': '2px solid #4496f6',
- 'width': '24px',
- 'height': '24px',
- '-webkit-animation': 'spin 2s linear infinite',
- 'animation': 'spin 2s linear infinite',
- 'display': 'block',
- 'font-size': '0px',
- 'position': 'absolute',
- 'top': '29px',
- 'left': '151px'
- });
- this.isLoading = true;
- methodObj.after(loader);
- },
- removeLoader: function () {
- $(this.loaderSelector).remove();
- this.isLoading = false;
- },
- appendLogos: function () {
- var me = this;
- this.logoInterval = setInterval(function () {
- var ccContainerObj = $(me.ccContainer);
- if (ccContainerObj.length) {
- var i = 0;
- var methodsObj = ccContainerObj.find(me.paymentHeaderSelector);
- methodsObj.each(function () {
- if ($(this).text().trim().toLowerCase() == 'splitit') {
- $(this).hide();
- me.appendSplititLogo($(this));
- me.appendCreditCardLogos($(this));
- me.appendSplititText($(this));
- clearInterval(me.logoInterval);
- i++;
- }
- });
- }
- }, 1000);
- },
- appendSplititLogo: function (targetObj) {
- targetObj.before('<img src="' + this.logoUrl + '" style="width:80px;">');
- },
- appendSplititText: function (targetObj) {
- targetObj.after('<span style="margin-left:10px;">' + this.logoText + '</span>');
- },
- appendCreditCardLogos: function (targetObj) {
- var ccContainerObj = $('<div class="paymentProviderHeader-cc creditCardTypes" style="margin-bottom: 10px;"></div>');
- for (var key in this.creditCards) {
- var card = this.creditCards[key];
- if (card.isAllowed == 1) {
- ccContainerObj.append('<img src="' + card.url + '" style="max-width: 40px;margin-left: 5px;">');
- }
- }
- targetObj.after(ccContainerObj);
- },
- getSplititMethodLabel: function () {
- var label;
- var methodsObj = $(this.ccContainer).find(this.paymentHeaderSelector);
- methodsObj.each(function () {
- if ($(this).text().trim().toLowerCase() == 'splitit') {
- label = $(this)
- .parent()
- .parent()
- .parent();
- }
- });
- return label;
- },
- appendInstallmentsExamplePlan: function () {
- var text = this.createText();
- var installmentPlanEl = document.querySelector(this.installmentPlanSelector);
- if (installmentPlanEl) {
- installmentPlanEl.parentNode.removeChild(installmentPlanEl);
- }
- $(this.cartPriceSelector).after(text);
- },
- createText: function() {
- var installmentValue = (this.cartAmount / this.configNumberOfInstallments).toFixed(2);
- var text = '<div class="' + this.installmentPlanClass + '"><p class="splitit-installment-example" style="font-size:14px;margin: 5px 0;text-align:right">' +
- 'Or $' + installmentValue + ' x ' + this.configNumberOfInstallments + '</p>';
- text += '<p class="' + this.learnMoreTextClass + '" ' +
- 'style="' + this.styles.learnMoreText + '">' +
- 'Interest - Free Payments ' +
- '<a class="' + this.learnMoreClass + '" ' +
- 'style="' + this.styles.learnMore + '">' +
- 'Learn more' +
- '</a>' +
- '</p>' +
- '</div>';
- return text;
- }
- };
- $(document).ready(function () {
- SplitIt.init();
- });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement