@blocklet/payment-react 1.20.4 → 1.20.6

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 (55) hide show
  1. package/.aigne/doc-smith/config.yaml +2 -2
  2. package/.aigne/doc-smith/upload-cache.yaml +381 -0
  3. package/docs/components-business-auto-topup.md +128 -179
  4. package/docs/components-business-overdue-invoice-payment.md +108 -143
  5. package/docs/components-business-resume-subscription.md +117 -104
  6. package/docs/components-business.md +12 -36
  7. package/docs/components-checkout-checkout-donate.md +209 -149
  8. package/docs/components-checkout-checkout-form.md +115 -136
  9. package/docs/components-checkout-checkout-table.md +92 -172
  10. package/docs/components-checkout.md +43 -109
  11. package/docs/components-history-credit-grants-list.md +45 -70
  12. package/docs/components-history-credit-transactions-list.md +57 -67
  13. package/docs/components-history-invoice-list.md +58 -52
  14. package/docs/components-history-payment-list.md +19 -40
  15. package/docs/components-history.md +42 -67
  16. package/docs/components-ui-form-elements-address-form.md +37 -65
  17. package/docs/components-ui-form-elements-country-select.md +80 -59
  18. package/docs/components-ui-form-elements-currency-selector.md +57 -73
  19. package/docs/components-ui-form-elements-phone-input.md +90 -112
  20. package/docs/components-ui-form-elements.md +46 -80
  21. package/docs/components-ui-payment-summary.md +71 -119
  22. package/docs/components-ui-pricing-table.md +117 -204
  23. package/docs/components-ui.md +59 -32
  24. package/docs/components.md +89 -62
  25. package/docs/getting-started.md +36 -63
  26. package/docs/guides-theming.md +122 -84
  27. package/docs/guides-utilities.md +107 -145
  28. package/docs/guides.md +7 -84
  29. package/docs/hooks-use-mobile.md +50 -36
  30. package/docs/hooks-use-subscription.md +72 -89
  31. package/docs/hooks.md +12 -82
  32. package/docs/overview.md +45 -52
  33. package/docs/providers-donate-provider.md +73 -95
  34. package/docs/providers-payment-provider.md +115 -169
  35. package/docs/providers.md +27 -86
  36. package/es/locales/en.js +7 -0
  37. package/es/locales/zh.js +8 -1
  38. package/es/payment/index.js +3 -0
  39. package/es/payment/progress-item.d.ts +12 -0
  40. package/es/payment/progress-item.js +78 -0
  41. package/es/payment/success.d.ts +4 -1
  42. package/es/payment/success.js +55 -3
  43. package/lib/locales/en.js +7 -0
  44. package/lib/locales/zh.js +8 -1
  45. package/lib/payment/index.js +3 -0
  46. package/lib/payment/progress-item.d.ts +12 -0
  47. package/lib/payment/progress-item.js +107 -0
  48. package/lib/payment/success.d.ts +4 -1
  49. package/lib/payment/success.js +59 -3
  50. package/package.json +7 -7
  51. package/src/locales/en.tsx +7 -0
  52. package/src/locales/zh.tsx +8 -1
  53. package/src/payment/index.tsx +6 -0
  54. package/src/payment/progress-item.tsx +107 -0
  55. package/src/payment/success.tsx +88 -3
@@ -1,78 +1,74 @@
1
1
  # DonateProvider
2
2
 
3
- The `DonateProvider` is a context provider that manages the state and settings for donation-related components, such as `CheckoutDonate`. It handles fetching donation configurations, updating settings, and providing this data to its children components. To function correctly, `DonateProvider` must be placed within a [`PaymentProvider`](./providers-payment-provider.md).
3
+ The `DonateProvider` is a crucial context provider that manages the state and settings for all donation-related components within your application. It handles fetching configuration from the backend, caching it for performance, and providing it to components like `CheckoutDonate`.
4
4
 
