### Install XPay SDK via npm Source: https://github.com/xpayeg/xpay-js/blob/main/README.md Use this command to install the SDK package in projects using a bundler. ```bash npm install @xpayeg/sdk ``` -------------------------------- ### Include XPay SDK via CDN Source: https://github.com/xpayeg/xpay-js/blob/main/README.md Use this script tag for non-bundler setups to load the SDK directly in the browser. ```html ``` -------------------------------- ### Create Checkout Session on Server Source: https://github.com/xpayeg/xpay-js/blob/main/README.md Example Node.js endpoint to create a checkout session and return the clientSecret to the frontend. ```javascript // Your server (Node.js example) app.post('/api/create-checkout', async (req, res) => { const response = await fetch('https://api.xpay.app/checkout/sessions', { method: 'POST', headers: { 'Authorization': `Bearer ${process.env.XPAY_SECRET_KEY}`, 'Content-Type': 'application/json', }, body: JSON.stringify({ uiMode: 'custom', // 'custom' for Elements SDK, 'embedded' for drop-in modal, 'hosted' for redirect lineItems: [ { priceData: { unitAmount: 50000, // 500.00 EGP in piasters currency: 'EGP', productData: { name: 'Premium Plan' }, }, quantity: 1, }, ], afterCompletion: { type: 'redirect', redirect: { // {CHECKOUT_SESSION_ID} is automatically replaced with the actual session ID url: 'https://yoursite.com/success?session_id={CHECKOUT_SESSION_ID}', }, }, }), }); const session = await response.json(); res.json({ clientSecret: session.clientSecret }); }); ``` -------------------------------- ### Load XPay SDK Source: https://github.com/xpayeg/xpay-js/blob/main/README.md Load the SDK from the CDN. This should be called at the module level. ```javascript import { loadXPay } from '@xpayeg/sdk'; const xpay = await loadXPay('pk_test_xxx'); ``` -------------------------------- ### XPay.checkout() Source: https://github.com/xpayeg/xpay-js/blob/main/README.md Initializes the checkout modal overlay for processing payments. ```APIDOC ## XPay.checkout(options) ### Description Initializes a checkout session in a modal overlay. Requires a client secret and provides callbacks for completion and closure. ### Parameters - **clientSecret** (string) - Required - The secret key for the checkout session. - **mode** (string) - Required - Set to 'modal' for the overlay experience. - **onComplete** (function) - Optional - Callback triggered upon successful payment. - **onClose** (function) - Optional - Callback triggered when the user closes the modal. ``` -------------------------------- ### xpay.initCheckout(options) Source: https://github.com/xpayeg/xpay-js/blob/main/README.md Initializes a checkout session and returns an object containing session fields and action methods. ```APIDOC ## xpay.initCheckout(options) ### Description Initialize a checkout session. Resolves with a merged object containing session fields and action methods. ### Parameters - **options** (object) - Required - Configuration object including clientSecret, appearance, and locale. ### Example ```javascript const checkout = await xpay.initCheckout({ clientSecret: 'cs_test_abc_secret_xyz', appearance: { colorMode: 'dark' }, locale: 'ar', }); ``` ``` -------------------------------- ### Initialize Checkout with elements Source: https://github.com/xpayeg/xpay-js/blob/main/README.md Provides event-driven initialization for lower-level control over the checkout lifecycle. ```javascript const xpay = await loadXPay('pk_test_xxx'); const elements = xpay.elements({ clientSecret }); elements.on('ready', ({ session }) => { console.log(session.status); // { type: "open" } console.log(session.canConfirm); // true console.log(session.amountTotal); // 52450 console.log(session.paymentMethods); // [{ type: 'card', ... }] }); elements.on('loaderror', (event) => { // Only fires for actual failures (invalid secret, network error, etc.) // event: { type: "invalid_request_error" | "api_error" | "network_error", message, code?, param?, docUrl? } console.error('Failed to load:', event.message); }); elements.on('error', (error) => { // Fires for unsolicited errors not triggered by a merchant action. // Examples: session expired during fee recalculation when switching payment methods, BIN detection failure. console.log(error.type); // "invalid_request_error" console.log(error.code); // "checkout_session_expired" console.log(error.message); // "This checkout session has expired" console.log(error.docUrl); // "https://docs.xpay.app/api/errors#checkout_session_expired" }); ``` -------------------------------- ### loadXPay(publishableKey) Source: https://github.com/xpayeg/xpay-js/blob/main/README.md Loads the XPay SDK from the CDN. This should be called at the module level. ```APIDOC ## loadXPay(publishableKey) ### Description Loads the XPay SDK from CDN. Returns a Promise. Call at module level, not inside components. ### Parameters - **publishableKey** (string) - Required - The public key for your XPay account. ### Example ```javascript import { loadXPay } from '@xpayeg/sdk'; const xpay = await loadXPay('pk_test_xxx'); ``` ``` -------------------------------- ### xpay.elements(options) Source: https://github.com/xpayeg/xpay-js/blob/main/README.md Creates an Elements instance for mounting payment elements. ```APIDOC ## xpay.elements(options) ### Description Create an Elements instance for mounting payment elements. ### Parameters - **options** (object) - Required - Configuration options for the elements instance. ``` -------------------------------- ### xpay.checkout(options) Source: https://github.com/xpayeg/xpay-js/blob/main/README.md Creates a drop-in checkout instance, either modal or inline. ```APIDOC ## xpay.checkout(options) ### Description Create a drop-in checkout instance (modal or inline). ### Parameters - **options** (object) - Required - Configuration options for the checkout instance. ``` -------------------------------- ### initCheckout(options) Source: https://github.com/xpayeg/xpay-js/blob/main/README.md Initializes a checkout session and returns an object containing session fields and action methods. ```APIDOC ## initCheckout(options) ### Description Initializes a checkout session using a client secret. Returns a combined object containing session state fields and methods to interact with the checkout. ### Parameters - **options** (object) - Required - **clientSecret** (string | Promise) - Required - The client secret obtained from your server. ### Response - **checkout** (object) - Returns an object containing: - **id** (string) - Session ID - **status** (SessionStatus) - Structured status object - **canConfirm** (boolean) - Whether the session is ready for confirmation - **amountTotal** (number) - Final total in smallest currency unit - **amountSubtotal** (number) - Subtotal before fees/discounts - **currency** (string) - ISO 4217 currency code - **merchantName** (string) - Merchant display name - **livemode** (boolean) - Whether live or test mode - **paymentMethods** (PaymentMethodInfo[]) - Available payment methods - **lineItems** (LineItemDto[]) - Line items with prices and quantities - **totalDetails** (TotalDetailsResponseDto) - Breakdown of fees, discounts, VAT - **discounts** (DiscountResponseDto[]) - Applied discounts ``` -------------------------------- ### Implement Drop-in Modal Checkout Source: https://github.com/xpayeg/xpay-js/blob/main/README.md Opens the full checkout experience in a modal overlay using the XPay SDK. Requires the SDK script to be loaded and a valid client secret. ```html ``` -------------------------------- ### elements(options) Source: https://github.com/xpayeg/xpay-js/blob/main/README.md Initializes an event-driven interface for lower-level control over the checkout session. ```APIDOC ## elements(options) ### Description Creates an elements instance for event-driven initialization. This allows listening to lifecycle events like 'ready', 'loaderror', and 'error'. ### Parameters - **options** (object) - Required - **clientSecret** (string) - Required - The client secret obtained from your server. ### Events - **ready** - Fired when the session is initialized. Provides the session object. - **loaderror** - Fired on initialization failures (e.g., invalid secret, network error). - **error** - Fired for unsolicited errors during the session lifecycle. ``` -------------------------------- ### xpay.initCheckout Source: https://github.com/xpayeg/xpay-js/blob/main/README.md Initializes the checkout session using a client secret. ```APIDOC ## xpay.initCheckout(options) ### Description Initializes the checkout session to prepare for payment processing. ### Parameters - **clientSecret** (string) - Required - The secret key provided by the server to initialize the session. ``` -------------------------------- ### useCheckout() Source: https://github.com/xpayeg/xpay-js/blob/main/README.md React hook for managing checkout state and confirmation. ```APIDOC ## useCheckout() ### Description A React hook provided by @xpayeg/react that manages loading states, error handling, and checkout confirmation. ### Returns - **checkoutState** (object) - Contains the current state (loading, error, or checkout data). - **confirm** (function) - A function to trigger the payment confirmation with customer details. ``` -------------------------------- ### Initialize Checkout with initCheckout Source: https://github.com/xpayeg/xpay-js/blob/main/README.md Initializes a checkout session and retrieves session fields and action methods in a single object. ```javascript import { loadXPay } from '@xpayeg/sdk'; const xpay = await loadXPay('pk_test_xxx'); // Fetch client secret from your server const { clientSecret } = await fetch('/api/create-checkout', { method: 'POST' }).then(r => r.json()); // Initialize checkout -- returns session data + action methods in one object const checkout = await xpay.initCheckout({ clientSecret }); // Destructure session fields and actions together const { status, currency, amountTotal, amountSubtotal, canConfirm, paymentMethods, confirm, applyPromotionCode, removePromotionCode, updateLineItemQuantity, } = checkout; // Display in your UI document.getElementById('total').textContent = `${currency} ${(amountTotal / 100).toFixed(2)}`; document.getElementById('methods').textContent = `Pay with: ${paymentMethods.map(pm => pm.displayName).join(', ')}`; ``` ```javascript const checkout = await xpay.initCheckout({ clientSecret: fetch('/api/create-checkout', { method: 'POST' }) .then(r => r.json()) .then(data => data.clientSecret), }); ``` -------------------------------- ### Integrate Checkout with React Source: https://github.com/xpayeg/xpay-js/blob/main/README.md Uses the useCheckout hook from @xpayeg/react to manage loading, error, and checkout states. Requires the @xpayeg/react package. ```javascript import { useCheckout } from '@xpayeg/react'; function CheckoutPage() { const checkoutState = useCheckout(); if (checkoutState.type === 'loading') { return ; } if (checkoutState.type === 'error') { return
Error: {checkoutState.error.message}
; } const { currency, lineItems, amountTotal, confirm } = checkoutState.checkout; return (

Total: {currency} {(amountTotal / 100).toFixed(2)}

{lineItems?.map(item => (
{item.price.product.name} x {item.quantity}
))}
); } ``` -------------------------------- ### Import XPay TypeScript types Source: https://github.com/xpayeg/xpay-js/blob/main/README.md Import the required types from the @xpayeg/sdk package to enable full TypeScript support. ```typescript import type { XPayInstance, Elements, PaymentMethodInfo, CheckoutSession, SessionStatus, CustomerDetails, Appearance, InitCheckoutResult, CheckoutActions, ActionResult, XPayError, CheckoutLineItem, CheckoutTotalDetails, CheckoutFees, CheckoutDiscount, } from '@xpayeg/sdk'; ``` -------------------------------- ### elements.create('payment') Source: https://github.com/xpayeg/xpay-js/blob/main/README.md Creates a payment element to handle method selection and card input. ```APIDOC ## elements.create('payment') ### Description Creates a payment element instance that can be mounted to the DOM. ### Methods - **mount(selector)**: Mounts the payment element to the specified DOM element. - **on('change', callback)**: Listens for changes in the payment form state. ``` -------------------------------- ### Initialize Checkout Session Source: https://github.com/xpayeg/xpay-js/blob/main/README.md Initialize a checkout session with a client secret and optional configuration. ```javascript const checkout = await xpay.initCheckout({ clientSecret: 'cs_test_abc_secret_xyz', // string | Promise appearance: { colorMode: 'dark' }, locale: 'ar', }); // Session fields: status, canConfirm, amountTotal, currency, paymentMethods, lineItems, totalDetails, ... // Action methods: confirm(), applyPromotionCode(), removePromotionCode(), updateLineItemQuantity(), // submit(), fetchUpdates(), changeAppearance(), on(), getElements() ``` -------------------------------- ### checkout.on('change', callback) Source: https://github.com/xpayeg/xpay-js/blob/main/README.md Registers a listener for session changes, such as promo code updates, quantity changes, or payment method selection. ```APIDOC ## on('change', callback) ### Description Registers a callback function that is triggered whenever the CheckoutSession is updated. ### Parameters - **event** (string) - Required - Must be 'change'. - **callback** (function) - Required - Function receiving the updated 'session' object. ``` -------------------------------- ### Customize Checkout Appearance Source: https://github.com/xpayeg/xpay-js/blob/main/README.md Override branding settings during initialization or update them dynamically using changeAppearance. ```javascript const checkout = await xpay.initCheckout({ clientSecret, appearance: { colorMode: 'dark', borderStyle: 'pill', inputStyle: 'filled', colors: { primary: '#FF6B35' }, }, }); // Update later with changeAppearance() checkout.changeAppearance({ colorMode: 'light' }); ``` ```javascript const elements = xpay.elements({ clientSecret, appearance: { colorMode: 'dark' } }); elements.changeAppearance({ colorMode: 'light' }); ``` -------------------------------- ### Mount the Payment Element Source: https://github.com/xpayeg/xpay-js/blob/main/README.md Initializes the checkout and mounts the payment element to a DOM node. The change event listener is used to toggle the submit button state based on form completion. ```javascript const checkout = await xpay.initCheckout({ clientSecret }); const elements = checkout.getElements(); const paymentElement = elements.create('payment'); paymentElement.mount('#payment-element'); paymentElement.on('change', (event) => { submitButton.disabled = !event.complete; console.log(event.value.type); // 'card', 'valu', etc. }); ``` -------------------------------- ### checkout.applyPromotionCode Source: https://github.com/xpayeg/xpay-js/blob/main/README.md Applies a promotion code to the current checkout session. ```APIDOC ## applyPromotionCode(code) ### Description Applies a promotion code to the current checkout session. ### Parameters - **code** (string) - Required - The promotion code string to apply. ### Returns - **Promise** - Resolves to an object with type 'success' and the session, or type 'error' with an error message. ``` -------------------------------- ### elements.fetchUpdates Source: https://github.com/xpayeg/xpay-js/blob/main/README.md Forces a fresh fetch of the checkout session from the server. ```APIDOC ## fetchUpdates() ### Description Forces a fresh session fetch from the server. ### Returns - **Promise** - Resolves to an object with type 'success' and the updated session, or type 'error'. ``` -------------------------------- ### xpay.confirmPayment(options) Source: https://github.com/xpayeg/xpay-js/blob/main/README.md Confirms and submits a payment using the classic API. ```APIDOC ## xpay.confirmPayment(options) ### Description Confirm and submit a payment (classic API). ### Parameters - **options** (object) - Required - Configuration options for confirming the payment. ``` -------------------------------- ### Retrieve Checkout Session on Server Source: https://github.com/xpayeg/xpay-js/blob/main/README.md Fetches session details from the XPay API using a secret key to verify order status. ```javascript // Your server -- retrieves session using your API key app.get('/api/order-status', async (req, res) => { const response = await fetch( `https://api.xpay.app/checkout/sessions/${req.query.session_id}`, { headers: { 'Authorization': `Bearer ${process.env.XPAY_SECRET_KEY}` } }, ); const session = await response.json(); res.json(session); }); ``` -------------------------------- ### elements.submit Source: https://github.com/xpayeg/xpay-js/blob/main/README.md Validates all fields in the payment form before confirmation. ```APIDOC ## elements.submit() ### Description Validates all fields and returns the selected payment method if successful. ``` -------------------------------- ### Handle Webhook Events Source: https://github.com/xpayeg/xpay-js/blob/main/README.md Listens for checkout.session.completed events to trigger order fulfillment logic. ```javascript app.post('/webhooks/xpay', (req, res) => { const event = req.body; if (event.type === 'checkout.session.completed') { fulfillOrder(event.data); // Ship product, send email, update DB } res.json({ received: true }); }); ``` -------------------------------- ### Check Session Status Source: https://github.com/xpayeg/xpay-js/blob/main/README.md Demonstrates how to handle the structured status object returned by the checkout session. ```javascript // Check session status if (checkout.status.type === 'open') { // Session is active, show payment form } if (checkout.status.type === 'expired') { // Session expired, show message or create a new one showMessage('This checkout session has expired.'); } if (checkout.status.type === 'complete') { // Payment finished -- check paymentStatus for details console.log(checkout.status.paymentStatus); // "paid" showMessage('Payment successful!'); } ``` -------------------------------- ### Display Order Status on Client Source: https://github.com/xpayeg/xpay-js/blob/main/README.md Retrieves the session ID from the URL and updates the DOM with payment status and order totals. ```javascript const sessionId = new URLSearchParams(window.location.search).get('session_id'); const session = await fetch(`/api/order-status?session_id=${sessionId}`).then(r => r.json()); document.getElementById('status').textContent = session.paymentStatus === 'paid' ? 'Payment Confirmed' : 'Processing...'; document.getElementById('total').textContent = `${session.currency} ${(session.amountTotal / 100).toFixed(2)}`; // Amounts breakdown // session.totalDetails.amountDiscount -- 0 // session.totalDetails.amountPlatformFee -- 1750 (Processing Fee, if fees pass-through) // session.totalDetails.amountCollectedVat -- 700 (VAT) // session.totalDetails.amountShipping -- 0 // session.totalDetails.amountTax -- 0 // Line items session.lineItems?.forEach(item => { console.log(item.price.product.name, 'x', item.quantity, '=', item.amountTotal); }); ``` -------------------------------- ### Listen for Session Changes Source: https://github.com/xpayeg/xpay-js/blob/main/README.md Event listeners to react to session updates, including amount breakdowns and item changes. ```javascript // initCheckout -- use on('change', ...) checkout.on('change', (session) => { totalDiv.textContent = `Total: ${session.currency} ${(session.amountTotal / 100).toFixed(2)}`; // Amounts breakdown via totalDetails console.log(session.totalDetails?.amountPlatformFee); // Processing fee console.log(session.totalDetails?.amountCollectedVat); // VAT console.log(session.totalDetails?.amountDiscount); // Discount amount console.log(session.totalDetails?.amountShipping); // Shipping console.log(session.totalDetails?.amountTax); // Tax console.log(session.discounts); // Applied discounts console.log(session.lineItems); // Updated line items }); ``` ```javascript elements.on('change', (session) => { console.log(session.amountTotal); console.log(session.totalDetails?.amountPlatformFee); }); ``` -------------------------------- ### Pre-validation with submit() Source: https://github.com/xpayeg/xpay-js/blob/main/README.md Validates form fields before proceeding to confirm the payment. ```javascript const { error, selectedPaymentMethod } = await elements.submit(); if (error) { errorDiv.textContent = error.message; return; } // Fields are valid, proceed to confirm const result = await checkout.confirm({ paymentMethod: selectedPaymentMethod }); ``` -------------------------------- ### Refresh Session Data Source: https://github.com/xpayeg/xpay-js/blob/main/README.md Manually trigger a fetch to synchronize the local session state with the server. ```javascript const result = await elements.fetchUpdates(); if (result.type === 'success') { console.log('Session refreshed:', result.session.amountTotal); } ``` -------------------------------- ### checkout.confirm Source: https://github.com/xpayeg/xpay-js/blob/main/README.md Confirms the payment and handles the transaction outcome. ```APIDOC ## checkout.confirm(options) ### Description Confirms the payment transaction. Returns a tagged union result. ### Parameters - **customerDetails** (object) - Optional - Object containing email, name, and phone. - **redirect** (string) - Optional - Defines redirect behavior: 'always' or 'if_required' (default). ``` -------------------------------- ### Migrate from CardElement to PaymentElement Source: https://github.com/xpayeg/xpay-js/blob/main/CHANGELOG.md Replace the deprecated card element with the unified payment element to support all payment methods. ```ts // Before const cardElement = elements.create("card"); cardElement.mount("#card"); // After const paymentElement = elements.create("payment"); paymentElement.mount("#payment"); ``` -------------------------------- ### Confirm Payment Source: https://github.com/xpayeg/xpay-js/blob/main/README.md Confirms the payment session. The redirect behavior can be controlled via the redirect parameter. ```javascript // Default behavior: returns result to your code (no redirect) const result = await checkout.confirm({ customerDetails: { email: 'customer@example.com', name: 'Ahmed Hassan', phone: '+201234567890', }, }); if (result.type === 'error') { errorDiv.textContent = result.error.message; } else { console.log(result.session.status); // { type: "complete", paymentStatus: "paid" } window.location.href = '/thank-you'; } ``` ```javascript await checkout.confirm({ customerDetails: { email: 'customer@example.com', name: 'Ahmed Hassan', }, redirect: 'always', // Redirect to afterCompletion.redirect.url }); // ^ If successful, the page navigates away. Code below only runs on error. ``` -------------------------------- ### Update Checkout Session State Source: https://github.com/xpayeg/xpay-js/blob/main/README.md Methods to apply or remove promotion codes and update line item quantities within the checkout session. ```javascript // Apply promotion code const result = await checkout.applyPromotionCode('SAVE20'); if (result.type === 'error') { errorDiv.textContent = result.error.message; // e.g., "Invalid promotion code" } else { console.log('New total:', result.session.amountTotal); } // Remove promotion code await checkout.removePromotionCode(); // Update line item quantity (object param, not positional) await checkout.updateLineItemQuantity({ lineItem: 'li_abc123', quantity: 3 }); ``` -------------------------------- ### checkout.updateLineItemQuantity Source: https://github.com/xpayeg/xpay-js/blob/main/README.md Updates the quantity of a specific line item in the checkout session. ```APIDOC ## updateLineItemQuantity(params) ### Description Updates the quantity of a specific line item. ### Parameters - **params** (object) - Required - Object containing 'lineItem' (string) and 'quantity' (number). ``` -------------------------------- ### checkout.removePromotionCode Source: https://github.com/xpayeg/xpay-js/blob/main/README.md Removes the currently applied promotion code from the checkout session. ```APIDOC ## removePromotionCode() ### Description Removes the currently applied promotion code from the checkout session. ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.