@tly-pay/vendure-plugin 0.0.0-stage → 1.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.
Files changed (86) hide show
  1. package/CHANGELOG.md +38 -0
  2. package/LICENSE +21 -0
  3. package/README.md +192 -2
  4. package/assets/coins/arb.svg +10 -0
  5. package/assets/coins/base.svg +4 -0
  6. package/assets/coins/bln.svg +4 -0
  7. package/assets/coins/bnb.svg +13 -0
  8. package/assets/coins/btc.svg +1 -0
  9. package/assets/coins/busd.svg +7 -0
  10. package/assets/coins/coin.svg +1 -0
  11. package/assets/coins/dai.svg +1 -0
  12. package/assets/coins/doge.svg +109 -0
  13. package/assets/coins/eth.svg +10 -0
  14. package/assets/coins/jst.svg +11 -0
  15. package/assets/coins/link.svg +4 -0
  16. package/assets/coins/ltc.svg +4 -0
  17. package/assets/coins/op.svg +12 -0
  18. package/assets/coins/pol.svg +11 -0
  19. package/assets/coins/shib.svg +18 -0
  20. package/assets/coins/sol.svg +15 -0
  21. package/assets/coins/sun.svg +71 -0
  22. package/assets/coins/trx.svg +4 -0
  23. package/assets/coins/uni.svg +10 -0
  24. package/assets/coins/usdc.svg +6 -0
  25. package/assets/coins/usdd.svg +18 -0
  26. package/assets/coins/usdt.svg +1 -0
  27. package/assets/coins/wbtc.svg +16 -0
  28. package/assets/coins/weth.svg +17 -0
  29. package/assets/tly-pay-mark.svg +31 -0
  30. package/dashboard/api.ts +167 -0
  31. package/dashboard/appearance.tsx +253 -0
  32. package/dashboard/banner.tsx +72 -0
  33. package/dashboard/i18n/en.po +584 -0
  34. package/dashboard/index.tsx +33 -0
  35. package/dashboard/logic.ts +219 -0
  36. package/dashboard/messages.tsx +90 -0
  37. package/dashboard/notice.tsx +15 -0
  38. package/dashboard/order-block.tsx +21 -0
  39. package/dashboard/orders.tsx +246 -0
  40. package/dashboard/page.tsx +174 -0
  41. package/dashboard/settings.tsx +186 -0
  42. package/dashboard/use-connect.ts +46 -0
  43. package/dist/api.d.ts +169 -0
  44. package/dist/api.js +541 -0
  45. package/dist/client-ref.d.ts +75 -0
  46. package/dist/client-ref.js +165 -0
  47. package/dist/connect-flow.d.ts +65 -0
  48. package/dist/connect-flow.js +177 -0
  49. package/dist/connection-check.d.ts +28 -0
  50. package/dist/connection-check.js +49 -0
  51. package/dist/connection.d.ts +140 -0
  52. package/dist/connection.js +361 -0
  53. package/dist/contracts.d.ts +66 -0
  54. package/dist/contracts.js +151 -0
  55. package/dist/creation-service.d.ts +136 -0
  56. package/dist/creation-service.js +242 -0
  57. package/dist/handler.d.ts +13 -0
  58. package/dist/handler.js +45 -0
  59. package/dist/hosted-checkout.d.ts +3 -0
  60. package/dist/hosted-checkout.js +25 -0
  61. package/dist/index.d.ts +11 -0
  62. package/dist/index.js +32 -0
  63. package/dist/ownership.d.ts +38 -0
  64. package/dist/ownership.js +38 -0
  65. package/dist/payment-sync.d.ts +45 -0
  66. package/dist/payment-sync.js +111 -0
  67. package/dist/persistence.d.ts +104 -0
  68. package/dist/persistence.js +405 -0
  69. package/dist/plugin.d.ts +26 -0
  70. package/dist/plugin.js +112 -0
  71. package/dist/public-api.d.ts +56 -0
  72. package/dist/public-api.js +221 -0
  73. package/dist/records.d.ts +53 -0
  74. package/dist/records.js +109 -0
  75. package/dist/release-config.d.ts +55 -0
  76. package/dist/release-config.js +107 -0
  77. package/dist/release-config.json +15 -0
  78. package/dist/secret-box.d.ts +19 -0
  79. package/dist/secret-box.js +65 -0
  80. package/dist/service.d.ts +267 -0
  81. package/dist/service.js +788 -0
  82. package/dist/signed-webhook.d.ts +67 -0
  83. package/dist/signed-webhook.js +119 -0
  84. package/dist/storefront/checkout.d.mts +86 -0
  85. package/dist/storefront/checkout.mjs +149 -0
  86. package/package.json +97 -4
