@blocklet/payment-react 1.19.23 → 1.20.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. package/.aigne/doc-smith/config.yaml +114 -0
  2. package/.aigne/doc-smith/output/structure-plan.json +361 -0
  3. package/.aigne/doc-smith/preferences.yml +55 -0
  4. package/.aigne/doc-smith/upload-cache.yaml +264 -0
  5. package/README.md +2 -3
  6. package/docs/_sidebar.md +33 -0
  7. package/docs/components-business-auto-topup.md +238 -0
  8. package/docs/components-business-overdue-invoice-payment.md +231 -0
  9. package/docs/components-business-resume-subscription.md +177 -0
  10. package/docs/components-business.md +45 -0
  11. package/docs/components-checkout-checkout-donate.md +199 -0
  12. package/docs/components-checkout-checkout-form.md +185 -0
  13. package/docs/components-checkout-checkout-table.md +228 -0
  14. package/docs/components-checkout.md +131 -0
  15. package/docs/components-history-credit-grants-list.md +98 -0
  16. package/docs/components-history-credit-transactions-list.md +116 -0
  17. package/docs/components-history-invoice-list.md +104 -0
  18. package/docs/components-history-payment-list.md +65 -0
  19. package/docs/components-history.md +92 -0
  20. package/docs/components-ui-form-elements-address-form.md +150 -0
  21. package/docs/components-ui-form-elements-country-select.md +105 -0
  22. package/docs/components-ui-form-elements-currency-selector.md +124 -0
  23. package/docs/components-ui-form-elements-phone-input.md +160 -0
  24. package/docs/components-ui-form-elements.md +125 -0
  25. package/docs/components-ui-payment-summary.md +157 -0
  26. package/docs/components-ui-pricing-table.md +227 -0
  27. package/docs/components-ui.md +44 -0
  28. package/docs/components.md +95 -0
  29. package/docs/getting-started.md +111 -0
  30. package/docs/guides-theming.md +175 -0
  31. package/docs/guides-utilities.md +235 -0
  32. package/docs/guides.md +95 -0
  33. package/docs/hooks-use-mobile.md +70 -0
  34. package/docs/hooks-use-subscription.md +129 -0
  35. package/docs/hooks.md +84 -0
  36. package/docs/overview.md +87 -0
  37. package/docs/providers-donate-provider.md +175 -0
  38. package/docs/providers-payment-provider.md +245 -0
  39. package/docs/providers.md +101 -0
  40. package/es/libs/util.d.ts +1 -1
  41. package/es/payment/form/index.js +15 -1
  42. package/es/payment/summary.js +1 -1
  43. package/lib/libs/util.d.ts +1 -1
  44. package/lib/payment/form/index.js +14 -1
  45. package/lib/payment/summary.js +1 -1
  46. package/package.json +9 -9
  47. package/src/libs/util.ts +1 -0
  48. package/src/payment/form/index.tsx +16 -1
  49. package/src/payment/summary.tsx +1 -2
