> ## Documentation Index
> Fetch the complete documentation index at: https://docs.withgale.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Checkout (Hosted Page)

> Redirect customers to Gale's hosted checkout page for seamless HSA/FSA payments

# Checkout Integration

The most common way to integrate Gale. Create a checkout session via API, redirect your customer to Gale's hosted page, and we handle the rest—including card collection, eligibility detection, and LMN flow for dual-purpose products.

## How It Works

1. **Customer clicks** "Checkout" on your site
2. **Your site** creates a checkout session via `POST /api/v2/checkout`
3. **Gale returns** a `checkout_url`
4. **Your site redirects** customer to the checkout URL
5. **Customer completes** payment on Gale's hosted page
6. **Gale sends** webhook with `order.created` event
7. **Your system** fulfills the order
8. **Customer is redirected** back to your `success_url`

## When to Use Checkout

<Info>
  **Using Shopify or WooCommerce?** Install our plugin instead:

  * [Shopify Plugin](/onboarding/shopify/installation)
  * [WooCommerce Plugin](/onboarding/woocommerce/installation)

  The Checkout API is for custom platforms and sites not supported by our plugins.
</Info>

**Perfect for:**

* Custom e-commerce platforms
* Membership and subscription platforms
* SaaS applications
* Next.js, React, or custom-built sites
* Adding HSA/FSA payments alongside existing payment methods

**Use cases:**

* Next.js membership site with monthly subscriptions
* Custom healthcare e-commerce store
* Wellness platform built on custom stack
* Telehealth service with custom checkout

## Quick Start

### 1. Create Checkout Session

```javascript theme={null}
const createCheckout = async (cart) => {
  const response = await fetch('https://api.withgale.com/api/v2/checkout', {
    method: 'POST',
    headers: {
      'Authorization': `Bearer ${process.env.GALE_API_KEY}`,
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      reference_id: cart.id,
      customer: {
        email: cart.customerEmail,
        first_name: cart.firstName,
        last_name: cart.lastName
      },
      line_items: cart.items.map(item => ({
        product_id: item.sku,
        name: item.name,
        quantity: item.quantity,
        price: item.price,
        currency: 'USD'
      })),
      shipping_info: cart.shippingAddress,
      shipping: cart.shipping,
      tax: cart.tax,
      success_url: 'https://yoursite.com/order/success',
      failure_url: 'https://yoursite.com/cart'
    })
  });

  const checkout = await response.json();
  return checkout.checkout_url;
};
```

### 2. Redirect Customer

```javascript theme={null}
// Redirect to Gale's hosted checkout
const checkoutUrl = await createCheckout(cart);
window.location.href = checkoutUrl;
```

### 3. Handle Webhook

```javascript theme={null}
app.post('/webhooks/gale', async (req, res) => {
  const event = req.body;

  if (event.type === 'order.created') {
    const order = event.data;

    // Fulfill the order
    await fulfillOrder(order.id, {
      items: order.line_items,
      shipping: order.customer.shipping_address
    });

    // Send confirmation email
    await sendEmail({
      to: order.customer.email,
      subject: `Order ${order.order_number} Confirmed`,
      template: 'order_confirmation'
    });
  }

  res.status(200).send('OK');
});
```

## Integration Examples

### Next.js Membership Site

```typescript theme={null}
// app/checkout/route.ts
import { NextResponse } from 'next/server';

export async function POST(request: Request) {
  const { tier, customerId } = await request.json();

  const membershipPlans = {
    basic: { productId: 'BASIC-001', price: 2900 },
    premium: { productId: 'PREMIUM-001', price: 4900 },
    elite: { productId: 'ELITE-001', price: 9900 }
  };

  const plan = membershipPlans[tier];

  const response = await fetch('https://api.withgale.com/api/v2/checkout', {
    method: 'POST',
    headers: {
      'Authorization': `Bearer ${process.env.GALE_API_KEY}`,
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      customer: await getCustomer(customerId),
      line_items: [{
        product_id: plan.productId,
        name: `${tier} Membership`,
        quantity: 1,
        price: plan.price,
        currency: 'USD'
      }],
      payment_type: 'subscription',
      subscription: {
        interval: 'monthly'
      },
      success_url: `${process.env.BASE_URL}/welcome?tier=${tier}`,
      failure_url: `${process.env.BASE_URL}/pricing`
    })
  });

  const checkout = await response.json();
  return NextResponse.json({ url: checkout.checkout_url });
}
```

### React E-commerce Checkout

```jsx theme={null}
function CheckoutButton({ cart }) {
  const handleCheckout = async () => {
    const response = await fetch('/api/create-checkout', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ cart })
    });

    const { checkout_url } = await response.json();
    window.location.href = checkout_url;
  };

  return (
    <button onClick={handleCheckout} className="checkout-btn">
      Pay with HSA/FSA
    </button>
  );
}
```

### Shopify Integration

```javascript theme={null}
// Add Gale as payment option
const addGalePaymentMethod = () => {
  // In checkout page
  const galeButton = document.createElement('button');
  galeButton.textContent = 'Pay with HSA/FSA';
  galeButton.onclick = async () => {
    const cart = await fetch('/cart.js').then(r => r.json());

    const checkout = await createGaleCheckout({
      customer: {
        email: cart.customer.email,
        first_name: cart.customer.first_name,
        last_name: cart.customer.last_name
      },
      line_items: cart.items.map(item => ({
        product_id: item.sku,
        name: item.title,
        quantity: item.quantity,
        price: item.price,
        currency: 'USD'
      })),
      success_url: window.location.origin + '/thank-you',
      failure_url: window.location.origin + '/cart'
    });

    window.location.href = checkout.checkout_url;
  };

  document.querySelector('.payment-methods').appendChild(galeButton);
};
```

## What Gale Handles

When customers reach the hosted checkout page, Gale automatically:

1. **Collects payment information** - Secure card entry
2. **Detects HSA/FSA eligibility** - Real-time SIGIS verification
3. **Handles dual-purpose items** - LMN flow when required
4. **Processes payment** - Charges appropriate payment method(s)
5. **Creates order** - Sends webhook notification to your system

## Checkout URL Customization

Pre-fill customer information to streamline checkout:

```javascript theme={null}
{
  customer: {
    email: "customer@example.com",
    first_name: "Jane",
    last_name: "Doe",
    phone: "+1-555-123-4567"
  },
  shipping_info: {
    address_line_1: "123 Main St",
    city: "New York",
    state: "NY",
    postal_code: "10001",
    country: "US"
  }
}
```

Customer only needs to enter payment details.

## Subscription Support

For recurring payments, add subscription parameters:

```javascript theme={null}
{
  payment_type: "subscription",
  subscription: {
    interval: "monthly",
    interval_count: 1,
    trial_period_days: 14
  }
}
```

## Testing

Use test API keys and test cards:

```javascript theme={null}
// Test card numbers
const testCards = {
  success: '4111111111111111',
  decline: '4000000000000002',
  requiresAuth: '4000002500003155'
};
```

See [Test Cards](/resources/test-cards) for full list.

## Related Resources

* [Checkout API Reference](/api-reference/endpoint/create-checkout-v2)
* [Webhooks](/developer-manual/webhooks)
* [Order Object](/api-reference/objects/order)

## Support

Questions about checkout integration?

* 📧 Email: [support@withgale.com](mailto:support@withgale.com)
* 💬 [Contact Support](https://www.withgale.com/contact/support)