5
- ```d2
6
- direction: down
5
+ To use any donation features, you must wrap your components with `DonateProvider`. This provider must also be nested within a [`PaymentProvider`](./providers-payment-provider.md) to ensure access to the necessary payment context and session information.
7
6
 
8
- "PaymentProvider": {
9
- shape: package
7
+ ## How It Works
10
8
 
11
- "DonateProvider": {
12
- shape: package
9
+ The `DonateProvider` performs several key functions:
13
10
 
14
- "CheckoutDonate": {
15
- shape: document
16
- label: "CheckoutDonate Component"
17
- }
18
- }
19
- }
20
-
21
- "PaymentProvider" -> "DonateProvider" -> "CheckoutDonate": "Provides Context"
22
- ```
23
-
24
- This structure ensures that donation components have access to both the general payment context and the specific donation settings.
11
+ 1. **Fetches Settings**: On mount, it calls an API endpoint to retrieve the donation settings associated with the unique `mountLocation` prop. These settings determine the behavior of child donation components.
12
+ 2. **Caches Data**: To improve performance and reduce network requests, the fetched settings are stored in `localStorage`. The cache is automatically used on subsequent loads and can be manually cleared if needed.
13
+ 3. **Provides Context**: It uses React's Context API to pass down the settings and control functions (`refresh`, `updateSettings`) to any descendant component that needs them.
14
+ 4. **Enables Donations**: For administrative users ('owner' or 'admin'), if the donation instance is inactive but the `enableDonate` prop is set, the provider will render a UI to activate it.
25
15
 
26
16
  ## Props
27
17
 
28
18
  The `DonateProvider` accepts the following props to configure its behavior:
29
19
 
30
- | Prop | Type | Required | Description |
31
- |---|---|---|---|
32
- | `mountLocation` | `string` | Yes | A unique identifier for this specific donation instance. It's used to fetch and store settings, ensuring that different donation points in your application have their own configurations. |
33
- | `description` | `string` | Yes | A description to help identify this donation instance in logs or admin interfaces. |
34
- | `defaultSettings` | `DonateConfigSettings` | No | An object with default settings for the donation component. These settings are used when no configuration has been saved for the given `mountLocation`. |
35
- | `children` | `any` | Yes | The child components that will be rendered within the provider. Typically, this will include one or more `CheckoutDonate` components. |
36
- | `active` | `boolean` | No | A flag to control whether the donation functionality is active. Defaults to `true`. |
37
- | `enableDonate` | `boolean` | No | If set to `true`, it allows administrators to enable a disabled donation instance directly from the UI. Defaults to `false`. |
38
-
39
- ### DonateConfigSettings
40
-
41
- The `defaultSettings` prop accepts an object with the following structure:
42
-
43
- | Key | Type | Description |
44
- |---|---|---|
45
- | `amount` | `object` | Configuration for donation amounts. Contains `presets` (array of strings), `preset` (string), `custom` (boolean), `minimum` (string), and `maximum` (string). |
46
- | `btnText` | `string` | Custom text for the main donation button (e.g., "Like", "Support"). |
47
- | `historyType` | `'table' \| 'avatar'` | Defines the display style for the donation history. |
20
+ | Prop | Type | Required | Description |
21
+ | ----------------- | ---------------------------------- | :------: | ---------------------------------------------------------------------------------------------------------------------------------------- |
22
+ | `mountLocation` | `string` | Yes | A unique string identifier for this specific donation instance. This is used as the key for fetching, caching, and updating settings. |
23
+ | `description` | `string` | Yes | A human-readable description to help identify this donation instance in the system backend or logs. |
24
+ | `children` | `ReactNode` | Yes | The child components that will render inside the provider, typically including `CheckoutDonate`. |
25
+ | `defaultSettings` | `DonateConfigSettings` | No | An object with default settings to apply if no settings are found on the backend. See the type definition below for available options. |
26
+ | `active` | `boolean` | No | Sets the initial active state for the donation instance when it's first created. Defaults to `true`. |
27
+ | `enableDonate` | `boolean` | No | If `true`, allows admin users to enable this donation instance from the UI if it's currently inactive. Defaults to `false`. |
28
+
29
+ ### DonateConfigSettings Type
30
+
31
+ This is the shape of the `defaultSettings` object:
32
+
33
+ ```typescript DonateConfigSettings type
34
+ export interface DonateConfigSettings {
35
+ amount?: {
36
+ presets?: string[]; // e.g., ['1', '5', '10']
37
+ preset?: string; // Default selected preset amount
38
+ custom: boolean; // Allow users to enter a custom amount
39
+ minimum?: string; // Minimum custom amount
40
+ maximum?: string; // Maximum custom amount
41
+ };
42
+ btnText?: string; // Text for the main donation button, e.g., "Donate"
43
+ historyType?: 'table' | 'avatar'; // How to display the list of supporters
44
+ }
45
+ ```
48
46
 