@@ -0,0 +1,174 @@
1
+ import { Trans, useLingui } from "@lingui/react/macro"
2
+ import {
3
+ Alert, AlertDescription, Badge, Button, buttonVariants, FullWidthPageBlock, Page, PageLayout, PageTitle, Tabs, TabsList,
4
+ TabsTrigger,
5
+ } from "@vendure/dashboard"
6
+ import { useCallback, useEffect, useState } from "react"
7
+ import markUrl from "../assets/tly-pay-mark.svg"
8
+ import { checkStatus, completeConnect, readStatus, retryConnect, Status } from "./api"
9
+ import { ConnectWindow, headerAction, relay, RelayedResult, returnParams } from "./logic"
10
+ import { useCopy } from "./messages"
11
+ import { ResultNotice } from "./notice"
12
+ import { OrdersTab } from "./orders"
13
+ import { SettingsTab } from "./settings"
14
+ import { useConnect } from "./use-connect"
15
+
16
+ type Tab = "orders" | "settings"
17
+
18
+ /** Badge variants of the Dashboard design system v2, whose `default` Badge is the neutral one. */
19
+ const PILL_TONE = { ok: "success", pending: "warning", warn: "destructive", off: "default" } as const
20
+
21
+ /**
22
+ * The TLY Pay page: branded header with the connection status pill and the account link, the Orders
23
+ * tab (default) and the Settings tab. It also completes the connection when TLY Pay returns here
24
+ * through `/tly-pay/connect/return`, inside the popup or in this tab.
25
+ */
26
+ export function TlyPayPage() {
27
+ const { t } = useLingui()
28
+ const copy = useCopy()
29
+ const initial = new URLSearchParams(window.location.search)
30
+ const [tab, setTab] = useState<Tab>(initial.get("tab") === "settings" ? "settings" : "orders")
31
+ const [status, setStatus] = useState<Status | null>(null)
32
+ const [result, setResult] = useState("")
33
+ const [retry, setRetry] = useState("")
34
+ const [busy, setBusy] = useState(false)
35
+ const [loadErr, setLoadErr] = useState(false)
36
+
37
+ const load = useCallback(async (recheck: boolean) => {
38
+ try {
39
+ setStatus(await (recheck ? checkStatus() : readStatus()))
40
+ setLoadErr(false)
41
+ } catch {
42
+ setLoadErr(true)
43
+ }
44
+ }, [])
45
+
46
+ const show = useCallback((message: RelayedResult) => {
47
+ setTab("settings")
48
+ setResult(message.result)
49
+ setRetry(message.retry)
50
+ void load(false)
51
+ }, [load])
52
+
53
+ const connect = useConnect(show)
54
+
55
+ useEffect(() => {
56
+ const params = returnParams(window.location.search)
57
+ if (params === null) {
58
+ void load(tab === "settings")
59
+ return
60
+ }
61
+ window.history.replaceState(null, "", window.location.pathname + "?tab=settings")
62
+ // `tly_popup` comes from the server's pending authorization. The window name is not checked: the TLY
63
+ // Pay app's Cross-Origin-Opener-Policy clears it on the way, so a popup back here has no name.
64
+ const inPopup = params.popup
65
+ const finish = (message: RelayedResult) => {
66
+ if (inPopup && !relay(window as unknown as ConnectWindow, message)) return
67
+ show(message)
68
+ }
69
+ if ("result" in params) {
70
+ finish({ result: params.result, retry: "" })
71
+ return
72
+ }
73
+ setBusy(true)
74
+ completeConnect(params.state, params.code)
75
+ .then((done) => finish({ result: done.result, retry: done.retry ? params.state : "" }),
76
+ () => finish({ result: "invalid_response", retry: params.state }))
77
+ .finally(() => setBusy(false))
78
+ // Runs once per page entry; later loads follow the tab.
79
+ // eslint-disable-next-line react-hooks/exhaustive-deps
80
+ }, [])
81
+
82
+ const selectTab = (next: string) => {
83
+ const value: Tab = next === "settings" ? "settings" : "orders"
84
+ setTab(value)
85
+ window.history.replaceState(null, "", window.location.pathname + (value === "settings" ? "?tab=settings" : ""))
86
+ if (value === "settings") void load(true)
87
+ }
88
+
89
+ const retryNow = async () => {
90
+ setBusy(true)
91
+ try {
92
+ const done = await retryConnect(retry)
93
+ setResult(done.result)
94
+ setRetry(done.retry ? retry : "")
95
+ await load(false)
96
+ } catch {
97
+ setResult("invalid_response")
98
+ } finally {
99
+ setBusy(false)
100
+ }
101
+ }
102
+
103
+ const state = status?.state ?? "off"
104
+ const apiHost = status?.apiHost ?? ""
105
+ return (
106
+ <Page pageId="tly-pay">
107
+ <PageTitle>TLY Pay</PageTitle>
108
+ <PageLayout>
109
+ <FullWidthPageBlock blockId="tly-pay-header">
110
+ <header className="flex flex-wrap items-center justify-between gap-4 rounded-lg border bg-card p-5">
111
+ <div className="flex items-center gap-4">
112
+ <span className="flex size-14 items-center justify-center rounded-md bg-muted">
113
+ <img src={markUrl} alt="" width={40} height={19} />
114
+ </span>
115
+ <div>
116
+ <h2 className="text-lg font-semibold"><Trans>TLY Pay for Vendure</Trans></h2>
117
+ <p className="text-sm text-muted-foreground">
118
+ <Trans>Accept crypto payments at checkout. Orders update automatically when a payment is confirmed.</Trans>
119
+ </p>
120
+ </div>
121
+ </div>
122
+ <div className="flex items-center gap-3">
123
+ <Badge variant={PILL_TONE[state]} aria-live="polite">{copy.pill(state)}</Badge>
124
+ {/* Until the store is connected the header starts the connection (as the WooCommerce
125
+ onboarding banner and the Medusa page do); once connected it opens the TLY Pay app. */}
126
+ {headerAction(status) === "connect" ? (
127
+ <Button disabled={busy || !status?.releaseComplete} onClick={() => void connect.start()}>
128
+ <Trans>Connect TLY Pay</Trans>
129
+ </Button>
130
+ ) : headerAction(status) === "account" && status !== null && (
131
+ <a className={buttonVariants({ variant: "outline" })} href={status.consoleOrigin} target="_blank"
132
+ rel="noopener noreferrer"><Trans>Open TLY Pay account</Trans></a>
133
+ )}
134
+ </div>
135
+ </header>
136
+ </FullWidthPageBlock>
137
+ <FullWidthPageBlock blockId="tly-pay-body">
138
+ <div className="flex flex-col gap-4">
139
+ <Tabs value={tab} onValueChange={(value: string) => selectTab(value)}>
140
+ <TabsList aria-label={t`TLY Pay views`}>
141
+ <TabsTrigger value="orders"><Trans>Orders</Trans></TabsTrigger>
142
+ <TabsTrigger value="settings"><Trans>Settings</Trans></TabsTrigger>
143
+ </TabsList>
144
+ </Tabs>
145
+ {loadErr && (
146
+ <Alert variant="destructive"><AlertDescription>
147
+ <Trans>The TLY Pay status could not be read. Reload this page to try again.</Trans>
148
+ </AlertDescription></Alert>
149
+ )}
150
+ <ResultNotice result={result} apiHost={apiHost} />
151
+ {tab === "settings" && retry !== "" && (
152
+ <div><Button variant="outline" disabled={busy} onClick={() => void retryNow()}>
153
+ <Trans>Retry connection validation</Trans>
154
+ </Button></div>
155
+ )}
156
+ {tab === "settings" && status !== null && status.unverified && (
157
+ <Alert><AlertDescription>{copy.unverified}</AlertDescription></Alert>
158
+ )}
159
+ {tab === "settings" && status !== null && !status.unverified && status.lastErr !== "" && status.lastErr !== result && (
160
+ <ResultNotice result={status.lastErr} apiHost={apiHost} />
161
+ )}
162
+ {tab === "orders"
163
+ ? <OrdersTab consoleOrigin={status?.consoleOrigin ?? ""} apiHost={apiHost} />
164
+ : status !== null && (
165
+ <SettingsTab status={status} busy={busy} phase={connect.phase}
166
+ onConnect={() => void connect.start()}
167
+ onResult={(next) => { setResult(next); setRetry(""); void load(false) }} />
168
+ )}
169
+ </div>
170
+ </FullWidthPageBlock>
171
+ </PageLayout>
172
+ </Page>
173
+ )
174
+ }
@@ -0,0 +1,186 @@
1
+ import { Trans, useLingui } from "@lingui/react/macro"
2
+ import { Alert, AlertDescription, Button, Card, CardContent, CardDescription, CardHeader, CardTitle, Checkbox, Label,
3
+ RadioGroup, RadioGroupItem } from "@vendure/dashboard"
4
+ import { useState } from "react"
5
+ import { createPaymentMethod, disconnect, saveCheckoutMode, saveSiteMode, Status } from "./api"
6
+ import { CheckoutAppearance } from "./appearance"
7
+ import { useCopy } from "./messages"
8
+
9
+ type Props = {
10
+ status: Status
11
+ busy: boolean
12
+ phase: "idle" | "waiting"
13
+ onConnect: () => void
14
+ onResult: (result: string) => void
15
+ }
16
+
17
+ type Option = { value: string; label: string; description: string }
18
+
19
+ /** Selectable option cards of one setting, as used by the checkout mode and the site. */
20
+ function OptionCards({ name, label, value, options, onChange }: { name: string; label: string; value: string;
21
+ options: Option[]; onChange: (value: string) => void }) {
22
+ return (
23
+ <RadioGroup value={value} onValueChange={(next: unknown) => onChange(String(next))} aria-label={label}
24
+ className="grid gap-3 sm:grid-cols-2">
25
+ {options.map((option) => (
26
+ <Label key={option.value} htmlFor={`tly-pay-${name}-${option.value}`}
27
+ className="flex cursor-pointer items-start gap-3 rounded-lg border p-4 has-[[data-checked]]:border-primary has-[[data-checked]]:bg-primary/5">
28
+ <RadioGroupItem id={`tly-pay-${name}-${option.value}`} value={option.value} />
29
+ <span className="flex flex-col gap-1">
30
+ <span className="font-medium">{option.label}</span>
31
+ <span className="text-sm font-normal text-muted-foreground">{option.description}</span>
32
+ </span>
33
+ </Label>
34
+ ))}
35
+ </RadioGroup>
36
+ )
37
+ }
38
+
39
+ /**
40
+ * Settings tab: connection, payment method, checkout mode and checkout appearance panels, then the
41
+ * collapsed Advanced panel with the TLY Pay site and, while connected, the disconnect section.
42
+ */
43
+ export function SettingsTab({ status, busy, phase, onConnect, onResult }: Props) {
44
+ const { t } = useLingui()
45
+ const copy = useCopy()
46
+ const [mode, setMode] = useState(status.checkoutMode)
47
+ const [site, setSite] = useState<string>(status.siteMode)
48
+ const [confirmed, setConfirmed] = useState(false)
49
+ const [working, setWorking] = useState(false)
50
+ const ready = status.state === "ok" || status.state === "pending"
51
+ const wallet = status.state === "pending"
52
+ const attention = status.state === "warn"
53
+
54
+ const run = async (action: () => Promise<{ result: string }>) => {
55
+ setWorking(true)
56
+ try {
57
+ onResult((await action()).result)
58
+ } catch {
59
+ onResult("invalid_response")
60
+ } finally {
61
+ setWorking(false)
62
+ }
63
+ }
64
+
65
+ const heading = wallet ? t`Finish the wallet setup in TLY Pay`
66
+ : ready ? t`Your store is connected`
67
+ : attention ? t`TLY Pay is unavailable at checkout`
68
+ : t`Connect your TLY Pay account`
69
+ const modes: Option[] = [
70
+ { value: "hosted", label: t`Hosted checkout page`,
71
+ description: t`Customers are sent to the TLY Pay payment page. Works with every storefront.` },
72
+ { value: "embedded", label: t`Embedded checkout`,
73
+ description: t`The payment window opens on your storefront's checkout page. Requires the TLY Pay storefront helper; the hosted page is used when the window cannot open.` },
74
+ ]
75
+ const sites: Option[] = [
76
+ { value: "standard", label: t`Standard`, description: t`The default TLY Pay site.` },
77
+ { value: "test", label: t`Test`, description: t`The shared test site.` },
78
+ ]
79
+
80
+ return (
81
+ <div className="grid gap-4 lg:grid-cols-2">
82
+ <Card id="tly-pay-setup-guide">
83
+ <CardHeader>
84
+ <CardTitle>{heading}</CardTitle>
85
+ <CardDescription>
86
+ {wallet ? <>{status.displayName} - {copy.walletSetup}</>
87
+ : ready ? <>{status.displayName} - <Trans>Payment credentials are valid. Complete a payment and check that its order updates to verify notification delivery.</Trans></>
88
+ : attention ? <Trans>Customers cannot choose TLY Pay until this is resolved. Follow the message above, then reload this page. If the problem continues, reconnect TLY Pay.</Trans>
89
+ : <Trans>Authorize this store in TLY Pay. The plugin will securely receive and save the configuration for you.</Trans>}
90
+ </CardDescription>
91
+ </CardHeader>
92
+ <CardContent className="flex flex-col gap-3 text-sm">
93
+ {wallet && (
94
+ <p><Trans>This page checks again each time it opens; the plugin also rechecks automatically, so no reconnect is needed once the wallet is ready.</Trans>{" "}
95
+ {status.consoleOrigin !== "" && <a className="underline" href={status.consoleOrigin} target="_blank" rel="noopener noreferrer"><Trans>Open TLY Pay</Trans></a>}</p>
96
+ )}
97
+ {!ready && (
98
+ <>
99
+ <ol className="list-decimal space-y-1 pl-5">
100
+ <li><Trans>A TLY Pay window opens. Sign in to your account; if your browser blocks the window, the same steps continue in this tab.</Trans></li>
101
+ <li><Trans>Check the store website and payment permissions, then approve the connection.</Trans></li>
102
+ <li><Trans>This page updates automatically. The plugin validates your store and configures payment notifications.</Trans></li>
103
+ </ol>
104
+ <p><Trans>Your Vendure server needs a public HTTPS URL and the same currency as your TLY Pay store ({status.channelCurrency}).</Trans></p>
105
+ </>
106
+ )}
107
+ <div role="status" aria-live="polite">
108
+ {phase === "waiting" && <Alert><AlertDescription><Trans>Finish the connection in the TLY Pay window.</Trans></AlertDescription></Alert>}
109
+ </div>
110
+ <div>
111
+ <Button variant={ready ? "outline" : "default"} disabled={busy || !status.releaseComplete} onClick={onConnect}>
112
+ {status.connected ? <Trans>Reconnect TLY Pay</Trans> : <Trans>Connect TLY Pay</Trans>}
113
+ </Button>
114
+ </div>
115
+ </CardContent>
116
+ </Card>
117
+
118
+ <Card id="tly-pay-payment-method">
119
+ <CardHeader>
120
+ <CardTitle><Trans>Payment method</Trans></CardTitle>
121
+ <CardDescription><Trans>Customers see this payment method's name, "Crypto payment" unless you change it, with the coin icons you choose under Checkout appearance. The method is offered only while the connection and the wallet are ready and the order uses your TLY Pay currency.</Trans></CardDescription>
122
+ </CardHeader>
123
+ <CardContent className="flex flex-col gap-3 text-sm">
124
+ {status.paymentMethod === "ready" && <p><Trans>This Channel has an enabled TLY Pay payment method.</Trans></p>}
125
+ {status.paymentMethod === "disabled" && <p><Trans>The TLY Pay payment method of this Channel is disabled. Enable it under Settings &gt; Payment methods.</Trans></p>}
126
+ {status.paymentMethod === "no_checker" && <p><Trans>The TLY Pay payment method of this Channel has no "TLY Pay connection and wallet are ready" eligibility checker, so customers could choose it while TLY Pay is not ready. Select that checker under Settings &gt; Payment methods.</Trans></p>}
127
+ {status.paymentMethod === "missing" && (
128
+ <>
129
+ <p><Trans>This Channel has no TLY Pay payment method yet.</Trans></p>
130
+ <div><Button variant="outline" disabled={working} onClick={() => void run(() => createPaymentMethod(t`Crypto payment`))}>
131
+ <Trans>Add Crypto payment method</Trans>
132
+ </Button></div>
133
+ </>
134
+ )}
135
+ {status.paymentAssets.length > 0 && (
136
+ <p className="text-muted-foreground"><Trans>Accepted now:</Trans> {status.paymentAssets.map((asset) => asset.symbol).join(", ")}</p>
137
+ )}
138
+ </CardContent>
139
+ </Card>
140
+
141
+ <Card id="tly-pay-checkout">
142
+ <CardHeader>
143
+ <CardTitle><Trans>Checkout</Trans></CardTitle>
144
+ <CardDescription><Trans>Choose where customers pay. The hosted page is also used when the payment window cannot open.</Trans></CardDescription>
145
+ </CardHeader>
146
+ <CardContent className="flex flex-col gap-3">
147
+ <OptionCards name="mode" label={t`Checkout mode`} value={mode} options={modes} onChange={setMode} />
148
+ <div><Button variant="outline" disabled={working || mode === status.checkoutMode}
149
+ onClick={() => void run(() => saveCheckoutMode(mode))}><Trans>Save</Trans></Button></div>
150
+ </CardContent>
151
+ </Card>
152
+
153
+ <CheckoutAppearance status={status} working={working} run={run} />
154
+
155
+ <Card id="tly-pay-advanced" className="gap-0 py-0 lg:col-span-2">
156
+ <details className="group">
157
+ <summary className="flex cursor-pointer list-none items-center justify-between gap-4 p-6 [&::-webkit-details-marker]:hidden">
158
+ <CardTitle><Trans>Advanced</Trans></CardTitle>
159
+ <span aria-hidden="true"
160
+ className="size-2 -translate-y-0.5 rotate-45 border-r-2 border-b-2 border-muted-foreground group-open:translate-y-0.5 group-open:rotate-[225deg]" />
161
+ </summary>
162
+ <CardContent className="flex flex-col gap-4 pb-6 text-sm">
163
+ <p className="text-muted-foreground"><Trans>Do not change this unless you maintain the site.</Trans></p>
164
+ <OptionCards name="site" label={t`Site`} value={site} options={sites} onChange={setSite} />
165
+ <div><Button variant="outline" disabled={working || site === status.siteMode}
166
+ onClick={() => void run(() => saveSiteMode(site))}><Trans>Save</Trans></Button></div>
167
+ {status.connected && (
168
+ <div id="tly-pay-disconnect" className="flex flex-col gap-3 border-t border-destructive/40 pt-4">
169
+ <h3 className="font-semibold text-destructive"><Trans>Disconnect TLY Pay</Trans></h3>
170
+ <p className="text-muted-foreground"><Trans>Removes the saved credentials and the account binding from this Vendure server so you can connect a different TLY Pay account. Existing orders are kept, but payments of the previous connection stop updating until the same account is connected again.</Trans></p>
171
+ <Label className="flex items-center gap-2 font-normal">
172
+ <Checkbox checked={confirmed} onCheckedChange={(value: boolean) => setConfirmed(value === true)} />
173
+ <Trans>I understand that new payments stop until this store is connected again.</Trans>
174
+ </Label>
175
+ <div><Button variant="destructive" disabled={!confirmed || working}
176
+ onClick={() => void run(async () => { const done = await disconnect(); setConfirmed(false); return done })}>
177
+ <Trans>Disconnect</Trans>
178
+ </Button></div>
179
+ </div>
180
+ )}
181
+ </CardContent>
182
+ </details>
183
+ </Card>
184
+ </div>
185
+ )
186
+ }
@@ -0,0 +1,46 @@
1
+ import { useRouter } from "@vendure/dashboard"
2
+ import { useCallback, useEffect, useRef, useState } from "react"
3
+ import { startConnect } from "./api"
4
+ import { ConnectWindow, listen, navigate, openPopup, RelayedResult } from "./logic"
5
+
6
+ /** Path of the TLY Pay page inside the Dashboard. */
7
+ export const PAGE_PATH = "/tly-pay"
8
+
9
+ /**
10
+ * Starts the account connection from a click: the popup opens synchronously, the consent URL follows
11
+ * once the server kept the pending state; a blocked popup continues in this tab. `phase` is `waiting`
12
+ * from the popup's navigation until its result is relayed. The popup's own state is hidden by the
13
+ * Console's Cross-Origin-Opener-Policy, so a new start stays possible while waiting.
14
+ */
15
+ export function useConnect(onResult: (message: RelayedResult) => void) {
16
+ const router = useRouter()
17
+ const [phase, setPhase] = useState<"idle" | "waiting">("idle")
18
+ const handler = useRef(onResult)
19
+ handler.current = onResult
20
+
21
+ useEffect(() => listen(window as unknown as ConnectWindow, (message) => {
22
+ setPhase("idle")
23
+ handler.current(message)
24
+ }), [])
25
+
26
+ const start = useCallback(async () => {
27
+ const win = window as unknown as ConnectWindow
28
+ const popup = openPopup(win)
29
+ const adminUrl = `${window.location.origin}${(router.basepath ?? "").replace(/\/+$/, "")}${PAGE_PATH}`
30
+ let started: { url: string | null; result: string }
31
+ try {
32
+ started = await startConnect(adminUrl, popup !== null)
33
+ } catch {
34
+ started = { url: null, result: "invalid_response" }
35
+ }
36
+ if (started.url === null) {
37
+ popup?.close()
38
+ setPhase("idle")
39
+ handler.current({ result: started.result, retry: "" })
40
+ return
41
+ }
42
+ if (navigate(win, popup, started.url) === "popup") setPhase("waiting")
43
+ }, [router])
44
+
45
+ return { phase, start }
46
+ }
package/dist/api.d.ts ADDED
@@ -0,0 +1,169 @@
1
+ import { RequestContext } from "@vendure/core";
2
+ import type { NextFunction, Request, Response } from "express";
3
+ import { TlyPayService } from "./service";
4
+ /** Largest Webhook body the plugin reads; `verifySignedEvent` accepts the same limit. */
5
+ export declare const MAX_WEBHOOK_BYTES = 65536;
6
+ export declare const shopApiExtensions: import("graphql").DocumentNode;
7
+ /** Intent ids are UUID strings, typed `String` so Vendure's entity ID codec leaves them unchanged. */
8
+ export declare const adminApiExtensions: import("graphql").DocumentNode;
9
+ export declare class TlyPayShopResolver {
10
+ private readonly service;
11
+ constructor(service: TlyPayService);
12
+ tlyPayCheckout(ctx: RequestContext): Promise<import("./service").CheckoutPresentation>;
13
+ createTlyPayPayment(ctx: RequestContext, args: {
14
+ returnUrl?: string | null;
15
+ }): Promise<import("./service").PaymentSession>;
16
+ }
17
+ export declare class TlyPayAdminResolver {
18
+ private readonly service;
19
+ constructor(service: TlyPayService);
20
+ private status;
21
+ tlyPayStatus(ctx: RequestContext): Promise<{
22
+ releaseComplete: boolean;
23
+ consoleOrigin: string;
24
+ apiHost: string;
25
+ checkoutMode: "embedded" | "hosted";
26
+ checkoutIcons: string[];
27
+ checkoutIconOptions: import("./service").CheckoutIconOption[];
28
+ checkoutCoinNames: boolean;
29
+ checkoutTitle: string;
30
+ paymentMethodId: import("@vendure/core").ID | null;
31
+ siteMode: "standard" | "test";
32
+ channelCurrency: import("@vendure/core").CurrencyCode;
33
+ paymentMethod: string;
34
+ connected: boolean;
35
+ state: "off" | "ok" | "pending" | "warn";
36
+ displayName: string;
37
+ storeId: string;
38
+ currency: string;
39
+ merchantDomain: string;
40
+ paymentsReady: boolean;
41
+ paymentAssets: import("./contracts").PaymentAsset[];
42
+ lastErr: string;
43
+ unverified: boolean;
44
+ validatedAt: number;
45
+ webhookUrl: string;
46
+ }>;
47
+ tlyPayOrders(ctx: RequestContext, args: {
48
+ filter?: string | null;
49
+ skip?: number | null;
50
+ take?: number | null;
51
+ }): Promise<{
52
+ items: import("./service").OrderRow[];
53
+ totalItems: number;
54
+ counts: Record<string, number>;
55
+ }>;
56
+ tlyPayOrder(ctx: RequestContext, args: {
57
+ id: string;
58
+ }): Promise<{
59
+ row: import("./service").OrderRow;
60
+ checkoutOrigin: string | null;
61
+ returnUrl: string | null;
62
+ clientRef: string | null;
63
+ live: import("./contracts").PaymentView | null;
64
+ liveErr: string | null;
65
+ events: import("./persistence").StoredEvent[];
66
+ } | null>;
67
+ tlyPayOrderIntent(ctx: RequestContext, args: {
68
+ orderCode: string;
69
+ }): Promise<string | null>;
70
+ tlyPayCheckConnection(ctx: RequestContext): Promise<{
71
+ releaseComplete: boolean;
72
+ consoleOrigin: string;
73
+ apiHost: string;
74
+ checkoutMode: "embedded" | "hosted";
75
+ checkoutIcons: string[];
76
+ checkoutIconOptions: import("./service").CheckoutIconOption[];
77
+ checkoutCoinNames: boolean;
78
+ checkoutTitle: string;
79
+ paymentMethodId: import("@vendure/core").ID | null;
80
+ siteMode: "standard" | "test";
81
+ channelCurrency: import("@vendure/core").CurrencyCode;
82
+ paymentMethod: string;
83
+ connected: boolean;
84
+ state: "off" | "ok" | "pending" | "warn";
85
+ displayName: string;
86
+ storeId: string;
87
+ currency: string;
88
+ merchantDomain: string;
89
+ paymentsReady: boolean;
90
+ paymentAssets: import("./contracts").PaymentAsset[];
91
+ lastErr: string;
92
+ unverified: boolean;
93
+ validatedAt: number;
94
+ webhookUrl: string;
95
+ }>;
96
+ tlyPayStartConnect(ctx: RequestContext, args: {
97
+ adminUrl: string;
98
+ popup: boolean;
99
+ }): Promise<{
100
+ url: string | null;
101
+ result: string;
102
+ }>;
103
+ tlyPayCompleteConnect(ctx: RequestContext, args: {
104
+ state: string;
105
+ code: string;
106
+ }): Promise<import("./connect-flow").ConnectResult>;
107
+ tlyPayRetryConnect(ctx: RequestContext, args: {
108
+ state: string;
109
+ }): Promise<import("./connect-flow").ConnectResult>;
110
+ tlyPayDisconnect(args: {
111
+ confirm: boolean;
112
+ }): Promise<import("./connect-flow").ConnectResult>;
113
+ tlyPaySetCheckoutMode(args: {
114
+ mode: string;
115
+ }): Promise<{
116
+ result: string;
117
+ retry: boolean;
118
+ }>;
119
+ /**
120
+ * Saves the checkout appearance: the marks replace the choice exactly (none is a valid choice) and the
121
+ * coin names switch is stored beside them. The title is the payment method's own name and is not
122
+ * saved here.
123
+ */
124
+ tlyPaySetCheckoutAppearance(args: {
125
+ marks: unknown;
126
+ coinNames: unknown;
127
+ }): Promise<{
128
+ result: string;
129
+ retry: boolean;
130
+ }>;
131
+ /** Runs the connection check, then selects exactly the coins the Store accepts now. */
132
+ tlyPaySyncCheckoutIcons(): Promise<import("./connect-flow").ConnectResult>;
133
+ /** Switches the TLY Pay site; the saved connection is kept and the store connects again. */
134
+ tlyPaySetSiteMode(args: {
135
+ mode: string;
136
+ }): Promise<{
137
+ result: string;
138
+ retry: boolean;
139
+ }>;
140
+ tlyPayReconcile(ctx: RequestContext, args: {
141
+ id: string;
142
+ }): Promise<import("./connect-flow").ConnectResult>;
143
+ tlyPayCreatePaymentMethod(ctx: RequestContext, args: {
144
+ name: string;
145
+ }): Promise<import("./connect-flow").ConnectResult>;
146
+ }
147
+ type RawRequest = Request & {
148
+ tlyPayRawBody?: Buffer;
149
+ _body?: boolean;
150
+ };
151
+ /**
152
+ * Reads the exact Webhook bytes before Vendure's JSON body parser, which skips a request already
153
+ * marked as parsed. Bodies over the limit are answered 413 without reading further.
154
+ */
155
+ export declare function rawWebhookBody(req: RawRequest, res: Response, next: NextFunction): void;
156
+ /**
157
+ * The public routes registered for Vendure in the platform connection registry: the Webhook
158
+ * `POST /tly-pay/webhook` and the connection callback `GET /tly-pay/connect/return`, plus the
159
+ * bundled coin icons the storefront shows beside the checkout title.
160
+ */
161
+ export declare class TlyPayController {
162
+ private readonly service;
163
+ constructor(service: TlyPayService);
164
+ webhook(req: RawRequest, res: Response): Promise<void>;
165
+ /** Needs no session: forwards `state` and `code` to the Dashboard page that started the connection. */
166
+ connectReturn(state: unknown, code: unknown, res: Response): Promise<void>;
167
+ coin(file: string, res: Response): Promise<void>;
168
+ }
169
+ export {};