@mayarin/react 0.1.0-next.0
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.
- package/LICENSE +201 -0
- package/README.md +44 -0
- package/dist/index.d.ts +83 -0
- package/dist/index.js +158 -0
- package/dist/index.js.map +1 -0
- package/package.json +35 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright 2026 Playrig Labs
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
package/README.md
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
# `@mayarin/react`
|
|
2
|
+
|
|
3
|
+
A pay button and a headless hook that send a buyer to Mayarin's hosted checkout, from any React 18+
|
|
4
|
+
app. Full guide: <https://docs.mayarin.xyz/sdk/typescript/react>.
|
|
5
|
+
|
|
6
|
+
```bash
|
|
7
|
+
npm install @mayarin/react@next @mayarin/sdk@next
|
|
8
|
+
```
|
|
9
|
+
|
|
10
|
+
## Server mode — anything you sell
|
|
11
|
+
|
|
12
|
+
Your backend mints the checkout with its secret key (`@mayarin/sdk`) and returns the URL. The price
|
|
13
|
+
never leaves the server.
|
|
14
|
+
|
|
15
|
+
```tsx
|
|
16
|
+
import { PayButton } from "@mayarin/react";
|
|
17
|
+
|
|
18
|
+
<PayButton
|
|
19
|
+
checkout={() => fetch("/api/pay", { method: "POST" }).then((r) => r.json())}
|
|
20
|
+
>
|
|
21
|
+
Pay with crypto
|
|
22
|
+
</PayButton>;
|
|
23
|
+
```
|
|
24
|
+
|
|
25
|
+
## Browser mode — donations, tips, pay-what-you-want
|
|
26
|
+
|
|
27
|
+
No backend: the browser mints the checkout with a publishable key (`pk_...`). The amount is whatever
|
|
28
|
+
the browser sends, so for a sale check the paid amount against your order in the webhook.
|
|
29
|
+
|
|
30
|
+
```tsx
|
|
31
|
+
<PayButton
|
|
32
|
+
publishableKey="pk_..."
|
|
33
|
+
baseUrl="https://api-testnet.mayarin.xyz"
|
|
34
|
+
amount="150000.00"
|
|
35
|
+
currency="IDR"
|
|
36
|
+
merchantReference="donation_42"
|
|
37
|
+
successUrl="https://shop.example/thanks"
|
|
38
|
+
/>
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
`useMayarinCheckout(options)` is the same flow without the button: wire its `redirect` to any
|
|
42
|
+
element.
|
|
43
|
+
|
|
44
|
+
Never pass a secret key (`sk_...`) to either — the SDK refuses it.
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
import { MayarinBrowserClient } from "@mayarin/sdk/browser";
|
|
2
|
+
import { ButtonHTMLAttributes, ReactNode } from "react";
|
|
3
|
+
//#region src/checkout.d.ts
|
|
4
|
+
/** The `POST /v1/carts/checkout` body, as the SDK types it. */
|
|
5
|
+
type CartBody = Parameters<MayarinBrowserClient["commerce"]["carts"]["checkout"]>[0];
|
|
6
|
+
/** What a server-mode `checkout` resolves to: the URL, or an object carrying it. */
|
|
7
|
+
type CheckoutUrl = string | {
|
|
8
|
+
readonly url: string;
|
|
9
|
+
};
|
|
10
|
+
interface ServerCheckout {
|
|
11
|
+
/** Calls your backend, which mints the intent and returns its checkout URL. */
|
|
12
|
+
readonly checkout: () => Promise<CheckoutUrl>;
|
|
13
|
+
readonly publishableKey?: never;
|
|
14
|
+
}
|
|
15
|
+
interface BrowserCheckout {
|
|
16
|
+
readonly checkout?: never;
|
|
17
|
+
/** A `pk_...` key from the dashboard. It names the merchant; no merchant id is needed. */
|
|
18
|
+
readonly publishableKey: string;
|
|
19
|
+
/** Origin of the payment API, e.g. `https://api-testnet.mayarin.xyz`. */
|
|
20
|
+
readonly baseUrl: string;
|
|
21
|
+
/** Decimal amount per unit in `currency`, e.g. `"150000.00"`. Never a float. */
|
|
22
|
+
readonly amount: string;
|
|
23
|
+
/** The currency the merchant prices in, e.g. `"IDR"`. */
|
|
24
|
+
readonly currency: CartBody["currency"];
|
|
25
|
+
/** The line the buyer sees on the checkout page. Defaults to `"Payment"`. */
|
|
26
|
+
readonly name?: string;
|
|
27
|
+
readonly quantity?: number;
|
|
28
|
+
/** Your order id. Comes back on the payment and in every webhook. */
|
|
29
|
+
readonly merchantReference?: string;
|
|
30
|
+
/** Where the buyer lands after paying: `{successUrl}/{paymentIntentId}`. HTTPS or localhost. */
|
|
31
|
+
readonly successUrl?: string;
|
|
32
|
+
readonly metadata?: Readonly<Record<string, string>>;
|
|
33
|
+
}
|
|
34
|
+
type CheckoutOptions = ServerCheckout | BrowserCheckout;
|
|
35
|
+
/** The `POST /v1/carts/checkout` body for a browser-mode checkout: one ad-hoc line. */
|
|
36
|
+
export declare function cartBody(options: BrowserCheckout): CartBody;
|
|
37
|
+
export declare function resolveCheckoutUrl(options: CheckoutOptions, fetcher?: typeof globalThis.fetch): Promise<string>;
|
|
38
|
+
//#endregion
|
|
39
|
+
//#region src/use-mayarin-checkout.d.ts
|
|
40
|
+
interface CheckoutCallbacks {
|
|
41
|
+
/**
|
|
42
|
+
* Called with the checkout URL instead of navigating, e.g. to open it in a
|
|
43
|
+
* new tab. Without it the current page goes to the checkout.
|
|
44
|
+
*/
|
|
45
|
+
readonly onRedirect?: (url: string) => void;
|
|
46
|
+
readonly onError?: (error: Error) => void;
|
|
47
|
+
}
|
|
48
|
+
interface MayarinCheckout {
|
|
49
|
+
/** Mints the checkout and sends the buyer there. A second call while one runs does nothing. */
|
|
50
|
+
readonly redirect: () => Promise<void>;
|
|
51
|
+
readonly loading: boolean;
|
|
52
|
+
readonly error: Error | undefined;
|
|
53
|
+
}
|
|
54
|
+
/**
|
|
55
|
+
* The headless form of `PayButton`: wire `redirect` to any element you like.
|
|
56
|
+
*
|
|
57
|
+
* Options are read when `redirect` runs, not when the hook first renders, so an
|
|
58
|
+
* amount that changes with the cart is always the current one.
|
|
59
|
+
*/
|
|
60
|
+
export declare function useMayarinCheckout(options: CheckoutOptions & CheckoutCallbacks): MayarinCheckout;
|
|
61
|
+
//#endregion
|
|
62
|
+
//#region src/pay-button.d.ts
|
|
63
|
+
type ButtonAttributes = Omit<ButtonHTMLAttributes<HTMLButtonElement>, "children" | "onClick" | "onError" | "type">;
|
|
64
|
+
type PayButtonProps = CheckoutOptions & CheckoutCallbacks & ButtonAttributes & {
|
|
65
|
+
/**
|
|
66
|
+
* Anything to render inside the button — text, an icon, a whole layout.
|
|
67
|
+
* A function receives `{ loading }` to show its own busy state.
|
|
68
|
+
* Defaults to "Pay with crypto".
|
|
69
|
+
*/
|
|
70
|
+
readonly children?: ReactNode | ((state: {
|
|
71
|
+
readonly loading: boolean;
|
|
72
|
+
}) => ReactNode);
|
|
73
|
+
};
|
|
74
|
+
/**
|
|
75
|
+
* A button that sends the buyer to Mayarin's hosted checkout.
|
|
76
|
+
*
|
|
77
|
+
* Unstyled on purpose: pass `className` or `style` and it looks like the rest
|
|
78
|
+
* of your page. It never submits a surrounding form.
|
|
79
|
+
*/
|
|
80
|
+
export declare function PayButton(props: PayButtonProps): import("react").JSX.Element;
|
|
81
|
+
//#endregion
|
|
82
|
+
export type { BrowserCheckout, CartBody, CheckoutCallbacks, CheckoutOptions, CheckoutUrl, MayarinCheckout, PayButtonProps, ServerCheckout };
|
|
83
|
+
//# sourceMappingURL=index.d.ts.map
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,158 @@
|
|
|
1
|
+
import { createMayarinBrowser } from "@mayarin/sdk/browser";
|
|
2
|
+
import { useCallback, useEffect, useRef, useState } from "react";
|
|
3
|
+
import { jsx } from "react/jsx-runtime";
|
|
4
|
+
//#region src/checkout.ts
|
|
5
|
+
/**
|
|
6
|
+
* Turning checkout options into the hosted checkout URL — no React here.
|
|
7
|
+
*
|
|
8
|
+
* Two ways to get a URL, and the difference is who decides the price:
|
|
9
|
+
*
|
|
10
|
+
* - **Server** (`checkout`): the merchant's own backend mints the intent with
|
|
11
|
+
* its secret key and hands back the URL. The price never leaves the server,
|
|
12
|
+
* so nobody can edit it. Use this for anything you sell.
|
|
13
|
+
* - **Browser** (`publishableKey` + `amount`): the browser mints the intent
|
|
14
|
+
* itself with a publishable key. No backend needed, but the amount is
|
|
15
|
+
* whatever the browser sends — a buyer with devtools can change it. Fine for
|
|
16
|
+
* donations, tips and pay-what-you-want; for a sale, check the paid amount
|
|
17
|
+
* against your order (by `merchantReference`) in the webhook before
|
|
18
|
+
* shipping anything.
|
|
19
|
+
*/
|
|
20
|
+
/** The `POST /v1/carts/checkout` body for a browser-mode checkout: one ad-hoc line. */
|
|
21
|
+
function cartBody(options) {
|
|
22
|
+
const metadata = {
|
|
23
|
+
...options.metadata,
|
|
24
|
+
...options.successUrl === void 0 ? {} : { checkoutSuccessBaseUrl: options.successUrl }
|
|
25
|
+
};
|
|
26
|
+
return {
|
|
27
|
+
currency: options.currency,
|
|
28
|
+
lines: [{
|
|
29
|
+
name: options.name ?? "Payment",
|
|
30
|
+
unitPrice: {
|
|
31
|
+
amount: options.amount,
|
|
32
|
+
asset: options.currency
|
|
33
|
+
},
|
|
34
|
+
quantity: options.quantity ?? 1
|
|
35
|
+
}],
|
|
36
|
+
...options.merchantReference === void 0 ? {} : { merchantReference: options.merchantReference },
|
|
37
|
+
...Object.keys(metadata).length === 0 ? {} : { metadata }
|
|
38
|
+
};
|
|
39
|
+
}
|
|
40
|
+
async function resolveCheckoutUrl(options, fetcher = globalThis.fetch) {
|
|
41
|
+
if (options.checkout !== void 0) {
|
|
42
|
+
const result = await options.checkout();
|
|
43
|
+
return checkoutUrl(typeof result === "string" ? result : result.url);
|
|
44
|
+
}
|
|
45
|
+
return checkoutUrl((await createMayarinBrowser({
|
|
46
|
+
baseUrl: options.baseUrl,
|
|
47
|
+
publishableKey: options.publishableKey,
|
|
48
|
+
fetch: fetcher
|
|
49
|
+
}).commerce.carts.checkout(cartBody(options))).url);
|
|
50
|
+
}
|
|
51
|
+
/**
|
|
52
|
+
* The page navigates to whatever this returns, so only a web URL passes: a
|
|
53
|
+
* `javascript:` URL from a backend echoing user input would run in the page.
|
|
54
|
+
*/
|
|
55
|
+
function checkoutUrl(value) {
|
|
56
|
+
let url;
|
|
57
|
+
try {
|
|
58
|
+
url = new URL(value);
|
|
59
|
+
} catch {
|
|
60
|
+
throw new TypeError(`The checkout URL is not a URL: ${value}`);
|
|
61
|
+
}
|
|
62
|
+
if (url.protocol !== "https:" && url.protocol !== "http:") throw new TypeError(`The checkout URL must be http(s), got ${url.protocol}`);
|
|
63
|
+
return url.href;
|
|
64
|
+
}
|
|
65
|
+
//#endregion
|
|
66
|
+
//#region src/use-mayarin-checkout.ts
|
|
67
|
+
/**
|
|
68
|
+
* The headless form of `PayButton`: wire `redirect` to any element you like.
|
|
69
|
+
*
|
|
70
|
+
* Options are read when `redirect` runs, not when the hook first renders, so an
|
|
71
|
+
* amount that changes with the cart is always the current one.
|
|
72
|
+
*/
|
|
73
|
+
function useMayarinCheckout(options) {
|
|
74
|
+
const [loading, setLoading] = useState(false);
|
|
75
|
+
const [error, setError] = useState(void 0);
|
|
76
|
+
const latest = useRef(options);
|
|
77
|
+
latest.current = options;
|
|
78
|
+
const running = useRef(false);
|
|
79
|
+
useEffect(() => {
|
|
80
|
+
const release = (event) => {
|
|
81
|
+
if (event.persisted) {
|
|
82
|
+
running.current = false;
|
|
83
|
+
setLoading(false);
|
|
84
|
+
}
|
|
85
|
+
};
|
|
86
|
+
window.addEventListener("pageshow", release);
|
|
87
|
+
return () => window.removeEventListener("pageshow", release);
|
|
88
|
+
}, []);
|
|
89
|
+
return {
|
|
90
|
+
redirect: useCallback(async () => {
|
|
91
|
+
if (running.current) return;
|
|
92
|
+
running.current = true;
|
|
93
|
+
setLoading(true);
|
|
94
|
+
setError(void 0);
|
|
95
|
+
const { onRedirect, onError } = latest.current;
|
|
96
|
+
try {
|
|
97
|
+
const url = await resolveCheckoutUrl(latest.current);
|
|
98
|
+
if (onRedirect === void 0) {
|
|
99
|
+
window.location.assign(url);
|
|
100
|
+
return;
|
|
101
|
+
}
|
|
102
|
+
onRedirect(url);
|
|
103
|
+
} catch (thrown) {
|
|
104
|
+
const failure = thrown instanceof Error ? thrown : new Error(String(thrown));
|
|
105
|
+
setError(failure);
|
|
106
|
+
onError?.(failure);
|
|
107
|
+
}
|
|
108
|
+
running.current = false;
|
|
109
|
+
setLoading(false);
|
|
110
|
+
}, []),
|
|
111
|
+
loading,
|
|
112
|
+
error
|
|
113
|
+
};
|
|
114
|
+
}
|
|
115
|
+
//#endregion
|
|
116
|
+
//#region src/pay-button.tsx
|
|
117
|
+
/** Every prop the checkout reads. The rest go on the `<button>` untouched. */
|
|
118
|
+
const CHECKOUT_PROPS = /* @__PURE__ */ new Set([
|
|
119
|
+
"checkout",
|
|
120
|
+
"publishableKey",
|
|
121
|
+
"baseUrl",
|
|
122
|
+
"amount",
|
|
123
|
+
"currency",
|
|
124
|
+
"name",
|
|
125
|
+
"quantity",
|
|
126
|
+
"merchantReference",
|
|
127
|
+
"successUrl",
|
|
128
|
+
"metadata",
|
|
129
|
+
"onRedirect",
|
|
130
|
+
"onError",
|
|
131
|
+
"children"
|
|
132
|
+
]);
|
|
133
|
+
function buttonAttributes(props) {
|
|
134
|
+
return Object.fromEntries(Object.entries(props).filter(([key]) => !CHECKOUT_PROPS.has(key)));
|
|
135
|
+
}
|
|
136
|
+
/**
|
|
137
|
+
* A button that sends the buyer to Mayarin's hosted checkout.
|
|
138
|
+
*
|
|
139
|
+
* Unstyled on purpose: pass `className` or `style` and it looks like the rest
|
|
140
|
+
* of your page. It never submits a surrounding form.
|
|
141
|
+
*/
|
|
142
|
+
function PayButton(props) {
|
|
143
|
+
const { redirect, loading } = useMayarinCheckout(props);
|
|
144
|
+
const { children = "Pay with crypto" } = props;
|
|
145
|
+
const attributes = buttonAttributes(props);
|
|
146
|
+
return /* @__PURE__ */ jsx("button", {
|
|
147
|
+
...attributes,
|
|
148
|
+
type: "button",
|
|
149
|
+
disabled: attributes.disabled === true || loading,
|
|
150
|
+
"aria-busy": loading,
|
|
151
|
+
onClick: () => void redirect(),
|
|
152
|
+
children: typeof children === "function" ? children({ loading }) : children
|
|
153
|
+
});
|
|
154
|
+
}
|
|
155
|
+
//#endregion
|
|
156
|
+
export { PayButton, cartBody, resolveCheckoutUrl, useMayarinCheckout };
|
|
157
|
+
|
|
158
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"sources":["../src/checkout.ts","../src/use-mayarin-checkout.ts","../src/pay-button.tsx"],"sourcesContent":["/**\n * Turning checkout options into the hosted checkout URL — no React here.\n *\n * Two ways to get a URL, and the difference is who decides the price:\n *\n * - **Server** (`checkout`): the merchant's own backend mints the intent with\n * its secret key and hands back the URL. The price never leaves the server,\n * so nobody can edit it. Use this for anything you sell.\n * - **Browser** (`publishableKey` + `amount`): the browser mints the intent\n * itself with a publishable key. No backend needed, but the amount is\n * whatever the browser sends — a buyer with devtools can change it. Fine for\n * donations, tips and pay-what-you-want; for a sale, check the paid amount\n * against your order (by `merchantReference`) in the webhook before\n * shipping anything.\n */\n\nimport { createMayarinBrowser, type MayarinBrowserClient } from \"@mayarin/sdk/browser\";\n\n/** The `POST /v1/carts/checkout` body, as the SDK types it. */\nexport type CartBody = Parameters<MayarinBrowserClient[\"commerce\"][\"carts\"][\"checkout\"]>[0];\n\n/** What a server-mode `checkout` resolves to: the URL, or an object carrying it. */\nexport type CheckoutUrl = string | { readonly url: string };\n\nexport interface ServerCheckout {\n /** Calls your backend, which mints the intent and returns its checkout URL. */\n readonly checkout: () => Promise<CheckoutUrl>;\n readonly publishableKey?: never;\n}\n\nexport interface BrowserCheckout {\n readonly checkout?: never;\n /** A `pk_...` key from the dashboard. It names the merchant; no merchant id is needed. */\n readonly publishableKey: string;\n /** Origin of the payment API, e.g. `https://api-testnet.mayarin.xyz`. */\n readonly baseUrl: string;\n /** Decimal amount per unit in `currency`, e.g. `\"150000.00\"`. Never a float. */\n readonly amount: string;\n /** The currency the merchant prices in, e.g. `\"IDR\"`. */\n readonly currency: CartBody[\"currency\"];\n /** The line the buyer sees on the checkout page. Defaults to `\"Payment\"`. */\n readonly name?: string;\n readonly quantity?: number;\n /** Your order id. Comes back on the payment and in every webhook. */\n readonly merchantReference?: string;\n /** Where the buyer lands after paying: `{successUrl}/{paymentIntentId}`. HTTPS or localhost. */\n readonly successUrl?: string;\n readonly metadata?: Readonly<Record<string, string>>;\n}\n\nexport type CheckoutOptions = ServerCheckout | BrowserCheckout;\n\n/** The `POST /v1/carts/checkout` body for a browser-mode checkout: one ad-hoc line. */\nexport function cartBody(options: BrowserCheckout): CartBody {\n const metadata: Record<string, string> = {\n ...options.metadata,\n ...(options.successUrl === undefined ? {} : { checkoutSuccessBaseUrl: options.successUrl }),\n };\n return {\n currency: options.currency,\n lines: [\n {\n name: options.name ?? \"Payment\",\n unitPrice: { amount: options.amount, asset: options.currency },\n quantity: options.quantity ?? 1,\n },\n ],\n ...(options.merchantReference === undefined\n ? {}\n : { merchantReference: options.merchantReference }),\n ...(Object.keys(metadata).length === 0 ? {} : { metadata }),\n };\n}\n\nexport async function resolveCheckoutUrl(\n options: CheckoutOptions,\n fetcher: typeof globalThis.fetch = globalThis.fetch,\n): Promise<string> {\n if (options.checkout !== undefined) {\n const result = await options.checkout();\n return checkoutUrl(typeof result === \"string\" ? result : result.url);\n }\n const client = createMayarinBrowser({\n baseUrl: options.baseUrl,\n publishableKey: options.publishableKey,\n fetch: fetcher,\n });\n return checkoutUrl((await client.commerce.carts.checkout(cartBody(options))).url);\n}\n\n/**\n * The page navigates to whatever this returns, so only a web URL passes: a\n * `javascript:` URL from a backend echoing user input would run in the page.\n */\nfunction checkoutUrl(value: string): string {\n let url: URL;\n try {\n url = new URL(value);\n } catch {\n throw new TypeError(`The checkout URL is not a URL: ${value}`);\n }\n if (url.protocol !== \"https:\" && url.protocol !== \"http:\") {\n throw new TypeError(`The checkout URL must be http(s), got ${url.protocol}`);\n }\n return url.href;\n}\n","import { useCallback, useEffect, useRef, useState } from \"react\";\nimport { type CheckoutOptions, resolveCheckoutUrl } from \"./checkout.ts\";\n\nexport interface CheckoutCallbacks {\n /**\n * Called with the checkout URL instead of navigating, e.g. to open it in a\n * new tab. Without it the current page goes to the checkout.\n */\n readonly onRedirect?: (url: string) => void;\n readonly onError?: (error: Error) => void;\n}\n\nexport interface MayarinCheckout {\n /** Mints the checkout and sends the buyer there. A second call while one runs does nothing. */\n readonly redirect: () => Promise<void>;\n readonly loading: boolean;\n readonly error: Error | undefined;\n}\n\n/**\n * The headless form of `PayButton`: wire `redirect` to any element you like.\n *\n * Options are read when `redirect` runs, not when the hook first renders, so an\n * amount that changes with the cart is always the current one.\n */\nexport function useMayarinCheckout(options: CheckoutOptions & CheckoutCallbacks): MayarinCheckout {\n const [loading, setLoading] = useState(false);\n const [error, setError] = useState<Error | undefined>(undefined);\n const latest = useRef(options);\n latest.current = options;\n const running = useRef(false);\n\n // Coming back with the browser's back button restores the page from the\n // back/forward cache with the button still busy. Release it.\n useEffect(() => {\n const release = (event: PageTransitionEvent) => {\n if (event.persisted) {\n running.current = false;\n setLoading(false);\n }\n };\n window.addEventListener(\"pageshow\", release);\n return () => window.removeEventListener(\"pageshow\", release);\n }, []);\n\n const redirect = useCallback(async () => {\n if (running.current) return;\n running.current = true;\n setLoading(true);\n setError(undefined);\n const { onRedirect, onError } = latest.current;\n try {\n const url = await resolveCheckoutUrl(latest.current);\n if (onRedirect === undefined) {\n // Stay busy: the page is leaving.\n window.location.assign(url);\n return;\n }\n onRedirect(url);\n } catch (thrown) {\n const failure = thrown instanceof Error ? thrown : new Error(String(thrown));\n setError(failure);\n onError?.(failure);\n }\n running.current = false;\n setLoading(false);\n }, []);\n\n return { redirect, loading, error };\n}\n","import type { ButtonHTMLAttributes, ReactNode } from \"react\";\nimport type { CheckoutOptions } from \"./checkout.ts\";\nimport { type CheckoutCallbacks, useMayarinCheckout } from \"./use-mayarin-checkout.ts\";\n\ntype ButtonAttributes = Omit<\n ButtonHTMLAttributes<HTMLButtonElement>,\n \"children\" | \"onClick\" | \"onError\" | \"type\"\n>;\n\nexport type PayButtonProps = CheckoutOptions &\n CheckoutCallbacks &\n ButtonAttributes & {\n /**\n * Anything to render inside the button — text, an icon, a whole layout.\n * A function receives `{ loading }` to show its own busy state.\n * Defaults to \"Pay with crypto\".\n */\n readonly children?: ReactNode | ((state: { readonly loading: boolean }) => ReactNode);\n };\n\n/** Every prop the checkout reads. The rest go on the `<button>` untouched. */\nconst CHECKOUT_PROPS: ReadonlySet<string> = new Set([\n \"checkout\",\n \"publishableKey\",\n \"baseUrl\",\n \"amount\",\n \"currency\",\n \"name\",\n \"quantity\",\n \"merchantReference\",\n \"successUrl\",\n \"metadata\",\n \"onRedirect\",\n \"onError\",\n \"children\",\n]);\n\nfunction buttonAttributes(props: PayButtonProps): ButtonAttributes {\n return Object.fromEntries(\n Object.entries(props).filter(([key]) => !CHECKOUT_PROPS.has(key)),\n ) as ButtonAttributes;\n}\n\n/**\n * A button that sends the buyer to Mayarin's hosted checkout.\n *\n * Unstyled on purpose: pass `className` or `style` and it looks like the rest\n * of your page. It never submits a surrounding form.\n */\nexport function PayButton(props: PayButtonProps) {\n const { redirect, loading } = useMayarinCheckout(props);\n const { children = \"Pay with crypto\" } = props;\n const attributes = buttonAttributes(props);\n\n return (\n <button\n {...attributes}\n type=\"button\"\n disabled={attributes.disabled === true || loading}\n aria-busy={loading}\n onClick={() => void redirect()}\n >\n {typeof children === \"function\" ? children({ loading }) : children}\n </button>\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAqDA,SAAgB,SAAS,SAAoC;CAC3D,MAAM,WAAmC;EACvC,GAAG,QAAQ;EACX,GAAI,QAAQ,eAAe,KAAA,IAAY,CAAC,IAAI,EAAE,wBAAwB,QAAQ,WAAW;CAC3F;CACA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;AAEZ"}
|
package/package.json
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@mayarin/react",
|
|
3
|
+
"version": "0.1.0-next.0",
|
|
4
|
+
"description": "React pay button and checkout hook for Mayarin.",
|
|
5
|
+
"license": "Apache-2.0",
|
|
6
|
+
"homepage": "https://docs.mayarin.xyz",
|
|
7
|
+
"repository": {
|
|
8
|
+
"type": "git",
|
|
9
|
+
"url": "git+https://github.com/playriglabs/mayarin.git",
|
|
10
|
+
"directory": "packages/react"
|
|
11
|
+
},
|
|
12
|
+
"type": "module",
|
|
13
|
+
"sideEffects": false,
|
|
14
|
+
"engines": {
|
|
15
|
+
"node": ">=20"
|
|
16
|
+
},
|
|
17
|
+
"exports": {
|
|
18
|
+
".": {
|
|
19
|
+
"types": "./dist/index.d.ts",
|
|
20
|
+
"import": "./dist/index.js"
|
|
21
|
+
}
|
|
22
|
+
},
|
|
23
|
+
"files": [
|
|
24
|
+
"dist"
|
|
25
|
+
],
|
|
26
|
+
"dependencies": {
|
|
27
|
+
"@mayarin/sdk": "^0.1.0-next.0"
|
|
28
|
+
},
|
|
29
|
+
"peerDependencies": {
|
|
30
|
+
"react": ">=18"
|
|
31
|
+
},
|
|
32
|
+
"publishConfig": {
|
|
33
|
+
"access": "public"
|
|
34
|
+
}
|
|
35
|
+
}
|