# Payment Flow

## Overview

The `createPaymentFlow()` method provides a complete, orchestrated payment experience. It handles navigation between all screens automatically, making it the easiest way to integrate payments.

***

## Flow Screens

The payment flow progresses through these screens:

```
┌─────────────────┐     ┌─────────────────┐     ┌─────────────────┐
│  Invoice Detail │ ──▶ │ Payment Method  │ ──▶ │   Confirmation  │
│                 │     │    Selection    │     │                 │
└─────────────────┘     └─────────────────┘     └─────────────────┘
                                                        │
                                                ┌───────▼─────────┐
                                                │ Payment Result  │
                                                │                 │
                                                └─────────────────┘
```

1. **Invoice Detail** - Displays invoice information and line items
2. **Payment Method Selection** - Choose existing or add new payment method
3. **Add Payment Method** - Card or bank account form (if adding new)
4. **Confirmation** - Review payment details before submitting
5. **Result** - Success or error screen

***

## Basic Usage

```typescript
const flow = client.createPaymentFlow({
  containerId: 'payment-container',
  invoiceId: 'inv_xxx', // Required
  onPaymentSuccess: (payment) => {
    console.log('Payment successful:', payment);
  },
  onPaymentError: (error) => {
    console.error('Payment failed:', error);
  },
  onClose: () => {
    console.log('Flow closed');
  },
});
```

***

## Configuration

### PaymentFlowConfig

| Property           | Type                         | Required | Description                                         |
| ------------------ | ---------------------------- | -------- | --------------------------------------------------- |
| `containerId`      | `string`                     | Yes      | ID of the container element                         |
| `invoiceId`        | `string`                     | Yes      | Invoice ID to pay                                   |
| `theme`            | `ThemeConfig`                | No       | Custom theme configuration                          |
| `onPaymentSuccess` | `(payment: Payment) => void` | No       | Called when payment succeeds                        |
| `onPaymentError`   | `(error: Error) => void`     | No       | Called when payment fails                           |
| `onClose`          | `() => void`                 | No       | Called when flow is closed                          |
| `onGoBack`         | `() => void`                 | No       | Called when user clicks "Go back" on success screen |

***

## Common Use Cases

### Basic Payment Flow

```typescript
const flow = client.createPaymentFlow({
  containerId: 'payment-container',
  invoiceId: 'inv_xxx',
  onPaymentSuccess: (payment) => {
    window.location.href = '/payment-success';
  },
  onGoBack: () => {
    window.location.href = '/dashboard';
  },
});
```

### Handle Payment Results

```typescript
const flow = client.createPaymentFlow({
  containerId: 'payment-container',
  invoiceId: 'inv_xxx',
  onPaymentSuccess: (payment) => {
    // Payment completed successfully
    console.log('Payment ID:', payment.id);
    console.log('Amount:', payment.amount);
    console.log('Status:', payment.status);

    // Redirect to success page
    window.location.href = `/success?payment=${payment.id}`;
  },
  onPaymentError: (error) => {
    // Payment failed
    console.error('Error:', error.message);

    // Show error to user or retry
    showNotification('Payment failed. Please try again.');
  },
  onClose: () => {
    // User closed the flow without completing
    // Navigate back or show message
  },
  onGoBack: () => {
    // User clicked "Go back" on success screen
    window.location.href = '/dashboard';
  },
});
```

***

## Component Instance Methods

The flow returns a `ComponentInstance` with these methods:

### mount()

Mounts the component to the DOM. Called automatically on creation.

```typescript
flow.mount();
```

### unmount()

Removes the component from the DOM. Call this when navigating away or cleaning up.

```typescript
flow.unmount();
```

### refresh()

Refreshes the component data. Useful after external changes.

```typescript
await flow.refresh();
```

***

## Cleanup

Always unmount the flow when the user navigates away to prevent memory leaks:

```typescript
// Vanilla JS
window.addEventListener('beforeunload', () => {
  flow.unmount();
});

// React
useEffect(() => {
  const flow = client.createPaymentFlow({ ... });
  return () => flow.unmount();
}, []);

// Vue
onUnmounted(() => {
  flow.unmount();
});
```

***

## Already Paid Invoices

If an invoice is already paid (status: `RECEIVED`), the flow will skip directly to the success screen, showing the payment details without requiring any user action.

***

## Related

{% content-ref url="components" %}
[components](https://docs.alternativepayments.io/web-sdk/components)
{% endcontent-ref %}

{% content-ref url="theming" %}
[theming](https://docs.alternativepayments.io/web-sdk/theming)
{% endcontent-ref %}
