@moonbase.sh/react 0.0.0-stage → 0.0.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/README.md +246 -2
- package/package.json +5 -4
package/README.md
CHANGED
|
@@ -1,3 +1,247 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @moonbase.sh/react
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
React storefront SDK built on top of `@moonbase.sh/storefront-api`: a storefront you make once, a provider, and
|
|
4
|
+
hooks for the catalog, the signed-in customer, the cart, checkout, what customers own, and activating it. It does
|
|
5
|
+
everything `@moonbase.sh/vue` does, shares its checkout code, and works with React 18 and 19.
|
|
6
|
+
|
|
7
|
+
## Install
|
|
8
|
+
|
|
9
|
+
```bash
|
|
10
|
+
pnpm add @moonbase.sh/react
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
Peer dependency: `react@>=18`.
|
|
14
|
+
|
|
15
|
+
## Basic setup (React + Vite)
|
|
16
|
+
|
|
17
|
+
```tsx
|
|
18
|
+
import { createStorefront, StorefrontProvider } from '@moonbase.sh/react'
|
|
19
|
+
import { createRoot } from 'react-dom/client'
|
|
20
|
+
import App from './App'
|
|
21
|
+
|
|
22
|
+
// Once, as the page loads, outside of any component
|
|
23
|
+
const storefront = createStorefront('https://demo.moonbase.sh')
|
|
24
|
+
|
|
25
|
+
createRoot(document.getElementById('root')!).render(
|
|
26
|
+
<StorefrontProvider storefront={storefront}>
|
|
27
|
+
<App />
|
|
28
|
+
</StorefrontProvider>,
|
|
29
|
+
)
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
Make the storefront at module level, not in a component: it reads the address the visitor arrived at, keeps the cart
|
|
33
|
+
in step with other tabs, and coming back from the hosted checkout it reopens the checkout and takes Moonbase's `mb_*`
|
|
34
|
+
parameters off the address. Make it before your router, which reads the address as it is made.
|
|
35
|
+
|
|
36
|
+
## Use hooks in components
|
|
37
|
+
|
|
38
|
+
```tsx
|
|
39
|
+
import { useAuth, useCart, useProducts } from '@moonbase.sh/react'
|
|
40
|
+
|
|
41
|
+
export function Shop() {
|
|
42
|
+
const products = useProducts()
|
|
43
|
+
const { user, signOut } = useAuth()
|
|
44
|
+
const cart = useCart()
|
|
45
|
+
|
|
46
|
+
return (
|
|
47
|
+
<>
|
|
48
|
+
{products.map(product => (
|
|
49
|
+
<button key={product.id} onClick={() => cart.addToCart(product)}>
|
|
50
|
+
{`Add ${product.name}`}
|
|
51
|
+
</button>
|
|
52
|
+
))}
|
|
53
|
+
<button disabled={cart.items.length === 0} onClick={() => cart.checkout()}>
|
|
54
|
+
{`Check out (${cart.items.length})`}
|
|
55
|
+
</button>
|
|
56
|
+
{user && (
|
|
57
|
+
<button onClick={signOut}>
|
|
58
|
+
{`Sign out ${user.name}`}
|
|
59
|
+
</button>
|
|
60
|
+
)}
|
|
61
|
+
</>
|
|
62
|
+
)
|
|
63
|
+
}
|
|
64
|
+
```
|
|
65
|
+
|
|
66
|
+
Hooks return plain values, and a component renders again only when the part of the storefront it reads changes:
|
|
67
|
+
adding to the cart renders the cart's components, not every product card. Every function a hook returns keeps its
|
|
68
|
+
identity across renders, so it can go in a dependency list or to a memoized child.
|
|
69
|
+
|
|
70
|
+
## Main hooks
|
|
71
|
+
|
|
72
|
+
- `useAuth()` - the signed-in `user`, whether that is `loaded` yet, and signing in, up and out, profile and address
|
|
73
|
+
updates, and the password, email and account confirmation flows. `signUp` sends the UTM tags, campaign IDs, ad click
|
|
74
|
+
IDs (only with consent, see below) and referrer the visitor arrived with, and the ad signals, as the cart and checkout
|
|
75
|
+
do, unless its options name their own `utm` or `signals`.
|
|
76
|
+
- `useCatalog()`, `useProducts()`, `useProduct(id)`, `useBundles()`, `useBundle(id)`, `useOffers()`, `useOffer(id)` -
|
|
77
|
+
the catalog, priced for this visitor, with `owned` for whoever is signed in. `useProduct` and `useBundle` are `null`
|
|
78
|
+
until the catalog has loaded.
|
|
79
|
+
- `usePromotions()` - the sales currently running across the catalog. Already filtered by the API to what is live and
|
|
80
|
+
applies to the current visitor, so render them as they are.
|
|
81
|
+
- `useCart()` - the lines, totals and price breakdown, `soldOutItems`, and `addToCart`, `setQuantity`,
|
|
82
|
+
`removeFromCart` and `checkout`.
|
|
83
|
+
- `useEligibleOffers()`, `useLockedOffers()`, `useCartOffer()` - the upsells the cart qualifies for, the offers it is
|
|
84
|
+
short of and by how much, and the cart offer it has earned or is working toward.
|
|
85
|
+
- `useCheckout()` - buying straight away without the cart: `const checkout = useCheckout()`, then
|
|
86
|
+
`checkout([{ item: product }])` from a "Buy now" button. Starting one again within 24 hours, as the same customer,
|
|
87
|
+
reopens the previous order with the new items while that order is still open, so the billing details the buyer already
|
|
88
|
+
entered are kept. A coupon the previous call passed is taken off again unless this call passes it too; one the buyer
|
|
89
|
+
typed into the checkout stays. If another tab reopens the order while its checkout overlay is open here, this overlay
|
|
90
|
+
closes and the call resolves with `completed: false`, so the buyer can't pay for items this tab isn't showing.
|
|
91
|
+
- `useInventory()` - owned products, licenses and the computers they're activated on, downloads, and subscriptions:
|
|
92
|
+
cancelling, renewing, changing plan and changing the card they're paid with.
|
|
93
|
+
- `useOrders()` - the signed-in customer's completed orders, newest first, and their receipt PDFs.
|
|
94
|
+
- `useVoucher()` - what a voucher code gives, and redeeming it.
|
|
95
|
+
- `useActivationRequest(token)` - activating a product in the browser: the request the app made, granting it a license
|
|
96
|
+
or a trial, and waiting for the app to pick it up.
|
|
97
|
+
- `useGroups()` - join the signed-in customer to a customer list of the store's that has been opened to sign-ups.
|
|
98
|
+
Throws `NotFoundError` for every reason a join can be refused, which the API deliberately does not distinguish.
|
|
99
|
+
- `useReviews()` - product reviews: `enabled` says whether the store takes them, `getReviews` and `getMoreReviews` read
|
|
100
|
+
the published ones a page at a time, `getMyReview` and `saveReview` read and write the signed-in customer's own,
|
|
101
|
+
`withdrawReview` takes it down and `voteOnReview` marks someone else's helpful or not. Each product's `rating` comes
|
|
102
|
+
with the catalog, and `hasRating(rating)` says whether there is a score worth showing yet.
|
|
103
|
+
- `useCommunicationPreferences()` - newsletter sign-ups, and the preferences page an email's footer links to.
|
|
104
|
+
- `useVendor()` - who runs the store.
|
|
105
|
+
- `useStorefront()` - the storefront itself, and `useStorefrontState(state => ...)` for any part of its state
|
|
106
|
+
(`catalog`, `catalogLoaded`, `closed`, `order`, `user`, `userLoaded`, `utm`).
|
|
107
|
+
|
|
108
|
+
### Where checkout happens
|
|
109
|
+
|
|
110
|
+
`cart.checkout()` and `useCheckout()` both take a `redirect` option:
|
|
111
|
+
|
|
112
|
+
| Value | Behavior |
|
|
113
|
+
| --- | --- |
|
|
114
|
+
| `'auto'` (default) | Overlay iframe on desktop, full-page redirect on mobile. |
|
|
115
|
+
| `'always'` / `true` | Always redirect to the Moonbase-hosted checkout. |
|
|
116
|
+
| `'never'` / `false` | Always use the overlay iframe. |
|
|
117
|
+
|
|
118
|
+
`'auto'` exists because Apple Pay and Google Pay cannot render inside the overlay: those wallets require the
|
|
119
|
+
*top-level* page's domain to be a registered payment-method domain, and on an embedded storefront that domain is your
|
|
120
|
+
own site, not Moonbase's. Redirecting makes the hosted checkout the top-level document, so the wallets appear. `'auto'`
|
|
121
|
+
takes that trade only on mobile, where wallet usage concentrates, and keeps the overlay on desktop.
|
|
122
|
+
|
|
123
|
+
When the call redirects it cannot report an outcome, since the result arrives on the return page, so it resolves with
|
|
124
|
+
`{ completed: false, redirected: true }`. Check `redirected` before treating `completed: false` as a failure.
|
|
125
|
+
|
|
126
|
+
A checkout's promise settles when the overlay closes, which can be minutes later, so keep a button's pending state in
|
|
127
|
+
the component's own state rather than in a transition. React batches pending transitions together, and one left
|
|
128
|
+
pending while the checkout is open would hold back every other transition, your router's navigations included.
|
|
129
|
+
|
|
130
|
+
```tsx
|
|
131
|
+
function CheckoutButton() {
|
|
132
|
+
const cart = useCart()
|
|
133
|
+
const [opening, setOpening] = useState(false)
|
|
134
|
+
|
|
135
|
+
async function checkout() {
|
|
136
|
+
setOpening(true)
|
|
137
|
+
try {
|
|
138
|
+
await cart.checkout()
|
|
139
|
+
}
|
|
140
|
+
finally {
|
|
141
|
+
setOpening(false)
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
return (
|
|
146
|
+
<button disabled={opening} onClick={checkout}>
|
|
147
|
+
{opening ? 'Opening checkout…' : 'Check out'}
|
|
148
|
+
</button>
|
|
149
|
+
)
|
|
150
|
+
}
|
|
151
|
+
```
|
|
152
|
+
|
|
153
|
+
## Checkout events
|
|
154
|
+
|
|
155
|
+
```tsx
|
|
156
|
+
import type { CompletedOrder } from '@moonbase.sh/react'
|
|
157
|
+
import { useStorefrontEvent } from '@moonbase.sh/react'
|
|
158
|
+
import { useState } from 'react'
|
|
159
|
+
|
|
160
|
+
function Thanks() {
|
|
161
|
+
const [order, setOrder] = useState<CompletedOrder | null>(null)
|
|
162
|
+
|
|
163
|
+
// Also after a phone comes back from the hosted checkout, which completes as the page loads again
|
|
164
|
+
useStorefrontEvent('checkoutCompleted', setOrder)
|
|
165
|
+
|
|
166
|
+
if (!order)
|
|
167
|
+
return null
|
|
168
|
+
|
|
169
|
+
return (
|
|
170
|
+
<p>
|
|
171
|
+
{`Thanks! A receipt is on its way to ${order.customer.email}.`}
|
|
172
|
+
</p>
|
|
173
|
+
)
|
|
174
|
+
}
|
|
175
|
+
```
|
|
176
|
+
|
|
177
|
+
The events are `checkoutInitiated`, `checkoutBillingDetailsAdded`, `checkoutPaymentStarted`, `checkoutPaymentFailed`
|
|
178
|
+
(with a `reason`: `Declined`, `AuthenticationFailed`, `CardDetails`, `ProcessingError` or `Other`, never the card
|
|
179
|
+
issuer's own decline code), `checkoutCouponApplied`, `checkoutCouponRemoved`, `checkoutCouponRejected`,
|
|
180
|
+
`checkoutCompleted`, `checkoutClosed`, `catalogUpdated` and `sessionEnded`. Each payment started is followed by a
|
|
181
|
+
failure or a completion. None of these fire while the buyer is on the hosted checkout after a full-page redirect, since
|
|
182
|
+
your page is not loaded then: subscribe a webhook to `OrderPaymentFailed` to follow every checkout.
|
|
183
|
+
|
|
184
|
+
Outside of React, `storefront.on('checkoutCompleted', order => ...)` does the same and returns the function that stops it.
|
|
185
|
+
|
|
186
|
+
## Outside of components
|
|
187
|
+
|
|
188
|
+
Nothing in the storefront depends on React, so a router loader, an analytics script or your own store can use it
|
|
189
|
+
directly:
|
|
190
|
+
|
|
191
|
+
```ts
|
|
192
|
+
// A route only for signed-in customers
|
|
193
|
+
async function loader() {
|
|
194
|
+
await storefront.userLoadedPromise
|
|
195
|
+
if (!storefront.getState().user)
|
|
196
|
+
throw redirect('/sign-in')
|
|
197
|
+
return null
|
|
198
|
+
}
|
|
199
|
+
```
|
|
200
|
+
|
|
201
|
+
`storefront.cart`, `storefront.auth` and `storefront.checkout()` are what the hooks hand out. `userLoadedPromise` and
|
|
202
|
+
`catalogLoadedPromise` are the same promise every time, so React 19's `use()` can suspend on them.
|
|
203
|
+
|
|
204
|
+
## Attribution and consent
|
|
205
|
+
|
|
206
|
+
The storefront reads the UTM tags, campaign IDs (`utm_id`, `gad_source`, `gad_campaignid`), referrer and ad click IDs
|
|
207
|
+
(`gclid`, `gbraid`, `wbraid`, `fbclid`, `msclkid`, `ttclid`) the visitor arrived with, and sends them with the cart,
|
|
208
|
+
checkout and sign-up. A click ID identifies the visitor's click, so without the visitor's consent to marketing cookies
|
|
209
|
+
it keeps and sends only the platforms they came from (`utm.adClicks`), not the IDs, and records a tagged arrival on the
|
|
210
|
+
order only with the first thing put in the cart. The campaign IDs name a campaign, not a visitor, so they are kept
|
|
211
|
+
either way. Until you say whether they agreed, it follows the store's setting in Moonbase (Account settings >
|
|
212
|
+
Storefront > "Features" > "Ad and campaign tracking": always, only outside the EEA, the UK and Switzerland, or only with
|
|
213
|
+
cookie consent), which the catalog reports for this visitor. Pass `attributionConsent` to `createStorefront`, or tell it
|
|
214
|
+
later from your cookie banner, and that wins:
|
|
215
|
+
|
|
216
|
+
```ts
|
|
217
|
+
onMarketingConsent(granted => storefront.setAttributionConsent(granted))
|
|
218
|
+
```
|
|
219
|
+
|
|
220
|
+
A banner that asks for Google's two consent mode signals separately can pass both, and the click IDs are kept when
|
|
221
|
+
`adUserData` is granted:
|
|
222
|
+
|
|
223
|
+
```ts
|
|
224
|
+
onConsentUpdate(({ adUserData, adPersonalization }) => storefront.setAttributionConsent({ adUserData, adPersonalization }))
|
|
225
|
+
```
|
|
226
|
+
|
|
227
|
+
The cart, checkout, sign-up, trial, newsletter subscription and download requests also tell Moonbase what your banner
|
|
228
|
+
reported (nothing until it reports) and when and on which page (origin and path only) a tagged visit first landed.
|
|
229
|
+
`storefront.adSignals()` returns what they send.
|
|
230
|
+
|
|
231
|
+
## Server rendering
|
|
232
|
+
|
|
233
|
+
The storefront can be made on a server, where it has no visitor: no cart, nobody signed in, and nothing sent. A
|
|
234
|
+
storefront made at module level in a client module, as above, renders on the server with an empty catalog, so show your
|
|
235
|
+
own fallback prices until it loads, and the browser takes over from there. The browser hydrates against that same
|
|
236
|
+
server state before switching to its own, so a catalog it cached on an earlier visit never causes a hydration mismatch.
|
|
237
|
+
|
|
238
|
+
To have the server render real prices, fetch the catalog there and start the page's storefront from it:
|
|
239
|
+
|
|
240
|
+
```tsx
|
|
241
|
+
'use client'
|
|
242
|
+
|
|
243
|
+
export function Providers({ catalog, children }: { catalog: Storefront, children: ReactNode }) {
|
|
244
|
+
const [storefront] = useState(() => createStorefront('https://demo.moonbase.sh', { initialCatalog: catalog }))
|
|
245
|
+
return <StorefrontProvider storefront={storefront}>{children}</StorefrontProvider>
|
|
246
|
+
}
|
|
247
|
+
```
|
package/package.json
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@moonbase.sh/react",
|
|
3
|
-
"version": "0.0.0
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.0.0",
|
|
4
|
+
"description": "Placeholder for the Moonbase React SDK. The first release is 1.1.0.",
|
|
5
|
+
"author": "Tobias Lønnerød Madsen <m@dsen.tv>",
|
|
6
|
+
"license": "MIT"
|
|
7
|
+
}
|