PageSourceSearch

https://www.advlaser.com/a/j/paypal-push-cart.js

js advlaser.com collected 2026-10-06 12:52:06 UTC 10,243 bytes, 264 lines download raw bytes

1const paypalPushCartBaseStoreUrl = window.location.origin.match(/^.+?[^/:](?=[?/]|$)/i)[0];
2
3const paypalPushCartGetCartId = () => {
4    const name = `CartID5=`;
5    try {
6        const decodedCookie = decodeURIComponent(document.cookie);
7        const ca = decodedCookie.split(";");
8        for (let i = 0; i < ca.length; i += 1) {
9            let c = ca[i];
10            while (c.charAt(0) === " ") {
11                c = c.substring(1);
12            }
13            if (c.indexOf(name) === 0) {
14                return c.substring(name.length, c.length);
15            }
16        }
17    } catch (e) {
18        const matches = document.cookie.match(`${name}([^;]+);?`);
19        if (matches && matches.length >= 2) {
20            return matches[1];
21        }
22    }
23
24    return "";
25};
26
27const paypalPushCartGetCartData = async (cartId) => {
28    try {
29        const response = await window.fetch(`${paypalPushCartBaseStoreUrl}/api/v1/carts/${cartId}`, {
30            credentials: "include",
31        });
32        const result = await response.json();
33        return result.data;
34    } catch (e) {
35        //
36    }
37    return {};
38};
39
40const paypalPushCartGetPayPalConfig = async () => {
41    const configResponse = await fetch(`${paypalPushCartBaseStoreUrl}/api/v1/config`);
42    const configBody = await configResponse.json();
43    const paypalConfig = configBody?.data?.paypalExpress ?? {};
44    return {
45        useNewCheckout: window.useNewCheckout && configBody?.data?.enabledState === "enabled",
46        isVenmo: false,
47        ...paypalConfig
48    }
49};
50
51const paypalPushCartHasNonZeroTotal = (cartData) => {
52    return cartData?.totals?.grandTotal > 0;
53};
54
55const paypalPushCartBuildPayPalRequest = (cartData, isDelayedCapture, defaultCurrency) => {
56    const captureMode = isDelayedCapture ? "authorize" : "sale";
57    const totals = cartData.totals ?? { grandTotal: 0, shipping: 0, taxTotal: 0 };
58    const paypalCartSubTotalValue = totals.grandTotal - (totals.shipping + totals.taxTotal);
59    return {
60        intent: captureMode,
61        payer: {
62            payment_method: "paypal",
63        },
64        transactions: {
65            Amount: {
66                currencyValue: defaultCurrency,
67                total: totals.grandTotal.toFixed(2),
68                details: {
69                    tax: totals.taxTotal.toFixed(2),
70                    shipping: totals.shipping.toFixed(2),
71                    subtotal: paypalCartSubTotalValue.toFixed(2),
72                },
73            },
74        },
75        redirect_urls: {
76            return_url: "https://www.paypal.com/checkoutnow/error",
77            cancel_url: "https://www.paypal.com/checkoutnow/error",
78        },
79    };
80};
81
82const paypalPushCartCreatePayPalOrder = async (paypalRequest) => {
83    let endpointLocation;
84    if (window.isUsingPpcp) {
85        endpointLocation = window.usePhpXferToNet ? '/a/php/net/Controllers/PayPalV2Controller.php?_route=paypalv2/order' : '/net/paypalv2/order';
86    } else {
87        endpointLocation = window.usePhpXferToNet ? '/a/php/net/Handlers/PayPalRestCreatePaymentHandler.php' : '/net/PayPalRestCreatePaymentHandler.ashx';
88    }
89    const response = await window.fetch(`${paypalPushCartBaseStoreUrl}${endpointLocation}`, {
90        method: "POST",
91        headers: { "Content-Type": "application/json;charset=UTF-8" },
92        body: JSON.stringify(paypalRequest),
93    });
94    return response.json();
95};
96
97const paypalPushCartAppendPayPalButtonDiv = () => {
98    const pushCartFooter = document.querySelector(".push-cart__footer");
99    const existingPayPalDiv = document.getElementById("paypal-cart-buttons");
100    if (pushCartFooter && !existingPayPalDiv) {
101        const payPalDiv = document.createElement("div");
102        payPalDiv.setAttribute("id", "paypal-cart-buttons");
103        payPalDiv.setAttribute("style", "margin-top: 10px;");
104        pushCartFooter.append(payPalDiv);
105    }
106};
107
108const paypalPushCartHasRecurringItem = (cartData) => {
109    return !!cartData?.items?.find(
110        item => item.pricing.recurringPrice.everyXMonths !== ''
111    );
112};
113
114function removePayPalDivFromPushCart() { 
115    const existingPayPalDiv = document.getElementById('paypalCartMessageDiv');
116    if (existingPayPalDiv) {
117        existingPayPalDiv.remove();
118    }
119}
120const paypalPushCartManageMessagingDiv = async () => {
121    const pushCartFooter = document.querySelector('.push-cart__payment');
122    const cartId = paypalPushCartGetCartId();
123    const cartData = await paypalPushCartGetCartData(cartId);
124    if (paypalPushCartHasRecurringItem(cartData)) {
125        removePayPalDivFromPushCart();
126        return;
127    }
128    if (!cartData?.totals?.grandTotal) {
129        removePayPalDivFromPushCart();
130        return;
131    }
132    if (pushCartFooter) {
133        const existingPayPalDiv = document.getElementById('paypalCartMessageDiv');
134        if (existingPayPalDiv) {
135            existingPayPalDiv.setAttribute('data-pp-amount', cartData.totals.grandTotal);
136        } else {
137            const payPalDiv = document.createElement('div');
138            payPalDiv.setAttribute('id', 'paypalCartMessageDiv');
139            payPalDiv.setAttribute('data-pp-message', '');
140            payPalDiv.setAttribute('data-pp-placement', 'cart');
141            payPalDiv.setAttribute('data-pp-style-layout', 'text');
142            payPalDiv.setAttribute('data-pp-style-logo-type', 'inline');
143            payPalDiv.setAttribute('data-pp-style-text-color', 'black');
144            payPalDiv.setAttribute('style', 'min-width: 290px; min-height: 30px;');
145            payPalDiv.setAttribute('data-pp-amount', cartData.totals.grandTotal);
146            pushCartFooter.prepend(payPalDiv);
147        }
148    }
149};
150
151const paypalPushCartRenderPayPalButtons = (cartData, paypalConfig) => {
152    const existingPayPalDiv = document.getElementById("paypal-cart-buttons");
153    if(existingPayPalDiv && existingPayPalDiv.children.length == 0) {
154        const { isDelayedCapture, defaultCurrency, useNewCheckout } = paypalConfig;
155        paypal
156            .Buttons({
157                style: {
158                    shape: "rect",
159                },
160                createOrder: async function (data, actions) {
161                    
162                    if (!cartData?.totals?.grandTotal) {
163                        alert("PayPal is not required for $0.00 orders. Please click 'Checkout' to proceed.");
164                        return;
165                    }
166                    const paypalRequest = paypalPushCartBuildPayPalRequest(cartData, isDelayedCapture, defaultCurrency);
167                    const result = await paypalPushCartCreatePayPalOrder(paypalRequest);
168                    return result.token;
169                },
170                onApprove: function (data, actions) {
171                    const queryString = `?token=${data.orderID}&PayerID=${data.payerID.toUpperCase()}&paymentId=${data.paymentID ? data.paymentID.toUpperCase() :  ''}`;
172                    if (useNewCheckout) {
173                        return actions.redirect(`${paypalPushCartBaseStoreUrl}/checkout/${queryString}
173&isVenmo=${paypalConfig.isVenmo}`);
174                    } else {
175                        return actions.redirect(`${paypalPushCartBaseStoreUrl}/one-page-checkout.asp${queryString}`);
176                    }
177                },
178                onClick: function (data, action) {
179                    paypalConfig.isVenmo = data.fundingSource?.toLowerCase() === 'venmo';
180                },
181                onCancel: function (data, actions) {
182                    //
183                },
184                onError: function (err) {
185                    //
186                },
187            })
188            .render("#paypal-cart-buttons");
189    }
190    else {
191        //TODO: update the paypal order attached to the buttons, when we have the capability
192    }
193};
194
195function removePaypalButtons() {
196    const existingPayPalDiv = document.getElementById("paypal-cart-buttons");
197    if(existingPayPalDiv) {
198        existingPayPalDiv.remove();
199    }
200}
201
202const paypalPushCartManagePaypalButtons = async () => {
203    const paypalConfig = await paypalPushCartGetPayPalConfig();
204    const cartId = paypalPushCartGetCartId();
205    const cartData = await paypalPushCartGetCartData(cartId);
206    if (paypalPushCartHasRecurringItem(cartData)) {
207        removePaypalButtons();
208        return;
209    }
210    if (!cartData?.totals?.grandTotal) {
211        removePaypalButtons();
212        return;
213    } 
214
215    setTimeout(() => {
216        paypalPushCartAppendPayPalButtonDiv();
217        paypalPushCartRenderPayPalButtons(cartData, paypalConfig);
218    }, 500);
219};
220
221const paypalPushCartManageMessagingElementOnceLoaded = () => {
222    const checkIfCartLoaded = window.setInterval(() => {
223        const loadingDiv = document.getElementsByClassName('push-cart--vol-loader__contents');
224        if (!loadingDiv.length) {
225            paypalPushCartManageMessagingDiv();
226            clearInterval(checkIfCartLoaded);
227        }
228    }, 200);
229};
230
231function addPaypalButtonsWhenPushCartOpen() {
232    const checkIfPushCartIsOpen = window.setInterval(() => {
233        const element = document.querySelector("body");
234        if (element) {
235            const className = element.className;
236            if (/push-cart-open/i.test(className)) {
237                paypalPushCartManagePaypalButtons();
238                clearInterval(checkIfPushCartIsOpen);
239            }
240        }
241    }, 200);
242}
243
244addPaypalButtonsWhenPushCartOpen();
245
246let paypalClassWatcher;
247function paypalPushCartAddClassNameWatcher() {
248    const checkAndSetClassWatch = window.setInterval(() => {
249        const element = document.querySelector('body');
250        if (element && !paypalClassWatcher) {
251            paypalClassWatcher = new ClassNameWatcher(
252                document.querySelector('body'),
253                'push-cart-open',
254                paypalPushCartManageMessagingElementOnceLoaded,
255                () => {},
256            );
257        }
258        if (element && paypalClassWatcher) {
259            clearInterval(checkAndSetClassWatch)
260        }
261    }, 500);
262}
263
264paypalPushCartAddClassNameWatcher();

Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.