Archived
Store Yoco secrets in the database; add Yoco settings tab
The Yoco secret key and webhook secret now live in AppSetting (AES-256-GCM encrypted), with .env as a fallback. A new Site Settings → Yoco tab shows them masked card-style, registers a webhook with Yoco (storing the secret it returns) or accepts one entered by hand, and lists/deletes the account's webhooks. Generic settings endpoints never read or write these keys. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,354 @@
|
||||
"use client";
|
||||
|
||||
import React, { useCallback, useEffect, useState } from "react";
|
||||
import { useAuth } from "@/hooks/useAuth";
|
||||
import { apiFetch } from "@/lib/api";
|
||||
import { useDismissingState } from "@/hooks/useDismissingState";
|
||||
import { Copy, CreditCard, KeyRound, Trash2, Webhook } from "lucide-react";
|
||||
|
||||
type Source = "db" | "env" | "none";
|
||||
|
||||
interface YocoConfig {
|
||||
secretKeyMasked: string;
|
||||
secretKeySource: Source;
|
||||
mode: "test" | "live" | "unknown";
|
||||
webhookSecretMasked: string;
|
||||
webhookSecretSource: Source;
|
||||
webhookId: string;
|
||||
webhookUrl: string;
|
||||
configured: boolean;
|
||||
}
|
||||
|
||||
interface YocoWebhook {
|
||||
id: string;
|
||||
name: string;
|
||||
url: string;
|
||||
mode: "test" | "live";
|
||||
isActive: boolean;
|
||||
pointsHere: boolean;
|
||||
}
|
||||
|
||||
const inputCls =
|
||||
"w-full border rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-brand-400";
|
||||
const primaryBtn =
|
||||
"px-3 py-1.5 text-sm rounded-lg bg-brand-600 hover:bg-brand-700 disabled:opacity-50 text-white font-medium";
|
||||
const secondaryBtn = "px-3 py-1.5 text-sm rounded-lg bg-gray-100 hover:bg-gray-200 disabled:opacity-50";
|
||||
|
||||
function ModeBadge({ mode }: { mode: string }) {
|
||||
if (mode !== "test" && mode !== "live") return null;
|
||||
return (
|
||||
<span
|
||||
className={`text-[11px] font-medium px-1.5 py-0.5 rounded ${
|
||||
mode === "live" ? "bg-green-100 text-green-700" : "bg-amber-100 text-amber-700"
|
||||
}`}
|
||||
>
|
||||
{mode === "live" ? "Live" : "Test"}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
function SourceNote({ source }: { source: Source }) {
|
||||
if (source === "env") {
|
||||
return <p className="text-xs text-amber-700 mt-1">From the server's .env file. Save it here to store it in the database instead.</p>;
|
||||
}
|
||||
if (source === "none") return <p className="text-xs text-gray-500 mt-1">Not set.</p>;
|
||||
return null;
|
||||
}
|
||||
|
||||
function Card({ icon: Icon, title, subtitle, children }: {
|
||||
icon: React.ElementType; title: string; subtitle: string; children: React.ReactNode;
|
||||
}) {
|
||||
return (
|
||||
<div className="border rounded-lg p-4 space-y-3">
|
||||
<div className="flex items-center gap-2">
|
||||
<Icon className="w-4 h-4 text-brand-600" />
|
||||
<div>
|
||||
<h3 className="text-sm font-semibold text-gray-900">{title}</h3>
|
||||
<p className="text-xs text-gray-500">{subtitle}</p>
|
||||
</div>
|
||||
</div>
|
||||
{children}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function YocoTab({ active }: { active: boolean }) {
|
||||
const { token } = useAuth();
|
||||
const [cfg, setCfg] = useState<YocoConfig | null>(null);
|
||||
const [hooks, setHooks] = useState<YocoWebhook[]>([]);
|
||||
const [hooksError, setHooksError] = useState<string | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [busy, setBusy] = useState<string | null>(null);
|
||||
const [message, setMessage] = useDismissingState<{ type: "ok" | "err"; text: string } | null>(null);
|
||||
|
||||
// API key editor
|
||||
const [editingKey, setEditingKey] = useState(false);
|
||||
const [keyInput, setKeyInput] = useState("");
|
||||
|
||||
// Webhook secret: generate (register at Yoco) or enter by hand
|
||||
const [secretMode, setSecretMode] = useState<"generate" | "enter">("generate");
|
||||
const [hookName, setHookName] = useState("hope-events");
|
||||
const [hookUrl, setHookUrl] = useState("");
|
||||
const [secretInput, setSecretInput] = useState("");
|
||||
|
||||
const [confirmDelete, setConfirmDelete] = useState<string | null>(null);
|
||||
|
||||
const loadHooks = useCallback(async () => {
|
||||
if (!token) return;
|
||||
try {
|
||||
const res = await apiFetch<{ webhooks: YocoWebhook[] }>("/api/yoco/webhooks", { authToken: token });
|
||||
setHooks(res.webhooks || []);
|
||||
setHooksError(null);
|
||||
} catch (e: any) {
|
||||
setHooks([]);
|
||||
setHooksError(e?.message || "Could not load webhooks from Yoco");
|
||||
}
|
||||
}, [token]);
|
||||
|
||||
const load = useCallback(async () => {
|
||||
if (!token) return;
|
||||
setLoading(true);
|
||||
try {
|
||||
const c = await apiFetch<YocoConfig>("/api/yoco/config", { authToken: token });
|
||||
setCfg(c);
|
||||
setHookUrl((prev) => prev || c.webhookUrl);
|
||||
if (c.secretKeySource !== "none") await loadHooks();
|
||||
else { setHooks([]); setHooksError(null); }
|
||||
} catch (e: any) {
|
||||
setMessage({ type: "err", text: e?.message || "Failed to load Yoco settings" });
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, [token, loadHooks, setMessage]);
|
||||
|
||||
useEffect(() => { if (active) load(); }, [active, load]);
|
||||
|
||||
const run = async (label: string, fn: () => Promise<string>) => {
|
||||
setBusy(label);
|
||||
setMessage(null);
|
||||
try {
|
||||
const text = await fn();
|
||||
setMessage({ type: "ok", text });
|
||||
await load();
|
||||
} catch (e: any) {
|
||||
setMessage({ type: "err", text: e?.message || "Something went wrong" });
|
||||
} finally {
|
||||
setBusy(null);
|
||||
}
|
||||
};
|
||||
|
||||
const saveKey = (value: string) => run("key", async () => {
|
||||
await apiFetch("/api/yoco/config", { method: "PUT", authToken: token!, body: { secretKey: value } });
|
||||
setEditingKey(false);
|
||||
setKeyInput("");
|
||||
return value ? "Secret key saved." : "Secret key removed.";
|
||||
});
|
||||
|
||||
const saveSecret = (value: string) => run("secret", async () => {
|
||||
await apiFetch("/api/yoco/config", { method: "PUT", authToken: token!, body: { webhookSecret: value } });
|
||||
setSecretInput("");
|
||||
return value ? "Webhook secret saved." : "Webhook secret removed.";
|
||||
});
|
||||
|
||||
const generate = () => run("generate", async () => {
|
||||
const res = await apiFetch<{ message: string }>("/api/yoco/webhooks", {
|
||||
method: "POST", authToken: token!, body: { name: hookName.trim(), url: hookUrl.trim() },
|
||||
});
|
||||
return res.message;
|
||||
});
|
||||
|
||||
const removeHook = (id: string) => run(`delete:${id}`, async () => {
|
||||
const res = await apiFetch<{ message: string }>(`/api/yoco/webhooks/${encodeURIComponent(id)}`, {
|
||||
method: "DELETE", authToken: token!,
|
||||
});
|
||||
setConfirmDelete(null);
|
||||
return res.message;
|
||||
});
|
||||
|
||||
const copy = (text: string) => {
|
||||
navigator.clipboard?.writeText(text).then(
|
||||
() => setMessage({ type: "ok", text: "Copied to clipboard." }),
|
||||
() => setMessage({ type: "err", text: "Could not copy." }),
|
||||
);
|
||||
};
|
||||
|
||||
const hasKey = !!cfg && cfg.secretKeySource !== "none";
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="w-9 h-9 rounded-lg bg-brand-50 flex items-center justify-center shrink-0">
|
||||
<CreditCard className="w-4 h-4 text-brand-600" />
|
||||
</div>
|
||||
<div>
|
||||
<h2 className="text-lg font-semibold text-gray-900">Yoco payments</h2>
|
||||
<p className="text-xs text-gray-500">Online card payments. Secrets are stored encrypted and never shown in full.</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{message && (
|
||||
<div className={`text-sm p-2.5 rounded-lg ${message.type === "ok" ? "bg-green-50 text-green-700" : "bg-red-50 text-red-700"}`}>
|
||||
{message.text}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{loading && !cfg ? (
|
||||
<p className="text-sm text-gray-400">Loading…</p>
|
||||
) : cfg && (
|
||||
<>
|
||||
{/* ── API key ─────────────────────────────────────────────────── */}
|
||||
<Card icon={KeyRound} title="Secret key" subtitle="From the Yoco app: Selling Online → Payment Gateway → API keys.">
|
||||
<div className="flex items-center gap-2 flex-wrap">
|
||||
<code className="text-sm bg-gray-50 border rounded px-2 py-1">{cfg.secretKeyMasked || "—"}</code>
|
||||
<ModeBadge mode={cfg.mode} />
|
||||
{!editingKey && (
|
||||
<button type="button" className={`${secondaryBtn} ml-auto`} onClick={() => setEditingKey(true)}>
|
||||
{hasKey ? "Change" : "Add key"}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
<SourceNote source={cfg.secretKeySource} />
|
||||
{editingKey && (
|
||||
<div className="space-y-2">
|
||||
<input
|
||||
type="password"
|
||||
autoComplete="off"
|
||||
className={inputCls}
|
||||
placeholder="sk_test_… or sk_live_…"
|
||||
value={keyInput}
|
||||
onChange={(e) => setKeyInput(e.target.value)}
|
||||
/>
|
||||
<div className="flex gap-2">
|
||||
<button type="button" className={primaryBtn} disabled={!keyInput.trim() || busy === "key"} onClick={() => saveKey(keyInput.trim())}>
|
||||
{busy === "key" ? "Checking…" : "Save"}
|
||||
</button>
|
||||
<button type="button" className={secondaryBtn} onClick={() => { setEditingKey(false); setKeyInput(""); }}>
|
||||
Cancel
|
||||
</button>
|
||||
{cfg.secretKeySource === "db" && (
|
||||
<button type="button" className={`${secondaryBtn} ml-auto text-red-600`} disabled={busy === "key"} onClick={() => saveKey("")}>
|
||||
Remove
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
<p className="text-xs text-gray-500">The key is checked with Yoco before it is saved.</p>
|
||||
</div>
|
||||
)}
|
||||
</Card>
|
||||
|
||||
{/* ── Webhook secret ──────────────────────────────────────────── */}
|
||||
<Card icon={Webhook} title="Webhook secret" subtitle="Used to check that payment notifications really come from Yoco.">
|
||||
<div className="flex items-center gap-2 flex-wrap">
|
||||
<code className="text-sm bg-gray-50 border rounded px-2 py-1">{cfg.webhookSecretMasked || "—"}</code>
|
||||
{cfg.webhookSecretSource === "db" && (
|
||||
<button type="button" className={`${secondaryBtn} ml-auto text-red-600`} disabled={busy === "secret"} onClick={() => saveSecret("")}>
|
||||
Remove
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
<SourceNote source={cfg.webhookSecretSource} />
|
||||
|
||||
<div>
|
||||
<label className="block text-xs text-gray-600 mb-1">Webhook endpoint on this server</label>
|
||||
<div className="flex items-center gap-2">
|
||||
<code className="text-xs bg-gray-50 border rounded px-2 py-1.5 flex-1 break-all">{cfg.webhookUrl || "—"}</code>
|
||||
{cfg.webhookUrl && (
|
||||
<button type="button" className={secondaryBtn} onClick={() => copy(cfg.webhookUrl)} aria-label="Copy webhook URL">
|
||||
<Copy className="w-3.5 h-3.5" />
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex gap-2 pt-1">
|
||||
{(["generate", "enter"] as const).map((m) => (
|
||||
<button
|
||||
key={m}
|
||||
type="button"
|
||||
onClick={() => setSecretMode(m)}
|
||||
className={`px-3 py-1 text-xs rounded-lg border ${secretMode === m ? "bg-brand-50 border-brand-300 text-brand-700" : "bg-white border-gray-200 text-gray-600"}`}
|
||||
>
|
||||
{m === "generate" ? "Generate new" : "Enter manually"}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{secretMode === "generate" ? (
|
||||
hasKey ? (
|
||||
<div className="space-y-2">
|
||||
<p className="text-xs text-gray-500">Registers a webhook with Yoco and saves the secret it returns. Yoco only shows the secret once, so it is stored straight away.</p>
|
||||
<div className="grid sm:grid-cols-3 gap-2">
|
||||
<input className={inputCls} value={hookName} onChange={(e) => setHookName(e.target.value)} placeholder="Name" />
|
||||
<input className={`${inputCls} sm:col-span-2`} value={hookUrl} onChange={(e) => setHookUrl(e.target.value)} placeholder="https://…/api/webhooks/yoco" />
|
||||
</div>
|
||||
<button type="button" className={primaryBtn} disabled={busy === "generate" || !hookUrl.trim()} onClick={generate}>
|
||||
{busy === "generate" ? "Registering…" : "Register webhook"}
|
||||
</button>
|
||||
</div>
|
||||
) : (
|
||||
<p className="text-xs text-gray-500">Add the secret key first.</p>
|
||||
)
|
||||
) : (
|
||||
<div className="space-y-2">
|
||||
<p className="text-xs text-gray-500">Paste the secret of a webhook you registered yourself.</p>
|
||||
<input
|
||||
type="password"
|
||||
autoComplete="off"
|
||||
className={inputCls}
|
||||
placeholder="whsec_…"
|
||||
value={secretInput}
|
||||
onChange={(e) => setSecretInput(e.target.value)}
|
||||
/>
|
||||
<button type="button" className={primaryBtn} disabled={!secretInput.trim() || busy === "secret"} onClick={() => saveSecret(secretInput.trim())}>
|
||||
{busy === "secret" ? "Saving…" : "Save secret"}
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</Card>
|
||||
|
||||
{/* ── Registered webhooks ─────────────────────────────────────── */}
|
||||
<Card icon={Webhook} title="Registered webhooks" subtitle="Webhooks on this Yoco account. Yoco allows up to 5 and recommends just one.">
|
||||
{!hasKey ? (
|
||||
<p className="text-xs text-gray-500">Add the secret key to see the webhooks.</p>
|
||||
) : hooksError ? (
|
||||
<p className="text-sm text-red-600">{hooksError}</p>
|
||||
) : hooks.length === 0 ? (
|
||||
<p className="text-sm text-gray-500">No webhooks registered.</p>
|
||||
) : (
|
||||
<ul className="divide-y border rounded-lg">
|
||||
{hooks.map((h) => (
|
||||
<li key={h.id} className="p-3 space-y-1">
|
||||
<div className="flex items-center gap-2 flex-wrap">
|
||||
<span className="text-sm font-medium text-gray-900">{h.name}</span>
|
||||
<ModeBadge mode={h.mode} />
|
||||
{h.isActive && <span className="text-[11px] font-medium px-1.5 py-0.5 rounded bg-brand-100 text-brand-700">Active</span>}
|
||||
<div className="ml-auto flex gap-2">
|
||||
{confirmDelete === h.id ? (
|
||||
<>
|
||||
<button type="button" className="px-3 py-1.5 text-sm rounded-lg bg-red-600 hover:bg-red-700 text-white disabled:opacity-50" disabled={busy === `delete:${h.id}`} onClick={() => removeHook(h.id)}>
|
||||
{busy === `delete:${h.id}` ? "Deleting…" : "Delete"}
|
||||
</button>
|
||||
<button type="button" className={secondaryBtn} onClick={() => setConfirmDelete(null)}>Cancel</button>
|
||||
</>
|
||||
) : (
|
||||
<button type="button" className={secondaryBtn} onClick={() => setConfirmDelete(h.id)} aria-label={`Delete ${h.name}`}>
|
||||
<Trash2 className="w-3.5 h-3.5" />
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
<p className="text-xs text-gray-500 break-all">{h.url}</p>
|
||||
{!h.pointsHere && <p className="text-xs text-amber-700">This URL isn't this server's webhook endpoint.</p>}
|
||||
{confirmDelete === h.id && h.isActive && (
|
||||
<p className="text-xs text-red-600">This is the active webhook. Deleting it also removes the stored secret, and payments won't be confirmed until a new one is set up.</p>
|
||||
)}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
</Card>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user