@blocklet/payment-react
Version:
Reusable react components for payment kit v2
165 lines (125 loc) • 8.24 kB
Markdown
# CheckoutForm
The `CheckoutForm` component is the primary entry point for handling payment links and checkout sessions. It acts as a high-level wrapper that fetches all necessary data based on a provided ID and renders the appropriate payment or donation interface. This component is the simplest way to integrate a complete checkout flow into your application.
It's essential to wrap `CheckoutForm` or any of its parent components with the `PaymentProvider` to ensure it has access to the necessary context, such as session information and API configuration. For more details, please refer to the [PaymentProvider documentation](./providers-payment-provider.md).
## How It Works
The component orchestrates the entire checkout process:
1. **Initialization**: It's mounted with a `paymentLink` ID (prefixed with `plink_`) or a `checkoutSession` ID (prefixed with `cs_`).
2. **Data Fetching**: It communicates with the payment backend to retrieve all necessary context, including payment methods, line items, and customer details.
3. **UI Rendering**: Based on the `formType` prop, it internally renders either the standard `Payment` component or the specialized `DonationForm` component.
4. **State Management**: It handles the entire lifecycle of the payment, including loading states, completion status, and error handling.
```d2 Basic Flow of CheckoutForm icon=lucide:workflow
direction: down
shape: sequence_diagram
User-Action: {
shape: c4-person
label: "User"
}
Application: {
label: "Your React Application"
CheckoutForm-Component: {
label: "CheckoutForm"
}
Payment-Component: {
label: "Payment Component"
}
Donation-Component: {
label: "DonationForm Component"
}
}
Payment-API: {
label: "Payment Backend API"
shape: cylinder
}
User-Action -> Application.CheckoutForm-Component: "1. Mounts with 'id' prop"
Application.CheckoutForm-Component -> Payment-API: "2. Fetch session data"
Payment-API -> Application.CheckoutForm-Component: "3. Return checkout context"
alt "if formType is 'payment'" {
Application.CheckoutForm-Component -> Application.Payment-Component: "4. Renders Payment UI"
}
alt "if formType is 'donation'" {
Application.CheckoutForm-Component -> Application.Donation-Component: "5. Renders Donation UI"
}
User-Action -> Application.Payment-Component: "6. Completes payment"
User-Action -> Application.Donation-Component: "7. Completes donation"
```
## Props
The `CheckoutForm` component accepts the following props:
| Prop | Type | Required | Default | Description |
|---------------|----------------------------------------------------------------------------|----------|---------------|-------------------------------------------------------------------------------------------------------------------------|
| `id` | `string` | Yes | - | The unique identifier for the payment link (`plink_...`) or checkout session (`cs_...`). |
| `mode` | `'standalone'` \| `'inline'` \| `'popup'` \| `'inline-minimal'` \| `'popup-minimal'` | No | `'inline'` | Defines the rendering mode. `'standalone'` for a full-page view, `'inline'` to embed in a container. |
| `formType` | `'payment'` \| `'donation'` | No | `'payment'` | Determines the type of form to render. Use `'donation'` for the specialized donation flow. |
| `onPaid` | `(res: CheckoutContext) => void` | No | - | Callback function executed upon successful payment. Receives the final checkout context as an argument. |
| `onError` | `(err: Error) => void` | No | `console.error` | Callback function executed when an error occurs during the process. |
| `onChange` | `(data: CheckoutFormData) => void` | No | - | Callback function that fires when any form field value changes. |
| `goBack` | `() => void` | No | - | If provided, renders a back button and calls this function when clicked. |
| `extraParams` | `Record<string, any>` | No | `{}` | An object of extra parameters to be passed in the URL when initiating a session from a payment link. |
| `theme` | `'default'` \| `'inherit'` \| `PaymentThemeOptions` | No | `'default'` | Controls the component's theme. `'inherit'` uses the parent theme, or you can pass a custom theme object. |
| `action` | `string` | No | `''` | A string identifier used for customizing UI elements like button text or tracking specific flows. |
## Usage
### Basic Inline Payment Form
This is the most common use case for embedding a payment form directly within your application's UI. The component handles all the logic internally.
```tsx MyStorePage.tsx icon=lucide:shopping-cart
import { PaymentProvider, CheckoutForm } from '@blocklet/payment-react';
import { useSessionContext } from './hooks/session-context'; // Your app's session hook
export default function MyStorePage() {
const { session, connectApi } = useSessionContext();
const handlePaymentSuccess = (result) => {
console.log('Payment successful!', result);
alert('Thank you for your purchase!');
};
const handlePaymentError = (error) => {
console.error('Payment failed:', error);
alert('Sorry, your payment could not be processed.');
};
return (
<PaymentProvider session={session} connectApi={connectApi}>
<div style={{ maxWidth: '960px', margin: '0 auto' }}>
<h1>Checkout</h1>
<CheckoutForm
id="plink_xxxxxxxxxxxxxx" // Replace with your Payment Link ID
mode="inline"
onPaid={handlePaymentSuccess}
onError={handlePaymentError}
/>
</div>
</PaymentProvider>
);
}
```
### Standalone Full-Page Checkout
Use `mode="standalone"` to render a dedicated, full-page checkout experience. This is ideal for scenarios where you redirect the user to a separate page to complete their payment.
```tsx CheckoutPage.tsx icon=lucide:layout-template
import { PaymentProvider, CheckoutForm } from '@blocklet/payment-react';
import { useSessionContext } from './hooks/session-context';
export default function CheckoutPage() {
const { session, connectApi } = useSessionContext();
const paymentLinkId = 'plink_xxxxxxxxxxxxxx'; // Can be retrieved from URL params
return (
<PaymentProvider session={session} connectApi={connectApi}>
<CheckoutForm id={paymentLinkId} mode="standalone" />
</PaymentProvider>
);
}
```
### Donation Form
By setting `formType="donation"`, the component renders a specialized UI tailored for donation campaigns, including features like amount presets and benefit displays.
```tsx DonationPage.tsx icon=lucide:gift
import { PaymentProvider, CheckoutForm } from '@blocklet/payment-react';
import { useSessionContext } from './hooks/session-context';
export default function DonationPage() {
const { session, connectApi } = useSessionContext();
return (
<PaymentProvider session={session} connectApi={connectApi}>
<div style={{ padding: '2rem' }}>
<h2>Support Our Cause</h2>
<CheckoutForm
id="plink_yyyyyyyyyyyyyy" // Replace with your Donation Link ID
formType="donation"
onPaid={() => alert('Thank you for your generous donation!')}
/>
</div>
</PaymentProvider>
);
}
```