49
47
  ## Usage Example
50
48
 
51
- Here is a complete example of how to set up `DonateProvider` to wrap a `CheckoutDonate` component. This setup ensures that the donation button has access to the necessary context from both providers.
49
+ Here is a complete example of setting up a donation section on a page. It shows how to wrap `CheckoutDonate` with both `DonateProvider` and `PaymentProvider`.
52
50
 
53
- ```tsx
51
+ ```tsx App.tsx icon=logos:react
54
52
  import {
55
53
  PaymentProvider,
56
54
  DonateProvider,
57
55
  CheckoutDonate,
58
56
  } from '@blocklet/payment-react';
59
- // This is a custom hook to get session context from your application.
60
- // See the PaymentProvider documentation for more on session setup.
61
- import { useSessionContext } from '../hooks/use-session-context';
57
+ import { useSessionContext } from './hooks/use-session'; // Your custom session hook
62
58
 
63
59
  function DonationSection() {
64
60
  const { session, connectApi } = useSessionContext();
65
61
 
66
- // Render a loading state or null until the session is available
67
- if (!session) {
68
- return <div>Loading session...</div>;
62
+ // Render nothing or a login prompt if the user is not authenticated
63
+ if (!session?.user) {
64
+ return <div>Please log in to make a donation.</div>;
69
65
  }
70
66
 
71
67
  return (
72
68
  <PaymentProvider session={session} connect={connectApi}>
73
69
  <DonateProvider
74
- mountLocation="unique-blog-post-123"
75
- description="Donation button for the blog post about React Hooks"
70
+ mountLocation="support-our-blog-post-123"
71
+ description="Donation for the article 'Getting Started with React'"
76
72
  defaultSettings={{
77
73
  btnText: 'Support the Author',
78
74
  amount: {
@@ -83,13 +79,13 @@ function DonationSection() {
83
79
  }}>
84
80
  <CheckoutDonate
85
81
  settings={{
86
- target: 'post-123',
87
- title: 'Support Author',
88
- description: 'If you find this article helpful, feel free to buy me a coffee',
82
+ target: 'post-123', // A unique identifier for the donation target
83
+ title: 'Support the Author',
84
+ description: 'If you found this article helpful, feel free to buy me a coffee.',
89
85
  reference: 'https://your-site.com/posts/123',
90
86
  beneficiaries: [
91
87
  {
92
- address: 'user-did-address',
88
+ address: 'z8iZ75n8fWJ2aL1c9a9f4c3b2e1a0d9f8e7d6c5b4a392817',
93
89
  share: '100',
94
90
  },
95
91
  ],
@@ -101,75 +97,57 @@ function DonationSection() {
101
97
  }
102
98
  ```
103
99
 
104
- ## Using the Context
105
-
106
- You can access the donation context's state and functions using the `useDonateContext` hook. This is useful for building custom UI or logic that interacts with the donation settings.
107
-
108
- ### Context Values
100
+ ## Hooks and Utilities
109
101
 
110
- The `useDonateContext` hook returns an object with the following properties:
102
+ The library also exports several helper functions for advanced control over the donation context and cache.
111
103
 
112
- | Key | Type | Description |
113
- |---|---|---|
114
- | `settings` | `TSetting` | An object containing the current settings for the donation instance, including its active status and configuration. |
115
- | `refresh` | `(forceRefresh?: boolean) => void` | A function to manually trigger a refresh of the donation settings from the server. Pass `true` to bypass the cache. |
116
- | `updateSettings` | `(newSettings: DonateConfigSettings) => Promise<void>` | An async function to update and persist new settings for the donation instance. |
117
- | `api` | `Axios` | An Axios instance configured for making requests to the payment API. |
104
+ ### `useDonateContext`
118
105
 
119
- ### Example
106
+ A React hook to access the donation context directly from any child component of `DonateProvider`.
120
107
 
121
108
  ```tsx
122
109
  import { useDonateContext } from '@blocklet/payment-react';
123
- import { Button, Typography } from '@mui/material';
124
-
125
- function CustomDonateUI() {
126
- const { settings, refresh, updateSettings } = useDonateContext();
127
-
128
- const handleUpdateBtnText = async () => {
129
- try {
130
- await updateSettings({ btnText: 'New Button Text!' });
131
- // The settings will be automatically refreshed after update.
132
- } catch (error) {
133
- console.error('Failed to update settings:', error);
134
- }
135
- };
110
+
111
+ function CustomDonationInfo() {
112
+ const { settings, refresh } = useDonateContext();
136
113
 
137
114
  return (
138
115
  <div>
139
- <Typography>Current Button Text: {settings.settings?.btnText}</Typography>
140
- <Button onClick={handleUpdateBtnText}>Change Text</Button>
141
- <Button onClick={() => refresh(true)}>Force Refresh</Button>
116
+ <p>Donations are currently {settings.active ? 'enabled' : 'disabled'}.</p>
117
+ <button onClick={() => refresh(true)}>Refresh Settings</button>
142
118
  </div>
143
119
  );
144
120
  }
145
121
  ```
146
122
 
147
- ## Utility Functions
148
-
149
- The library also exports utility functions to manage the donation settings cache outside of the React component lifecycle.
123
+ ### `clearDonateCache`
150
124
 
151
- ### clearDonateCache
125
+ This function manually removes the cached settings for a specific `mountLocation` from `localStorage`. This is useful when you know the settings have changed on the server and you want to force a fresh fetch on the next component render.
152
126
 
153
- Removes the cached settings for a specific `mountLocation` from `localStorage`.
154
-
155
- ```tsx
127
+ ```javascript
156
128
  import { clearDonateCache } from '@blocklet/payment-react';
157
129
 
158
- // Call this when you know the settings are stale, for example after a user logs out.
159
- clearDonateCache('unique-blog-post-123');
130
+ // Call this function when you need to invalidate the cache
131
+ clearDonateCache('support-our-blog-post-123');
160
132
  ```
161
133
 
162
- ### clearDonateSettings
134
+ ### `clearDonateSettings`
163
135
 
164
- Sends a `DELETE` request to the server to completely remove the settings for a `mountLocation` and also clears the local cache.
136
+ This function sends a `DELETE` request to the backend API to permanently remove the settings for a given `mountLocation`. It also clears the local cache for that location.
165
137
 
166
- ```tsx
138
+ ```javascript
167
139
  import { clearDonateSettings } from '@blocklet/payment-react';
168
140
 
169
- // Use this to reset a donation instance to its default state.
170
- async function resetDonationSettings() {
171
- await clearDonateSettings('unique-blog-post-123');
141
+ async function deleteDonationInstance() {
142
+ try {
143
+ await clearDonateSettings('support-our-blog-post-123');
144
+ console.log('Donation settings have been deleted.');
145
+ } catch (error) {
146
+ console.error('Failed to delete settings:', error);
147
+ }
172
148
  }
173
149
  ```
174
150
 
175
- After setting up the provider, the next step is to implement the donation UI using the [`CheckoutDonate`](./components-checkout-checkout-donate.md) component to render the donation widget and display donation history.
151
+ With `DonateProvider` configured, you can now implement various donation features. The next step is to explore the main component for displaying the donation UI.
152
+
153
+ ➡️ Next, learn how to use the [`CheckoutDonate`](./components-checkout-checkout-donate.md) component to render the donation widget.
@@ -1,245 +1,191 @@
1
1
  # PaymentProvider
2
2
 
3
- The `PaymentProvider` is the cornerstone of the `@blocklet/payment-react` library. It's a context provider that must wrap your application or the specific sections that utilize payment components. It initializes the payment context, fetches necessary settings from the Payment Kit, and makes payment functions and data available to all its child components.
3
+ The `PaymentProvider` is the cornerstone of the `@blocklet/payment-react` library. It functions as a context provider that must wrap your application or the relevant payment-related components. It handles fetching essential settings, managing application state, and providing helper functions and an API client to all its children.
4
4
 
5
- Any component from this library, such as `CheckoutForm` or `CustomerInvoiceList`, must be nested within a `PaymentProvider` to function correctly.
5
+ Nearly every component and hook in this library requires being nested within a `PaymentProvider` to function correctly.
6
+
7
+ ## How It Works
8
+
9
+ The provider initializes and fetches configuration data from the Payment Kit backend when it mounts. This data, along with the user's session and other utilities, is then made available to any descendant component via the `usePaymentContext` hook. This pattern ensures that your payment components always have access to the necessary context without prop drilling.
6
10
 
7
11
  ```d2
8
12
  direction: down
9
13
 
10
- "Your React App": {
11
- "PaymentProvider": {
12
- shape: package
14
+ Your-Application: {
15
+ label: "Your Application"
16
+ shape: rectangle
13
17
 
14
- "Payment Components": {
15
- grid-columns: 3
16
-
17
- "CheckoutForm": {shape: document}
18
- "CustomerInvoiceList": {shape: document}
19
- "Custom Component (usePaymentContext)": {shape: document}
20
- }
18
+ PaymentProvider: {
19
+ label: "PaymentProvider"
20
+ style.fill: "#d1e7dd"
21
+ }
21
22
 
23
+ Payment-Components: {
24
+ label: "Payment Components\n(e.g., CheckoutForm)"
25
+ shape: rectangle
26
+ style.fill: "#cfe2ff"
22
27
  }
23
28
  }
24
29
 
25
- "PaymentProvider" -> "Payment Components": "Provides context"
30
+ Payment-Kit-API: {
31
+ label: "Payment Kit API"
32
+ shape: cylinder
33
+ }
26
34
 
27
- ```
35
+ Your-Application.PaymentProvider -> Payment-Kit-API: "1. Fetches settings & methods"
36
+ Your-Application.PaymentProvider -> Your-Application.Payment-Components: "2. Provides context (session, settings, API client)"
37
+ Your-Application.Payment-Components -> Payment-Kit-API: "3. Makes API calls (e.g., create checkout)"
28
38
 
29
- ## Prerequisite: Setting Up the Session Context
39
+ ```
30
40
 
31
- The `PaymentProvider` requires `session` and `connect` props, which are typically managed by `@arcblock/did-connect-react`. To streamline their use across your application, it's best practice to create a dedicated session context.
41
+ ## Setup and Usage
32
42
 
33
- Create a file, for example, at `src/contexts/session.tsx`, with the following content. This will create a `SessionProvider` to wrap your app and a `useSessionContext` hook to access session data easily.
43
+ To use `PaymentProvider`, you need to supply it with `session` and `connect` objects from your application's authentication context. Throughout this documentation, we'll use a custom hook `useSessionContext` to represent your app's authentication logic. Here is a typical implementation of such a hook:
34
44
 
35
- ```tsx
36
- // src/contexts/session.tsx
37
- import { createAuthServiceSessionContext } from '@arcblock/did-connect-react/lib/Session';
38
- import { useContext } from 'react';
45
+ ```typescript SessionContext.tsx icon=logos:react
46
+ import React, { createContext, useContext } from 'react';
47
+ import { SessionProvider, useSessionContext as useDidSessionContext } from '@arcblock/did-connect-react';
39
48
 
40
- const { SessionProvider, SessionContext, SessionConsumer, withSession } = createAuthServiceSessionContext();
49
+ // You can create your own context or use an existing one
50
+ const AppContext = createContext({});
41
51
 
42
- function useSessionContext() {
43
- const info = useContext(SessionContext);
44
- return info;
52
+ export function AppProvider({ children }) {
53
+ return (
54
+ <SessionProvider>
55
+ <AppContext.Provider value={{}}>
56
+ {children}
57
+ </AppContext.Provider>
58
+ </SessionProvider>
59
+ );
45
60
  }
46
61
 
47
- export { SessionProvider, SessionContext, SessionConsumer, useSessionContext, withSession };
62
+ // This custom hook provides the session and connectApi to PaymentProvider
63
+ export function useSessionContext() {
64
+ const { session, connect } = useDidSessionContext();
65
+ return { session, connectApi: connect };
66
+ }
48
67
  ```
49
68
 
50
- Then, wrap your application's root component with the `SessionProvider` you just created:
69
+ Once you have your session management in place, wrap your main application component with `PaymentProvider`.
51
70
 
52
- ```tsx
53
- // src/App.tsx
54
- import { SessionProvider } from './contexts/session';
71
+ ```tsx App.tsx icon=logos:react
72
+ import { PaymentProvider } from '@blocklet/payment-react';
73
+ import { useSessionContext } from './SessionContext'; // Your session context hook
74
+ import MyPaymentPage from './MyPaymentPage';
55
75
 
56
76
  function App() {
77
+ const { session, connectApi } = useSessionContext();
78
+
57
79
  return (
58
- <SessionProvider>
59
- {/* Your application components */}
60
- </SessionProvider>
80
+ <PaymentProvider session={session} connect={connectApi}>
81
+ <MyPaymentPage />
82
+ </PaymentProvider>
61
83
  );
62
84
  }
85
+
86
+ export default App;
63
87
  ```
64
88
 
65
89
  ## Props
66
90
 
67
- The `PaymentProvider` accepts the following props to configure the payment environment.
91
+ The `PaymentProvider` component accepts the following props:
68
92
 
69
93
  | Prop | Type | Required | Description |
70
- |---|---|---|---|
71
- | `session` | `SessionContext['session']` | Yes | The user session object obtained from `useSessionContext()`. It contains essential user data like their DID. |
72
- | `connect` | `SessionContext['connectApi']` | Yes | The connect API instance from `useSessionContext()`, used for handling DID Connect interactions. |
73
- | `children`| `React.ReactNode` | Yes | The React components or part of your application tree that needs access to the payment context. |
74
- | `baseUrl` | `string` | No | The base URL of the Payment Kit blocklet. This is only necessary if your application and the Payment Kit are running on different origins. The provider uses this URL to fetch configuration for cross-origin API requests. |
75
- | `authToken` | `string` | No | An optional authentication token. If provided, it will be used for API requests, overriding the default token from the session. |
94
+ | --- | --- | --- | --- |
95
+ | `session` | `Session` | Yes | The user session object from your authentication context (e.g., `@arcblock/did-connect-react`). |
96
+ | `connect` | `Connect` | Yes | The `connect` API function from your authentication context, used for DID Connect operations. |
97
+ | `children` | `React.ReactNode` | Yes | The child components that will have access to the payment context. |
98
+ | `baseUrl` | `string` | No | The base URL of the Payment Kit blocklet. Required only when integrating payment components from a different origin (cross-origin). |
99
+ | `authToken` | `string` | No | A specific authentication token for API requests. If provided, it will be used instead of the session-based authentication. |
76
100
 
77
- ## Basic Integration
78
101
 
79
- To get started, wrap your main application component or the relevant layout with `PaymentProvider`. The required `session` and `connectApi` props are obtained from the `useSessionContext` hook you created earlier.
102
+ ## Context Values
80
103
 
81
- ```tsx
82
- import { PaymentProvider, CheckoutForm } from '@blocklet/payment-react';
83
- import { useSessionContext } from './contexts/session'; // Adjust path as needed
104
+ Components within `PaymentProvider` can access the following values using the `usePaymentContext` hook.
84
105
 
85
- function App() {
86
- const { session, connectApi } = useSessionContext();
106
+ ```typescript MyComponent.tsx icon=logos:react
107
+ import { usePaymentContext } from '@blocklet/payment-react';
87
108
 
88
- if (!session.user) {
89
- // Render a login button or a loading state
90
- return <button onClick={() => connectApi.open()}>Login</button>;
91
- }
109
+ function MyComponent() {
110
+ const { settings, livemode, setLivemode } = usePaymentContext();
92
111
 
93
112
  return (
94
- <PaymentProvider session={session} connect={connectApi}>
95
- {/* All child components now have access to the payment context */}
96
- <h1>My Store</h1>
97
- <CheckoutForm
98
- id="plink_xxx" // A valid Payment Link ID
99
- mode="inline"
100
- />
101
- </PaymentProvider>
113
+ <div>
114
+ <p>Base Currency: {settings.baseCurrency?.name}</p>
115
+ <p>Mode: {livemode ? 'Live' : 'Test'}</p>
116
+ <button onClick={() => setLivemode(!livemode)}>Toggle Mode</button>
117
+ </div>
102
118
  );
103
119
  }
104
120
  ```
105
121
 
106
- ## Advanced Usage
107
-
108
- ### Cross-Origin Communication with `baseUrl`
122
+ Here is a complete list of available context values:
109
123
 
110
- If your payment blocklet is hosted on a different domain than your main application (e.g., `payments.example.com` vs `app.example.com`), you must provide the `baseUrl` prop. The `PaymentProvider` will use this URL to correctly resolve API endpoints and fetch necessary blocklet information for seamless cross-origin communication.
111
-
112
- ```tsx
113
- import { PaymentProvider, CustomerInvoiceList } from '@blocklet/payment-react';
114
- import { useSessionContext } from './contexts/session';
115
-
116
- function MyAccountPage() {
117
- const { session, connectApi } = useSessionContext();
118
- const paymentKitBaseUrl = 'https://your-payment-blocklet-domain.com';
124
+ | Key | Type | Description |
125
+ | --- | --- | --- |
126
+ | `session` | `object` | The authenticated user session, including user details. |
127
+ | `connect` | `function` | The `connect` function for initiating DID Wallet interactions. |
128
+ | `livemode` | `boolean` | Indicates if the context is in live (`true`) or test (`false`) mode. |
129
+ | `setLivemode` | `(livemode: boolean) => void` | A function to toggle between live and test modes. This will trigger a refetch of settings. |
130
+ | `settings` | `Settings` | An object containing `paymentMethods` and `baseCurrency` configuration fetched from the backend. |
131
+ | `refresh` | `(forceRefresh?: boolean) => void` | A function to manually trigger a refetch of the settings data. |
132
+ | `getCurrency` | `(id: string) => TPaymentCurrency` | A helper function to retrieve a specific currency's details by its ID. |
133
+ | `getMethod` | `(id: string) => TPaymentMethodExpanded` | A helper function to retrieve a specific payment method's details by its ID. |
134
+ | `api` | `AxiosInstance` | A pre-configured Axios instance for making authenticated API calls to the Payment Kit backend. |
135
+ | `prefix` | `string` | The URL prefix of the blocklet. |
136
+ | `payable` | `boolean` | A state that can be used to control the availability of payment actions. |
137
+ | `setPayable` | `(status: boolean) => void` | A function to update the `payable` status. |
119
138
 
120
- if (!session.user) {
121
- return <button onClick={() => connectApi.open()}>Login</button>;
122
- }
123
139
 
124
- return (
125
- <PaymentProvider
126
- session={session}
127
- connect={connectApi}
128
- baseUrl={paymentKitBaseUrl}
129
- >
130
- <h2>My Invoice History</h2>
131
- <CustomerInvoiceList />
132
- </PaymentProvider>
133
- );
134
- }
135
- ```
140
+ ## Advanced Scenarios
136
141
 
137
- ### Using a Custom `authToken`
142
+ ### Cross-Origin Integration
138
143
 
139
- In scenarios where you need to use a specific API token instead of relying on the user's session—for example, in a backend-for-frontend pattern or when using a service account token—you can pass the `authToken` prop. This token will be used for all subsequent API requests made by the components within the provider.
144
+ If your application and the Payment Kit blocklet are hosted on different domains, you must use the `baseUrl` prop. This allows `PaymentProvider` to correctly locate and communicate with the Payment Kit API.
140
145
 
141
- ```tsx
142
- import { PaymentProvider, ResumeSubscription } from '@blocklet/payment-react';
143
- import { useSessionContext } from './contexts/session';
146
+ ```tsx CrossOriginApp.tsx icon=logos:react
147
+ import { PaymentProvider } from '@blocklet/payment-react';
148
+ import { useSessionContext } from './SessionContext';
144
149
 
145
- function SubscriptionManager({ temporaryAuthToken }) {
150
+ function CrossOriginApp() {
146
151
  const { session, connectApi } = useSessionContext();
147
152
 
148
- if (!session.user) {
149
- return <button onClick={() => connectApi.open()}>Login</button>;
150
- }
151
-
152
153
  return (
153
154
  <PaymentProvider
154
155
  session={session}
155
- connect={connectApi}
156
- authToken={temporaryAuthToken}
156
+ connect={connectApi}
157
+ baseUrl="https://payment-kit.another-domain.com"
157
158
  >
158
- <ResumeSubscription subscriptionId="sub_xxx" />
159
+ {/* Your payment components */}
159
160
  </PaymentProvider>
160
161
  );
161
162
  }
162
163
  ```
163
164
 
164
- ## Accessing Context Data with `usePaymentContext`
165
-
166
- Child components can access the data and functions provided by `PaymentProvider` using the `usePaymentContext` hook. This hook provides access to settings, the current operational mode, a pre-configured API client, and more.
167
-
168
- ### Context Values
169
-
170
- Here are the key values returned by the `usePaymentContext` hook:
171
-
172
- | Key | Type | Description |
173
- |---|---|---|
174
- | `settings` | `object` | An object containing available `paymentMethods` and the `baseCurrency`. |
175
- | `livemode` | `boolean` | Returns `true` for live mode and `false` for test mode. This state is persisted in local storage. |
176
- | `setLivemode` | `(livemode: boolean) => void` | A function to toggle between live and test mode. |
177
- | `api` | `AxiosInstance` | A pre-configured Axios instance for making authenticated requests to the Payment Kit API. |
178
- | `refresh` | `(forceRefresh?: boolean) => void` | A function to manually trigger a refresh of the settings data. |
179
- | `getCurrency` | `(id: string) => TPaymentCurrency` | A helper function to find a currency object by its ID from the settings. |
180
- | `getMethod` | `(id: string) => TPaymentMethodExpanded` | A helper function to find a payment method object by its ID from the settings. |
181
- | `session` | `object` | The currently active user session object that was passed to the provider. |
182
-
183
- ### Example: Custom Payment Info Component
184
-
185
- This example shows a component that uses the `usePaymentContext` hook to display the current mode and a list of available payment methods.
186
-
187
- ```tsx
188
- import { usePaymentContext } from '@blocklet/payment-react';
189
- import { useSessionContext } from './contexts/session';
190
- import { Chip, List, ListItem, ListItemText, Typography, Button } from '@mui/material';
165
+ ### Custom Authentication Token
191
166
 
192
- function PaymentInfo() {
193
- const { settings, livemode, refresh, setLivemode } = usePaymentContext();
167
+ In scenarios where you need to use a specific API token instead of the default session-based authentication (e.g., for server-to-server communication or specific access grants), you can pass the `authToken` prop.
194
168
 
195
- return (
196
- <div>
197
- <Typography variant="h6" component="h2" gutterBottom>
198
- Payment Status
199
- {livemode ?
200
- <Chip label="Live Mode" color="success" size="small" sx={{ ml: 1 }} /> :
201
- <Chip label="Test Mode" color="warning" size="small" sx={{ ml: 1 }} />
202
- }
203
- </Typography>
204
-
205
- <Typography>Available Payment Methods:</Typography>
206
- <List dense>
207
- {settings.paymentMethods.map(method => (
208
- <ListItem key={method.id}>
209
- <ListItemText primary={method.name} />
210
- </ListItem>
211
- ))}
212
- </List>
213
-
214
- <Button variant="outlined" onClick={() => setLivemode(!livemode)} sx={{ mr: 1 }}>
215
- Toggle Mode
216
- </Button>
217
- <Button variant="outlined" onClick={() => refresh(true)}>
218
- Refresh Settings
219
- </Button>
220
- </div>
221
- );
222
- }
169
+ ```tsx TokenAuthApp.tsx icon=logos:react
170
+ import { PaymentProvider } from '@blocklet/payment-react';
171
+ import { useSessionContext } from './SessionContext';
223
172
 
224
- // This component must be rendered inside a <PaymentProvider>
225
- function AppWithPaymentInfo() {
173
+ function TokenAuthApp() {
226
174
  const { session, connectApi } = useSessionContext();
227
-
228
- if (!session.user) {
229
- return <button onClick={() => connectApi.open()}>Login</button>;
230
- }
175
+ const myCustomAuthToken = 'sk_xxxxxx'; // Your secret token
231
176
 
232
177
  return (
233
- <PaymentProvider session={session} connect={connectApi}>
234
- <PaymentInfo />
178
+ <PaymentProvider
179
+ session={session}
180
+ connect={connectApi}
181
+ authToken={myCustomAuthToken}
182
+ >
183
+ {/* Components will use the provided authToken for API calls */}
235
184
  </PaymentProvider>
236
185
  );
237
186
  }
238
187
  ```
239
188
 
240
- ## Next Steps
241
-
242
- With `PaymentProvider` set up, you are ready to integrate other components. A good next step is to implement a donation flow or build a checkout page.
189
+ ---
243
190
 
244
- - **[DonateProvider](./providers-donate-provider.md)**: Learn how to configure the context for donation-related components.
245
- - **[CheckoutForm](./components-checkout-checkout-form.md)**: Dive into the primary component for handling payments and checkout sessions.
191
+ With `PaymentProvider` set up, you are now ready to start integrating payment components into your application. A good next step is to explore how to create a payment flow using the [CheckoutForm](./components-checkout-checkout-form.md) component.