@strimz/sdk-react 0.1.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.
@@ -0,0 +1,139 @@
1
+ 'use client'
2
+
3
+ import * as React from 'react'
4
+ import { useStrimzCheckout, type CheckoutMode } from '../hooks/useStrimzCheckout.js'
5
+
6
+ export type StrimzPayButtonTheme = 'auto' | 'light' | 'dark'
7
+ export type StrimzPayButtonSize = 'sm' | 'md' | 'lg'
8
+
9
+ export interface StrimzPayButtonProps extends Omit<
10
+ React.ButtonHTMLAttributes<HTMLButtonElement>,
11
+ 'onError'
12
+ > {
13
+ /** Strimz session id created via `@strimz/sdk` on your backend. */
14
+ sessionId: string
15
+ /** Hosted checkout open mode. Default `popup`. */
16
+ mode?: CheckoutMode
17
+ /** Visual theme. `auto` follows the user's `prefers-color-scheme`. */
18
+ theme?: StrimzPayButtonTheme
19
+ /** Button size token. Default `md`. */
20
+ size?: StrimzPayButtonSize
21
+ /** Called on a successful payment with the on-chain transaction hash. */
22
+ onSuccess?: (txHash?: string) => void
23
+ /** Called when the payer closes the checkout without completing. */
24
+ onCancel?: () => void
25
+ /** Called when the checkout reports an error. */
26
+ onError?: (error: Error) => void
27
+ /** Override the button label. Default "Pay with Strimz". */
28
+ label?: React.ReactNode
29
+ }
30
+
31
+ /**
32
+ * Drop-in pay button. Opens Strimz hosted checkout in a popup or redirect.
33
+ *
34
+ * <StrimzPayButton sessionId={sess.id} onSuccess={(tx) => router.push('/done')} />
35
+ */
36
+ export const StrimzPayButton = React.forwardRef<HTMLButtonElement, StrimzPayButtonProps>(
37
+ function StrimzPayButton(
38
+ {
39
+ sessionId,
40
+ mode = 'popup',
41
+ theme = 'auto',
42
+ size = 'md',
43
+ onSuccess,
44
+ onCancel,
45
+ onError,
46
+ label,
47
+ onClick,
48
+ style,
49
+ ...rest
50
+ },
51
+ ref,
52
+ ) {
53
+ const checkout = useStrimzCheckout({ mode, onSuccess, onCancel, onError })
54
+
55
+ const handleClick = (ev: React.MouseEvent<HTMLButtonElement>) => {
56
+ onClick?.(ev)
57
+ if (ev.defaultPrevented || !sessionId) return
58
+ checkout.open(sessionId)
59
+ }
60
+
61
+ return (
62
+ <button
63
+ ref={ref}
64
+ type="button"
65
+ onClick={handleClick}
66
+ style={{ ...buttonStyle({ theme, size }), ...(style ?? {}) }}
67
+ data-strimz-pay-button
68
+ data-status={checkout.status}
69
+ {...rest}
70
+ >
71
+ {label ?? defaultLabel}
72
+ </button>
73
+ )
74
+ },
75
+ )
76
+
77
+ const defaultLabel = (
78
+ <span style={{ display: 'inline-flex', alignItems: 'center', gap: 8 }}>
79
+ <StrimzMark size={16} />
80
+ Pay with Strimz
81
+ </span>
82
+ )
83
+
84
+ function StrimzMark({ size }: { size: number }) {
85
+ // Inline SVG keeps the bundle dependency-free.
86
+ return (
87
+ <svg
88
+ width={size}
89
+ height={size}
90
+ viewBox="0 0 16 16"
91
+ role="img"
92
+ aria-label="Strimz"
93
+ xmlns="http://www.w3.org/2000/svg"
94
+ >
95
+ <circle cx="8" cy="8" r="8" fill="#02C76A" />
96
+ <path d="M5 9h6M5 7h6" stroke="white" strokeWidth="1.6" strokeLinecap="round" />
97
+ </svg>
98
+ )
99
+ }
100
+
101
+ interface StyleParams {
102
+ theme: StrimzPayButtonTheme
103
+ size: StrimzPayButtonSize
104
+ }
105
+
106
+ function buttonStyle({ theme, size }: StyleParams): React.CSSProperties {
107
+ const dimensions = sizeMap[size]
108
+ const palette = paletteFor(theme)
109
+ return {
110
+ appearance: 'none',
111
+ border: 'none',
112
+ cursor: 'pointer',
113
+ fontFamily:
114
+ 'ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif',
115
+ fontWeight: 600,
116
+ background: palette.background,
117
+ color: palette.foreground,
118
+ borderRadius: 10,
119
+ paddingInline: dimensions.padX,
120
+ paddingBlock: dimensions.padY,
121
+ fontSize: dimensions.font,
122
+ lineHeight: 1.2,
123
+ transition: 'background-color 120ms ease, transform 80ms ease',
124
+ boxShadow: '0 1px 2px rgba(0,0,0,0.06)',
125
+ }
126
+ }
127
+
128
+ const sizeMap: Record<StrimzPayButtonSize, { padX: number; padY: number; font: number }> = {
129
+ sm: { padX: 12, padY: 6, font: 13 },
130
+ md: { padX: 16, padY: 10, font: 15 },
131
+ lg: { padX: 20, padY: 14, font: 17 },
132
+ }
133
+
134
+ function paletteFor(theme: StrimzPayButtonTheme): { background: string; foreground: string } {
135
+ if (theme === 'light') return { background: '#02C76A', foreground: '#FFFFFF' }
136
+ if (theme === 'dark') return { background: '#02C76A', foreground: '#FFFFFF' }
137
+ // auto — same brand for both modes; the surrounding app's theme handles context
138
+ return { background: '#02C76A', foreground: '#FFFFFF' }
139
+ }
@@ -0,0 +1,102 @@
1
+ 'use client'
2
+
3
+ import * as React from 'react'
4
+ import { useStrimzContext } from '../provider.js'
5
+
6
+ export type CheckoutMode = 'redirect' | 'popup'
7
+
8
+ export interface UseStrimzCheckoutOptions {
9
+ /** How to open the hosted checkout. Default `popup`. */
10
+ mode?: CheckoutMode
11
+ /** Called when the checkout reports a successful payment. */
12
+ onSuccess?: (txHash?: string) => void
13
+ /** Called when the payer closes the checkout without completing. */
14
+ onCancel?: () => void
15
+ /** Called on any error reported by the checkout. */
16
+ onError?: (error: Error) => void
17
+ }
18
+
19
+ export interface UseStrimzCheckoutResult {
20
+ open: (sessionId: string) => void
21
+ close: () => void
22
+ status: 'idle' | 'open' | 'success' | 'cancelled' | 'error'
23
+ }
24
+
25
+ /**
26
+ * Imperative checkout opener. Lower-level than `<StrimzPayButton/>`.
27
+ *
28
+ * const checkout = useStrimzCheckout({ onSuccess: ... })
29
+ * <button onClick={() => checkout.open(sessionId)}>Pay</button>
30
+ */
31
+ export function useStrimzCheckout(options: UseStrimzCheckoutOptions = {}): UseStrimzCheckoutResult {
32
+ const { checkoutOrigin } = useStrimzContext()
33
+ const [status, setStatus] = React.useState<UseStrimzCheckoutResult['status']>('idle')
34
+ const popupRef = React.useRef<Window | null>(null)
35
+ const optsRef = React.useRef(options)
36
+ optsRef.current = options
37
+
38
+ const close = React.useCallback(() => {
39
+ if (popupRef.current && !popupRef.current.closed) {
40
+ popupRef.current.close()
41
+ }
42
+ popupRef.current = null
43
+ }, [])
44
+
45
+ React.useEffect(() => {
46
+ function onMessage(ev: MessageEvent) {
47
+ if (ev.origin !== checkoutOrigin) return
48
+ const data = ev.data as { type?: string; txHash?: string; message?: string }
49
+ if (!data || typeof data.type !== 'string' || !data.type.startsWith('strimz:checkout:'))
50
+ return
51
+
52
+ switch (data.type) {
53
+ case 'strimz:checkout:success':
54
+ setStatus('success')
55
+ optsRef.current.onSuccess?.(data.txHash)
56
+ close()
57
+ break
58
+ case 'strimz:checkout:cancel':
59
+ setStatus('cancelled')
60
+ optsRef.current.onCancel?.()
61
+ close()
62
+ break
63
+ case 'strimz:checkout:error':
64
+ setStatus('error')
65
+ optsRef.current.onError?.(new Error(data.message ?? 'Checkout error'))
66
+ close()
67
+ break
68
+ }
69
+ }
70
+ window.addEventListener('message', onMessage)
71
+ return () => window.removeEventListener('message', onMessage)
72
+ }, [checkoutOrigin, close])
73
+
74
+ const open = React.useCallback(
75
+ (sessionId: string) => {
76
+ const url = `${checkoutOrigin}/${encodeURIComponent(sessionId)}`
77
+ const mode = optsRef.current.mode ?? 'popup'
78
+ if (mode === 'redirect') {
79
+ window.location.assign(url)
80
+ return
81
+ }
82
+ const w = window.open(url, 'strimz-checkout', 'width=480,height=720')
83
+ popupRef.current = w
84
+ setStatus('open')
85
+ // Detect manual close.
86
+ const closeWatch = setInterval(() => {
87
+ if (!w || w.closed) {
88
+ clearInterval(closeWatch)
89
+ if (popupRef.current === w) {
90
+ // Only treat as cancel if we haven't already transitioned out of `open`.
91
+ setStatus((prev) => (prev === 'open' ? 'cancelled' : prev))
92
+ popupRef.current = null
93
+ if (status === 'open') optsRef.current.onCancel?.()
94
+ }
95
+ }
96
+ }, 500)
97
+ },
98
+ [checkoutOrigin, status],
99
+ )
100
+
101
+ return { open, close, status }
102
+ }
@@ -0,0 +1,9 @@
1
+ 'use client'
2
+
3
+ import type { StrimzBrowserClient } from '@strimz/sdk/browser'
4
+ import { useStrimzContext } from '../provider.js'
5
+
6
+ /** Read the singleton browser client out of context. */
7
+ export function useStrimzClient(): StrimzBrowserClient {
8
+ return useStrimzContext().client
9
+ }
@@ -0,0 +1,79 @@
1
+ 'use client'
2
+
3
+ import * as React from 'react'
4
+ import type { PaymentSession } from '@strimz/shared-types'
5
+ import { useStrimzClient } from './useStrimzClient.js'
6
+
7
+ export interface UseStrimzSessionResult {
8
+ session: PaymentSession | null
9
+ loading: boolean
10
+ error: Error | null
11
+ refresh: () => Promise<void>
12
+ }
13
+
14
+ export interface UseStrimzSessionOptions {
15
+ /** Poll interval in milliseconds while the session is in a non-terminal state. */
16
+ pollIntervalMs?: number
17
+ }
18
+
19
+ const TERMINAL_STATES: ReadonlyArray<PaymentSession['status']> = [
20
+ 'confirmed',
21
+ 'failed',
22
+ 'expired',
23
+ 'cancelled',
24
+ ]
25
+
26
+ /**
27
+ * Subscribe to a Strimz payment session. Polls until the session reaches
28
+ * a terminal state, then stops.
29
+ */
30
+ export function useStrimzSession(
31
+ sessionId: string | null | undefined,
32
+ options: UseStrimzSessionOptions = {},
33
+ ): UseStrimzSessionResult {
34
+ const client = useStrimzClient()
35
+ const [session, setSession] = React.useState<PaymentSession | null>(null)
36
+ const [loading, setLoading] = React.useState<boolean>(false)
37
+ const [error, setError] = React.useState<Error | null>(null)
38
+ const cancelledRef = React.useRef(false)
39
+
40
+ const fetchOnce = React.useCallback(async () => {
41
+ if (!sessionId) return
42
+ setLoading(true)
43
+ try {
44
+ // Browser checkout reads go through the public /v1/checkout/* namespace
45
+ // — paymentSessions.retrieve required a secret key and is no longer on
46
+ // the BrowserClient. See packages/sdk/src/resources/checkout.ts.
47
+ const next = await client.checkout.session(sessionId)
48
+ if (!cancelledRef.current) {
49
+ setSession(next)
50
+ setError(null)
51
+ }
52
+ } catch (err) {
53
+ if (!cancelledRef.current) setError(err as Error)
54
+ } finally {
55
+ if (!cancelledRef.current) setLoading(false)
56
+ }
57
+ }, [client, sessionId])
58
+
59
+ React.useEffect(() => {
60
+ cancelledRef.current = false
61
+ if (!sessionId) return
62
+
63
+ void fetchOnce()
64
+ const interval = options.pollIntervalMs ?? 3_000
65
+ const timer = setInterval(() => {
66
+ if (session && TERMINAL_STATES.includes(session.status)) return
67
+ void fetchOnce()
68
+ }, interval)
69
+
70
+ return () => {
71
+ cancelledRef.current = true
72
+ clearInterval(timer)
73
+ }
74
+ // session is intentionally not in deps — interval reads the latest via closure
75
+ // eslint-disable-next-line react-hooks/exhaustive-deps
76
+ }, [sessionId, fetchOnce, options.pollIntervalMs])
77
+
78
+ return { session, loading, error, refresh: fetchOnce }
79
+ }
package/src/index.ts ADDED
@@ -0,0 +1,37 @@
1
+ /**
2
+ * @strimz/sdk-react
3
+ *
4
+ * Drop-in React components and hooks for Strimz hosted checkout.
5
+ * All exports are 'use client' — they cannot run during SSR / RSC.
6
+ */
7
+
8
+ export {
9
+ StrimzProvider,
10
+ useStrimzContext,
11
+ type StrimzProviderProps,
12
+ type StrimzContextValue,
13
+ } from './provider.js'
14
+
15
+ export { useStrimzClient } from './hooks/useStrimzClient.js'
16
+ export {
17
+ useStrimzSession,
18
+ type UseStrimzSessionResult,
19
+ type UseStrimzSessionOptions,
20
+ } from './hooks/useStrimzSession.js'
21
+ export {
22
+ useStrimzCheckout,
23
+ type UseStrimzCheckoutOptions,
24
+ type UseStrimzCheckoutResult,
25
+ type CheckoutMode,
26
+ } from './hooks/useStrimzCheckout.js'
27
+
28
+ export {
29
+ StrimzPayButton,
30
+ type StrimzPayButtonProps,
31
+ type StrimzPayButtonTheme,
32
+ type StrimzPayButtonSize,
33
+ } from './components/StrimzPayButton.js'
34
+ export {
35
+ StrimzCheckoutEmbed,
36
+ type StrimzCheckoutEmbedProps,
37
+ } from './components/StrimzCheckoutEmbed.js'
@@ -0,0 +1,50 @@
1
+ 'use client'
2
+
3
+ import * as React from 'react'
4
+ import { StrimzBrowserClient } from '@strimz/sdk/browser'
5
+
6
+ export interface StrimzContextValue {
7
+ client: StrimzBrowserClient
8
+ /** Public origin where Strimz hosts its checkout UI. */
9
+ checkoutOrigin: string
10
+ }
11
+
12
+ const StrimzContext = React.createContext<StrimzContextValue | null>(null)
13
+
14
+ export interface StrimzProviderProps {
15
+ /** Publishable key, e.g. process.env.NEXT_PUBLIC_STRIMZ_PUBLISHABLE_KEY. */
16
+ publishableKey: string
17
+ /** Override the API base URL. */
18
+ apiBaseUrl?: string
19
+ /** Override the hosted-checkout origin. Defaults to https://checkout.strimz.io. */
20
+ checkoutOrigin?: string
21
+ children: React.ReactNode
22
+ }
23
+
24
+ /**
25
+ * Wrap any tree that uses Strimz components or hooks.
26
+ * Builds a memoised `StrimzBrowserClient` and a checkout origin.
27
+ */
28
+ export function StrimzProvider({
29
+ publishableKey,
30
+ apiBaseUrl,
31
+ checkoutOrigin = 'https://checkout.strimz.io',
32
+ children,
33
+ }: StrimzProviderProps) {
34
+ const value = React.useMemo<StrimzContextValue>(
35
+ () => ({
36
+ client: new StrimzBrowserClient({ publishableKey, baseUrl: apiBaseUrl }),
37
+ checkoutOrigin,
38
+ }),
39
+ [publishableKey, apiBaseUrl, checkoutOrigin],
40
+ )
41
+ return <StrimzContext.Provider value={value}>{children}</StrimzContext.Provider>
42
+ }
43
+
44
+ export function useStrimzContext(): StrimzContextValue {
45
+ const ctx = React.useContext(StrimzContext)
46
+ if (!ctx) {
47
+ throw new Error('useStrimzContext / Strimz components must be used inside a <StrimzProvider/>.')
48
+ }
49
+ return ctx
50
+ }