function($ = recurpayScript) { if ((window.location.href.indexOf("/products/") > -1) && (window.location.href.indexOf("recurpay_preview=true") > -1)) { recurpay.pdpAPI = recurpay.generalURL + '/storefront/api/2024-07/widgets/products/plans?shop=' + recurpay.shopDomainURL + '&fetch=force'; } var accountTemplate = '', accountSelector = "#recurpay-account-widget", pdpSelector = ".recurpay-pdp-widget", subscriptionSelector = "#recurpay-manage-subscriptions", checkoutSelector = '[href="/checkout"], form[action="/cart"] button[type="submit"][name="checkout"], form[action="/cart"] input[type="submit"][name="checkout"], form[action="/checkout"] input[type="submit"][name="checkout"], form[action="/checkout"] button[type="submit"][name="checkout"], button[type="submit"][name="checkout"],button[name="checkout"], button[name="checkout"].cart__checkout, button.ucd-checkout-btn, #checkout2.flo-checkout-btn', atcFormSelector = 'form[action*="/cart/add"], form[action*="/cart/add.js"], form[id^="product_form_"], form[data-productid], form[action*="/cart/add"][data-js-product-form], form#AddToCartForm, #addToCartFormId1, form.product-form, #AddToCartForm_id, form[data-cart-submit="data-cart-submit"][data-productid], form.lh-product-form, form.shg-product-atc-btn-wrapper, form.shopify-product-form, product-form.product-form', atcSelector = '.buy-buttons [type="submit"], [name="add"], [type=\"submit\"],button#AddToCart, button.gf_add-to-cart, button.gp-button-atc, #button-cart,.new-form-atc[data-add-to-cart], button[data-type="addToCart"], .product-buy-buttons--primary[data-text="Add to cart"], product-variant-render button[type="submit"],.x-buy-now-button', buynowSelector = '.shopify-payment-button,.shopify-payment-button__button', priceQuantitySelector = '[name=quantity]', footerManageSubcriptionSelector = ".recurpay-manage-subscription-link-footer", footerLinkSelector = 'footer, .footer', appBlockSelector = '[id*="recurpay_app_block_widget"], .shopify-app-block[data-block-handle="recurpay-app-block-widget"]', appBlockParentSelector = ".product-info, .shop-product-info, .product-single__meta [data-product-blocks], .shopify-block, .product__info-container"; recurpay.pdpAPI = recurpay.generalURL + '/storefront/api/2024-07/widgets/products/plans?shop=' + recurpay.shopDomainURL; // ACCOUNT PAGE if(recurpay.pageTemplate == "customers/account" && $(accountSelector).length <= 0) { if($('.card__linklist').length >0) { $('.card__linklist').before('
'); } else if($('.flits-account-page-title').length >0) { $('.flits-account-page-title').append('
'); } else if($('a[href*="/account/addresses"]').length >0) { $('a[href*="/account/addresses"]').before('
'); } else if ($('.order-history').length >0) { $('.order-history').before('
'); } else if ($('a[href*="/account/logout"]').length >0) { $('a[href*="/account/logout"]').before('
'); } else { recurpay.logEvent("account_widget","Failed to show account snippet", "critical"); } } //LOGIN PAGE function loginPageSubscriptionLink() { var accountLoginHTML = "", footerLinkHTML = "", managesubscriptionSelector = ".recurpay-manage-subscription-link", signUpFormSelector = 'form[action*="/account"]'; if ($(managesubscriptionSelector).length <= 0 && $(signUpFormSelector).length > 0) { $(signUpFormSelector).append(""); } if ($(footerManageSubcriptionSelector).length <= 0 && $(footerLinkSelector).length > 0) { $(footerLinkSelector).find('.footer__content-bottom .footer__content-bottom-wrapper .footer__copyright').append(''); } var account_url = ""; account_url = recurpay.customer ? recurpay.accountAPI + "&settings=true" : recurpay.generalURL + "/api/storefront/v3/customers/subscriptions/count?" + recurpay.urlParam + "&settings=true"; $.ajax( { url: account_url, type: 'POST', data: { customer_id: recurpay.customer || '', customer_hash: recurpay.secret_potion || '' }, async: true, success: function (response) { if (response != "ERROR") { if (response.settings !== null && !$.isEmptyObject(response.settings) && response.translations.breadcrumb_manage_subscription_link != undefined) { if ($(managesubscriptionSelector).length >= 0) { accountLoginHTML += "" + response.translations.breadcrumb_manage_subscription_link + ""; } if ($(footerManageSubcriptionSelector).length >= 0) { footerLinkHTML += "" + response.translations.breadcrumb_manage_subscription_link + ""; } } } $(managesubscriptionSelector).html(accountLoginHTML); $(footerManageSubcriptionSelector).html(footerLinkHTML); } }); } loginPageSubscriptionLink(); if($(accountSelector).length && recurpay.customer !== "guest") { function recurAccount(count) { accountTemplate += '
' accountTemplate += '
' accountTemplate += '' if(count !== 0) { accountTemplate += '' accountTemplate += '' } else { accountTemplate += '' accountTemplate += '' } accountTemplate += '
' return accountTemplate; } $.ajax( { url: recurpay.accountAPI+"&settings=true", type: 'POST', data: { customer_id: recurpay.customer || '', customer_hash: recurpay.secret_potion || '' }, async:true, success: function(response) { var accountHTML = ''; if(response != "ERROR") { if(response.settings !== null && !$.isEmptyObject(response.settings)) { recurpay.accountSettings = response.settings; document.documentElement.style.setProperty('--recurpay_primary_color', recurpay.accountSettings.snippet_color_codes.account_brand_color); document.documentElement.style.setProperty('--recurpay_button_text_color', recurpay.accountSettings.snippet_color_codes.account_button_text_color); document.documentElement.style.setProperty('--recurpay_button_bg_color', recurpay.accountSettings.snippet_color_codes.account_button_color); } accountHTML = recurAccount(response.count); } else { accountHTML = recurAccount(0); } if($(accountSelector).length) { $(accountSelector).html(accountHTML); } }, error: function(jqXhr, textStatus, errorThrown) { console.log( errorThrown ); } }); $(document).on('click', subscriptionSelector, function(e) { e.preventDefault(); $.ajax( { url: recurpay.manageAccountAPI, type: 'POST', data: { customer_id: recurpay.customer, customer_hash: recurpay.secret_potion || '' }, success: function(response) { var redirect_url = response.account.url; if(redirect_url !== "" && redirect_url !== null && redirect_url !== undefined) { setTimeout(() => { window.location.href = redirect_url; }, 100); } else { console.log('redirect url error'); } }, error: function(response) { console.log('redirect url error'); } }) }); } function formatPriceMoney(r){var e=100*r;return recurpay.recurMoney.formatPrice(e)}$(atcFormSelector).closest(".product__meta").find("button.product__chip").on("click",function(){var r=$(this);setTimeout(function(){recurpay.product.selectedVariant=r.parents(atcFormSelector).find('select[name="id"]').val(),null!=recurpay.product.selectedVariant&&null!=recurpay.product.selectedVariant&&""!=recurpay.product.selectedVariant&&(recurDiscountedPrice(recurpay.product.selectedVariant),recurpay.handlePlanOnVariant(recurpay.product.selectedVariant))},100)}); $(atcFormSelector).find(".combobox, .wetheme-dropdown__wrapper ul[id^='SingleOptionSelector-'] li, .option-values-radio .popover-list-item .form-element-radio, .single-option-selector .bcpo-image-parent, .regular-select-item, .bcpo-dd.single-option-selector ul.inner li, #clickyboxes-SingleOptionSelector-0 a, button.product__chip, .form-swatch-item, .product-variant__container .product-variant__label, .options-selection__option-value, .popout-list__option--product, .option-swatch .custom-swatch, ul.select-dropdown li, .swatch-element, .swatch_pr_item, .basel-swatch, .swatchBox label, .swatchBox span").on("click",function(){var e=$(this);setTimeout(function(){recurpay.product.selectedVariant=e.parents(atcFormSelector).find('select[name="id"], input[name="id"][type="radio"]:checked').val(),null!=recurpay.product.selectedVariant&&null!=recurpay.product.selectedVariant&&""!=recurpay.product.selectedVariant&&(recurDiscountedPrice(recurpay.product.selectedVariant),recurpay.handlePlanOnVariant(recurpay.product.selectedVariant))},100)}); $(atcFormSelector).closest(".product-selection").find("select.single-option-selector").on("change",function(){var e=$(this);setTimeout(function(){recurpay.product.selectedVariant=e.parents(atcFormSelector).find('select[name="id"]').val(),null!=recurpay.product.selectedVariant&&null!=recurpay.product.selectedVariant&&""!=recurpay.product.selectedVariant&&(recurDiscountedPrice(recurpay.product.selectedVariant),recurpay.handlePlanOnVariant(recurpay.product.selectedVariant))},100)}); $(atcFormSelector).find(".product-single__swatch__input").on("change",function(){var e=$(this);setTimeout(function(){recurpay.product.selectedVariant=e.parents(atcFormSelector).find('select[name="id"]').val(),null!=recurpay.product.selectedVariant&&null!=recurpay.product.selectedVariant&&""!=recurpay.product.selectedVariant&&(recurDiscountedPrice(recurpay.product.selectedVariant),recurpay.handlePlanOnVariant(recurpay.product.selectedVariant))},100)}); $(atcFormSelector).find('input#SelectedId, select.js-variant-select, input[name="id"], select[name="id"], select.single-option-selector, .zpa-single-option-selector, .select.options-selection__input-select, .form-options input.option-value-input, .variant-input input[type="radio"], .product-form__option-select, .option-selectors .selector-wrapper select, select.single-option-list-type, .product-options .option-input, select.input-reset, select.js-product-variant, select[data-single-option-selector], input[data-single-option-selector], select.single-option-selector-product-template, .single-option-selector[type="radio"], .single-option-selector-product-template[type="radio"], .variant-option').on("change",function(){var e=$(this);setTimeout(function(){recurpay.product.selectedVariant=e.parents(atcFormSelector).find('input[name="id"], select[name="id"], input#SelectedId').val(),null!=recurpay.product.selectedVariant&&null!=recurpay.product.selectedVariant&&""!=recurpay.product.selectedVariant&&(recurDiscountedPrice(recurpay.product.selectedVariant),recurpay.handlePlanOnVariant(recurpay.product.selectedVariant))},100)}); $(document).find(".quantity-breaks input[name='quantity']").on("change",function(){let e=$(this);setTimeout(function(){recurpay.product.selectedVariant=e.parents(".product__info-container").find(atcFormSelector).find('input.product-variant-id,input[name="id"],select[name="id"],input#SelectedId').val(),null!=recurpay.product.selectedVariant&&null!=recurpay.product.selectedVariant&&""!=recurpay.product.selectedVariant&&(recurDiscountedPrice(recurpay.product.selectedVariant),recurpay.handlePlanOnVariant(recurpay.product.selectedVariant))},100)}); $(document).find("form.variant-picker__form .variant-option input[type='radio']").on("change",function(){let r=$(this);setTimeout(function(){recurpay.product.selectedVariant=r.attr("data-variant-id"),null!=recurpay.product.selectedVariant&&null!=recurpay.product.selectedVariant&&""!=recurpay.product.selectedVariant&&(recurDiscountedPrice(recurpay.product.selectedVariant),recurpay.handlePlanOnVariant(recurpay.product.selectedVariant))},100)}); var getLastUrl=location.href;new MutationObserver(()=>{var e=location.href;e!==getLastUrl&&(getLastUrl=e,onUrlChange())}).observe(document,{subtree:!0,childList:!0}); function onUrlChange(){var a=new URLSearchParams(window.location.search);a.has("variant")&&(recurpay.product.selectedVariant=a.get("variant"),recurDiscountedPrice(recurpay.product.selectedVariant),recurpay.handlePlanOnVariant(recurpay.product.selectedVariant))} function fetchVariants(){!1!==recurpay.getProductHandle()&&$.ajax({url:"/products/"+recurpay.getProductHandle()+".json",type:"GET",success:function(r){recurpay.productDatas[0].product.variants=r.product.variants,recurDiscountedPrice(recurpay.product.selectedVariant),recurpay.handlePlanOnVariant(recurpay.product.selectedVariant)},error:function(r,a,c){console.log(c)}})} recurpay.handlePlanOnVariant=function(e){let a=[];var r=recurpay.calculatePrice(e),t=parseInt(r.product_id);let n=e;(recurpay.globalPlanObjectMap[String(t)]||[]).forEach(e=>{(Array.isArray(e.products)?e.products:[e.products]).forEach(r=>{r&&r.excluded_variants&&r.excluded_variants.length>0&&r.excluded_variants.forEach(r=>{r.id==n&&a.push(e.id)})})});let c=$('.recurpay-pdp-widget[data-product-id="'+t+'"]'),d=a.length>0,i=0,o=c.find(".recurpay__frequency_select").find("option:selected").attr("data-plan")||null,l=c.find(".recurpay__frequency_select").attr("data-original-options");if(l){let e=decodeURIComponent(l);c.find(".recurpay__frequency_select").html(e)}if(c.find(".recurpay__frequency_select option").each(function(){let e=$(this);var r=e.attr("data-plan");d&&a.includes(parseInt(r))?e.remove():i++}),0===i)c.hide(),c.parents(atcFormSelector).find(atcSelector).hasClass("recurpay-hide")&&c.parents(atcFormSelector).find(atcSelector).removeClass("recurpay-hide"),c.parents(atcFormSelector).find(buynowSelector).hasClass("recurpay-hide")&&c.parents(atcFormSelector).find(buynowSelector).removeClass("recurpay-hide"),$(document).find(".recurpay_plan_name").attr("name",""),$(document).find(".recurpay_plan_id").attr("name",""),$(document).find(".recurpay_purchase_data").attr("name",""),$(document).find(".recurpay_selling_plan_id").attr("name","");else{if(c.show(),"subscription"==$(document).find("[name='recurpay__group_main']:checked").val())c.find('.recurpay__widget_container[data-type="subscription-purchase"]').find('button[name="recurpay-subscribe"], button[data-recurpay-action]').length>0?(c.parents(atcFormSelector).find(atcSelector).addClass("recurpay-hide"),c.parents(atcFormSelector).find(buynowSelector).addClass("recurpay-hide")):(c.parents(atcFormSelector).find(atcSelector).removeClass("recurpay-hide"),c.parents(atcFormSelector).find(buynowSelector).removeClass("recurpay-hide")),$(document).find(".recurpay_plan_name").attr("name","properties[Plan]"),$(document).find(".recurpay_plan_id").attr("name","properties[_PlanId]"),$(document).find(".recurpay_purchase_data").attr("name","properties[_PurchaseData]"),$(document).find(".recurpay_selling_plan_id").attr("name","selling_plan");let e=c.find(".recurpay__frequency_select"),a=o?e.find(`option[data-plan="${o}"]`):null;a&&a.length||(a=e.find('option[data-recommended-frequency="true"]'),a.length||(a=e.find("option").first())),a&&a.length&&(a.prop("selected",!0),e[0].dispatchEvent(new Event("change",{bubbles:!0})))}}; function getOneTimeSavingValue(e,a,t,n=1){e=parseFloat(e)||0,t=parseFloat(t)||0;const r=e*(n=parseInt(n,10)||1);let i=0;return"percentage"===(a=(a||"percentage").toLowerCase())?t>0&&(i=r*(t/100)):"fixed"===a?t>0&&(i=Math.min(t,r)):"price"===a&&(i=0===t?r:t>0&&t"; } else { dropdownOptionHtml = "" + getPlanName + "" + " (" + formatPriceMoney(discountedTotalPrice) + ")"; } $this.html(dropdownOptionHtml); if ($this.is(':selected')) { var $pdpWidget = $('.recurpay-pdp-widget[data-product-id="' + getProductId + '"]'); var $subscriptionContainer = $pdpWidget.find(".recurpay__widget_container[data-type='subscription-purchase']"); var $oneTimeBanner = $pdpWidget.find(".recurpay__offer_onetime"); if (discountedTotalPrice < totalPlanPrice) { $subscriptionContainer .find(".recurpay__group_compare_price") .html("" + formatPriceMoney(totalPlanPrice) + ""); } else { $subscriptionContainer .find(".recurpay__group_compare_price") .html(""); } $subscriptionContainer .find(".recurpay__group_selling_price") .html("" + formatPriceMoney(discountedTotalPrice) + ""); const subscriptionDiscountLabel = getSubscriptionDiscountLabel( getDiscountType, getDiscount, getSavings ); $subscriptionContainer .find(".recurpay__saving_amount") .html(subscriptionDiscountLabel); const oneTimeSaving = getOneTimeSavingValue(basePrice, getDiscountType, getDiscount, getPlanShipment); if (oneTimeSaving > 0) { if (getDiscountType === "percentage") { const oneTimeDiscountLabel = getOneTimeDiscountLabel(getDiscountType, getDiscount, oneTimeSaving); $oneTimeBanner .find(".recurpay__offer_saving_message_amount_text") .html(oneTimeDiscountLabel); $oneTimeBanner.find(".recurpay__saving_amount").html(formatPriceMoney(oneTimeSaving)); $oneTimeBanner.find(".recurpay__offer_saving_message_text").show(); } else { const oneTimeDiscountLabel = getOneTimeDiscountLabel(getDiscountType, getDiscount, oneTimeSaving); $oneTimeBanner.find(".recurpay__offer_saving_message_amount_text").html(""); $oneTimeBanner.find(".recurpay__saving_amount").html(""); $oneTimeBanner.find(".recurpay__offer_saving_message_text") .html(oneTimeDiscountLabel) .show(); } $oneTimeBanner.show(); } else { $oneTimeBanner.hide(); $oneTimeBanner.find(".recurpay__offer_saving_message_amount_text").html(""); $oneTimeBanner.find(".recurpay__saving_amount").html(""); } let recommendedCheck = $this.attr("data-recommended-frequency"); if ( recommendedCheck == "true" && $pdpWidget.find(".recurpay__frequency_select option").length > 1 ) { $this.parents(".recurpay__group_frequency").addClass("recommended_frequency"); } else { $this.parents(".recurpay__group_frequency").removeClass("recommended_frequency"); } if ( (recurpay.settings.sell_only_as_subscription == true || recurpay.product.onlySubscription == "true") && $pdpWidget.parents(".product__info-container").length ) { const $container = $pdpWidget.parents(".product__info-container"); if ($container.find(".price__container .price__sale .price-item.price-item--sale").length) { $container .find(".price__container .price__sale .price-item.price-item--sale") .html("" + formatPriceMoney(discountedTotalPrice) + ""); } if ($container.find(".price__container .price__regular .price-item").length) { $container .find(".price__container .price__regular .price-item") .html("" + formatPriceMoney(discountedTotalPrice) + ""); } } } $('.recurpay-pdp-widget[data-product-id="' + getProductId + '"]') .find(".recurpay__widget_container[data-type='onetime-purchase']") .find(".recurpay__group_selling_price") .html("" + formatPriceMoney(getVariantPrice) + ""); }); if (recurpay.hasOffers) { promotionalOffer($('.recurpay-pdp-widget[data-product-id="' + getProductId + '"]')); } } function offerSavings(e){const a=$(e),t=a.find('[name="recurpay__group_main"]:checked').val(),i=a.find(".recurpay__frequency_select option:selected"),n=parseFloat(i.attr("data-plan-discount")||0),r=(i.attr("data-plan-discount-type")||"percentage").toLowerCase(),c=a.parents(atcFormSelector).find('input[name="id"], select[name="id"], input#SelectedId').val()||recurpay.product.availableVariant;let p=0;if(c){const e=recurpay.calculatePrice(c);p=parseFloat(e.variant_price)||0}const s=parseInt(i.attr("data-plan-shipment")||1,10)||1,l=getOneTimeSavingValue(p,r,n,s),o=a.find(".recurpay__offer_onetime"),d=a.find(".recurpay__offer_subscription");o.hide(),d.hide(),"one-time"===t?l>0&&o.css("display","flex"):"subscription"===t&&("price"===r?(0===n||n0&&d.css("display","flex"))} function replaceTranslationPlaceholders(n,c){return n=n||"",Object.keys(c||{}).forEach(function(e){const l=null!=c[e]?c[e]:"";n=n.split(`[[${e}]]`).join(l)}),n} function getCurrencySymbolFromMoney(e){return e?e.replace(/[0-9.,\s]/g,""):""} function getDiscountDisplayValue(e,a){return"percentage"===e?parseFloat(a).toFixed(2).replace(/\.0+$/,"").replace(/\.00$/,""):formatPriceMoney(a)} function getOneTimeDiscountLabel(e,r,t){const i=recurpay?.settings?.translations||{},n=parseFloat(r)||0,o=parseFloat(t)||0,a=formatPriceMoney(n),_=formatPriceMoney(o),c=n.toFixed(2).replace(/\.0+$/,"").replace(/\.00$/,""),l=getCurrencySymbolFromMoney(formatPriceMoney(n));let m="";return m="percentage"===e?i.premium_one_time_percentage_discount_label||i.premium_one_time_discount_label||"[[DISCOUNT]]% ↓":"fixed"===e?i.premium_one_time_fixed_discount_label||"Save [[SAVING_AMOUNT]]":"price"===e?i.premium_one_time_price_discount_label||"Save [[SAVING_AMOUNT]]":i.premium_one_time_discount_label||"[[DISCOUNT]]% ↓",replaceTranslationPlaceholders(m,{DISCOUNT:"percentage"===e?c:a,DISCOUNT_PERCENTAGE:c,SAVING_AMOUNT:_,CURRENCY:l})} function getSubscriptionDiscountLabel(e,t,n){const r=recurpay?.settings?.translations||{},o=getDiscountDisplayValue(e,t),i=formatPriceMoney(n||0),s=getCurrencySymbolFromMoney(formatPriceMoney(t));let a=r.premium_subscription_discount_label||"[[SAVING_AMOUNT]]";return replaceTranslationPlaceholders(a,{DISCOUNT:o,DISCOUNT_PERCENTAGE:o,SAVING_AMOUNT:i,CURRENCY:s})} function normalizeProductPlans(product) { const topLevelPlans = Array.isArray(product?.plans) ? product.plans : []; const normalizedPlans = []; const seenKeys = new Set(); topLevelPlans.forEach(function(plan) { if (!plan) return; const groupProducts = Array.isArray(plan.products) ? plan.products : []; const groupShippingPolicy = plan.shipping_policy || {}; const groupId = plan.selling_plan_group_id || ""; const sellingPlans = Array.isArray(plan.selling_plans) && plan.selling_plans.length ? plan.selling_plans : [plan]; sellingPlans.forEach(function(sellingPlan, sellingPlanIndex) { if (!sellingPlan) return; const sellingPlanNumericId = sellingPlan.id != null ? String(sellingPlan.id) : ""; const sellingPlanGid = sellingPlan.selling_plan_id ? String(sellingPlan.selling_plan_id) : ""; const dedupeKey = sellingPlanGid || sellingPlanNumericId || `${groupId}::${sellingPlan.name || ""}::${sellingPlanIndex}`; if (seenKeys.has(dedupeKey)) return; seenKeys.add(dedupeKey); normalizedPlans.push({ id: sellingPlan.id != null ? sellingPlan.id : plan.id, parent_plan_id: plan.id, selling_plan_group_id: groupId, selling_plan_id: sellingPlan.selling_plan_id || "", name: sellingPlan.name || plan.name || "", description: sellingPlan.description || plan.description || "", delivery_policy: sellingPlan.delivery_policy || {}, billing_policy: sellingPlan.billing_policy || {}, pricing_polices: Array.isArray(sellingPlan.pricing_polices) ? sellingPlan.pricing_polices : [], position: sellingPlan.position != null ? sellingPlan.position : plan.position, recommended: sellingPlan.recommended != null ? !!sellingPlan.recommended : !!plan.recommended, type: plan.type || "regular", products: groupProducts, shipping_policy: groupShippingPolicy }); }); }); normalizedPlans.sort(function(a, b) { return (parseInt(a.position, 10) || 0) - (parseInt(b.position, 10) || 0); }); return normalizedPlans; } function getPlanShipmentCount(deliveryPolicy, billingPolicy) { var deliveryFrequency = parseInt(deliveryPolicy?.frequency, 10) || 0; var billingFrequency = parseInt(billingPolicy?.frequency, 10) || 0; var deliveryInterval = (deliveryPolicy?.interval || "").toLowerCase(); var billingInterval = (billingPolicy?.interval || "").toLowerCase(); if (!deliveryFrequency || !billingFrequency) return 1; if ( deliveryInterval && billingInterval && deliveryInterval === billingInterval && billingFrequency >= deliveryFrequency && billingFrequency % deliveryFrequency === 0 ) { return billingFrequency / deliveryFrequency; } return 1; } function recurPDP(data) { var prepaidCount = 0, regularCount = 0, prepaidDiscount = [], maxPrepaidDiscount = "", getPlanDesc = "", pdpTemplate = "", GetPlans = "", plans = Array.isArray(data?.plans) ? data.plans : []; const GetPlansLength = plans.length; $.each(plans, function(key, plan) { if (!plan) return; var DiscountPercentageHtml = "", DescriptionHtml = "", PlanHtml = "", PlanDiscount = 0, PlanDiscountType = "percentage", PlanType = "regular"; var pricingPolicy = ( Array.isArray(plan.pricing_polices) && plan.pricing_polices.length) ? plan.pricing_polices[0] : null; var deliveryPolicy = plan.delivery_policy || {}; var billingPolicy = plan.billing_policy || {}; var rawSellingPlanId = plan.selling_plan_id || ""; var sellingPlanId = rawSellingPlanId ? String(rawSellingPlanId).split("/").pop() : ""; var deliveryFrequency = parseInt(deliveryPolicy.frequency, 10) || ""; var deliveryInterval = deliveryPolicy.interval || ""; var billingFrequency = parseInt(billingPolicy.frequency, 10) || ""; var billingInterval = billingPolicy.interval || ""; var shipmentCount = getPlanShipmentCount(deliveryPolicy, billingPolicy); PlanType = plan.type || "regular"; if (shipmentCount > 1) { PlanType = "prepaid"; } if (PlanType === "prepaid") { prepaidCount += 1; if (pricingPolicy && pricingPolicy.discount) { prepaidDiscount.push(pricingPolicy.discount.value); } } else { regularCount += 1; } if (pricingPolicy && pricingPolicy.discount) { PlanDiscountType = pricingPolicy.discount.type || "percentage"; PlanDiscount = parseFloat(pricingPolicy.discount.value) || 0; if (PlanDiscount !== 0) { if (PlanDiscountType === "percentage") { DiscountPercentageHtml = '(' + PlanDiscount + '% Off)'; } else if (PlanDiscountType === "fixed") { DiscountPercentageHtml = '(Save ' + formatPriceMoney(PlanDiscount) + ')'; } else if (PlanDiscountType === "price") { DiscountPercentageHtml = '(Price ' + formatPriceMoney(PlanDiscount) + ')'; } } } if (plan.description) { DescriptionHtml = '"; } var optionAttrs = ' data-plan="' + (plan.id || "") + '"' + ' data-selling-plan="' + sellingPlanId + '"' + ' data-plan-name="' + (plan.name || "") + '"' + ' data-plan-shipment="' + shipmentCount + '"' + ' data-plan-discount="' + PlanDiscount + '"' + ' data-plan-discount-type="' + PlanDiscountType + '"' + ' data-delivery-frequency="' + deliveryFrequency + '"' + ' data-delivery-interval="' + deliveryInterval + '"' + ' data-billing-frequency="' + billingFrequency + '"' + ' data-billing-interval="' + billingInterval + '"' + ' data-plan-type="' + PlanType + '"' + ' data-recommended-frequency="' + (!!plan.recommended) + '"'; var optionAttrsWithoutSellingPlan = ' data-plan="' + (plan.id || "") + '"' + ' data-plan-name="' + (plan.name || "") + '"' + ' data-plan-shipment="' + shipmentCount + '"' + ' data-plan-discount="' + PlanDiscount + '"' + ' data-plan-discount-type="' + PlanDiscountType + '"' + ' data-delivery-frequency="' + deliveryFrequency + '"' + ' data-delivery-interval="' + deliveryInterval + '"' + ' data-billing-frequency="' + billingFrequency + '"' + ' data-billing-interval="' + billingInterval + '"' + ' data-plan-type="' + PlanType + '"' + ' data-recommended-frequency="' + (!!plan.recommended) + '"'; if (recurpay.checkout == "shopify") { if (plan.recommended === true) { PlanHtml += '"; } else { PlanHtml += '"; } } else { if (plan.recommended === true) { PlanHtml += '"; } else { PlanHtml += '"; } } GetPlans += PlanHtml; getPlanDesc += DescriptionHtml; }); if (regularCount > 0 && prepaidCount > 0 && prepaidDiscount.length) { maxPrepaidDiscount = Math.max.apply(Math, prepaidDiscount); } if (recurpay.subscriptionFirst == true) { pdpTemplate += '
'; } else { pdpTemplate += '
'; } pdpTemplate += '
'; pdpTemplate += ''; pdpTemplate += '
'; pdpTemplate += '
'; pdpTemplate += ''; pdpTemplate += '
' + recurpay.settings.translations.premium_subscription_label + "
"; pdpTemplate += '
' + recurpay.settings.translations.premium_subscription_label_description + "
"; pdpTemplate += '
'; pdpTemplate += '
'; pdpTemplate += '
'; pdpTemplate += '
'; let encodedPlans = encodeURIComponent(GetPlans); if ( recurpay.settings.translations.premium_frequency_dropdown_label != "" && recurpay.settings.translations.premium_frequency_dropdown_label != null && recurpay.settings.translations.premium_frequency_dropdown_label != undefined ) { pdpTemplate += '
' + recurpay.settings.translations.premium_frequency_dropdown_label + "
"; if (GetPlansLength == 1) { pdpTemplate += '"; } else { pdpTemplate += '"; } } else { if (GetPlansLength == 1) { pdpTemplate += '"; } else { pdpTemplate += '"; } } pdpTemplate += '
' + getPlanDesc + '
"; const hasOfferLabels = (recurpay.settings.translations.promotion_offer_applied_label || "") !== "" || (recurpay.settings.translations.promotion_view_offer_applied_label || "") !== ""; if (recurpay.hasOffers && hasOfferLabels) { pdpTemplate += '"; } pdpTemplate += "
"; pdpTemplate += '
' + recurpay.settings.translations.premium_one_time_saving_icon + ""; pdpTemplate += '
'; pdpTemplate += "" + recurpay.settings.translations.premium_one_time_saving_msg + ""; pdpTemplate += ''; pdpTemplate += ''; pdpTemplate += '' + recurpay.settings.translations.premium_one_time_saving_label + ""; pdpTemplate += "
"; pdpTemplate += '
' + recurpay.settings.translations.premium_subscription_saving_icon + ""; pdpTemplate += '
'; pdpTemplate += "" + recurpay.settings.translations.premium_subscription_saving_msg + ""; pdpTemplate += '' + recurpay.settings.translations.premium_subscription_discount_label + ""; pdpTemplate += '' + recurpay.settings.translations.premium_subscription_saving_label + ""; pdpTemplate += "
"; pdpTemplate += "
"; pdpTemplate += '
'; pdpTemplate += ''; pdpTemplate += '
'; pdpTemplate += '
'; pdpTemplate += '
'; pdpTemplate += ''; pdpTemplate += '
' + recurpay.settings.translations.premium_onetime_label + "
"; pdpTemplate += '
'; pdpTemplate += "
"; pdpTemplate += ''; pdpTemplate += ''; pdpTemplate += ''; if (recurpay.checkout == "shopify") { pdpTemplate += ''; } pdpTemplate = pdpTemplate .split("[[SAVING_AMOUNT]]") .join(""); pdpTemplate = pdpTemplate .split("[[SAVING_AMOUNT]]") .join(""); return pdpTemplate; } function updateGeneralSettings(primary_background,primary_foreground,secondary_background) { let settings_url=recurpay.generalURL+'/storefront/api/2024-07/widgets/configurations?'+recurpay.urlParam; $.ajax( { url:settings_url,type:"POST",data: { subscription_brand_color:primary_background,subscription_button_color:primary_background,subscription_button_text_color:primary_foreground,subscription_secondary_color:secondary_background,cart_upsell_brand_color:primary_background,cart_upsell_button_color:primary_background,cart_upsell_button_text_color:primary_foreground,cart_upsell_secondary_color:secondary_background }, success:function(response) { console.log(response); }, error:function(error) { console.log(error); } }); } if($(document).find(appBlockSelector).length > 0) { if($(document).find('.recurpay-pdp-widget').length <= 0) { if(window.location.href.indexOf("/products/") > -1 && $(document).find('.recurpay-pdp-widget').length <= 0) { $(document).find(appBlockSelector).append('
'); } else { $(document).find(appBlockSelector).each(function () { let $appBlock = $(this); let $productContainer = ""; if(window.location.href.indexOf("/collections/") > -1) { $productContainer = $appBlock.closest("li.product-grid__item"); } else { $productContainer = $appBlock.closest(".product__info-container, .product-info, .shop-product-info, .product-single__meta [data-product-blocks]"); } let $form = $productContainer.find(atcFormSelector); let product_id = $form.find("input[name='product-id']").val(); let default_variant_id = $form.find("input[name='id']").val(); $appBlock.append(`
`); }); } } } else if($(pdpSelector).length <= 0) { if(window.location.href.indexOf("/products/") > -1 && $(document).find(appBlockSelector).length <= 0) { if($(atcFormSelector).find(atcSelector).filter(':visible').length) { if($(atcFormSelector).find(atcSelector).filter(':visible').first().parent().css('display') == 'flex' && $(atcFormSelector).find(atcSelector).filter(':visible').first().parent().css('flex-direction') == 'row') { $(atcFormSelector).find(atcSelector).filter(':visible').first().parent().before('
'); } else if($(atcFormSelector).find(atcSelector).filter(':visible').first().parent().css('display') == 'grid' || $(atcFormSelector).find(atcSelector).filter(':visible').first().parent().css('display') == 'inline-grid') { $(atcFormSelector).find(atcSelector).filter(':visible').first().parent().before('
'); } else { if($(atcFormSelector).parents('.product__info-container').find(atcSelector).length) { $(atcFormSelector).parents('.product__info-container').find(atcSelector).filter(':visible').first().before('
'); } else { $(atcFormSelector).find(atcSelector).filter(':visible').first().before('
'); } } if($(pdpSelector).parent().css('position') == 'fixed' || $(pdpSelector).parent().css('position') == 'sticky' || $(pdpSelector).parent().css('position') == 'absolute' ) { $(pdpSelector).parent().addClass("recurpay-z-index"); } } else if($(atcFormSelector).find(atcSelector).length) { if($(atcFormSelector).find(atcSelector).first().parent().css('display') == 'flex' && $(atcFormSelector).find(atcSelector).filter(':visible').first().parent().css('flex-direction') == 'row') { $(atcFormSelector).find(atcSelector).first().parent().before('
'); } else { $(atcFormSelector).find(atcSelector).first().before('
'); } if($(pdpSelector).parent().css('position') == 'fixed' || $(pdpSelector).parent().css('position') == 'sticky' || $(pdpSelector).parent().css('position') == 'absolute' ) { $(pdpSelector).parent().addClass("recurpay-z-index"); } } else { $(atcFormSelector).append('
') } } } if($(pdpSelector).length) { recurpay.allProducts = []; for(i=0;i<$(pdpSelector).length; i++) { if($(pdpSelector).eq(i).attr("data-product-id") != undefined && $(pdpSelector).eq(i).attr("data-product-available") != undefined ) { recurpay.allProducts.push($(pdpSelector).eq(i).attr("data-product-id")); } } $.ajax({ url: recurpay.pdpAPI, type: 'POST', async: true, contentType: 'application/json', data: JSON.stringify({ products: recurpay.allProducts.map(id => ({ id: parseInt(id) })) }), success: function(response) { const payload = response?.data || {}; const rawProducts = Array.isArray(payload.products) ? payload.products : []; const settings = payload.configurations || {}; const store = payload.store || {}; const productMap = {}; rawProducts.forEach(function(product) { if (!product || !product.id) return; const productId = String(product.id); if (!productMap[productId]) { productMap[productId] = { ...product, plans: Array.isArray(product.plans) ? [...product.plans] : [], variants: Array.isArray(product.variants) ? [...product.variants] : [] }; } else { const existing = productMap[productId]; if (Array.isArray(product.plans)) { existing.plans = existing.plans.concat(product.plans); } if ((!existing.variants || !existing.variants.length) && Array.isArray(product.variants)) { existing.variants = product.variants; } } }); const normalizedProducts = Object.values(productMap).map(function(product) { return { ...product, plans: normalizeProductPlans(product) }; }); if (!normalizedProducts.length) { console.log("No products found in widget response", response); return; } const productsWithPlans = normalizedProducts.filter(function(product) { return Array.isArray(product.plans) && product.plans.length; }); if (!productsWithPlans.length) { console.log("No product/plans found in widget response", response); return; } recurpay.productDatas = normalizedProducts.map(function(product) { return { product: product }; }); if (settings.default_purchase_option === 'onetime') { recurpay.subscriptionFirst = false; } if (settings.default_purchase_redirection !== undefined) { recurpay.action = settings.default_purchase_redirection; } if (settings.translations && !$.isEmptyObject(settings.translations)) { recurpay.settings = settings; recurpay.hasOffers = !!settings.has_offers; recurpay.hasScript = !!settings.has_scripts; let brandPrimaryBg = recurpay.shop_brand_primary_background_color; let brandPrimaryFg = recurpay.shop_brand_primary_foreground_color; let brandSecondaryBg = recurpay.shop_brand_secondary_background_color; if ( settings.snippet_color_codes && settings.snippet_color_codes.is_default_widget_configuration && (brandPrimaryBg || brandSecondaryBg) ) { document.documentElement.style.setProperty('--recurpay_primary_color', brandPrimaryBg); document.documentElement.style.setProperty('--recurpay_secondary_color', brandSecondaryBg); document.documentElement.style.setProperty('--recurpay_button_text_color', brandPrimaryFg); document.documentElement.style.setProperty('--recurpay_button_bg_color', brandPrimaryBg); document.documentElement.style.setProperty('--recurpay_savings_bg_color', recurpay.hexToRgbA(brandPrimaryBg)); updateGeneralSettings(brandPrimaryBg, brandPrimaryFg, brandSecondaryBg); } else if (settings.snippet_color_codes) { document.documentElement.style.setProperty('--recurpay_primary_color', settings.snippet_color_codes.subscription_brand_color); document.documentElement.style.setProperty('--recurpay_secondary_color', settings.snippet_color_codes.subscription_secondary_color); document.documentElement.style.setProperty('--recurpay_button_text_color', settings.snippet_color_codes.subscription_button_text_color); document.documentElement.style.setProperty('--recurpay_button_bg_color', settings.snippet_color_codes.subscription_button_color); document.documentElement.style.setProperty('--recurpay_savings_bg_color', recurpay.hexToRgbA(settings.snippet_color_codes.subscription_brand_color)); } } recurpay.globalPlanObjectMap = recurpay.globalPlanObjectMap || {}; normalizedProducts.forEach(function(product) { const normalizedProduct = { id: parseInt(product.id, 10), plans: Array.isArray(product.plans) ? product.plans : [], variants: Array.isArray(product.variants) ? product.variants : [] }; if (!normalizedProduct.plans.length) return; recurpay.globalPlanObjectMap[String(normalizedProduct.id)] = normalizedProduct.plans; const pdpHTML = recurPDP(normalizedProduct); const getElem = $('.recurpay-pdp-widget[data-product-id="' + normalizedProduct.id + '"]'); if ($(getElem).length && $(getElem).attr("data-product-available") == "true") { $(getElem).html(pdpHTML); } if (normalizedProduct.variants.length) { const variantId = recurpay.product.availableVariant || normalizedProduct.variants[0].id; recurDiscountedPrice(variantId); recurpay.handlePlanOnVariant(variantId); } }); recurpay.hasOffers = settings.has_offers || false; recurpay.hasScript = settings.has_scripts || false; if ( recurpay.product.availableVariant !== "" && recurpay.product.availableVariant !== undefined ) { recurpay.product.selectedVariant = recurpay.product.availableVariant; recurDiscountedPrice(recurpay.product.availableVariant); recurpay.handlePlanOnVariant(recurpay.product.availableVariant); } else { const firstProductWithVariants = normalizedProducts.find(function(product) { return Array.isArray(product.variants) && product.variants.length; }); if (!firstProductWithVariants) { fetchVariants(); } } if (settings.sell_only_as_subscription === true) { updateSelectors(true); } else { updateSelectors(); } if (store.created_at) { const createdDate = new Date(store.created_at); const releaseDate = new Date('2024-07-16T00:00:00.000Z'); if (createdDate.toISOString().split('T')[0] < releaseDate.toISOString().split('T')[0]) { $(footerManageSubcriptionSelector).hide(); } } }, error: function(xhr) { console.log("PDP widget load failed", xhr); } }); if(window.location.href.indexOf("/products/") > -1) { var offersModalHTML = ""; offersModalHTML += '
' offersModalHTML += '
' offersModalHTML += '
' offersModalHTML += '
' offersModalHTML += '
' offersModalHTML += '' offersModalHTML += '
' offersModalHTML += '
' offersModalHTML += '
' if($('body').length) { $('body').append(offersModalHTML); } else if($('html').length) { $('html').append(offersModalHTML); } } } else { if((window.location.href.indexOf("/products/") > -1) && (window.location.href.indexOf("recurpay_preview=true") > -1)) { var domain_array = recurpay.shopDomainURL.split('.'); var domain_string = domain_array[0]; var recurpay_domain = 'https://' + domain_string + '.recurpay.com'; var modalHTML = ""; modalHTML += '
' modalHTML += '
' modalHTML += '
' modalHTML += '
' modalHTML += '
' modalHTML += '
' modalHTML += '' modalHTML += '
' modalHTML += 'Note: This is not visible to your customers' modalHTML += '
' modalHTML += '
' modalHTML += '
' modalHTML += '
Looks like the subscription option is not visible on your store due to some conflict with theme. Talk to us on Live Chat to get it resolved instantly
' modalHTML += '
' modalHTML += '
' if($('[data-recurpay-visibility-modal]').length <= 0) { if($('body').length) { $('body').append(modalHTML); } else if($('html').length) { $('html').append(modalHTML); } } } if((window.location.href.indexOf("/products/") > -1)) { recurpay.logEvent("product_widget","Failed to show product snippet", "critical"); } } function ordinalSuffix(n) { return["st","nd","rd"][((n+90)%100-10)%10-1]||"th" } function promotionalOffer(e){const r=$(e),t=r.find(".offer-applied-div"),o=$(".recurpay-preview-modal-container"),a=o.find(".bot-offer-wrapper");let i=1,n="",l=[];const s=parseInt(r.attr("data-product-id")),p=r.parents(atcFormSelector).find('[name="id"]'),c=r.parents(atcFormSelector).find('[name="quantity"]'),d=r.find('[name="recurpay-input"] option:selected'),_=parseInt(d.attr("data-plan")),f=d.attr("data-delivery-interval"),u=parseInt(d.attr("data-delivery-frequency"));return recurpay.hasOffers&&s&&d.length&&_?(recurpay.settings?.translations?.promotion_popup_heading_label&&$(".recurpay-preview-preview-title").html(recurpay.settings.translations.promotion_popup_heading_label),c.length&&(i=parseInt(c.val())||1),n=p.length?parseInt(p.val()):parseInt(r.attr("data-default-variant")),n?(l.push({variant_id:n,product_id:s,quantity:i,plan:{id:_,delivery_policy:{interval:f,frequency:u}}}),void $.ajax({url:recurpay.offersAPI,type:"POST",data:{product_set:l},async:!0,success:function(e){const r=e?.data?.applicable_offers;if(!0===e?.success&&Array.isArray(r)&&r.length>0){let e="",o=[];for(let e=0;e
',e+=''+t.cycle+""+o+'
order
',e+='
',e+="
",e+=''+l+"",e+="
")}),a.html(e),t.show()}else t.hide(),a.html(""),o.fadeOut()},error:function(){t.hide(),a.html(""),o.fadeOut()}})):(t.hide(),a.html(""),void o.fadeOut())):(t.hide(),a.html(""),void o.fadeOut())} function recurProperties(e){var a=$(e).parents(pdpSelector);if($(a).find("[name='recurpay__group_main'][value='subscription']").is(":checked")){var r=$(a).find('[name="recurpay-input"] option:selected').attr("data-plan-name"),t=$(a).find('[name="recurpay-input"] option:selected').attr("data-plan");if(e.closest(appBlockSelector).length>0?(e.closest(appBlockSelector).parents(appBlockParentSelector).find(atcFormSelector).find(".recurpay_plan_name").length<=0?e.closest(appBlockSelector).parents(appBlockParentSelector).find(atcFormSelector).append(``):e.closest(appBlockSelector).parents(appBlockParentSelector).find(atcFormSelector).find(".recurpay_plan_name").attr("name","properties[_Plan]").val(r),e.closest(appBlockSelector).parents(appBlockParentSelector).find(atcFormSelector).find(".recurpay_plan_id").length<=0?e.closest(appBlockSelector).parents(appBlockParentSelector).find(atcFormSelector).append(``):e.closest(appBlockSelector).parents(appBlockParentSelector).find(atcFormSelector).find(".recurpay_plan_id").attr("name","properties[_PlanId]").val(t)):($(a).find(".recurpay_plan_name").attr("name","properties[_Plan]").val(r),$(a).find(".recurpay_plan_id").attr("name","properties[_PlanId]").val(t)),parseInt(recurpay.subscriptionInfluence&&recurpay.subscriptionInfluenceCount)>=1&&(e.closest(appBlockSelector).length>0?e.closest(appBlockSelector).parents(appBlockParentSelector).find(atcFormSelector).find(".recurpay_purchase_data").length<=0?e.closest(appBlockSelector).parents(appBlockParentSelector).find(atcFormSelector).append(``):e.closest(appBlockSelector).parents(appBlockParentSelector).find(atcFormSelector).find(".recurpay_purchase_data").attr("name","properties[_PurchaseData]").val(recurpay.subscriptionInfluenceCount):$(a).find(".recurpay_purchase_data").attr("name","properties[_PurchaseData]").val(recurpay.subscriptionInfluenceCount)),$(a).find(".recurpay__description[data-description-id]").hide(),$(a).find('.recurpay__description[data-description-id="'+t+'"]').show(),"shopify"==recurpay.checkout){var n=$(a).find('[name="recurpay-input"] option:selected').attr("data-selling-plan");e.closest(appBlockSelector).length>0?e.closest(appBlockSelector).parents(appBlockParentSelector).find(atcFormSelector).find(".recurpay_selling_plan_id").length<=0?e.closest(appBlockSelector).parents(appBlockParentSelector).find(atcFormSelector).append(''):e.closest(appBlockSelector).parents(appBlockParentSelector).find(atcFormSelector).find(".recurpay_selling_plan_id").attr("name","selling_plan").val(n):$(a).find(".recurpay_selling_plan_id").attr("name","selling_plan").val(n),window._RestockRocket&&"function"==typeof window._RestockRocket.getSellingPlan&&($('.restock-rocket-form-input[name="selling_plan"]').attr("name",""),$(".restock-rocket-preorder-description").hide())}}else if(e.closest(appBlockSelector).length>0?(e.closest(appBlockSelector).parents(appBlockParentSelector).find(atcFormSelector).find(".recurpay_plan_name").attr("name",""),e.closest(appBlockSelector).parents(appBlockParentSelector).find(atcFormSelector).find(".recurpay_plan_id").attr("name",""),e.closest(appBlockSelector).parents(appBlockParentSelector).find(atcFormSelector).find(".recurpay_purchase_data").attr("name","")):($(a).find(".recurpay_plan_name").attr("name",""),$(a).find(".recurpay_plan_id").attr("name",""),$(a).find(".recurpay_purchase_data").attr("name","")),"shopify"==recurpay.checkout&&(e.closest(appBlockSelector).length>0?e.closest(appBlockSelector).parents(appBlockParentSelector).find(atcFormSelector).find(".recurpay_selling_plan_id").attr("name",""):$(a).find(".recurpay_selling_plan_id").attr("name",""),window._RestockRocket&&"function"==typeof window._RestockRocket.getSellingPlan)){var p=window._RestockRocket.getSellingPlan();$(".restock-rocket-form-input").attr("name","selling_plan"),$(".restock-rocket-form-input").val(p.shopify_selling_plan_id),$(".restock-rocket-preorder-description").show()}offerSavings(a),recurpay.hasOffers&&promotionalOffer(a)} function addSubscription(btn) { let $appBlock = $(btn).closest(appBlockSelector); let isInsideAppBlock = $appBlock.length > 0 && $(pdpSelector).closest(appBlockSelector).length > 0; let $form = null; if ($appBlock.parents(appBlockParentSelector).length && $appBlock.parents(appBlockParentSelector).find(atcSelector).length) { $form = isInsideAppBlock ? $appBlock.parents(appBlockParentSelector).find(atcSelector).parents(atcFormSelector) : $(btn).parents(atcFormSelector); } else if ($appBlock.closest(".product-grid__item").length && $appBlock.closest(".product-grid__item").find(atcSelector).length) { $form = isInsideAppBlock ? $appBlock.closest(".product-grid__item").find(atcSelector).parents(atcFormSelector) : $(btn).parents(atcFormSelector); } else { $form = isInsideAppBlock ? $(atcSelector).parents(atcFormSelector) : $(btn).parents(atcFormSelector); } let $variantSelector = $form.find('[name="id"]'); let $quantitySelector = $form.find('[name="quantity"]'); let $inputSelect = isInsideAppBlock ? $appBlock.find(pdpSelector).find('[name="recurpay-input"] option:selected') : $form.find(pdpSelector).find('[name="recurpay-input"] option:selected'); let subscriptionPlanId = $inputSelect.attr('data-plan') || ''; let subscriptionPlanName = $inputSelect.attr('data-plan-name') || ''; let subscriptionPlanType = $inputSelect.attr('data-plan-type') || ''; let planVariant = $variantSelector.length > 0 ? parseInt($variantSelector.val()) : parseInt(recurpay.product.availableVariant); let planQuantity = $quantitySelector.length > 0 ? parseInt($quantitySelector.val()) : 1; recurProperties($(btn).closest(pdpSelector).find('[name="recurpay__group_main"]')); let planParams = {}; if (recurpay.checkout == "shopify") { let sellingPlanId = isInsideAppBlock ? $appBlock.find(pdpSelector).find('[name="recurpay-input"] option:selected').attr('data-selling-plan') : $form.find(pdpSelector).find('[name="recurpay-input"] option:selected').attr('data-selling-plan'); if (!sellingPlanId || sellingPlanId === 'undefined' || sellingPlanId === 'null') { console.warn('[Recurpay] selling_plan ID is missing — cannot add subscription to cart.'); return; } planParams = { id: planVariant, quantity: planQuantity, selling_plan: sellingPlanId, properties: { '_Plan': subscriptionPlanName, '_PlanId': subscriptionPlanId } }; } else { planParams = { id: planVariant, quantity: planQuantity, properties: { '_Plan': subscriptionPlanName, '_PlanId': subscriptionPlanId } }; } if (recurpay.checkout == "recurpay" && !recurpay.prepaidMixedCart && subscriptionPlanType == "prepaid") { $.getJSON('/cart', function(response) { response.items = []; response.items.push(planParams); recurpay.recurCart(response); }); } else { if (recurpay.action == "default" && $(atcFormSelector).find(atcSelector).length) { $form.find(atcSelector).click(); } else { $.ajax({ type: 'POST', url: '/cart/add.js', dataType: 'json', data: planParams, success: function() { if (recurpay.checkout == "recurpay" && recurpay.action == "checkout") { $.getJSON('/cart', function(response) { recurpay.recurCart(response); }); } else if (recurpay.action == "cart") { document.location.href = '/cart'; } else { document.location.href = '/checkout'; } }, error: function(xhr) { var err = eval("(" + xhr.responseText + ")"); $('[data-recurpay-error]').html(err.description).show().delay(3000).fadeOut(); } }); } } } function loadRecurpayScripts() { $.ajax( { url:recurpay.scriptsAPI,type:'GET',async:true,success:function(htmlContent) { if(!$.trim(htmlContent))return; var $tempDiv=$('
').html(htmlContent); $tempDiv.find('style').each(function() { $('head').append($('