@@ -0,0 +1,185 @@
1
+ # CheckoutForm
2
+
3
+ The `CheckoutForm` component is the primary entry point for rendering a complete payment or donation flow. It orchestrates the entire checkout process by fetching session details and rendering the appropriate user interface based on the provided configuration. It requires a `paymentLink` ID (starting with `plink_`) or a `checkoutSession` ID (starting with `cs_`) to initialize.
4
+
5
+ This component is highly flexible and can be rendered in several modes, including as an inline element, a standalone full-page experience, or a popup modal.
6
+
7
+ ## How It Works
8
+
9
+ The `CheckoutForm` component follows a clear internal logic to manage the checkout process. It starts by identifying the type of ID provided, fetches the necessary data, and then renders the appropriate form (`Payment` or `DonationForm`) to handle user interaction.
10
+
11
+ ```d2
12
+ direction: down
13
+
14
+ A: "CheckoutForm Component Mounted"
15
+ B: "Analyze 'id' prop prefix"
16
+ C: "Call startFromPaymentLink API"
17
+ D: "Call fetchCheckoutSession API"
18
+ E: "Receive CheckoutContext"
19
+ F: "Check 'formType' prop"
20
+ G: "Render <Payment /> component"
21
+ H: "Render <DonationForm /> component"
22
+ I: "User completes payment flow"
23
+ J: "Payment successful?"
24
+ K: "Execute onPaid callback"
25
+ L: "Execute onError callback"
26
+
27
+ A -> B
28
+ B -> C: "'plink_...'"
29
+ B -> D: "'cs_...'"
30
+ C -> E
31
+ D -> E
32
+ E -> F
33
+ F -> G: "'payment' (default)"
34
+ F -> H: "'donation'"
35
+ G -> I
36
+ H -> I
37
+ I -> J
38
+ J -> K: "Yes"
39
+ J -> L: "No"
40
+ ```
41
+
42
+ ## Props
43
+
44
+ The `CheckoutForm` accepts the following props to customize its behavior and appearance.
45
+
46
+ | Prop | Type | Description |
47
+ |---------------|-----------------------------------------------------------------------------|--------------------------------------------------------------------------------------------------------------------------------------------------|
48
+ | `id` | `string` | **Required.** The unique identifier for the checkout. Must start with `plink_` for a Payment Link or `cs_` for a Checkout Session. |
49
+ | `mode` | `'standalone' \| 'inline' \| 'popup' \| 'inline-minimal' \| 'popup-minimal'` | The display mode. Defaults to `'inline'`. |
50
+ | `formType` | `'payment' \| 'donation'` | The type of form to render. Use `'donation'` for a donation-specific UI. Defaults to `'payment'`. |
51
+ | `onPaid` | `(res: CheckoutContext) => void` | Callback function executed upon successful payment. It receives the final checkout context. |
52
+ | `onError` | `(err: Error) => void` | Callback function executed when an error occurs during the process. |
53
+ | `onChange` | `(data: CheckoutFormData) => void` | Optional. Callback executed when form data (e.g., selected currency) changes. |
54
+ | `goBack` | `() => void` | Optional. A function to handle a "back" button action, useful in multi-step flows. |
55
+ | `extraParams` | `Record<string, any>` | Optional. An object of extra parameters to be sent when initializing a session from a Payment Link. |
56
+ | `action` | `string` | Optional. A string to customize button text or other UI elements based on the action being performed (e.g., 'subscribe', 'donate'). |
57
+ | `theme` | `'default' \| 'inherit' \| object` | The theme to apply. `'default'` uses the built-in theme, `'inherit'` uses the parent theme, and an object allows for custom Material-UI theme options. |
58
+ | `formRender` | `Record<string, any>` | Optional. Used with `formType='donation'` to inject custom render elements or callbacks, such as a custom cancel button. |
59
+
60
+ ## Usage
61
+
62
+ ### Prerequisite: Wrapping with PaymentProvider
63
+
64
+ To use `CheckoutForm`, your application must be wrapped with the `PaymentProvider`. This provider is essential as it supplies the necessary context, including API configuration and session information, to all nested payment components.
65
+
66
+ A common pattern is to integrate `PaymentProvider` with your application's existing session management. In the example below, `useSessionContext` is a placeholder for your own custom hook that provides the user session. This setup ensures that `CheckoutForm` has access to user data when needed.
67
+
68
+ For a complete guide on setting up the `PaymentProvider` and creating your `useSessionContext` hook, please refer to the [PaymentProvider documentation](./providers-payment-provider.md).
69
+
70
+ ```tsx
71
+ import { PaymentProvider } from '@blocklet/payment-react';
72
+ import { CheckoutForm } from '@blocklet/payment-react';
73
+ // This is a placeholder for your application's session context hook.
74
+ // See the PaymentProvider documentation for implementation details.
75
+ import { useSessionContext } from '../hooks/session-context';
76
+
77
+ // Your main application component
78
+ function App() {
79
+ const { session, connectDid, disconnectDid } = useSessionContext();
80
+
81
+ return (
82
+ <PaymentProvider
83
+ apiHost="https://your-api-host"
84
+ // Pass session and connection handlers from your local context
85
+ session={session}
86
+ connect={connectDid}
87
+ disconnectDid={disconnectDid}>
88
+ <MyCheckoutPage />
89
+ </PaymentProvider>
90
+ );
91
+ }
92
+
93
+ // A component that renders the checkout form
94
+ function MyCheckoutPage() {
95
+ const { session } = useSessionContext();
96
+ const paymentLinkId = 'plink_xxxxxxxxxxxx';
97
+
98
+ // Conditionally render based on user login status
99
+ if (!session?.user) {
100
+ return <p>Please log in to proceed with the payment.</p>;
101
+ }
102
+
103
+ return (
104
+ <CheckoutForm
105
+ id={paymentLinkId}
106
+ onPaid={() => console.log('Payment successful!')}
107
+ onError={(err) => console.error('Payment failed:', err)}
108
+ />
109
+ );
110
+ }
111
+ ```
112
+
113
+ ### Standard Inline Payment
114
+
115
+ This is the default behavior. The component renders directly where it's placed in the DOM, which is suitable for embedding the payment form within a product or pricing page.
116
+
117
+ ```tsx
118
+ import { CheckoutForm } from '@blocklet/payment-react';
119
+
120
+ export default function InlinePayment() {
121
+ return (
122
+ <div>
123
+ <h2>Complete Your Purchase</h2>
124
+ <CheckoutForm
125
+ id="plink_xxxxxxxxxxxx"
126
+ mode="inline"
127
+ onPaid={(data) => {
128
+ console.log('Payment successful:', data.checkoutSession.id);
129
+ }}
130
+ onError={(err) => console.error('Payment failed:', err)}
131
+ />
132
+ </div>
133
+ );
134
+ }
135
+ ```
136
+
137
+ ### Standalone Checkout Page
138
+
139
+ By setting `mode='standalone'`, the component will render a full-page checkout experience, including a header and footer. This is ideal for redirecting users to a dedicated payment page.
140
+
141
+ ```tsx
142
+ import { CheckoutForm } from '@blocklet/payment-react';
143
+
144
+ export default function StandaloneCheckoutPage() {
145
+ return (
146
+ <CheckoutForm
147
+ id="cs_xxxxxxxxxxxx"
148
+ mode="standalone"
149
+ onPaid={(data) => {
150
+ // Redirect to a success page
151
+ window.location.href = `/payment-success?session_id=${data.checkoutSession.id}`;
152
+ }}
153
+ onError={(err) => console.error('Payment failed:', err)}
154
+ />
155
+ );
156
+ }
157
+ ```
158
+
159
+ ### Donation Form
160
+
161
+ To render a UI optimized for donations, set `formType='donation'`. This changes the layout and terminology to better suit a donation flow.
162
+
163
+ ```tsx
164
+ import { CheckoutForm } from '@blocklet/payment-react';
165
+
166
+ export default function DonationPage() {
167
+ return (
168
+ <div>
169
+ <h2>Support Our Cause</h2>
170
+ <CheckoutForm
171
+ id="plink_donation_xxxxxxxx"
172
+ formType="donation"
173
+ onPaid={(data) => {
174
+ console.log(`Thank you for your donation! Invoice ID: ${data.checkoutSession.invoice_id}`);
175
+ }}
176
+ onError={(err) => {
177
+ console.error('Donation failed:', err);
178
+ }}
179
+ />
180
+ </div>
181
+ );
182
+ }
183
+ ```
184
+
185
+ After integrating the checkout form, you may want to display a summary of the items being purchased. To learn more, see the documentation for the [PaymentSummary](./components-ui-payment-summary.md) component.
@@ -0,0 +1,228 @@
1
+ # CheckoutTable
2
+
3
+ The `CheckoutTable` component provides a complete, out-of-the-box solution for displaying a pricing table and handling the entire checkout flow. It fetches pricing table data by ID, allows users to select a plan, and then either redirects them to a checkout page or renders an inline payment form.
4
+
5
+ This component is a high-level abstraction that internally uses [`PricingTable`](./components-ui-pricing-table.md) for display and [`CheckoutForm`](./components-checkout-checkout-form.md) for payment processing, simplifying the integration of subscription or one-time payment flows.
6
+
7
+ ## How It Works
8
+
9
+ The component follows a clear, logical flow to guide the user from plan selection to payment completion.
10
+
11
+ ```d2
12
+ direction: down
13
+
14
+ CheckoutTable: {
15
+ label: "CheckoutTable Mounted with 'id'"
16
+ shape: step
17
+ }
18
+
19
+ FetchData: {
20
+ label: "Fetch Pricing Table Data"
21
+ shape: step
22
+ }
23
+
24
+ DisplayPricing: {
25
+ label: "Display PricingTable"
26
+ shape: step
27
+ }
28
+
29
+ DisplayError: {
30
+ label: "Display Error Message"
31
+ shape: step
32
+ style: {
33
+ stroke: "#d32f2f"
34
+ }
35
+ }
36
+
37
+ HandleSelect: {
38
+ label: "User selects a plan (handleSelect)"
39
+ shape: step
40
+ }
41
+
42
+ CreateSession: {
43
+ label: "Create Checkout Session via API"
44
+ shape: step
45
+ }
46
+
47
+ ModeCheck: {
48
+ label: "mode === 'standalone'?"
49
+ shape: diamond
50
+ }
51
+
52
+ Redirect: {
53
+ label: "Redirect to Checkout URL"
54
+ shape: step
55
+ style: {
56
+ fill: "#e8f5e9"
57
+ }
58
+ }
59
+
60
+ UpdateHash: {
61
+ label: "Update URL hash with Session ID"
62
+ shape: step
63
+ }
64
+
65
+ RenderForm: {
66
+ label: "Render CheckoutForm"
67
+ shape: step
68
+ }
69
+
70
+ OnPaid: {
71
+ label: "onPaid() callback"
72
+ shape: step
73
+ style: {
74
+ fill: "#e8f5e9"
75
+ }
76
+ }
77
+
78
+ OnError: {
79
+ label: "onError() callback"
80
+ shape: step
81
+ style: {
82
+ stroke: "#d32f2f"
83
+ }
84
+ }
85
+
86
+ ToastError: {
87
+ label: "Show Toast Error"
88
+ shape: step
89
+ style: {
90
+ stroke: "#d32f2f"
91
+ }
92
+ }
93
+
94
+ CheckoutTable -> FetchData
95
+ FetchData -> DisplayPricing: "Success"
96
+ FetchData -> DisplayError: "Error"
97
+ DisplayPricing -> HandleSelect
98
+ HandleSelect -> CreateSession
99
+ CreateSession -> ModeCheck: "Success"
100
+ CreateSession -> ToastError: "Error"
101
+ ModeCheck -> Redirect: "Yes"
102
+ ModeCheck -> UpdateHash: "No (Embedded)"
103
+ UpdateHash -> RenderForm
104
+ RenderForm -> OnPaid: "Payment Success"
105
+ RenderForm -> OnError: "Payment Error"
106
+ ```
107
+
108
+ ## Props
109
+
110
+ The `CheckoutTable` component requires a `PaymentProvider` to be present in the component tree. For more details, refer to the [`PaymentProvider`](./providers-payment-provider.md) documentation.
111
+
112
+ | Prop | Type | Required | Description |
113
+ |---|---|---|---|
114
+ | `id` | `string` | Yes | The ID of the pricing table to display. This must start with `prctbl_`. |
115
+ | `mode` | `'standalone' \| 'embedded'` | No | Determines the checkout behavior. In `'standalone'` mode, the user is redirected to a separate checkout page. In `'embedded'` mode (default), the `CheckoutForm` is rendered inline, replacing the pricing table. |
116
+ | `onPaid` | `(data: TCheckout) => void` | No | Callback function executed when the payment is successfully completed. It receives the final checkout session data. |
117
+ | `onError` | `(err: Error) => void` | No | Callback function executed if an error occurs during the payment process. |
118
+ | `onChange` | `(session: TCheckout) => void` | No | Callback function executed whenever the checkout session state changes (e.g., from `pending` to `processing`). |
119
+ | `extraParams` | `object` | No | An object containing extra query parameters to be sent when creating the checkout session. |
120
+ | `goBack` | `() => void` | No | A function that is called when the user clicks the "back" button on the `CheckoutForm`. This enables navigation back to the pricing table view in embedded mode. |
121
+ | `theme` | `object \| 'inherit'` | No | A custom Material-UI theme object to style the component. Set to `'inherit'` to use the ambient theme without an additional `ThemeProvider`. |
122
+
123
+ ## Usage Scenarios
124
+
125
+ `CheckoutTable` can be configured for two primary user experiences: a full-page redirect or a seamless embedded flow.
126
+
127
+ > **Note on Context:** The following examples assume you have set up a session context in your application. The `PaymentProvider` relies on this context to get authentication and API details. For a complete guide on this setup, please see the [`PaymentProvider`](./providers-payment-provider.md) documentation.
128
+
129
+ ### Standalone Mode
130
+
131
+ In `standalone` mode, the component handles plan selection and then redirects the user to a dedicated, hosted checkout page. This is the simplest way to integrate.
132
+
133
+ ```jsx
134
+ import { CheckoutTable, PaymentProvider } from '@blocklet/payment-react';
135
+ import { useSessionContext } from '../contexts/session'; // Path to your custom session context hook
136
+
137
+ function MyPaymentPage() {
138
+ const { session, connectApi } = useSessionContext();
139
+
140
+ if (!session.user) {
141
+ return <p>Please log in to see pricing.</p>;
142
+ }
143
+
144
+ return (
145
+ <PaymentProvider session={session} connect={connectApi}>
146
+ <div style={{ height: '600px', width: '100%' }}>
147
+ <CheckoutTable
148
+ id="prctbl_xxxxxxxxxxxx" // Replace with your actual pricing table ID
149
+ mode="standalone"
150
+ />
151
+ </div>
152
+ </PaymentProvider>
153
+ );
154
+ }
155
+ ```
156
+
157
+ When a user clicks a subscription button in the pricing table, `window.location.replace` is called to navigate them to the checkout URL provided by the payment service API.
158
+
159
+ ### Embedded Mode
160
+
161
+ In `embedded` mode (the default behavior), the entire checkout process happens within your application. After a plan is selected, the pricing table is replaced by the `CheckoutForm` component.
162
+
163
+ This mode relies on the URL hash (`#`) to store and retrieve the checkout session ID, enabling a smooth, single-page application experience.
164
+
165
+ ```jsx
166
+ import { CheckoutTable, PaymentProvider } from '@blocklet/payment-react';
167
+ import { useSessionContext } from '../contexts/session'; // Path to your custom session context hook
168
+ import type { TCheckout } from '@blocklet/payment-types';
169
+
170
+ function MyEmbeddedCheckout() {
171
+ const { session, connectApi } = useSessionContext();
172
+
173
+ const handlePaymentSuccess = (checkoutData: TCheckout) => {
174
+ console.log('Payment successful!', checkoutData);
175
+ alert('Thank you for your payment!');
176
+ };
177
+
178
+ const handlePaymentError = (error: Error) => {
179
+ console.error('Payment failed:', error);
180
+ alert('There was an issue with your payment.');
181
+ };
182
+
183
+ const handleGoBack = () => {
184
+ // The component handles clearing the URL hash internally.
185
+ // You can add custom logic here if needed.
186
+ console.log('User returned to the pricing table view.');
187
+ };
188
+
189
+ if (!session.user) {
190
+ return <p>Please log in to see pricing.</p>;
191
+ }
192
+
193
+ return (
194
+ <PaymentProvider session={session} connect={connectApi}>
195
+ <div style={{ height: '800px', width: '100%' }}>
196
+ <CheckoutTable
197
+ id="prctbl_xxxxxxxxxxxx" // Replace with your actual pricing table ID
198
+ onPaid={handlePaymentSuccess}
199
+ onError={handlePaymentError}
200
+ goBack={handleGoBack}
201
+ />
202
+ </div>
203
+ </PaymentProvider>
204
+ );
205
+ }
206
+ ```
207
+
208
+ In this example:
209
+ - The `onPaid` and `onError` callbacks are used to handle the final state of the transaction.
210
+ - The `goBack` prop enables a back button on the payment form, allowing users to return to the plan selection screen without losing context.
211
+
212
+ ## `CheckoutTable` vs. `PricingTable`
213
+
214
+ It's important to understand the difference between `CheckoutTable` and the lower-level `PricingTable` component to choose the right one for your needs.
215
+
216
+ #### CheckoutTable
217
+
218
+ A high-level, all-in-one component that manages the entire checkout flow. It handles data fetching, plan selection, and payment form rendering.
219
+
220
+ **Use when:** You need a complete, ready-to-use pricing and checkout solution with minimal configuration.
221
+
222
+ #### PricingTable
223
+
224
+ A low-level, presentational component that only displays pricing data passed to it. It does not manage state or handle the checkout process.
225
+
226
+ **Use when:** You need to build a custom checkout flow or display pricing plans in a non-checkout context.
227
+
228
+ For most use cases, **`CheckoutTable` is the recommended starting point** as it provides a complete and integrated experience. If you find you need more granular control over the user flow, you can then use `PricingTable` and `CheckoutForm` as separate building blocks.
@@ -0,0 +1,131 @@
1
+ # Checkout Components
2
+
3
+ Checkout components are high-level, pre-built components designed to serve as complete entry points for various payment flows. They encapsulate the entire user experience, from presenting payment options to processing transactions and handling success or error states. This allows you to integrate complex payment scenarios like one-time payments, subscriptions from a pricing table, or donations with minimal setup.
4
+
5
+ These components act as orchestrators for the payment process, as illustrated below:
6
+
7
+ ```d2
8
+ direction: down
9
+
10
+ user_journey: {
11
+ action: "User Initiates Action"
12
+ select_flow: "Selects Checkout Flow" { shape: diamond }
13
+ action -> select_flow
14
+ }
15
+
16
+ checkout_components: "Checkout Components" {
17
+ shape: package
18
+ form: "CheckoutForm"
19
+ table: "CheckoutTable"
20
+ donate: "CheckoutDonate"
21
+ }
22
+
23
+ payment_flow: "Payment Flow" {
24
+ ui: "Payment UI"
25
+ plan: "Plan Selection"
26
+ dialog: "Donation Dialog"
27
+ completion: "Payment Completion"
28
+ ui -> completion
29
+ }
30
+
31
+ select_flow -> checkout_components.form: "Direct Payment"
32
+ select_flow -> checkout_components.table: "Select Plan"
33
+ select_flow -> checkout_components.donate: "Make Donation"
34
+
35
+ checkout_components.form -> payment_flow.ui
36
+ checkout_components.table -> payment_flow.plan: "Displays PricingTable"
37
+ payment_flow.plan -> checkout_components.form: "Creates Session & Uses"
38
+ checkout_components.donate -> payment_flow.dialog: "Opens Dialog"
39
+ payment_flow.dialog -> checkout_components.form: "Uses"
40
+ ```
41
+
42
+ This section provides an overview of the primary checkout components. For detailed API references and advanced usage, please refer to the specific documentation for each component.
43
+
44
+ ---
45
+
46
+ <x-cards data-columns="3">
47
+ <x-card data-title="CheckoutForm" data-icon="lucide:credit-card" data-href="/components/checkout/checkout-form">
48
+ The core component for processing payments from a `paymentLink` or `checkoutSession`, managing the entire payment UI and state.
49
+ </x-card>
50
+ <x-card data-title="CheckoutTable" data-icon="lucide:table" data-href="/components/checkout/checkout-table">
51
+ Renders a pricing table and handles the checkout flow when a user selects a plan. Ideal for subscription-based services.
52
+ </x-card>
53
+ <x-card data-title="CheckoutDonate" data-icon="lucide:heart" data-href="/components/checkout/checkout-donate">
54
+ A flexible component for implementing donations, supporting multiple display modes and managing the donation payment process.
55
+ </x-card>
56
+ </x-cards>
57
+
58
+ ## Provider Dependencies
59
+
60
+ All checkout components require being wrapped within the `PaymentProvider` to function correctly, as it supplies the necessary context for API communication and session management.
61
+
62
+ For `CheckoutDonate`, it is also recommended to wrap it with `DonateProvider` to manage global donation settings and state effectively.
63
+
64
+ Here is a typical provider setup in an application. This example uses a local session context for DID connect, which is a common pattern.
65
+
66
+ ```tsx
67
+ import React from 'react';
68
+ import { CheckoutTable, CheckoutDonate } from '@blocklet/payment-react';
69
+ import { PaymentProvider } from '@blocklet/payment-react/lib/contexts/payment';
70
+ import { DonateProvider } from '@blocklet/payment-react/lib/contexts/donate';
71
+
72
+ // This is a local file you would create to manage your DID-Connect session.
73
+ // See the PaymentProvider documentation for setup instructions.
74
+ import { SessionProvider, useSessionContext } from '../contexts/session';
75
+
76
+ const donationSettings = {
77
+ target: 'unique_target_id_for_your_project',
78
+ title: 'Support Our Project',
79
+ description: 'Your contribution helps us continue our work.',
80
+ beneficiaries: [{ did: 'z2qa...', weight: 100 }], // Replace with actual beneficiary DID
81
+ };
82
+
83
+ function MyPaymentFeatures() {
84
+ // Obtain session and connectApi from your local session context.
85
+ const { session, connectApi } = useSessionContext();
86
+
87
+ return (
88
+ // PaymentProvider requires the session and connectApi for authentication and communication.
89
+ <PaymentProvider session={session} connect={connectApi}>
90
+ {/* Example 1: Using CheckoutTable for subscription plans */}
91
+ <div style={{ marginBottom: '40px' }}>
92
+ <h2>Choose a Subscription Plan</h2>
93
+ <CheckoutTable
94
+ id="prctbl_xxxxxxxxxxxx" // Replace with your pricing table ID
95
+ onPaid={(context) => console.log('Subscription successfully started!', context)}
96
+ onError={(error) => console.error('Subscription failed:', error)}
97
+ />
98
+ </div>
99
+
100
+ {/* Example 2: Using CheckoutDonate with its specific provider */}
101
+ <div>
102
+ <h2>Make a Donation</h2>
103
+ <DonateProvider>
104
+ <CheckoutDonate
105
+ settings={donationSettings}
106
+ onPaid={() => console.log('Thank you for your donation!')}
107
+ onError={(error) => console.error('Donation failed:', error)}
108
+ />
109
+ </DonateProvider>
110
+ </div>
111
+ </PaymentProvider>
112
+ );
113
+ }
114
+
115
+ function App() {
116
+ // The SessionProvider wraps your application to provide session context.
117
+ // For a detailed guide on setting up your session context and PaymentProvider,
118
+ // please see the [PaymentProvider documentation](./providers-payment-provider.md).
119
+ return (
120
+ <SessionProvider>
121
+ <MyPaymentFeatures />
122
+ </SessionProvider>
123
+ );
124
+ }
125
+
126
+ export default App;
127
+ ```
128
+
129
+ ## Next Steps
130
+
131
+ These components provide powerful, out-of-the-box solutions for common payment scenarios. To build more customized payment experiences, you can explore the lower-level [UI Components](./components-ui.md).
@@ -0,0 +1,98 @@
1
+ # CreditGrantsList
2
+
3
+ The `CreditGrantsList` component is designed to display a comprehensive list of credit grants associated with a specific customer. It presents key information such as the grant's status, remaining balance, scope, and effective dates in a clear, tabular format. This component is essential for both customers checking their credit balance and administrators managing credit grants.
4
+
5
+ This component must be used within a `PaymentProvider` to access the necessary session and context information.
6
+
7
+ ## Props
8
+
9
+ The `CreditGrantsList` component accepts the following props to customize its behavior and filter the displayed data.
10
+
11
+ | Prop | Type | Description |
12
+ |---------------------|------------------------------------|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
13
+ | `customer_id` | `string` | The ID of the customer whose credit grants are to be displayed. If not provided, it defaults to the DID of the currently logged-in user from the session context. |
14
+ | `subscription_id` | `string` | Optional. Filters the credit grants to show only those associated with a specific subscription ID. |
15
+ | `status` | `string` | Optional. A comma-separated string of statuses to filter by. Defaults to `'granted,pending,depleted,expired'`. Valid statuses include `granted`, `pending`, `expired`, `depleted`, and `voided`. |
16
+ | `pageSize` | `number` | Optional. The number of items to display per page. Defaults to `10`. |
17
+ | `onTableDataChange` | `(data, prevData) => void` | Optional. A callback function that is invoked when the table's data is fetched or updated. It receives the new and previous data sets as arguments. |
18
+ | `mode` | `'dashboard'` \| `'portal'` | Optional. Determines the navigation behavior. In `'dashboard'` mode (for admins), links navigate to admin-specific routes. In `'portal'` mode (for customers), links navigate to customer-facing routes. |
19
+
20
+ ## Usage Example
21
+
22
+ To use `CreditGrantsList`, it must be wrapped in a `PaymentProvider`. The provider requires `session` and `connectApi` props, which should be supplied by a session context in your application.
23
+
24
+ For a detailed guide on setting up `PaymentProvider` and creating a `useSessionContext` hook, please refer to the [PaymentProvider documentation](./providers-payment-provider.md).
25
+
26
+ Below is a typical implementation:
27
+
28
+ ```jsx
29
+ import React from 'react';
30
+ import { PaymentProvider } from '@blocklet/payment-react';
31
+ import CreditGrantsList from '@blocklet/payment-react/lib/components/history/credit-grants-list';
32
+ // This is your local hook to get session context.
33
+ // See the PaymentProvider docs for how to create it.
34
+ import { useSessionContext } from '../../contexts/session';
35
+
36
+ // A component that displays the credit grants list.
37
+ const MyCreditGrantsPage = () => {
38
+ // If you don't provide a customer_id, the component will automatically
39
+ // use the DID of the currently logged-in user.
40
+ const customerId = 'cus_xxxxxxxxxxxxxx'; // Optional: replace with a specific customer ID
41
+
42
+ return (
43
+ <div>
44
+ <h2>My Credit Grants</h2>
45
+ <CreditGrantsList customer_id={customerId} pageSize={5} />
46
+ </div>
47
+ );
48
+ };
49
+
50
+ // Your main App component where you set up the providers.
51
+ const App = () => {
52
+ const { session, connectApi } = useSessionContext();
53
+
54
+ // Render the PaymentProvider only when the session is ready.
55
+ if (!session) {
56
+ return <div>Loading session...</div>;
57
+ }
58
+
59
+ return (
60
+ <PaymentProvider session={session} connectApi={connectApi}>
61
+ <MyCreditGrantsPage />
62
+ </PaymentProvider>
63
+ );
64
+ };
65
+
66
+ export default App;
67
+ ```
68
+
69
+ In this example, the `App` component retrieves `session` and `connectApi` using a local `useSessionContext` hook and passes them to `PaymentProvider`. The `MyCreditGrantsPage` component then renders `CreditGrantsList` within this context, ensuring it has access to the necessary data.
70
+
71
+ ## Displayed Information
72
+
73
+ The component renders a table with the following columns, providing a detailed overview of each credit grant:
74
+
75
+ - **Name**: The name of the credit grant, or its ID if no name is provided.
76
+ - **Status**: The current status of the grant (e.g., `granted`, `pending`, `expired`), displayed using a color-coded chip for easy identification.
77
+ - **Remaining Credit**: The amount of credit still available in the grant, along with the currency symbol.
78
+ - **Scope**: Indicates whether the credit is `general` (applicable to any charge) or `specific` (applicable only to certain prices).
79
+ - **Effective Date**: The date and time when the credit grant becomes active.
80
+ - **Expiration Date**: The date and time when the credit grant expires. A hyphen (`-`) is shown if there is no expiration date.
81
+
82
+ Each row in the table is clickable, navigating the user to a detailed view of that specific credit grant.
83
+
84
+ ## StatusChip Helper
85
+
86
+ The `CreditGrantsList` utilizes an internal `StatusChip` component to visually represent the status of each grant. The colors are mapped as follows:
87
+
88
+ | Status | Color |
89
+ |-----------|---------|
90
+ | `granted` | Success |
91
+ | `pending` | Warning |
92
+ | `expired` | Default |
93
+ | `depleted`| Default |
94
+ | `voided` | Default |
95
+
96
+ ---
97
+
98
+ Next, you can explore how to display a detailed log of credit usage with the [CreditTransactionsList](./components-history-credit-transactions-list.md) component.