Swell.js SDK

repository·master·Indexed 41 days ago

https://github.com/swellstores/swell-js

A headless ecommerce storefront SDK providing a client-safe JavaScript interface for Swell's Frontend API. Version 5.8.1 allows developers to build custom shopping experiences, including product and cart management, checkout flows, and customer accounts, in JAMstack and SSR environments using a public key and session token.

Tokens
19.1K
Snippets
70
Records
94
Agent score
50%

What's inside Swell.js

  1. Overview of Swell.js

    master

    Swell.js is a universal JavaScript SDK designed for interacting with Swell's Frontend API. It provides client-safe access to store and customer data, making it suitable for use in JAMstack or SSR (Server-Side Rendering) applications.

    Key capabilities include:

    • Product & Content Management: Fetch products, categories, store settings, navigation menus, and custom content.
    • Cart Management: Create, recover, and update shopping carts.
    • Checkout & Subscriptions: Build custom checkout and subscription flows.
    • Customer Management: Authenticate customers and manage account details, orders, and subscriptions.
    • Dynamic Content: Resolve linked content to generate page URLs and format prices according to the store's currency.

    Security Note: This SDK is authorized using a public key and a session token, making it safe for client-side use. For operations requiring secret keys, you must use Swell's Backend API in a server-side environment only.

  2. Integrate Bancontact payments

    master

    Bancontact integration uses Stripe Sources and does not require Stripe Elements. Note that Bancontact must always use eur currency.

    1. Create a Bancontact Source (Client Side)

    const source = await stripe.createSource({
      type: 'bancontact',
      amount: '<amount>',
      currency: 'eur',
      owner: {
        name: '<name>',
      },
      redirect: {
        return_url: '<return_url>',
      },
    });

    2. Authorize Payment

    Redirect the customer to the URL provided in source.redirect.url. After authorization, they will return to your return_url.

    3. Capture Payment in Swell

    When the user returns, check the URL query for redirect_status and the source ID, then update the Swell cart/order:

    const billing = {
      method: 'bancontact',
      bancontact: {
        source: '<source_id>',
      },
    };
    
    await swell.cart.update({ billing });
  3. Initialize a Saferpay Payment Page

    master

    To begin a transaction, you must send an initialization request to the Saferpay API. This request sets up the transaction details, including amount, currency, and the redirect URLs for success and failure scenarios.

    Key Request Fields:

    • Payment.Amount.Value & Payment.Amount.CurrencyCode: The transaction amount and currency.
    • Payment.OrderId: The ID of the order.
    • PaymentMethods: An array of supported methods. Note that Swell currently only supports card payment methods.
    • ReturnUrls.Success: The URL where the customer is redirected after a successful payment.
    • ReturnUrls.Fail: The URL where the customer is redirected if the payment fails.
    • RegisterAlias: (Optional) Used to save and reuse a payment card via IdGenerator: "MANUAL" and a unique Id.

    Response Handling: Upon success, Saferpay returns a Token and a RedirectUrl. You must save the Token for the assertion step and redirect the customer to the RedirectUrl to complete their payment.

    // POST: /Payment/v1/PaymentPage/Initialize
    {
      "RequestHeader": {
        "SpecVersion": "[current Spec-Version]",
        "CustomerId": "[your customer id]",
        "RequestId": "[unique request identifier]",
        "RetryIndicator": 0
      },
      "TerminalId": "[your terminal id]",
      "Payment": {
        "Amount": {
          "Value": "100",
          "CurrencyCode": "CHF"
        },
        "OrderId": "Id of the order",
        "Description": "Description of payment"
      },
      "RegisterAlias": {
        "IdGenerator": "MANUAL",
        "Id": "[unique random value]"
      },
      "PaymentMethods": ["card payment methods"],
      "ReturnUrls": {
        "Success": "[your shop payment success url]",
        "Fail": "[your shop payment fail url]"
      }
    }
    
    // RESPONSE
    {
      "ResponseHeader": {
        "SpecVersion": "[current Spec-Version]",
        "RequestId": "Id of the request"
      },
      "Token": "234uhfh78234hlasdfh8234e1234",
      "Expiration": "2015-01-30T12:45:22.258+01:00",
      "RedirectUrl": "https://www.saferpay.com/vt2/api/..."
    }
  4. Integrate iDEAL payments

    master

    iDEAL integration requires using Stripe Elements on the client side, creating a Payment Method, and then creating a Payment Intent on the server side.

    1. Create the iDEAL Element (Client Side)

    Mount the iDEAL element into an HTML container (e.g., <div id="stripe-ideal"></div>).

    const elements = stripe.elements();
    const ideal = elements.create('idealBank', options?);
    ideal.mount('#stripe-ideal');

    2. Create a Payment Method (Client Side)

    const result = await stripe.createPaymentMethod({
      type: 'ideal',
      ideal: idealElement,
      billing_details: {
        name: 'Jenny Rosen',
      },
    });

    3. Create a Payment Intent (Server Side)

    Pass the payment_method_id and a return_url to the Stripe API.

    await stripe.paymentIntents.create({
      payment_method: '<payment_method_id>',
      amount: '<amount in cents>',
      currency: 'eur',
      payment_method_types: 'ideal',
      confirmation_method: 'manual',
      confirm: true,
      return_url: '<return_url>',
    });

    4. Authorize Payment (Client Side)

    await stripe.handleCardAction(paymentIntent.client_secret);

    5. Capture Payment in Swell

    After the user is redirected back to your site, use the payment_intent ID from the URL query to update the Swell cart or order.

    const billing = {
      method: 'ideal',
      ideal: {
        token: '<payment_method_id>',
      },
      intent: {
        stripe: {
          id: '<payment_intent_id>',
        }
      },
    };
    
    // Using Swell JS library
    await swell.cart.update({ billing });
  5. Enable Klarna, iDEAL, and Bancontact in Swell

    master

    Before integrating these payment methods, you must enable them in your Swell dashboard:

    1. Connect a Stripe account to Swell via Settings > Payments.
    2. Open Advanced options under the Stripe settings.
    3. Check the boxes for Enable Klarna, Enable iDEAL, and/or Enable Bancontact.
  6. Capture Saferpay payment via Assertion

    master

    Once the customer has been redirected back to your store (via the ReturnUrls.Success URL), you must verify the transaction by sending an assertion request to Saferpay. This step confirms the payment details and provides the card information needed to finalize the order.

    Request: Send a POST to /Payment/v1/PaymentPage/Assert containing the Token received during the initialization step.

    Response: The response contains RegistrationResult.Alias.Id (if a card was saved) and PaymentMeans, which includes details like Brand.Name, Card.ExpMonth, Card.ExpYear, and Card.MaskedNumber.

    // POST: /Payment/v1/PaymentPage/Assert
    {
      "RequestHeader": {
        "SpecVersion": "[current Spec-Version]",
        "CustomerId": "[your customer id]",
        "RequestId": "[unique request identifier]",
        "RetryIndicator": 0
      },
      "Token": "234uhfh78234hlasdfh8234e1234"
    }
    
    // RESPONSE
    {
      "RegistrationResult": {
        "Alias": {
          "Id": "alias35nfd9mkzfw0x57iwx"
        }
      },
      "PaymentMeans": {
        "Brand": {
          "PaymentMethod": "VISA",
          "Name": "VISA Saferpay Test"
        },
        "DisplayText": "9123 45xx xxxx 1234",
        "Card": {
          "MaskedNumber": "912345xxxxxx1234",
          "ExpYear": 2015,
          "ExpMonth": 9,
          "HolderName": "Max Mustermann",
          "CountryCode": "CH"
        }
      }
    }
  7. Integrate Klarna payments

    master

    Klarna integration uses Stripe Sources and does not require Stripe Elements.

    1. Create a Klarna Source (Client Side)

    const source = await stripe.createSource({
      type: 'klarna',
      flow: 'redirect',
      amount: '<amount>',
      currency: '<iso currency code>',
      klarna: {
        product: 'payment',
        purchase_country: '<2-digit country code>',
      },
      source_order: {
        items: '<items>',
      },
      redirect: {
        return_url: '<return_url>',
      },
    });

    2. Authorize Payment

    Redirect the customer to the URL provided in source.redirect.url. After authorization, they will return to your return_url.

    3. Capture Payment in Swell

    When the user returns, check the URL query for redirect_status and the source ID, then update the Swell cart/order:

    const billing = {
      method: 'klarna',
      klarna: {
        source: '<source_id>',
      },
    };
    
    await swell.cart.update({ billing });
  8. Include and initialize Stripe.js

    master

    To use Stripe on the client side, you must include Stripe.js on your payment page. You can load it via a script tag or use the @stripe/stripe-js npm package.

    Loading via Script Tag

    <script src="https://js.stripe.com/v3/"></script>

    Loading via NPM Module

    import { loadStripe } from '@stripe/stripe-js';
    const stripe = await loadStstripe('pk_test_...');

    Initializing with Publishable Key

    If you loaded via a script tag:

    const stripe = Stripe('pk_test_...');
    // Client side
    const stripe = Stripe('pk_test_...');
  9. Initialize the SwellClient

    master

    To use the SDK, you must initialize the SwellClient. You can use the default exported instance or create a new instance using create. The client supports both snake_case (default) and camelCase data formats via the useCamelCase option.

    Configuration Options

    When initializing, you can pass an InitOptions object:

    • store: The store ID.
    • key: The public API key.
    • useCamelCase: Set to true to use camelCase for all response data.
    • currency: Default currency code.
    • locale: Default locale.
    • previewContent: Boolean to enable preview mode for content.
    • session: Session identifier.
    • url: Custom API URL.
    • vaultUrl: Custom vault URL.
    • headers: Custom headers for requests.
    • getCart / updateCart: Functions to override default cart behavior.
    • setCookie / getCookie: Functions to manage client-side cookies.
    // Using the default instance (snake_case)
    import swell from 'swell-js';
    swell.init('YOUR_STORE_ID', 'YOUR_PUBLIC_KEY');
    
    // Creating a new instance with camelCase
    import { create } from 'swell-js';
    const client = create('YOUR_STORE_ID', 'YOUR_PUBLIC_KEY', {
      useCamelCase: true,
      currency: 'USD',
      locale: 'en-US'
    });
  10. Finalize Order with Saferpay billing details

    master

    After asserting the payment, you must attach the payment details to the Swell cart or order. Use the data returned from the Saferpay assertion response to construct the billing object.

    Billing Object Mapping:

    • method: Set to 'card'.
    • card.token: Use RegistrationResult.Alias.Id.
    • card.exp_month: Use PaymentMeans.Card.ExpMonth.
    • card.exp_year: Use PaymentMeans.Card.ExpYear.
    • card.brand: Use PaymentMeans.Brand.Name.
    • card.last4: Extract the last 4 characters from PaymentMeans.Card.MaskedNumber.
    • card.gateway: Must be set to 'saferpay'.
    const billing = {
      method: 'card',
      card: {
        token: RegistrationResult.Alias.Id,
        exp_month: PaymentMeans.Card.ExpMonth,
        exp_year: PaymentMeans.Card.ExpYear,
        brand: PaymentMeans.Brand.Name,
        last4: "[last 4 characters from 'PaymentMeans.Card.MaskedNumber']",
        gateway: 'saferpay',
      },
    };
    
    // Using Swell JS library
    await swell.cart.update({ billing });
    await swell.cart.submitOrder();
    
    // Using Swell Node.js library
    const cart = await swell.put('/carts/<id>', { billing });
    await swell.post('/orders', { cart_id: cart.id });