@blocklet/payment-react
Version:
Reusable react components for payment kit v2
148 lines (110 loc) • 7.76 kB
Markdown
# CheckoutTable
The `CheckoutTable` component provides a complete, out-of-the-box solution for subscription checkouts. It fetches and renders a pricing table, allows users to select a plan, and then seamlessly transitions them to a payment form to complete the purchase. This high-level component is the fastest way to integrate a plan-based payment flow into your application.
It internally uses the [`PricingTable`](./components-ui-pricing-table.md) component to display the plans and the [`CheckoutForm`](./components-checkout-checkout-form.md) component to process the payment.
## How it Works
The checkout flow managed by `CheckoutTable` is straightforward:
1. **Fetch Data**: The component fetches the pricing table configuration from the server using the provided `id`.
2. **Display Plans**: It renders the subscription plans in a responsive table, allowing users to switch between billing intervals (e.g., monthly/yearly) and currencies.
3. **Create Session**: When a user selects a plan, the component communicates with the backend to create a secure checkout session.
4. **Process Payment**: It then displays the `CheckoutForm`, pre-filled with the session details, allowing the user to enter their payment information and finalize the transaction.
```d2 CheckoutTable Flow Diagram
direction: down
User: {
shape: c4-person
}
CheckoutTable-Component: {
label: "CheckoutTable Component"
shape: rectangle
Pricing-Table-View: {
label: "Pricing Table View"
}
Checkout-Form-View: {
label: "Checkout Form View"
}
}
Payment-API: {
label: "Payment API"
shape: cylinder
}
User -> CheckoutTable-Component.Pricing-Table-View: "1. Views plans"
CheckoutTable-Component.Pricing-Table-View -> User: " "
User -> CheckoutTable-Component.Pricing-Table-View: "2. Selects a plan"
CheckoutTable-Component.Pricing-Table-View -> Payment-API: "3. Create checkout session"
Payment-API -> CheckoutTable-Component.Pricing-Table-View: "4. Return session ID"
CheckoutTable-Component.Pricing-Table-View -> CheckoutTable-Component.Checkout-Form-View: "5. Transition with session ID"
User -> CheckoutTable-Component.Checkout-Form-View: "6. Fills payment details & pays"
CheckoutTable-Component.Checkout-Form-View -> User: ""
```
## Props
| Prop | Type | Required | Default | Description |
|---------------|-----------------------------------|----------|--------------|------------------------------------------------------------------------------------------------------------------------------------------|
| `id` | `string` | Yes | - | The ID of the pricing table to display (must start with `prctbl_`). |
| `mode` | `'standalone'` or `'embedded'` | No | `'embedded'` | The display mode. `'standalone'` redirects to a separate page, while `'embedded'` handles the flow inline within the component. |
| `onPaid` | `(sessionId: string) => void` | No | - | Callback function triggered when the payment is successfully completed. |
| `onError` | `(error: Error) => void` | No | - | Callback function for handling errors during the checkout process. |
| `onChange` | `(data: any) => void` | No | - | Callback for any state change within the checkout form. |
| `extraParams` | `Record<string, any>` | No | `{}` | An object of extra parameters to be sent when creating the checkout session, useful for passing custom data like a user ID. |
| `goBack` | `() => void` | No | - | A function to handle the back action from the payment form, returning the user to the pricing table view. |
| `theme` | `object` or `'inherit'` | No | - | Custom Material-UI theme object to style the component. For more details, see the [Theming guide](./guides-theming.md). |
## Usage
To use the `CheckoutTable` component, you must wrap it in a `PaymentProvider`. Pass the pricing table `id` and an `onPaid` callback to handle successful transactions.
```javascript Basic CheckoutTable Example icon=logos:react
import { PaymentProvider, CheckoutTable } from '@blocklet/payment-react';
import { useSessionContext } from './path-to-your-session-context'; // Centralize this context as per guidelines
export default function MyCheckoutPage() {
const { session, connectApi } = useSessionContext();
const handlePaymentSuccess = (sessionId) => {
console.log(`Payment successful for session: ${sessionId}`);
alert('Thank you for your subscription!');
};
if (!session) {
return <div>Loading session...</div>;
}
return (
<PaymentProvider session={session} connectApi={connectApi}>
<div style={{ height: '700px', width: '100%' }}>
<CheckoutTable
id="prctbl_xxxxxxxxxxxxxxxx" // Replace with your actual pricing table ID
onPaid={handlePaymentSuccess}
/>
</div>
</PaymentProvider>
);
}
```
## Modes of Operation
### Embedded Mode (Default)
By default, `CheckoutTable` operates in `'embedded'` mode. The component manages the entire flow inline, transitioning from the pricing table view to the payment form within its own container. This is ideal for single-page applications where you want the checkout to feel like an integrated part of the page.
### Standalone Mode
By setting `mode='standalone'`, the component's behavior changes. When a user selects a plan, they are redirected to a dedicated, hosted checkout page. This mode is useful for simpler integrations that don't require an embedded payment form.
```javascript Standalone Mode icon=logos:react
<CheckoutTable
id="prctbl_xxxxxxxxxxxxxxxx"
mode="standalone"
/>
```
## Advanced Usage
### Handling Back Navigation
The `goBack` prop allows you to define custom logic when the user navigates back from the payment form to the pricing table. The component handles the view transition automatically, but this callback is useful for synchronizing your application's state.
```javascript goBack Prop Example icon=logos:react
const handleGoBack = () => {
console.log('User returned to the pricing table.');
// You can add custom logic here, like updating your app's state.
};
<CheckoutTable
id="prctbl_xxxxxxxxxxxxxxxx"
onPaid={handlePaymentSuccess}
goBack={handleGoBack}
/>
```
### Passing Extra Parameters
Use the `extraParams` prop to send additional data when creating the checkout session. This data can be associated with the resulting payment and is useful for tracking and reconciliation on your backend.
```javascript extraParams Example icon=logos:react
<CheckoutTable
id="prctbl_xxxxxxxxxxxxxxxx"
onPaid={handlePaymentSuccess}
extraParams={{ userId: 'user_123', source: 'marketing_campaign' }}
/>
```
## Customization
While `CheckoutTable` is a high-level component designed for ease of use, you can achieve more granular control by using its constituent parts. For a fully custom UI, you can use the [`PricingTable`](./components-ui-pricing-table.md) component to display plans and then manually trigger a checkout session that renders in a [`CheckoutForm`](./components-checkout-checkout-form.md).