UNPKG

@spot-flow/vue-spotflow-checkout

Version:

This **Spotflow Vue.js library** wraps around the [inline library](https://github.com/Spotflow-One/spotflow-checkout-inline), which enables users to make payments seamlessly. It integrates smoothly into your Vue.js application, providing a streamlined ch

79 lines (78 loc) 2.37 kB
import { defineNuxtPlugin } from "nuxt/app"; import { ref, onUnmounted } from "vue"; let libraryPromise = null; function useSpotflowPayment() { const gateway = ref(null); const loadCdnScript = (cdnUrl) => { const script = document.createElement("script"); script.src = cdnUrl; script.defer = true; script.onload = () => { }; script.onerror = () => { console.error("Failed to load Spotflow Inline SDK script."); }; document.head.appendChild(script); }; const waitForLibrary = (timeout = 1e4) => { if (libraryPromise) { return libraryPromise; } libraryPromise = new Promise((resolve, reject) => { if (window.SpotflowCheckout) { return resolve(window.SpotflowCheckout); } const startTime = Date.now(); const checkInterval = setInterval(() => { if (window.SpotflowCheckout) { clearInterval(checkInterval); resolve(window.SpotflowCheckout); } else if (Date.now() - startTime > timeout) { clearInterval(checkInterval); reject(new Error( "SpotflowCheckout SDK not loaded after " + timeout + "ms. Ensure the CDN script is in your HTML." )); } }, 50); }); return libraryPromise; }; const loadSpotflow = async (options) => { const cdnUrl = "https://v1.inline-checkout.spotflow.one/dist/checkout-inline.js"; await loadCdnScript(cdnUrl); if (typeof window === "undefined") { throw new Error("SpotflowCheckout is not available in the window object"); } await waitForLibrary(); try { if (window.SpotflowCheckout) { const checkout = window.SpotflowCheckout; gateway.value = new checkout.CheckoutForm(); gateway.value.setup(options); } else { console.error("try to load popup error"); throw new Error("SpotflowCheckout SDK is not loaded"); } } catch (error) { console.error("Error loading popup:", error); } }; const cleanup = () => { if (gateway.value && typeof gateway.value.destroy === "function") { gateway.value.destroy(); } gateway.value = null; }; onUnmounted(cleanup); return loadSpotflow; } const plugin = defineNuxtPlugin(() => { return { provide: { paymentGateway: useSpotflowPayment() } }; }); export { plugin as default };