@easy-cms/plugin-ecommerce 0.0.0-stage → 0.45.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 +21 -0
- package/README.md +48 -2
- package/dist/admin.js +62 -0
- package/dist/chunk-KON3VWC6.js +302 -0
- package/dist/chunk-RRF3IDUV.js +1937 -0
- package/dist/client.d.ts +250 -0
- package/dist/client.js +18 -0
- package/dist/index.d.ts +530 -0
- package/dist/index.js +44 -0
- package/dist/payments-tPD3bTTW.d.ts +213 -0
- package/dist/react.d.ts +95 -0
- package/dist/react.js +170 -0
- package/dist/stripe.d.ts +58 -0
- package/dist/stripe.js +90 -0
- package/dist/vue.d.ts +119 -0
- package/dist/vue.js +179 -0
- package/package.json +84 -4
|
@@ -0,0 +1,213 @@
|
|
|
1
|
+
import { Label, EasyCMS, ID as ID$1, Endpoint } from '@easy-cms/core';
|
|
2
|
+
|
|
3
|
+
type ID = string | number;
|
|
4
|
+
/** A currency prices are given in. Amounts are whole numbers of its smallest unit (satang, cents). */
|
|
5
|
+
interface Currency {
|
|
6
|
+
/** ISO 4217, e.g. `THB`. */
|
|
7
|
+
readonly code: string;
|
|
8
|
+
/** e.g. `฿`. */
|
|
9
|
+
readonly symbol: string;
|
|
10
|
+
readonly label: string;
|
|
11
|
+
/** Digits after the point: 2 for THB (1 baht = 100 satang), 0 for JPY. */
|
|
12
|
+
readonly decimals: number;
|
|
13
|
+
}
|
|
14
|
+
/** Currencies to choose from by code; others are given in full. */
|
|
15
|
+
declare const CURRENCIES: Readonly<Record<string, Currency>>;
|
|
16
|
+
/** The field holding a product's or variant's price in a currency, e.g. `priceInTHB`. */
|
|
17
|
+
declare const priceField: (code: string) => string;
|
|
18
|
+
/**
|
|
19
|
+
* An amount in a currency's smallest unit, for people: `formatPrice(123450, THB)` →
|
|
20
|
+
* `฿1,234.50`. `locale` picks the digits and separators (default `en`).
|
|
21
|
+
*/
|
|
22
|
+
declare function formatPrice(amount: number, currency: Currency, locale?: string): string;
|
|
23
|
+
/** Where an order is in its life. */
|
|
24
|
+
declare const ORDER_STATUSES: readonly ["pending", "paid", "fulfilled", "cancelled", "refunded"];
|
|
25
|
+
/**
|
|
26
|
+
* - `pending`: waiting for payment (bank transfer).
|
|
27
|
+
* - `paid`: paid, to be sent.
|
|
28
|
+
* - `fulfilled`: sent or handed over.
|
|
29
|
+
* - `cancelled`: called off before payment.
|
|
30
|
+
* - `refunded`: the money went back.
|
|
31
|
+
*/
|
|
32
|
+
type OrderStatus = (typeof ORDER_STATUSES)[number];
|
|
33
|
+
/** Where a payment is. */
|
|
34
|
+
declare const TRANSACTION_STATUSES: readonly ["pending", "processing", "succeeded", "failed", "refunded"];
|
|
35
|
+
type TransactionStatus = (typeof TRANSACTION_STATUSES)[number];
|
|
36
|
+
/** An addition to or deduction from a cart's total (a negative amount), e.g. shipping or a discount. */
|
|
37
|
+
interface Adjustment {
|
|
38
|
+
readonly label: string;
|
|
39
|
+
readonly amount: number;
|
|
40
|
+
}
|
|
41
|
+
/** A line of a cart, as pages see it. */
|
|
42
|
+
interface CartLine {
|
|
43
|
+
/** The line's id, for changing or removing it. */
|
|
44
|
+
readonly id: string;
|
|
45
|
+
readonly product: {
|
|
46
|
+
readonly id: ID;
|
|
47
|
+
readonly title: string;
|
|
48
|
+
readonly slug: string | null;
|
|
49
|
+
/** The first image's URL. */
|
|
50
|
+
readonly image: string | null;
|
|
51
|
+
};
|
|
52
|
+
readonly variant: {
|
|
53
|
+
readonly id: ID;
|
|
54
|
+
readonly title: string;
|
|
55
|
+
} | null;
|
|
56
|
+
readonly quantity: number;
|
|
57
|
+
/** Price of one, in the cart's currency; `null` when it has no price there. */
|
|
58
|
+
readonly unitPrice: number | null;
|
|
59
|
+
readonly total: number;
|
|
60
|
+
/** Whether it can be bought as it is: priced, in stock, still for sale. */
|
|
61
|
+
readonly available: boolean;
|
|
62
|
+
/** How many are left, when stock is kept; `null` otherwise. */
|
|
63
|
+
readonly stock: number | null;
|
|
64
|
+
}
|
|
65
|
+
/** A cart, as pages see it. */
|
|
66
|
+
interface CartView {
|
|
67
|
+
readonly id: ID;
|
|
68
|
+
readonly currency: string;
|
|
69
|
+
readonly lines: readonly CartLine[];
|
|
70
|
+
/** How many items, counting quantities. */
|
|
71
|
+
readonly count: number;
|
|
72
|
+
readonly subtotal: number;
|
|
73
|
+
/** From the shop's `totals` (shipping, tax, discounts), without an address yet. */
|
|
74
|
+
readonly adjustments: readonly Adjustment[];
|
|
75
|
+
readonly total: number;
|
|
76
|
+
}
|
|
77
|
+
/** What `GET <api>/shop/config` tells pages. */
|
|
78
|
+
interface ShopSettings {
|
|
79
|
+
readonly currencies: readonly Currency[];
|
|
80
|
+
readonly defaultCurrency: string;
|
|
81
|
+
readonly paymentMethods: readonly {
|
|
82
|
+
readonly name: string;
|
|
83
|
+
readonly label: string;
|
|
84
|
+
}[];
|
|
85
|
+
readonly guests: boolean;
|
|
86
|
+
readonly countries: readonly string[];
|
|
87
|
+
}
|
|
88
|
+
/** A postal address, as stored on addresses and orders. */
|
|
89
|
+
interface Address {
|
|
90
|
+
readonly name?: string | null;
|
|
91
|
+
readonly phone?: string | null;
|
|
92
|
+
readonly line1?: string | null;
|
|
93
|
+
readonly line2?: string | null;
|
|
94
|
+
/** Sub-district (แขวง / ตำบล). */
|
|
95
|
+
readonly subdistrict?: string | null;
|
|
96
|
+
/** District (เขต / อำเภอ). */
|
|
97
|
+
readonly district?: string | null;
|
|
98
|
+
readonly province?: string | null;
|
|
99
|
+
readonly postalCode?: string | null;
|
|
100
|
+
/** ISO 3166-1 alpha-2, e.g. `TH`. */
|
|
101
|
+
readonly country?: string | null;
|
|
102
|
+
readonly [field: string]: unknown;
|
|
103
|
+
}
|
|
104
|
+
/** What starting a checkout returns to the page. */
|
|
105
|
+
interface CheckoutResult {
|
|
106
|
+
readonly transaction: ID;
|
|
107
|
+
/** What the payment method needs on the page, e.g. Stripe's client secret. */
|
|
108
|
+
readonly payment: Readonly<Record<string, unknown>>;
|
|
109
|
+
/** Set when the order exists already, e.g. paid later by bank transfer. */
|
|
110
|
+
readonly order: {
|
|
111
|
+
readonly id: ID;
|
|
112
|
+
readonly orderNumber: string;
|
|
113
|
+
readonly status: OrderStatus;
|
|
114
|
+
} | null;
|
|
115
|
+
}
|
|
116
|
+
/** What confirming a payment returns. */
|
|
117
|
+
interface ConfirmResult {
|
|
118
|
+
readonly status: TransactionStatus;
|
|
119
|
+
readonly order: {
|
|
120
|
+
readonly id: ID;
|
|
121
|
+
readonly orderNumber: string;
|
|
122
|
+
readonly status: OrderStatus;
|
|
123
|
+
} | null;
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
/** A payment as an adapter sees it. */
|
|
127
|
+
interface PaymentTransaction {
|
|
128
|
+
readonly id: ID$1;
|
|
129
|
+
/** In the currency's smallest unit. */
|
|
130
|
+
readonly amount: number;
|
|
131
|
+
/** ISO 4217, e.g. `THB`. */
|
|
132
|
+
readonly currency: string;
|
|
133
|
+
/** Who pays: the customer's email (guests give theirs). */
|
|
134
|
+
readonly email: string;
|
|
135
|
+
readonly status: TransactionStatus;
|
|
136
|
+
/** What the adapter stored: `data` from `initiate`. */
|
|
137
|
+
readonly data: Readonly<Record<string, unknown>>;
|
|
138
|
+
}
|
|
139
|
+
/** What `initiate` returns. */
|
|
140
|
+
interface InitiateResult {
|
|
141
|
+
/** Kept on the transaction for later calls. */
|
|
142
|
+
readonly data?: Record<string, unknown>;
|
|
143
|
+
/**
|
|
144
|
+
* The provider's id of the payment, e.g. Stripe's payment intent: webhooks find the
|
|
145
|
+
* transaction by it (`paymentSucceeded(reference)`).
|
|
146
|
+
*/
|
|
147
|
+
readonly reference?: string;
|
|
148
|
+
/** Sent to the page, e.g. Stripe's client secret or bank account details. */
|
|
149
|
+
readonly client?: Record<string, unknown>;
|
|
150
|
+
}
|
|
151
|
+
/**
|
|
152
|
+
* A way to pay, e.g. Stripe (`stripeAdapter` from `@easy-cms/plugin-ecommerce/stripe`) or a bank
|
|
153
|
+
* transfer (`manualAdapter`). The shop creates a transaction, the adapter starts the payment, and
|
|
154
|
+
* once the adapter says it succeeded the shop creates the order, exactly once.
|
|
155
|
+
*/
|
|
156
|
+
interface PaymentAdapter {
|
|
157
|
+
/** Lowercase letters, digits and `-`, e.g. `stripe`. */
|
|
158
|
+
readonly name: string;
|
|
159
|
+
/** What customers see, e.g. `Card or PromptPay`. */
|
|
160
|
+
readonly label: Label;
|
|
161
|
+
/**
|
|
162
|
+
* Paid later, out of band (a bank transfer, cash on delivery): the order is made at checkout
|
|
163
|
+
* as `pending`, and an admin marks it paid.
|
|
164
|
+
*/
|
|
165
|
+
readonly manual?: boolean;
|
|
166
|
+
/** For `manual` ones: what to tell the customer, e.g. the bank account (page and email). */
|
|
167
|
+
readonly instructions?: Label;
|
|
168
|
+
/** Starts the payment of a new transaction. */
|
|
169
|
+
readonly initiate: (args: {
|
|
170
|
+
readonly cms: EasyCMS;
|
|
171
|
+
readonly transaction: PaymentTransaction;
|
|
172
|
+
}) => Promise<InitiateResult> | InitiateResult;
|
|
173
|
+
/**
|
|
174
|
+
* Asks the provider whether the payment went through, after the page says it did. Never trust
|
|
175
|
+
* the page: check with the provider. Not needed for `manual` adapters.
|
|
176
|
+
*/
|
|
177
|
+
readonly confirm?: (args: {
|
|
178
|
+
readonly cms: EasyCMS;
|
|
179
|
+
readonly transaction: PaymentTransaction;
|
|
180
|
+
/** What the page sent, e.g. `{ paymentIntent }`. */
|
|
181
|
+
readonly input: Readonly<Record<string, unknown>>;
|
|
182
|
+
}) => Promise<'succeeded' | 'processing' | 'failed'>;
|
|
183
|
+
/** Gives the money back. Without it, refunds are marked only (the money goes back by hand). */
|
|
184
|
+
readonly refund?: (args: {
|
|
185
|
+
readonly cms: EasyCMS;
|
|
186
|
+
readonly transaction: PaymentTransaction;
|
|
187
|
+
}) => Promise<void>;
|
|
188
|
+
/**
|
|
189
|
+
* Extra endpoints, e.g. the provider's webhook. Served under `<api>/shop/payments/<name>/`;
|
|
190
|
+
* `path` is relative to that, e.g. `/webhook`.
|
|
191
|
+
*/
|
|
192
|
+
readonly endpoints?: readonly Endpoint[];
|
|
193
|
+
}
|
|
194
|
+
/** Declares a payment adapter; returns it unchanged. */
|
|
195
|
+
declare const definePaymentAdapter: (adapter: PaymentAdapter) => PaymentAdapter;
|
|
196
|
+
interface ManualAdapterOptions {
|
|
197
|
+
/** Default `bank-transfer`. */
|
|
198
|
+
readonly name?: string;
|
|
199
|
+
/** Default `Bank transfer` / `โอนเงิน`. */
|
|
200
|
+
readonly label?: Label;
|
|
201
|
+
/**
|
|
202
|
+
* What to tell the customer, e.g. the bank account: on the page after checkout and in the
|
|
203
|
+
* order email.
|
|
204
|
+
*/
|
|
205
|
+
readonly instructions?: Label;
|
|
206
|
+
}
|
|
207
|
+
/**
|
|
208
|
+
* Payment by bank transfer, cash on delivery or any other way outside the site: the order is
|
|
209
|
+
* made at checkout as `pending`, and an admin marks it paid (the order's "Payment received").
|
|
210
|
+
*/
|
|
211
|
+
declare function manualAdapter(options?: ManualAdapterOptions): PaymentAdapter;
|
|
212
|
+
|
|
213
|
+
export { type Address as A, type CartView as C, type InitiateResult as I, type ManualAdapterOptions as M, ORDER_STATUSES as O, type PaymentAdapter as P, type ShopSettings as S, TRANSACTION_STATUSES as T, type Currency as a, type Adjustment as b, type OrderStatus as c, CURRENCIES as d, type CartLine as e, type CheckoutResult as f, type ConfirmResult as g, type PaymentTransaction as h, type TransactionStatus as i, definePaymentAdapter as j, formatPrice as k, manualAdapter as m, priceField as p };
|
package/dist/react.d.ts
ADDED
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
import { ShopClientOptions, ShopClient, Address, CartView, Currency, ShopUser, CheckoutResult, ConfirmResult } from './client.js';
|
|
2
|
+
export { Adjustment, CURRENCIES, CartLine, ORDER_STATUSES, OrderStatus, ShopError, ShopSettings, ShopState, TRANSACTION_STATUSES, TransactionStatus, createShopClient, formatPrice, priceField } from './client.js';
|
|
3
|
+
import * as react from 'react';
|
|
4
|
+
import { ReactNode } from 'react';
|
|
5
|
+
|
|
6
|
+
interface ShopProviderProps extends ShopClientOptions {
|
|
7
|
+
/** A client of your own, e.g. made once for the app; by default one is made from the options. */
|
|
8
|
+
readonly client?: ShopClient;
|
|
9
|
+
readonly children?: ReactNode;
|
|
10
|
+
}
|
|
11
|
+
/** Gives the components below it the shop, loading settings, customer and cart on mount. */
|
|
12
|
+
declare function ShopProvider(props: ShopProviderProps): react.FunctionComponentElement<react.ProviderProps<ShopClient | null>>;
|
|
13
|
+
/** The shop's client, for everything the hooks don't cover. */
|
|
14
|
+
declare function useShop(): ShopClient;
|
|
15
|
+
/** The cart and what to do with it. */
|
|
16
|
+
declare function useCart(): {
|
|
17
|
+
cart: CartView | null;
|
|
18
|
+
loading: boolean;
|
|
19
|
+
busy: boolean;
|
|
20
|
+
addItem: (product: string | number, options?: {
|
|
21
|
+
variant?: (string | number) | null;
|
|
22
|
+
quantity?: number;
|
|
23
|
+
}) => Promise<CartView>;
|
|
24
|
+
updateItem: (line: string, quantity: number) => Promise<CartView>;
|
|
25
|
+
incrementItem: (line: string) => Promise<CartView>;
|
|
26
|
+
decrementItem: (line: string) => Promise<CartView>;
|
|
27
|
+
removeItem: (line: string) => Promise<CartView>;
|
|
28
|
+
clearCart: () => Promise<CartView | null>;
|
|
29
|
+
refreshCart: () => Promise<CartView | null>;
|
|
30
|
+
};
|
|
31
|
+
/** The signed-in customer, and signing in, out and up. */
|
|
32
|
+
declare function useCustomer(): {
|
|
33
|
+
user: ShopUser | null;
|
|
34
|
+
loading: boolean;
|
|
35
|
+
login: (email: string, password: string) => Promise<ShopUser>;
|
|
36
|
+
logout: () => Promise<void>;
|
|
37
|
+
signup: (data: {
|
|
38
|
+
email: string;
|
|
39
|
+
password: string;
|
|
40
|
+
name?: string;
|
|
41
|
+
turnstile?: string;
|
|
42
|
+
}) => Promise<{
|
|
43
|
+
verify: boolean;
|
|
44
|
+
}>;
|
|
45
|
+
verifyEmail: (token: string) => Promise<ShopUser>;
|
|
46
|
+
forgotPassword: (email: string) => Promise<void>;
|
|
47
|
+
resetPassword: (token: string, password: string) => Promise<ShopUser>;
|
|
48
|
+
};
|
|
49
|
+
/** The payment methods, and paying for the cart. */
|
|
50
|
+
declare function usePayments(): {
|
|
51
|
+
paymentMethods: readonly {
|
|
52
|
+
readonly name: string;
|
|
53
|
+
readonly label: string;
|
|
54
|
+
}[];
|
|
55
|
+
checkout: (input: {
|
|
56
|
+
method: string;
|
|
57
|
+
email?: string;
|
|
58
|
+
shippingAddress?: Address;
|
|
59
|
+
address?: string | number;
|
|
60
|
+
}) => Promise<CheckoutResult>;
|
|
61
|
+
confirm: (transaction: string | number, input?: Record<string, unknown>) => Promise<ConfirmResult>;
|
|
62
|
+
};
|
|
63
|
+
/** Currencies, the cart's, and amounts for people. */
|
|
64
|
+
declare function useCurrency(): {
|
|
65
|
+
currency: Currency | null;
|
|
66
|
+
currencies: readonly Currency[];
|
|
67
|
+
setCurrency: (code: string) => Promise<CartView>;
|
|
68
|
+
formatPrice: (amount: number, code?: string) => string;
|
|
69
|
+
};
|
|
70
|
+
/** The customer's saved addresses. */
|
|
71
|
+
declare function useAddresses(): {
|
|
72
|
+
addresses: (Address & {
|
|
73
|
+
id: string | number;
|
|
74
|
+
})[];
|
|
75
|
+
loading: boolean;
|
|
76
|
+
reload: () => Promise<void>;
|
|
77
|
+
createAddress: (address: Address) => Promise<Address & {
|
|
78
|
+
id: string | number;
|
|
79
|
+
}>;
|
|
80
|
+
updateAddress: (id: string | number, address: Partial<Address>) => Promise<Address & {
|
|
81
|
+
id: string | number;
|
|
82
|
+
}>;
|
|
83
|
+
deleteAddress: (id: string | number) => Promise<void>;
|
|
84
|
+
};
|
|
85
|
+
/** The customer's orders, newest first. */
|
|
86
|
+
declare function useOrders(options?: {
|
|
87
|
+
page?: number;
|
|
88
|
+
limit?: number;
|
|
89
|
+
}): {
|
|
90
|
+
orders: Record<string, unknown>[];
|
|
91
|
+
totalPages: number;
|
|
92
|
+
loading: boolean;
|
|
93
|
+
};
|
|
94
|
+
|
|
95
|
+
export { Address, CartView, CheckoutResult, ConfirmResult, Currency, ShopClient, ShopClientOptions, ShopProvider, type ShopProviderProps, ShopUser, useAddresses, useCart, useCurrency, useCustomer, useOrders, usePayments, useShop };
|
package/dist/react.js
ADDED
|
@@ -0,0 +1,170 @@
|
|
|
1
|
+
import {
|
|
2
|
+
CURRENCIES,
|
|
3
|
+
ORDER_STATUSES,
|
|
4
|
+
ShopError,
|
|
5
|
+
TRANSACTION_STATUSES,
|
|
6
|
+
createShopClient,
|
|
7
|
+
formatPrice,
|
|
8
|
+
priceField
|
|
9
|
+
} from "./chunk-KON3VWC6.js";
|
|
10
|
+
|
|
11
|
+
// src/react.ts
|
|
12
|
+
import {
|
|
13
|
+
createContext,
|
|
14
|
+
createElement,
|
|
15
|
+
useCallback,
|
|
16
|
+
useContext,
|
|
17
|
+
useEffect,
|
|
18
|
+
useMemo,
|
|
19
|
+
useState,
|
|
20
|
+
useSyncExternalStore
|
|
21
|
+
} from "react";
|
|
22
|
+
var ShopContext = createContext(null);
|
|
23
|
+
function ShopProvider(props) {
|
|
24
|
+
const { client: given, children, api, storage, storageKey, locale } = props;
|
|
25
|
+
const client = useMemo(
|
|
26
|
+
() => given ?? createShopClient({
|
|
27
|
+
...api !== void 0 ? { api } : {},
|
|
28
|
+
...storage !== void 0 ? { storage } : {},
|
|
29
|
+
...storageKey !== void 0 ? { storageKey } : {},
|
|
30
|
+
...locale !== void 0 ? { locale } : {}
|
|
31
|
+
}),
|
|
32
|
+
[given, api, storage, storageKey, locale]
|
|
33
|
+
);
|
|
34
|
+
useEffect(() => {
|
|
35
|
+
void client.load().catch(() => {
|
|
36
|
+
});
|
|
37
|
+
}, [client]);
|
|
38
|
+
return createElement(ShopContext.Provider, { value: client }, children);
|
|
39
|
+
}
|
|
40
|
+
function useShop() {
|
|
41
|
+
const client = useContext(ShopContext);
|
|
42
|
+
if (!client) throw new Error("useShop: put <ShopProvider> around the app");
|
|
43
|
+
return client;
|
|
44
|
+
}
|
|
45
|
+
function useShopState() {
|
|
46
|
+
const client = useShop();
|
|
47
|
+
return useSyncExternalStore(client.subscribe, client.getState, client.getState);
|
|
48
|
+
}
|
|
49
|
+
function useCart() {
|
|
50
|
+
const client = useShop();
|
|
51
|
+
const state = useShopState();
|
|
52
|
+
return {
|
|
53
|
+
cart: state.cart,
|
|
54
|
+
loading: state.loading,
|
|
55
|
+
busy: state.busy,
|
|
56
|
+
addItem: client.addItem,
|
|
57
|
+
updateItem: client.updateItem,
|
|
58
|
+
incrementItem: client.incrementItem,
|
|
59
|
+
decrementItem: client.decrementItem,
|
|
60
|
+
removeItem: client.removeItem,
|
|
61
|
+
clearCart: client.clearCart,
|
|
62
|
+
refreshCart: client.refreshCart
|
|
63
|
+
};
|
|
64
|
+
}
|
|
65
|
+
function useCustomer() {
|
|
66
|
+
const client = useShop();
|
|
67
|
+
const state = useShopState();
|
|
68
|
+
return {
|
|
69
|
+
user: state.user,
|
|
70
|
+
loading: state.loading,
|
|
71
|
+
login: client.login,
|
|
72
|
+
logout: client.logout,
|
|
73
|
+
signup: client.signup,
|
|
74
|
+
verifyEmail: client.verifyEmail,
|
|
75
|
+
forgotPassword: client.forgotPassword,
|
|
76
|
+
resetPassword: client.resetPassword
|
|
77
|
+
};
|
|
78
|
+
}
|
|
79
|
+
function usePayments() {
|
|
80
|
+
const client = useShop();
|
|
81
|
+
const state = useShopState();
|
|
82
|
+
return {
|
|
83
|
+
paymentMethods: state.settings?.paymentMethods ?? [],
|
|
84
|
+
checkout: client.checkout,
|
|
85
|
+
confirm: client.confirm
|
|
86
|
+
};
|
|
87
|
+
}
|
|
88
|
+
function useCurrency() {
|
|
89
|
+
const client = useShop();
|
|
90
|
+
const state = useShopState();
|
|
91
|
+
return {
|
|
92
|
+
currency: client.currency(),
|
|
93
|
+
currencies: state.settings?.currencies ?? [],
|
|
94
|
+
setCurrency: client.setCurrency,
|
|
95
|
+
formatPrice: client.formatPrice
|
|
96
|
+
};
|
|
97
|
+
}
|
|
98
|
+
function useAddresses() {
|
|
99
|
+
const client = useShop();
|
|
100
|
+
const { user } = useShopState();
|
|
101
|
+
const [addresses, setAddresses] = useState([]);
|
|
102
|
+
const [loading, setLoading] = useState(false);
|
|
103
|
+
const reload = useCallback(async () => {
|
|
104
|
+
if (!user) return setAddresses([]);
|
|
105
|
+
setLoading(true);
|
|
106
|
+
try {
|
|
107
|
+
setAddresses(await client.addresses());
|
|
108
|
+
} finally {
|
|
109
|
+
setLoading(false);
|
|
110
|
+
}
|
|
111
|
+
}, [client, user]);
|
|
112
|
+
useEffect(() => {
|
|
113
|
+
void reload();
|
|
114
|
+
}, [reload]);
|
|
115
|
+
return {
|
|
116
|
+
addresses,
|
|
117
|
+
loading,
|
|
118
|
+
reload,
|
|
119
|
+
createAddress: async (...args) => {
|
|
120
|
+
const saved = await client.createAddress(...args);
|
|
121
|
+
await reload();
|
|
122
|
+
return saved;
|
|
123
|
+
},
|
|
124
|
+
updateAddress: async (...args) => {
|
|
125
|
+
const saved = await client.updateAddress(...args);
|
|
126
|
+
await reload();
|
|
127
|
+
return saved;
|
|
128
|
+
},
|
|
129
|
+
deleteAddress: async (...args) => {
|
|
130
|
+
await client.deleteAddress(...args);
|
|
131
|
+
await reload();
|
|
132
|
+
}
|
|
133
|
+
};
|
|
134
|
+
}
|
|
135
|
+
function useOrders(options = {}) {
|
|
136
|
+
const client = useShop();
|
|
137
|
+
const { user } = useShopState();
|
|
138
|
+
const [result, setResult] = useState(null);
|
|
139
|
+
const { page, limit } = options;
|
|
140
|
+
useEffect(() => {
|
|
141
|
+
if (!user) return setResult(null);
|
|
142
|
+
let current = true;
|
|
143
|
+
void client.orders({ ...page ? { page } : {}, ...limit ? { limit } : {} }).then((r) => current && setResult(r)).catch(() => current && setResult(null));
|
|
144
|
+
return () => {
|
|
145
|
+
current = false;
|
|
146
|
+
};
|
|
147
|
+
}, [client, user, page, limit]);
|
|
148
|
+
return {
|
|
149
|
+
orders: result?.docs ?? [],
|
|
150
|
+
totalPages: result?.totalPages ?? 0,
|
|
151
|
+
loading: !result && !!user
|
|
152
|
+
};
|
|
153
|
+
}
|
|
154
|
+
export {
|
|
155
|
+
CURRENCIES,
|
|
156
|
+
ORDER_STATUSES,
|
|
157
|
+
ShopError,
|
|
158
|
+
ShopProvider,
|
|
159
|
+
TRANSACTION_STATUSES,
|
|
160
|
+
createShopClient,
|
|
161
|
+
formatPrice,
|
|
162
|
+
priceField,
|
|
163
|
+
useAddresses,
|
|
164
|
+
useCart,
|
|
165
|
+
useCurrency,
|
|
166
|
+
useCustomer,
|
|
167
|
+
useOrders,
|
|
168
|
+
usePayments,
|
|
169
|
+
useShop
|
|
170
|
+
};
|
package/dist/stripe.d.ts
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
import { Label } from '@easy-cms/core';
|
|
2
|
+
import { P as PaymentAdapter } from './payments-tPD3bTTW.js';
|
|
3
|
+
|
|
4
|
+
/** The parts of the `stripe` package's client the adapter uses. */
|
|
5
|
+
interface StripeClient {
|
|
6
|
+
readonly paymentIntents: {
|
|
7
|
+
create(params: Record<string, unknown>, options?: {
|
|
8
|
+
idempotencyKey?: string;
|
|
9
|
+
}): Promise<{
|
|
10
|
+
id: string;
|
|
11
|
+
client_secret: string | null;
|
|
12
|
+
status: string;
|
|
13
|
+
}>;
|
|
14
|
+
retrieve(id: string): Promise<{
|
|
15
|
+
id: string;
|
|
16
|
+
status: string;
|
|
17
|
+
amount: number;
|
|
18
|
+
currency: string;
|
|
19
|
+
}>;
|
|
20
|
+
};
|
|
21
|
+
readonly refunds: {
|
|
22
|
+
create(params: Record<string, unknown>): Promise<unknown>;
|
|
23
|
+
};
|
|
24
|
+
readonly webhooks: {
|
|
25
|
+
constructEventAsync(body: string, signature: string, secret: string): Promise<{
|
|
26
|
+
type: string;
|
|
27
|
+
data: {
|
|
28
|
+
object: Record<string, unknown>;
|
|
29
|
+
};
|
|
30
|
+
}>;
|
|
31
|
+
};
|
|
32
|
+
}
|
|
33
|
+
interface StripeAdapterOptions {
|
|
34
|
+
/** `sk_…`, from `process.env.STRIPE_SECRET_KEY`. */
|
|
35
|
+
readonly secretKey: string;
|
|
36
|
+
/** `pk_…`: sent to the page for Stripe.js. */
|
|
37
|
+
readonly publishableKey: string;
|
|
38
|
+
/**
|
|
39
|
+
* `whsec_…` of the webhook endpoint `<api>/shop/payments/stripe/webhook` (events
|
|
40
|
+
* `payment_intent.succeeded` and `payment_intent.payment_failed`): orders are then made even
|
|
41
|
+
* when the customer closes the page before it confirms.
|
|
42
|
+
*/
|
|
43
|
+
readonly webhookSecret?: string;
|
|
44
|
+
/** Default `Card or PromptPay` / `บัตร หรือ พร้อมเพย์`. */
|
|
45
|
+
readonly label?: Label;
|
|
46
|
+
/** Extra `PaymentIntent` parameters, e.g. `{ payment_method_types: ['card', 'promptpay'] }`. */
|
|
47
|
+
readonly paymentIntent?: Record<string, unknown>;
|
|
48
|
+
/** A Stripe client of your own (or a stand-in in tests). Default: `new Stripe(secretKey)`. */
|
|
49
|
+
readonly client?: StripeClient;
|
|
50
|
+
}
|
|
51
|
+
/**
|
|
52
|
+
* Card, PromptPay and the other methods of Stripe's Payment Element: a `PaymentIntent` per
|
|
53
|
+
* checkout, confirmed on the page with Stripe.js, checked with Stripe before the order is made.
|
|
54
|
+
* Needs the `stripe` package.
|
|
55
|
+
*/
|
|
56
|
+
declare function stripeAdapter(options: StripeAdapterOptions): PaymentAdapter;
|
|
57
|
+
|
|
58
|
+
export { type StripeAdapterOptions, type StripeClient, stripeAdapter };
|
package/dist/stripe.js
ADDED
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
import {
|
|
2
|
+
paymentFailed,
|
|
3
|
+
paymentSucceeded
|
|
4
|
+
} from "./chunk-RRF3IDUV.js";
|
|
5
|
+
|
|
6
|
+
// src/stripe.ts
|
|
7
|
+
function stripeAdapter(options) {
|
|
8
|
+
let client;
|
|
9
|
+
const stripe = () => {
|
|
10
|
+
if (options.client) return Promise.resolve(options.client);
|
|
11
|
+
const name = "stripe";
|
|
12
|
+
client ??= import(name).then(
|
|
13
|
+
(mod) => new mod.default(options.secretKey, {
|
|
14
|
+
appInfo: { name: "Easy CMS ecommerce", url: "https://github.com/maritonx/easy-cms" }
|
|
15
|
+
})
|
|
16
|
+
);
|
|
17
|
+
return client;
|
|
18
|
+
};
|
|
19
|
+
const intentOf = (data) => {
|
|
20
|
+
const id = data.paymentIntent;
|
|
21
|
+
if (typeof id !== "string") throw new Error("This payment has no Stripe payment intent");
|
|
22
|
+
return id;
|
|
23
|
+
};
|
|
24
|
+
return {
|
|
25
|
+
name: "stripe",
|
|
26
|
+
label: options.label ?? { en: "Card or PromptPay", th: "\u0E1A\u0E31\u0E15\u0E23 \u0E2B\u0E23\u0E37\u0E2D \u0E1E\u0E23\u0E49\u0E2D\u0E21\u0E40\u0E1E\u0E22\u0E4C" },
|
|
27
|
+
async initiate({ transaction }) {
|
|
28
|
+
const intent = await (await stripe()).paymentIntents.create(
|
|
29
|
+
{
|
|
30
|
+
amount: transaction.amount,
|
|
31
|
+
currency: transaction.currency.toLowerCase(),
|
|
32
|
+
receipt_email: transaction.email,
|
|
33
|
+
automatic_payment_methods: { enabled: true },
|
|
34
|
+
metadata: { transaction: String(transaction.id) },
|
|
35
|
+
...options.paymentIntent
|
|
36
|
+
},
|
|
37
|
+
// A retried checkout never makes a second intent for the same transaction.
|
|
38
|
+
{ idempotencyKey: `easy-cms-transaction-${transaction.id}` }
|
|
39
|
+
);
|
|
40
|
+
return {
|
|
41
|
+
data: { paymentIntent: intent.id },
|
|
42
|
+
reference: intent.id,
|
|
43
|
+
client: { clientSecret: intent.client_secret, publishableKey: options.publishableKey }
|
|
44
|
+
};
|
|
45
|
+
},
|
|
46
|
+
async confirm({ transaction }) {
|
|
47
|
+
const intent = await (await stripe()).paymentIntents.retrieve(intentOf(transaction.data));
|
|
48
|
+
if (intent.amount !== transaction.amount || intent.currency !== transaction.currency.toLowerCase())
|
|
49
|
+
return "failed";
|
|
50
|
+
if (intent.status === "succeeded") return "succeeded";
|
|
51
|
+
if (intent.status === "processing" || intent.status === "requires_capture")
|
|
52
|
+
return "processing";
|
|
53
|
+
return intent.status === "canceled" || intent.status === "requires_payment_method" ? "failed" : "processing";
|
|
54
|
+
},
|
|
55
|
+
async refund({ transaction }) {
|
|
56
|
+
await (await stripe()).refunds.create({ payment_intent: intentOf(transaction.data) });
|
|
57
|
+
},
|
|
58
|
+
endpoints: options.webhookSecret ? [
|
|
59
|
+
{
|
|
60
|
+
path: "/webhook",
|
|
61
|
+
method: "post",
|
|
62
|
+
handler: async (req) => {
|
|
63
|
+
const signature = req.request.headers.get("stripe-signature") ?? "";
|
|
64
|
+
const body = await req.request.text();
|
|
65
|
+
let event;
|
|
66
|
+
try {
|
|
67
|
+
event = await (await stripe()).webhooks.constructEventAsync(
|
|
68
|
+
body,
|
|
69
|
+
signature,
|
|
70
|
+
options.webhookSecret
|
|
71
|
+
);
|
|
72
|
+
} catch {
|
|
73
|
+
return new Response("Invalid signature", { status: 400 });
|
|
74
|
+
}
|
|
75
|
+
const intent = event.data.object;
|
|
76
|
+
const id = typeof intent.id === "string" ? intent.id : "";
|
|
77
|
+
if (event.type === "payment_intent.succeeded" && id) await paymentSucceeded(id);
|
|
78
|
+
if (event.type === "payment_intent.payment_failed" && id) {
|
|
79
|
+
const error = intent.last_payment_error?.message;
|
|
80
|
+
await paymentFailed(id, error ?? "payment failed");
|
|
81
|
+
}
|
|
82
|
+
return { received: true };
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
] : []
|
|
86
|
+
};
|
|
87
|
+
}
|
|
88
|
+
export {
|
|
89
|
+
stripeAdapter
|
|
90
|
+
};
|