@superlogic/spree-pay 0.4.12 → 0.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -49,7 +49,6 @@ function CheckoutContent() {
49
49
  const result = await process({
50
50
  hash: order.hash,
51
51
  capture: true, // Optional: auto-capture payment
52
- metadata: { orderId: order.id }, // Optional: additional data
53
52
  });
54
53
 
55
54
  console.log('Payment result:', result);
@@ -59,6 +58,7 @@ function CheckoutContent() {
59
58
 
60
59
  setStatus('success');
61
60
  } catch (err) {
61
+ // `process` always rejects with a PaymentError — see "Error Handling" below
62
62
  console.error('Payment failed:', err);
63
63
  setStatus('error');
64
64
  }
@@ -177,11 +177,10 @@ async function process(params: ProcessFnParams): Promise<PaymentMethodResult>;
177
177
  type ProcessFnParams = {
178
178
  hash: string; // Order hash from your backend
179
179
  capture?: boolean; // Optional: auto-capture payment (default: false)
180
- metadata?: Record<string, unknown>; // Optional: additional metadata to pass through
181
180
  };
182
181
 
183
182
  type PaymentMethodResult = {
184
- status: SlapiPaymentStatus; // Payment status (AUTHORIZED, CAPTURED, FAILED, etc.)
183
+ status: PaymentStatus; // Payment status (AUTHORIZED, CAPTURED, FAILED, etc.)
185
184
  paymentId: string; // Unique payment identifier
186
185
  txHash: string | null; // Transaction hash (for crypto payments)
187
186
  txId: string | null; // Transaction ID
@@ -200,7 +199,7 @@ enum PaymentType {
200
199
  POINTS = 'POINTS',
201
200
  }
202
201
 
203
- enum SlapiPaymentStatus {
202
+ enum PaymentStatus {
204
203
  AUTHORIZED = 'AUTHORIZED', // Payment authorized (success)
205
204
  CAPTURED = 'CAPTURED', // Payment captured (success)
206
205
  FAILED = 'FAILED', // Payment failed
@@ -211,11 +210,76 @@ enum SlapiPaymentStatus {
211
210
  }
212
211
  ```
213
212
 
213
+ ### Error Handling
214
+
215
+ `process()` always rejects with a `PaymentError`. **Branch on `code`** (the failure category) to show your own UI copy. The original error — including any raw backend detail — is kept on `cause` **for logging only; never render it to end users.**
216
+
217
+ | `code` | When | Suggested UX |
218
+ | -------------------------------- | ---------------------------------------------------------------------------------------------------------- | --------------------------------------------------------- |
219
+ | `PaymentErrorCode.CARD_ERROR` | A card payment was rejected by the backend (a 4xx response, or a terminal `FAILED` status on a card flow). | "We couldn't process your card — check it / try another." |
220
+ | `PaymentErrorCode.PAYMENT_ERROR` | Anything else: network/server error, timeout, cancelled flow, or a crypto/points failure. | Generic "payment failed, try again". |
221
+
222
+ > **Safety:** `message` is a fixed, generic label (e.g. `"Card payment failed"`) — it never contains raw backend text, so it's safe to log or show. To distinguish a real decline (e.g. "insufficient funds") from another 4xx, the backend must return a machine-readable error code; the widget intentionally does **not** surface the backend's free-text message to end users.
223
+
224
+ ```typescript
225
+ import { PaymentError, PaymentErrorCode, SpreePayHttpError, isPaymentError } from '@superlogic/spree-pay';
226
+
227
+ try {
228
+ const result = await process({ hash, capture: true });
229
+ // result.status is AUTHORIZED or CAPTURED
230
+ } catch (err) {
231
+ if (isPaymentError(err)) {
232
+ // Choose user-facing copy from the category — do NOT show err.cause to users.
233
+ if (err.code === PaymentErrorCode.CARD_ERROR) {
234
+ // card-payment problem — prompt the user to check the card or try another
235
+ }
236
+
237
+ err.code; // PaymentErrorCode — the category to branch on
238
+ err.status; // PaymentStatus — e.g. FAILED
239
+ err.backendCode; // string | undefined — a stable backend code when available (e.g. 'INSUFFICIENT_FUNDS')
240
+
241
+ // For logging/debugging only — may carry sensitive backend detail:
242
+ if (err.cause instanceof SpreePayHttpError) {
243
+ err.cause.status; // numeric HTTP status (e.g. 400, 500)
244
+ err.cause.body; // raw response body
245
+ err.cause.url; // request URL
246
+ }
247
+ }
248
+ }
249
+ ```
250
+
251
+ ```typescript
252
+ enum PaymentErrorCode {
253
+ CARD_ERROR = 'CARD_ERROR', // a card payment was rejected by the backend
254
+ PAYMENT_ERROR = 'PAYMENT_ERROR', // network/server/timeout/cancelled/crypto/points failure
255
+ }
256
+
257
+ // Thrown by the widget; detect it with `isPaymentError` and read its fields.
258
+ // Not meant to be constructed by consumers.
259
+ class PaymentError extends Error {
260
+ message: string; // fixed, generic label — never raw backend text; safe to log/show
261
+ code: PaymentErrorCode; // failure category to branch on (defaults to PAYMENT_ERROR)
262
+ status: PaymentStatus; // payment status at the point of failure
263
+ backendCode?: string; // stable machine code from the backend when available (e.g. 'INSUFFICIENT_FUNDS') — for finer branching
264
+ cause?: unknown; // the original thrown value (standard Error.cause) — log only, may hold sensitive detail
265
+ }
266
+
267
+ // Type guard for consumers — the supported way to detect a PaymentError
268
+ function isPaymentError(e: unknown): e is PaymentError;
269
+
270
+ // Thrown by the fetcher on a non-ok HTTP response; reachable via PaymentError.cause
271
+ class SpreePayHttpError extends Error {
272
+ status: number; // HTTP status code
273
+ body: string; // raw response body
274
+ url: string; // request URL
275
+ }
276
+ ```
277
+
214
278
  ### useCapture3DS Hook
215
279
 
216
280
  ```typescript
217
281
  // Use in your 3DS redirect page to capture payment intent and close the modal
218
- useCapture3DS(searchParams: Record<string, string | null>);
282
+ useCapture3DS(params: { paymentIntent?: string | null });
219
283
  ```
220
284
 
221
285
  ### Logger API
@@ -248,6 +312,19 @@ enum LogLevel {
248
312
  }
249
313
  ```
250
314
 
315
+ Supporting types are exported so you can name them in your own code:
316
+
317
+ ```typescript
318
+ import type { Environment, LogContext, LoggerConfig } from '@superlogic/spree-pay';
319
+
320
+ type Environment = 'dev' | 'stg' | 'prod'; // also the `environment` field of the provider's ENV
321
+ type LoggerConfig = { minLevel: LogLevel; prefix: string; environment?: Environment };
322
+ type LogContext = Record<string, unknown>; // the optional context arg on logger.debug/info/warn/error
323
+
324
+ // configureLogger accepts a partial config:
325
+ function configureLogger(config: Partial<LoggerConfig> & { environment?: Environment }): void;
326
+ ```
327
+
251
328
  ## Theme Customization
252
329
 
253
330
  SpreePay uses CSS variables for theming (see all 58+ variables in `packages/spree-pay/src/styles/globals.css:22-82`). You can override these using CSS or CSS-in-JS.
@@ -1,18 +1,20 @@
1
1
  import {
2
2
  Iframe3ds
3
- } from "./chunk-JXZZJ7NS.js";
3
+ } from "./chunk-AXNTOSBU.js";
4
4
  import {
5
5
  InfoBanner,
6
6
  Legal,
7
- PaymentError,
8
7
  SlapiPaymentService,
9
8
  logger,
9
+ settlePaymentResult,
10
+ toPaymentError,
11
+ useIsLoggedIn,
10
12
  useSpreePayConfig,
11
13
  useSpreePayEnv,
12
14
  useSpreePayRegister,
13
15
  useSpreePaymentMethod,
14
16
  useStaticConfig
15
- } from "./chunk-WRFG6YIS.js";
17
+ } from "./chunk-PTEQVWLJ.js";
16
18
 
17
19
  // src/components/CryptoComTab/CryptoComTab.tsx
18
20
  import { useCallback, useEffect } from "react";
@@ -27,11 +29,10 @@ var useCryptoComPayment = () => {
27
29
  if (selectedPaymentMethod.type !== "CDC" /* CDC */) {
28
30
  throw new Error("Unsupported payment method");
29
31
  }
30
- const { hash, metadata } = params;
32
+ const { hash } = params;
31
33
  cryptoComLogger.info("Starting Crypto.com Pay payment", { hash });
32
34
  const { data: paymentResData } = await SlapiPaymentService.createPayment({
33
35
  hash,
34
- metadata,
35
36
  type: "CDC" /* CDC */,
36
37
  cdc: {
37
38
  returnUrl: `${typeof window !== "undefined" ? window.location.origin : ""}${redirect3dsURI}?payment_intent=success`,
@@ -77,13 +78,14 @@ var useCryptoComPayment = () => {
77
78
  // src/components/CryptoComTab/Checkout.tsx
78
79
  import { jsx, jsxs } from "react/jsx-runtime";
79
80
  var Checkout = () => {
81
+ const isLoggedIn = useIsLoggedIn();
80
82
  const { appProps } = useStaticConfig();
81
83
  const { isInternalProcessing } = useSpreePaymentMethod();
82
84
  return /* @__PURE__ */ jsx(
83
85
  "button",
84
86
  {
85
87
  onClick: appProps.onProcess,
86
- disabled: !!appProps.isProcessing || isInternalProcessing,
88
+ disabled: !isLoggedIn || !!appProps.isProcessing || isInternalProcessing,
87
89
  className: "flex flex-col items-center rounded-md bg-(--crypto-pay-bg) p-2 text-(--brand-primary) hover:bg-(--crypto-pay-bg-hover) disabled:cursor-not-allowed disabled:bg-(--crypto-pay-bg-hover) disabled:text-(--disabled)",
88
90
  children: /* @__PURE__ */ jsxs("svg", { xmlns: "http://www.w3.org/2000/svg", className: "h-7 w-[76px]", fill: "none", viewBox: "0 0 76 28", children: [
89
91
  /* @__PURE__ */ jsx(
@@ -146,12 +148,9 @@ var CryptoComTab = () => {
146
148
  async (data) => {
147
149
  try {
148
150
  const res = await cryptoComPayment(data);
149
- if (["AUTHORIZED" /* AUTHORIZED */, "CAPTURED" /* CAPTURED */].includes(res.status)) {
150
- return Promise.resolve(res);
151
- }
152
- return Promise.reject(new PaymentError("Crypto payment failed", res.status));
153
- } catch (_) {
154
- return Promise.reject(new PaymentError("Payment failed", "FAILED" /* FAILED */));
151
+ return settlePaymentResult(res, "Crypto payment failed");
152
+ } catch (e) {
153
+ return Promise.reject(toPaymentError(e, "Crypto payment failed"));
155
154
  }
156
155
  },
157
156
  [cryptoComPayment]
@@ -2,21 +2,23 @@ import {
2
2
  CheckoutButton,
3
3
  PointsSwitch,
4
4
  cn as cn2
5
- } from "./chunk-RORSHUSF.js";
5
+ } from "./chunk-4BM6VTMT.js";
6
6
  import {
7
7
  Dialog,
8
8
  DialogContent,
9
9
  DialogDescription,
10
10
  DialogTitle,
11
11
  InfoBanner,
12
- PaymentError,
13
12
  SlapiPaymentService,
14
13
  cn,
15
14
  logger,
15
+ settlePaymentResult,
16
+ toPaymentError,
17
+ useIsLoggedIn,
16
18
  useSpreePayConfig,
17
19
  useSpreePayRegister,
18
20
  useSpreePaymentMethod
19
- } from "./chunk-WRFG6YIS.js";
21
+ } from "./chunk-PTEQVWLJ.js";
20
22
 
21
23
  // src/components/CryptoTab/Crypto/CryptoWrapper.tsx
22
24
  import { useMemo as useMemo2 } from "react";
@@ -153,7 +155,7 @@ var useCryptoPayment = () => {
153
155
  });
154
156
  throw error;
155
157
  }
156
- const { capture, hash, metadata } = params;
158
+ const { capture, hash } = params;
157
159
  const TOKEN = selectedPaymentMethod.method.symbol;
158
160
  cryptoPaymentLogger.info("Starting crypto payment", {
159
161
  hash,
@@ -213,7 +215,6 @@ var useCryptoPayment = () => {
213
215
  const paymentRes = await SlapiPaymentService.createPayment({
214
216
  hash,
215
217
  capture,
216
- metadata,
217
218
  type: "CRYPTO" /* CRYPTO */,
218
219
  crypto: {
219
220
  token: TOKEN,
@@ -763,12 +764,9 @@ var Crypto = () => {
763
764
  async (data) => {
764
765
  try {
765
766
  const res = await cryptoPayment(data);
766
- if (["AUTHORIZED" /* AUTHORIZED */, "CAPTURED" /* CAPTURED */].includes(res.status)) {
767
- return Promise.resolve(res);
768
- }
769
- return Promise.reject(new PaymentError("Crypto payment failed", res.status));
770
- } catch (_) {
771
- return Promise.reject(new PaymentError("Payment failed", "FAILED" /* FAILED */));
767
+ return settlePaymentResult(res, "Crypto payment failed");
768
+ } catch (e) {
769
+ return Promise.reject(toPaymentError(e, "Crypto payment failed"));
772
770
  }
773
771
  },
774
772
  [cryptoPayment]
@@ -812,23 +810,24 @@ function getCachedWagmiConfig(projectId, appName) {
812
810
  return cfg;
813
811
  }
814
812
  var CryptoWrapper = () => {
813
+ const isLoggedIn = useIsLoggedIn();
815
814
  const { spreePayConfig, configIsLoading } = useSpreePayConfig();
816
815
  const wagmiConfig = useMemo2(() => {
817
816
  if (!spreePayConfig) return null;
818
817
  return getCachedWagmiConfig(spreePayConfig.rainbowProjectId, spreePayConfig.rainbowAppName);
819
818
  }, [spreePayConfig]);
820
- if (configIsLoading || !wagmiConfig) return null;
819
+ if (!isLoggedIn || configIsLoading || !wagmiConfig) return null;
821
820
  return /* @__PURE__ */ jsx12(WagmiProvider, { config: wagmiConfig, children: /* @__PURE__ */ jsx12(QueryClientProvider, { client: queryClient, children: /* @__PURE__ */ jsx12(RainbowKitProvider, { theme: lightTheme({ borderRadius: "large" }), children: /* @__PURE__ */ jsx12(NiceModal3.Provider, { children: /* @__PURE__ */ jsx12(Crypto, {}) }) }) }) });
822
821
  };
823
822
 
824
823
  // src/components/CryptoTab/CryptoTab.tsx
825
824
  import { jsx as jsx13, jsxs as jsxs8 } from "react/jsx-runtime";
826
- var CryptoTab = ({ isLoggedIn }) => {
825
+ var CryptoTab = () => {
827
826
  const { spreePayConfig } = useSpreePayConfig();
828
827
  return /* @__PURE__ */ jsxs8("div", { children: [
829
828
  /* @__PURE__ */ jsx13("div", { className: "border-b border-(--border-component-specific-card) px-5 py-5 md:px-7 md:py-6", children: /* @__PURE__ */ jsx13(CryptoWrapper, {}) }),
830
829
  !spreePayConfig?.crypto.hidePoints && /* @__PURE__ */ jsx13("div", { className: "border-b border-(--border-component-specific-card) px-5 py-5 md:px-7 md:py-6", children: /* @__PURE__ */ jsx13(PointsSwitch, { disabled: true, message: spreePayConfig?.crypto.pointsInfoMessage }) }),
831
- /* @__PURE__ */ jsx13(CheckoutButton, { isLoggedIn })
830
+ /* @__PURE__ */ jsx13(CheckoutButton, {})
832
831
  ] });
833
832
  };
834
833
  export {
@@ -2,11 +2,12 @@ import {
2
2
  InfoBanner,
3
3
  Legal,
4
4
  cn,
5
+ useIsLoggedIn,
5
6
  useSpreePayConfig,
6
7
  useSpreePayEnv,
7
8
  useSpreePaymentMethod,
8
9
  useStaticConfig
9
- } from "./chunk-WRFG6YIS.js";
10
+ } from "./chunk-PTEQVWLJ.js";
10
11
 
11
12
  // src/components/common/PointsSwitch.tsx
12
13
  import { useId } from "react";
@@ -205,7 +206,8 @@ var getTransactionFee = (amount = 0, transactionFeePercentage) => {
205
206
 
206
207
  // src/components/CheckoutButton.tsx
207
208
  import { Fragment, jsx as jsx5, jsxs as jsxs3 } from "react/jsx-runtime";
208
- var CheckoutButton = ({ isLoggedIn }) => {
209
+ var CheckoutButton = () => {
210
+ const isLoggedIn = useIsLoggedIn();
209
211
  const { appProps, staticConfig } = useStaticConfig();
210
212
  const {
211
213
  amount,
@@ -257,15 +259,12 @@ var CheckoutButton = ({ isLoggedIn }) => {
257
259
  const checkoutClass = "text-(--inverse) h-14 leading-14 w-full cursor-pointer rounded-4xl bg-(--s-brand) hover:bg-(--s-brand-hover) px-4 text-center text-xl leading-6 font-medium disabled:cursor-not-allowed disabled:bg-(--s-disabled) disabled:text-(--disabled)";
258
260
  return /* @__PURE__ */ jsxs3("div", { className: "flex w-full flex-col gap-4 p-6 text-xs leading-5 font-medium text-(--secondary) md:px-7", children: [
259
261
  /* @__PURE__ */ jsx5(Legal, {}),
260
- isLoggedIn ? /* @__PURE__ */ jsx5(Fragment, { children: onProcess && /* @__PURE__ */ jsx5("button", { disabled: isDisabled, onClick: onProcess, className: checkoutClass, children: getCheckoutContent() }) }) : /* @__PURE__ */ jsxs3(
262
+ isLoggedIn ? /* @__PURE__ */ jsx5(Fragment, { children: onProcess && /* @__PURE__ */ jsx5("button", { disabled: isDisabled, onClick: onProcess, className: checkoutClass, children: getCheckoutContent() }) }) : /* @__PURE__ */ jsx5(
261
263
  "a",
262
264
  {
263
265
  href: `${staticConfig.keycloakUrl}/realms/${tenantId}/protocol/openid-connect/auth?client_id=${keycloakClientId ?? "oneof-next"}&response_type=code&redirect_uri=${window.location.href}`,
264
266
  className: checkoutClass,
265
- children: [
266
- "Log in / Sign up",
267
- tenantId === "moca" ? " for an AIR account" : ""
268
- ]
267
+ children: spreePayConfig?.loginLabel || "Log in / Sign up"
269
268
  }
270
269
  ),
271
270
  /* @__PURE__ */ jsxs3("a", { href: "https://www.spree.finance/", className: "flex items-center justify-center gap-2 hover:underline", children: [
@@ -3,7 +3,7 @@ import {
3
3
  DialogContent,
4
4
  DialogDescription,
5
5
  DialogTitle
6
- } from "./chunk-WRFG6YIS.js";
6
+ } from "./chunk-PTEQVWLJ.js";
7
7
 
8
8
  // src/modals/Iframe3ds.tsx
9
9
  import { useEffect } from "react";