Geführte Einrichtung für Stripe, PayPal, DHL, Google und Apple unter Verbindungen
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01SvuGvHpbAQ4syfuLuRvutL
This commit is contained in:
parent
85638061c8
commit
bf679e82bf
18 changed files with 839 additions and 224 deletions
|
|
@ -1,39 +0,0 @@
|
||||||
"use server";
|
|
||||||
import { revalidatePath } from "next/cache";
|
|
||||||
import { assertPermission, audit } from "@/lib/auth";
|
|
||||||
import { fail, ok, type ActionResult } from "@/lib/action-result";
|
|
||||||
import { getLoginProviders, isConfigured, saveLoginProviders, type LoginProviders } from "@/lib/social/config";
|
|
||||||
import { isValidApplePrivateKey } from "@/lib/social/oauth";
|
|
||||||
|
|
||||||
const str = (fd: FormData, k: string) => String(fd.get(k) ?? "").trim();
|
|
||||||
|
|
||||||
export async function saveLoginSettings(_prev: ActionResult, fd: FormData): Promise<ActionResult> {
|
|
||||||
const user = await assertPermission("settings.edit");
|
|
||||||
const current = await getLoginProviders();
|
|
||||||
// Leere Geheimfelder behalten den gespeicherten Wert
|
|
||||||
const keep = (v: string, old: string) => (v ? v : old);
|
|
||||||
const privateKey = keep(str(fd, "applePrivateKey").replace(/\r\n/g, "\n"), current.apple.privateKey);
|
|
||||||
if (privateKey && !isValidApplePrivateKey(privateKey))
|
|
||||||
return fail("Der Apple-Schlüssel lässt sich nicht lesen. Füge den ganzen Inhalt der .p8-Datei ein, mit den Zeilen BEGIN und END.", { applePrivateKey: "Ungültiger Schlüssel" });
|
|
||||||
|
|
||||||
const next: LoginProviders = {
|
|
||||||
google: {
|
|
||||||
enabled: fd.get("googleEnabled") === "on",
|
|
||||||
clientId: str(fd, "googleClientId"),
|
|
||||||
clientSecret: fd.get("googleClear") === "on" ? "" : keep(str(fd, "googleClientSecret"), current.google.clientSecret),
|
|
||||||
},
|
|
||||||
apple: {
|
|
||||||
enabled: fd.get("appleEnabled") === "on",
|
|
||||||
servicesId: str(fd, "appleServicesId"),
|
|
||||||
teamId: str(fd, "appleTeamId").toUpperCase(),
|
|
||||||
keyId: str(fd, "appleKeyId").toUpperCase(),
|
|
||||||
privateKey: fd.get("appleClear") === "on" ? "" : privateKey,
|
|
||||||
},
|
|
||||||
};
|
|
||||||
if (next.google.enabled && !isConfigured("google", next)) return fail("Für Google brauchst du Client-ID und Client-Secret.");
|
|
||||||
if (next.apple.enabled && !isConfigured("apple", next)) return fail("Für Apple brauchst du Services-ID, Team-ID, Key-ID und den Schlüssel.");
|
|
||||||
await saveLoginProviders(next);
|
|
||||||
await audit(user, "Anmeldung mit Google/Apple geändert", `Google: ${next.google.enabled ? "an" : "aus"}, Apple: ${next.apple.enabled ? "an" : "aus"}`);
|
|
||||||
revalidatePath("/admin/anmeldung");
|
|
||||||
return ok();
|
|
||||||
}
|
|
||||||
|
|
@ -1,44 +1,6 @@
|
||||||
import { requireAdmin } from "@/lib/auth";
|
import { redirect } from "next/navigation";
|
||||||
import { mask } from "@/lib/payments/credentials";
|
|
||||||
import { callbackUrl, getLoginProviders, isConfigured } from "@/lib/social/config";
|
|
||||||
import { Field, TextareaField } from "@/components/Field";
|
|
||||||
import { AdminForm } from "@/components/admin/AdminForm";
|
|
||||||
import { Card, PageHead, Pill, Switch } from "@/components/admin/ui";
|
|
||||||
import { saveLoginSettings } from "./actions";
|
|
||||||
|
|
||||||
export default async function LoginSettingsPage() {
|
// Die Einrichtung von Google und Apple ist nach „Verbindungen“ umgezogen
|
||||||
await requireAdmin("settings.edit");
|
export default function LoginSettingsPage() {
|
||||||
const c = await getLoginProviders();
|
redirect("/admin/verbindungen");
|
||||||
const status = (p: "google" | "apple") =>
|
|
||||||
!isConfigured(p, c) ? <Pill tone="neutral">Nicht eingerichtet</Pill> : c[p].enabled ? <Pill tone="success">Aktiv</Pill> : <Pill tone="gold">Aus</Pill>;
|
|
||||||
const domain = new URL(callbackUrl("apple")).host;
|
|
||||||
return (
|
|
||||||
<div className="ad-wrap ad-wrap--narrow">
|
|
||||||
<PageHead title="Anmeldung" lead="Kunden und Team können sich zusätzlich mit Google oder Apple anmelden. Gibt es zur E-Mail-Adresse schon ein Konto, wird es verknüpft." />
|
|
||||||
<AdminForm action={saveLoginSettings}>
|
|
||||||
<Card title="Google" lead="„Mit Google anmelden“ auf den Anmelde- und Registrierungsseiten." action={status("google")}>
|
|
||||||
<Switch name="googleEnabled" label="Im Shop anbieten" defaultChecked={c.google.enabled} />
|
|
||||||
<Field label="Client-ID" name="googleClientId" defaultValue={c.google.clientId} placeholder="…apps.googleusercontent.com" />
|
|
||||||
<Field label="Client-Secret" name="googleClientSecret" type="password" autoComplete="off" placeholder={c.google.clientSecret ? mask(c.google.clientSecret) : "GOCSPX-…"} hint={c.google.clientSecret ? "Leer lassen, um das gespeicherte Secret zu behalten." : undefined} />
|
|
||||||
<div className="ad-help" style={{ marginTop: "var(--space-4)" }}>
|
|
||||||
In der Google Cloud Console unter APIs & Dienste → Anmeldedaten eine OAuth-Client-ID vom Typ „Webanwendung“ anlegen. Als autorisierte Weiterleitungs-URI eintragen: <code>{callbackUrl("google")}</code>
|
|
||||||
</div>
|
|
||||||
{c.google.clientSecret && <label className="sm-check" style={{ marginTop: "var(--space-3)" }}><input type="checkbox" name="googleClear" /><span className="sm-check__text">Google-Verbindung entfernen</span></label>}
|
|
||||||
</Card>
|
|
||||||
<Card title="Apple" lead="„Mit Apple anmelden“. Braucht ein Apple-Developer-Konto." action={status("apple")}>
|
|
||||||
<Switch name="appleEnabled" label="Im Shop anbieten" defaultChecked={c.apple.enabled} />
|
|
||||||
<Field label="Services-ID" name="appleServicesId" defaultValue={c.apple.servicesId} placeholder="de.sanamare.login" hint="Die Kennung der Services-ID, nicht die der App." />
|
|
||||||
<div className="sm-form-row">
|
|
||||||
<Field label="Team-ID" name="appleTeamId" defaultValue={c.apple.teamId} placeholder="ABCDE12345" />
|
|
||||||
<Field label="Key-ID" name="appleKeyId" defaultValue={c.apple.keyId} placeholder="XYZ987WVU6" />
|
|
||||||
</div>
|
|
||||||
<TextareaField label="Schlüssel (.p8-Datei)" name="applePrivateKey" rows={4} placeholder={c.apple.privateKey ? "Gespeichert. Leer lassen, um ihn zu behalten." : "-----BEGIN PRIVATE KEY-----\n…\n-----END PRIVATE KEY-----"} hint="Den ganzen Inhalt der heruntergeladenen .p8-Datei einfügen." />
|
|
||||||
<div className="ad-help" style={{ marginTop: "var(--space-4)" }}>
|
|
||||||
Im Apple-Developer-Bereich unter Certificates, Identifiers & Profiles: eine Services-ID mit „Sign in with Apple“ anlegen, als Domain <code>{domain}</code> und als Return-URL <code>{callbackUrl("apple")}</code> eintragen. Danach unter Keys einen Schlüssel mit „Sign in with Apple“ erstellen und die .p8-Datei herunterladen.
|
|
||||||
</div>
|
|
||||||
{c.apple.privateKey && <label className="sm-check" style={{ marginTop: "var(--space-3)" }}><input type="checkbox" name="appleClear" /><span className="sm-check__text">Apple-Verbindung entfernen</span></label>}
|
|
||||||
</Card>
|
|
||||||
</AdminForm>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -2,7 +2,7 @@
|
||||||
import { revalidatePath } from "next/cache";
|
import { revalidatePath } from "next/cache";
|
||||||
import { assertPermission, audit } from "@/lib/auth";
|
import { assertPermission, audit } from "@/lib/auth";
|
||||||
import { fail, ok, type ActionResult } from "@/lib/action-result";
|
import { fail, ok, type ActionResult } from "@/lib/action-result";
|
||||||
import { getDhlConfig, saveDhlConfig, testConnection, type DhlConfig } from "@/lib/dhl";
|
import { getDhlConfig, saveDhlConfig, type DhlConfig } from "@/lib/dhl";
|
||||||
|
|
||||||
const str = (fd: FormData, k: string) => String(fd.get(k) ?? "").trim();
|
const str = (fd: FormData, k: string) => String(fd.get(k) ?? "").trim();
|
||||||
const grams = (fd: FormData, k: string, fallback: number) => {
|
const grams = (fd: FormData, k: string, fallback: number) => {
|
||||||
|
|
@ -13,16 +13,15 @@ const grams = (fd: FormData, k: string, fallback: number) => {
|
||||||
export async function saveDhl(_prev: ActionResult, fd: FormData): Promise<ActionResult> {
|
export async function saveDhl(_prev: ActionResult, fd: FormData): Promise<ActionResult> {
|
||||||
const user = await assertPermission("shipping.edit");
|
const user = await assertPermission("shipping.edit");
|
||||||
const current = await getDhlConfig();
|
const current = await getDhlConfig();
|
||||||
// Leere Geheimfelder behalten den gespeicherten Wert
|
|
||||||
const keep = (v: string, old: string) => (v ? v : old);
|
|
||||||
const next: DhlConfig = {
|
const next: DhlConfig = {
|
||||||
enabled: fd.get("enabled") === "on",
|
// Die Verbindung selbst wird unter Verbindungen gepflegt
|
||||||
sandbox: fd.get("sandbox") === "on",
|
enabled: current.enabled,
|
||||||
apiKey: keep(str(fd, "apiKey"), current.apiKey),
|
sandbox: current.sandbox,
|
||||||
username: str(fd, "username"),
|
apiKey: current.apiKey,
|
||||||
password: keep(str(fd, "password"), current.password),
|
username: current.username,
|
||||||
billingNational: str(fd, "billingNational").replace(/\s/g, ""),
|
password: current.password,
|
||||||
billingInternational: str(fd, "billingInternational").replace(/\s/g, ""),
|
billingNational: current.billingNational,
|
||||||
|
billingInternational: current.billingInternational,
|
||||||
shipperName: str(fd, "shipperName"),
|
shipperName: str(fd, "shipperName"),
|
||||||
shipperStreet: str(fd, "shipperStreet"),
|
shipperStreet: str(fd, "shipperStreet"),
|
||||||
shipperHouse: str(fd, "shipperHouse"),
|
shipperHouse: str(fd, "shipperHouse"),
|
||||||
|
|
@ -35,28 +34,9 @@ export async function saveDhl(_prev: ActionResult, fd: FormData): Promise<Action
|
||||||
shareEmail: fd.get("shareEmail") === "on",
|
shareEmail: fd.get("shareEmail") === "on",
|
||||||
autoComplete: fd.get("autoComplete") === "on",
|
autoComplete: fd.get("autoComplete") === "on",
|
||||||
};
|
};
|
||||||
if (fd.get("clear") === "on") {
|
if (next.shipperZip && !/^\d{5}$/.test(next.shipperZip)) return fail("Bitte prüfe die Postleitzahl.", { shipperZip: "5 Ziffern" });
|
||||||
next.apiKey = "";
|
|
||||||
next.password = "";
|
|
||||||
}
|
|
||||||
const errors: Record<string, string> = {};
|
|
||||||
for (const k of ["billingNational", "billingInternational"] as const) {
|
|
||||||
if (next[k] && !/^\d{14}$/.test(next[k])) errors[k] = "14 Ziffern, z. B. 22222222220101";
|
|
||||||
}
|
|
||||||
if (next.shipperZip && !/^\d{5}$/.test(next.shipperZip)) errors.shipperZip = "5 Ziffern";
|
|
||||||
if (Object.keys(errors).length) return fail("Bitte prüfe die markierten Felder.", errors);
|
|
||||||
if (next.enabled && !next.apiKey) return fail("Zum Einschalten braucht DHL einen API-Schlüssel.", { apiKey: "Bitte eintragen" });
|
|
||||||
if (next.enabled && !next.sandbox && (!next.username || !next.password || !next.billingNational)) {
|
|
||||||
return fail("Für den Live-Betrieb fehlen Benutzername, Passwort oder Abrechnungsnummer.");
|
|
||||||
}
|
|
||||||
await saveDhlConfig(next);
|
await saveDhlConfig(next);
|
||||||
await audit(user, "DHL-Einstellungen geändert", `${next.enabled ? "an" : "aus"}, ${next.sandbox ? "Sandbox" : "Live"}`);
|
await audit(user, "DHL-Einstellungen geändert", "Absender und Pakete");
|
||||||
revalidatePath("/admin/dhl");
|
revalidatePath("/admin/dhl");
|
||||||
return ok("Gespeichert.");
|
return ok("Gespeichert.");
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function testDhl(_prev: ActionResult): Promise<ActionResult> {
|
|
||||||
await assertPermission("shipping.edit");
|
|
||||||
const r = await testConnection(await getDhlConfig());
|
|
||||||
return r.ok ? ok(r.message) : fail(r.message);
|
|
||||||
}
|
|
||||||
|
|
|
||||||
|
|
@ -1,12 +1,11 @@
|
||||||
|
import Link from "next/link";
|
||||||
import { requireAdmin } from "@/lib/auth";
|
import { requireAdmin } from "@/lib/auth";
|
||||||
import { getSettings } from "@/lib/settings";
|
import { getSettings } from "@/lib/settings";
|
||||||
import { canCreateLabels, getDhlConfig, splitStreet } from "@/lib/dhl";
|
import { canCreateLabels, getDhlConfig, splitStreet } from "@/lib/dhl";
|
||||||
import { mask } from "@/lib/payments/credentials";
|
|
||||||
import { Field } from "@/components/Field";
|
import { Field } from "@/components/Field";
|
||||||
import { AdminForm } from "@/components/admin/AdminForm";
|
import { AdminForm } from "@/components/admin/AdminForm";
|
||||||
import { TestButton } from "@/components/admin/TestButton";
|
|
||||||
import { Card, PageHead, Pill, Switch } from "@/components/admin/ui";
|
import { Card, PageHead, Pill, Switch } from "@/components/admin/ui";
|
||||||
import { saveDhl, testDhl } from "./actions";
|
import { saveDhl } from "./actions";
|
||||||
|
|
||||||
const kg = (g: number) => (g ? String(g / 1000).replace(".", ",") : "");
|
const kg = (g: number) => (g ? String(g / 1000).replace(".", ",") : "");
|
||||||
|
|
||||||
|
|
@ -19,26 +18,14 @@ export default async function DhlPage() {
|
||||||
const ready = canCreateLabels(c);
|
const ready = canCreateLabels(c);
|
||||||
return (
|
return (
|
||||||
<div className="ad-wrap ad-wrap--narrow">
|
<div className="ad-wrap ad-wrap--narrow">
|
||||||
<PageHead title="DHL-Versand" lead="Versandlabels direkt aus der Bestellung erstellen und den Sendungsstatus im Shop anzeigen." />
|
<PageHead title="DHL-Versand" lead="Absender, Paketgewichte und Sendungsstatus. Die Verbindung zu DHL richtest du unter Verbindungen ein." />
|
||||||
<AdminForm action={saveDhl}>
|
<Card title="Verbindung" action={!ready ? <Pill tone="neutral">Nicht eingerichtet</Pill> : <Pill tone={c.sandbox ? "gold" : "success"}>{c.sandbox ? "Sandbox" : "Live"}</Pill>}>
|
||||||
<Card
|
<p className="body" style={{ margin: 0 }}>
|
||||||
title="Verbindung"
|
{ready ? "DHL ist verbunden. Labels erstellst du direkt in der Bestellung." : "Noch nicht verbunden."}{" "}
|
||||||
lead="Zugang aus dem DHL-Geschäftskundenportal und ein API-Schlüssel vom DHL-Entwicklerportal."
|
<Link href="/admin/verbindungen/dhl">{ready ? "Verbindung ansehen" : "Jetzt einrichten"}</Link>
|
||||||
action={!ready ? <Pill tone="neutral">Nicht eingerichtet</Pill> : <Pill tone={c.sandbox ? "gold" : "success"}>{c.sandbox ? "Sandbox" : "Live"}</Pill>}
|
</p>
|
||||||
>
|
|
||||||
<Switch name="enabled" label="DHL-Labels im Admin anbieten" defaultChecked={c.enabled} />
|
|
||||||
<Switch name="sandbox" label="Sandbox (Testmodus)" hint="Erzeugt Test-Labels, die nicht versendet werden können. Ohne eigene Zugangsdaten nutzt die Sandbox die DHL-Testzugänge." defaultChecked={c.sandbox} />
|
|
||||||
<Field label="API-Schlüssel" name="apiKey" type="password" autoComplete="off" placeholder={c.apiKey ? mask(c.apiKey) : ""} hint={c.apiKey ? "Leer lassen, um den gespeicherten Schlüssel zu behalten." : "developer.dhl.com → App anlegen mit „Parcel DE Shipping“ und „Shipment Tracking – Unified“ → API Key."} />
|
|
||||||
<div className="sm-form-row">
|
|
||||||
<Field label="Benutzername (Geschäftskundenportal)" optional={c.sandbox} name="username" defaultValue={c.username} autoComplete="off" />
|
|
||||||
<Field label="Passwort" optional={c.sandbox} name="password" type="password" autoComplete="off" placeholder={c.password ? mask(c.password) : ""} hint={c.password ? "Leer lassen, um es zu behalten." : undefined} />
|
|
||||||
</div>
|
|
||||||
<div className="sm-form-row">
|
|
||||||
<Field label="Abrechnungsnummer DHL Paket" optional={c.sandbox} name="billingNational" defaultValue={c.billingNational} inputMode="numeric" placeholder="14 Ziffern" hint="Für Sendungen innerhalb Deutschlands." />
|
|
||||||
<Field label="Abrechnungsnummer DHL Paket International" optional name="billingInternational" defaultValue={c.billingInternational} inputMode="numeric" placeholder="14 Ziffern" hint="Für Österreich und andere EU-Länder." />
|
|
||||||
</div>
|
|
||||||
{(c.apiKey || c.password) && <label className="sm-check" style={{ marginTop: "var(--space-3)" }}><input type="checkbox" name="clear" /><span className="sm-check__text">API-Schlüssel und Passwort entfernen</span></label>}
|
|
||||||
</Card>
|
</Card>
|
||||||
|
<AdminForm action={saveDhl}>
|
||||||
<Card title="Absender" lead="Steht als Absender auf jedem Label.">
|
<Card title="Absender" lead="Steht als Absender auf jedem Label.">
|
||||||
<Field label="Name oder Firma" name="shipperName" defaultValue={c.shipperName || s.general.company} />
|
<Field label="Name oder Firma" name="shipperName" defaultValue={c.shipperName || s.general.company} />
|
||||||
<div className="sm-form-row">
|
<div className="sm-form-row">
|
||||||
|
|
@ -63,9 +50,6 @@ export default async function DhlPage() {
|
||||||
<Switch name="shareEmail" label="E-Mail und Telefon des Kunden an DHL übergeben" hint="Damit DHL den Kunden über die Zustellung informiert. Nur einschalten, wenn deine Datenschutzerklärung das abdeckt." defaultChecked={c.shareEmail} />
|
<Switch name="shareEmail" label="E-Mail und Telefon des Kunden an DHL übergeben" hint="Damit DHL den Kunden über die Zustellung informiert. Nur einschalten, wenn deine Datenschutzerklärung das abdeckt." defaultChecked={c.shareEmail} />
|
||||||
</Card>
|
</Card>
|
||||||
</AdminForm>
|
</AdminForm>
|
||||||
<div style={{ margin: "var(--space-2) 0 var(--space-8)" }}>
|
|
||||||
<TestButton action={testDhl} provider="dhl" />
|
|
||||||
</div>
|
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
|
||||||
271
src/app/admin/(panel)/verbindungen/[provider]/page.tsx
Normal file
271
src/app/admin/(panel)/verbindungen/[provider]/page.tsx
Normal file
|
|
@ -0,0 +1,271 @@
|
||||||
|
import { notFound } from "next/navigation";
|
||||||
|
import { requireAdmin } from "@/lib/auth";
|
||||||
|
import { getCredentials, mask } from "@/lib/payments/credentials";
|
||||||
|
import { getDhlConfig } from "@/lib/dhl";
|
||||||
|
import { appUrl, callbackUrl, getLoginProviders } from "@/lib/social/config";
|
||||||
|
import { INTEGRATIONS, STRIPE_WEBHOOK_EVENTS, getStatuses, stripeWebhookUrl, type IntegrationKey, type TestResult } from "@/lib/integrations";
|
||||||
|
import { dateFmt } from "@/lib/status";
|
||||||
|
import { Field } from "@/components/Field";
|
||||||
|
import { AdminForm, ConfirmButton } from "@/components/admin/AdminForm";
|
||||||
|
import { Card, PageHead, Switch } from "@/components/admin/ui";
|
||||||
|
import { TestButton } from "@/components/admin/TestButton";
|
||||||
|
import { CopyValue } from "@/components/admin/CopyValue";
|
||||||
|
import { KeyFileInput } from "@/components/admin/KeyFileInput";
|
||||||
|
import { OpenLink, Step, Steps } from "@/components/admin/Setup";
|
||||||
|
import { StatusPill } from "@/components/admin/IntegrationStatus";
|
||||||
|
import { disconnect, retest, saveApple, saveDhlConnection, saveGoogle, savePaypal, saveStripe } from "../actions";
|
||||||
|
|
||||||
|
function LastTest({ t }: { t: TestResult | null }) {
|
||||||
|
if (!t) return null;
|
||||||
|
return (
|
||||||
|
<div className={`ad-result ${t.ok ? "ad-result--ok" : "ad-result--err"}`} role="status">
|
||||||
|
<div>
|
||||||
|
{t.message}
|
||||||
|
<small>Zuletzt geprüft: {dateFmt.format(new Date(t.at))}</small>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export default async function IntegrationSetup({ params }: { params: Promise<{ provider: string }> }) {
|
||||||
|
const { provider } = await params;
|
||||||
|
const meta = INTEGRATIONS.find((i) => i.key === provider);
|
||||||
|
if (!meta) notFound();
|
||||||
|
await requireAdmin(meta.permission);
|
||||||
|
const status = (await getStatuses())[meta.key];
|
||||||
|
const Wizard = WIZARDS[meta.key];
|
||||||
|
return (
|
||||||
|
<div className="ad-wrap ad-wrap--narrow">
|
||||||
|
<PageHead title={`${meta.name} einrichten`} lead={meta.purpose} back={{ href: "/admin/verbindungen", label: "Verbindungen" }}>
|
||||||
|
<StatusPill s={status} />
|
||||||
|
</PageHead>
|
||||||
|
<LastTest t={status.lastTest} />
|
||||||
|
<Wizard ok={Boolean(status.lastTest?.ok)} />
|
||||||
|
{status.configured && (
|
||||||
|
<div style={{ display: "flex", gap: "var(--space-5)", alignItems: "center", flexWrap: "wrap", margin: "var(--space-2) 0 var(--space-8)" }}>
|
||||||
|
<TestButton action={retest} provider={meta.key} />
|
||||||
|
<ConfirmButton action={disconnect} hidden={{ provider: meta.key }} confirm="Verbindung wirklich entfernen?" className="sm-btn sm-btn--ghost sm-btn--sm">Verbindung entfernen</ConfirmButton>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------- Stripe ----------
|
||||||
|
|
||||||
|
async function StripeWizard({ ok }: { ok: boolean }) {
|
||||||
|
const c = (await getCredentials()).stripe;
|
||||||
|
return (
|
||||||
|
<AdminForm action={saveStripe} submitLabel="Speichern und testen">
|
||||||
|
<Card>
|
||||||
|
<Steps>
|
||||||
|
<Step n={1} title="Stripe-Konto anlegen" done={ok && Boolean(c.secretKey)}>
|
||||||
|
<p>Falls du noch keins hast: kostenlos registrieren und im Dashboard „Konto aktivieren“ durchgehen (Firmendaten und Bankkonto für Auszahlungen). Zum Ausprobieren reicht der Testmodus, dann geht es auch ohne Aktivierung.</p>
|
||||||
|
<OpenLink href="https://dashboard.stripe.com/register">Bei Stripe registrieren</OpenLink>
|
||||||
|
<p>Unter Zahlungsmethoden schaltest du ein, was Kunden nutzen dürfen: Karten, Apple Pay, Google Pay, Klarna, SEPA-Lastschrift.</p>
|
||||||
|
<OpenLink href="https://dashboard.stripe.com/settings/payment_methods">Zahlungsmethoden öffnen</OpenLink>
|
||||||
|
</Step>
|
||||||
|
<Step n={2} title="Geheimschlüssel kopieren" done={ok && Boolean(c.secretKey)}>
|
||||||
|
<p>Öffne die API-Schlüssel und klicke beim <strong>Geheimschlüssel</strong> auf „Anzeigen“. Er beginnt mit <code>sk_live_</code>. Für Testzahlungen nimm den Schlüssel aus dem Testmodus (<code>sk_test_</code>).</p>
|
||||||
|
<OpenLink href="https://dashboard.stripe.com/apikeys">Live-Schlüssel</OpenLink>
|
||||||
|
<OpenLink href="https://dashboard.stripe.com/test/apikeys">Test-Schlüssel</OpenLink>
|
||||||
|
<Field label="Geheimschlüssel" name="secretKey" type="password" autoComplete="off" placeholder={c.secretKey ? mask(c.secretKey) : "sk_live_… oder sk_test_…"} hint={c.secretKey ? "Gespeichert. Nur ausfüllen, wenn du ihn ersetzen willst." : undefined} />
|
||||||
|
</Step>
|
||||||
|
<Step n={3} title="Zahlungsbestätigungen (Webhook)" done={ok && Boolean(c.webhookSecret)}>
|
||||||
|
<p>Damit Bestellungen automatisch auf „Bezahlt“ springen, auch bei SEPA und Klarna, braucht Stripe eine Rücksende-Adresse. Die richte ich beim Speichern selbst ein.</p>
|
||||||
|
<Switch name="autoWebhook" label="Webhook automatisch einrichten" defaultChecked />
|
||||||
|
{c.webhookSecret && <Switch name="renewWebhook" label="Webhook neu anlegen" hint="Nur nötig, wenn Zahlungen nicht mehr bestätigt werden." />}
|
||||||
|
<details className="ad-help" style={{ marginTop: "var(--space-3)" }}>
|
||||||
|
<summary style={{ cursor: "pointer" }}>Lieber von Hand einrichten</summary>
|
||||||
|
<div style={{ marginTop: "var(--space-3)" }}>
|
||||||
|
<OpenLink href="https://dashboard.stripe.com/webhooks">Webhooks öffnen</OpenLink>
|
||||||
|
<CopyValue label="Endpunkt-URL" value={stripeWebhookUrl()} />
|
||||||
|
<CopyValue label="Ereignisse" value={STRIPE_WEBHOOK_EVENTS.join(", ")} />
|
||||||
|
<Field label="Signaturschlüssel" optional name="webhookSecret" type="password" autoComplete="off" placeholder={c.webhookSecret ? mask(c.webhookSecret) : "whsec_…"} />
|
||||||
|
</div>
|
||||||
|
</details>
|
||||||
|
</Step>
|
||||||
|
<Step n={4} title="Speichern und testen">
|
||||||
|
<p>Ich prüfe den Schlüssel direkt bei Stripe. Danach schaltest du unter <a href="/admin/zahlung">Zahlungsarten</a> ein, was im Shop erscheinen soll.</p>
|
||||||
|
</Step>
|
||||||
|
</Steps>
|
||||||
|
</Card>
|
||||||
|
</AdminForm>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------- PayPal ----------
|
||||||
|
|
||||||
|
async function PaypalWizard({ ok }: { ok: boolean }) {
|
||||||
|
const c = (await getCredentials()).paypal;
|
||||||
|
const has = Boolean(c.clientId && c.clientSecret);
|
||||||
|
return (
|
||||||
|
<AdminForm action={savePaypal} submitLabel="Speichern und testen">
|
||||||
|
<Card>
|
||||||
|
<Steps>
|
||||||
|
<Step n={1} title="PayPal-Geschäftskonto" done={ok && has}>
|
||||||
|
<p>Du brauchst ein PayPal-Geschäftskonto. Ein privates Konto lässt sich dort kostenlos umwandeln.</p>
|
||||||
|
<OpenLink href="https://www.paypal.com/de/business">PayPal Business</OpenLink>
|
||||||
|
</Step>
|
||||||
|
<Step n={2} title="App anlegen und Zugangsdaten kopieren" done={ok && has}>
|
||||||
|
<ol>
|
||||||
|
<li>Im PayPal-Entwicklerbereich mit deinem Geschäftskonto anmelden.</li>
|
||||||
|
<li>Oben auf „Live“ stellen (oder „Sandbox“ zum Testen) und „Create App“ klicken.</li>
|
||||||
|
<li>Einen Namen eingeben, z. B. „Sanamare Shop“, Typ „Merchant“.</li>
|
||||||
|
<li>Client-ID und Secret kopieren und hier einfügen.</li>
|
||||||
|
</ol>
|
||||||
|
<OpenLink href="https://developer.paypal.com/dashboard/applications/live">Live-Apps</OpenLink>
|
||||||
|
<OpenLink href="https://developer.paypal.com/dashboard/applications/sandbox">Sandbox-Apps</OpenLink>
|
||||||
|
<Field label="Client-ID" name="clientId" defaultValue={c.clientId} autoComplete="off" />
|
||||||
|
<Field label="Secret" name="clientSecret" type="password" autoComplete="off" placeholder={c.clientSecret ? mask(c.clientSecret) : ""} hint={c.clientSecret ? "Gespeichert. Nur ausfüllen, wenn du es ersetzen willst." : undefined} />
|
||||||
|
</Step>
|
||||||
|
<Step n={3} title="Speichern und testen">
|
||||||
|
<p>Ob die Daten zu Live oder Sandbox gehören, erkenne ich selbst. Danach schaltest du PayPal unter <a href="/admin/zahlung">Zahlungsarten</a> ein.</p>
|
||||||
|
</Step>
|
||||||
|
</Steps>
|
||||||
|
</Card>
|
||||||
|
</AdminForm>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------- DHL ----------
|
||||||
|
|
||||||
|
async function DhlWizard({ ok }: { ok: boolean }) {
|
||||||
|
const c = await getDhlConfig();
|
||||||
|
return (
|
||||||
|
<AdminForm action={saveDhlConnection} submitLabel="Speichern und testen">
|
||||||
|
<Card>
|
||||||
|
<Steps>
|
||||||
|
<Step n={1} title="Ausprobieren oder gleich echt?" done={ok && Boolean(c.apiKey)}>
|
||||||
|
<p>Im Testmodus brauchst du nur den API-Schlüssel aus Schritt 2. Die Labels sind dann Muster und können nicht verschickt werden. Für echte Labels brauchst du ein DHL-Geschäftskundenkonto.</p>
|
||||||
|
<Switch name="sandbox" label="Testmodus (Sandbox)" defaultChecked={c.sandbox} />
|
||||||
|
<OpenLink href="https://www.dhl.de/de/geschaeftskunden/paket/kunde-werden.html">DHL-Geschäftskunde werden</OpenLink>
|
||||||
|
</Step>
|
||||||
|
<Step n={2} title="API-Schlüssel holen" done={ok && Boolean(c.apiKey)}>
|
||||||
|
<ol>
|
||||||
|
<li>Im DHL-Entwicklerportal kostenlos registrieren.</li>
|
||||||
|
<li>Unter „My Apps“ eine App anlegen und die APIs „Parcel DE Shipping (Post & Parcel Germany)“ und „Shipment Tracking – Unified“ auswählen.</li>
|
||||||
|
<li>Nach der Freigabe den „API Key“ der App kopieren.</li>
|
||||||
|
</ol>
|
||||||
|
<OpenLink href="https://developer.dhl.com/user/register">Registrieren</OpenLink>
|
||||||
|
<OpenLink href="https://developer.dhl.com/user/apps">My Apps</OpenLink>
|
||||||
|
<Field label="API-Schlüssel" name="apiKey" type="password" autoComplete="off" placeholder={c.apiKey ? mask(c.apiKey) : ""} hint={c.apiKey ? "Gespeichert. Nur ausfüllen, wenn du ihn ersetzen willst." : undefined} />
|
||||||
|
</Step>
|
||||||
|
<Step n={3} title="Zugang zum Geschäftskundenportal" done={ok && Boolean(c.username && c.password)}>
|
||||||
|
<p>Nur für echte Labels. Lege im Geschäftskundenportal unter Benutzerverwaltung einen <strong>Systembenutzer</strong> an und trag ihn hier ein. Im Testmodus leer lassen.</p>
|
||||||
|
<OpenLink href="https://geschaeftskunden.dhl.de">Geschäftskundenportal</OpenLink>
|
||||||
|
<div className="sm-form-row">
|
||||||
|
<Field label="Benutzername" optional name="username" defaultValue={c.username} autoComplete="off" />
|
||||||
|
<Field label="Passwort" optional name="password" type="password" autoComplete="off" placeholder={c.password ? mask(c.password) : ""} />
|
||||||
|
</div>
|
||||||
|
</Step>
|
||||||
|
<Step n={4} title="Abrechnungsnummer" done={ok && Boolean(c.billingNational)}>
|
||||||
|
<p>Deine EKP (10 Ziffern) steht im Geschäftskundenportal unter Vertragsdaten. Daraus bilde ich die Abrechnungsnummern für DHL Paket und Paket International. Hast du andere Nummern, trag sie direkt ein.</p>
|
||||||
|
<Field label="EKP" optional name="ekp" inputMode="numeric" placeholder="10 Ziffern" defaultValue={c.billingNational ? c.billingNational.slice(0, 10) : ""} />
|
||||||
|
<details className="ad-help">
|
||||||
|
<summary style={{ cursor: "pointer" }}>Abrechnungsnummern selbst eintragen</summary>
|
||||||
|
<div className="sm-form-row" style={{ marginTop: "var(--space-3)" }}>
|
||||||
|
<Field label="DHL Paket" optional name="billingNational" inputMode="numeric" placeholder="14 Ziffern" defaultValue={c.billingNational} />
|
||||||
|
<Field label="DHL Paket International" optional name="billingInternational" inputMode="numeric" placeholder="14 Ziffern" defaultValue={c.billingInternational} />
|
||||||
|
</div>
|
||||||
|
</details>
|
||||||
|
</Step>
|
||||||
|
<Step n={5} title="Einschalten, speichern und testen">
|
||||||
|
<p>Ich lege zum Test ein Probelabel an, das nicht gedruckt wird. Absender und Paketgewichte stellst du unter <a href="/admin/dhl">DHL-Versand</a> ein.</p>
|
||||||
|
<Switch name="enabled" label="DHL-Labels in den Bestellungen anbieten" defaultChecked={c.enabled || !c.apiKey} />
|
||||||
|
</Step>
|
||||||
|
</Steps>
|
||||||
|
</Card>
|
||||||
|
</AdminForm>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------- Google ----------
|
||||||
|
|
||||||
|
async function GoogleWizard({ ok }: { ok: boolean }) {
|
||||||
|
const c = (await getLoginProviders()).google;
|
||||||
|
const has = Boolean(c.clientId && c.clientSecret);
|
||||||
|
return (
|
||||||
|
<AdminForm action={saveGoogle} submitLabel="Speichern und testen">
|
||||||
|
<Card>
|
||||||
|
<Steps>
|
||||||
|
<Step n={1} title="Projekt in der Google Cloud anlegen" done={ok && has}>
|
||||||
|
<p>Mit deinem Google-Konto anmelden und ein Projekt anlegen, z. B. „Sanamare“. Das ist kostenlos.</p>
|
||||||
|
<OpenLink href="https://console.cloud.google.com/projectcreate">Projekt anlegen</OpenLink>
|
||||||
|
</Step>
|
||||||
|
<Step n={2} title="Anmeldeseite einrichten" done={ok && has}>
|
||||||
|
<p>Unter „Google Auth Platform“ auf „Jetzt starten“ klicken: App-Name „Sanamare“, deine E-Mail als Support-Adresse, Zielgruppe „Extern“. Danach unter „Zielgruppe“ die App veröffentlichen, sonst können sich nur Testnutzer anmelden.</p>
|
||||||
|
<OpenLink href="https://console.cloud.google.com/auth/overview">Google Auth Platform</OpenLink>
|
||||||
|
<OpenLink href="https://console.cloud.google.com/auth/audience">Zielgruppe</OpenLink>
|
||||||
|
</Step>
|
||||||
|
<Step n={3} title="OAuth-Client anlegen" done={ok && has}>
|
||||||
|
<p>Neuen Client vom Typ „Webanwendung“ erstellen und diese zwei Werte eintragen:</p>
|
||||||
|
<OpenLink href="https://console.cloud.google.com/auth/clients/create">Client erstellen</OpenLink>
|
||||||
|
<CopyValue label="Autorisierte JavaScript-Quelle" value={appUrl()} />
|
||||||
|
<CopyValue label="Autorisierte Weiterleitungs-URI" value={callbackUrl("google")} />
|
||||||
|
</Step>
|
||||||
|
<Step n={4} title="Client-ID und Secret einfügen" done={ok && has}>
|
||||||
|
<p>Nach dem Erstellen zeigt Google beide Werte an.</p>
|
||||||
|
<Field label="Client-ID" name="clientId" defaultValue={c.clientId} placeholder="…apps.googleusercontent.com" autoComplete="off" />
|
||||||
|
<Field label="Client-Secret" name="clientSecret" type="password" autoComplete="off" placeholder={c.clientSecret ? mask(c.clientSecret) : "GOCSPX-…"} hint={c.clientSecret ? "Gespeichert. Nur ausfüllen, wenn du es ersetzen willst." : undefined} />
|
||||||
|
</Step>
|
||||||
|
<Step n={5} title="Einschalten, speichern und testen">
|
||||||
|
<p>Ich prüfe die Daten direkt bei Google.</p>
|
||||||
|
<Switch name="enabled" label="„Mit Google anmelden“ im Shop anbieten" defaultChecked={c.enabled || !has} />
|
||||||
|
</Step>
|
||||||
|
</Steps>
|
||||||
|
</Card>
|
||||||
|
</AdminForm>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------- Apple ----------
|
||||||
|
|
||||||
|
async function AppleWizard({ ok }: { ok: boolean }) {
|
||||||
|
const c = (await getLoginProviders()).apple;
|
||||||
|
const has = Boolean(c.servicesId && c.teamId && c.keyId && c.privateKey);
|
||||||
|
const domain = new URL(callbackUrl("apple")).host;
|
||||||
|
return (
|
||||||
|
<AdminForm action={saveApple} submitLabel="Speichern und testen">
|
||||||
|
<Card>
|
||||||
|
<Steps>
|
||||||
|
<Step n={1} title="Apple-Developer-Konto" done={ok && has}>
|
||||||
|
<p>„Mit Apple anmelden“ braucht eine Mitgliedschaft im Apple Developer Program (99 € im Jahr). Deine Team-ID steht danach in den Mitgliedsdaten.</p>
|
||||||
|
<OpenLink href="https://developer.apple.com/programs/enroll/">Mitglied werden</OpenLink>
|
||||||
|
<OpenLink href="https://developer.apple.com/account">Mitgliedsdaten (Team-ID)</OpenLink>
|
||||||
|
<Field label="Team-ID" name="teamId" defaultValue={c.teamId} placeholder="ABCDE12345" autoComplete="off" />
|
||||||
|
</Step>
|
||||||
|
<Step n={2} title="App-ID anlegen" done={ok && has}>
|
||||||
|
<p>Apple verlangt eine App-ID als Grundlage, auch ohne echte App. Neue App-ID anlegen, Beschreibung „Sanamare“, Bundle-ID z. B. <code>de.sanamare.shop</code>, und bei den Fähigkeiten „Sign in with Apple“ ankreuzen.</p>
|
||||||
|
<OpenLink href="https://developer.apple.com/account/resources/identifiers/add/bundleId">App-ID anlegen</OpenLink>
|
||||||
|
</Step>
|
||||||
|
<Step n={3} title="Services-ID anlegen" done={ok && has}>
|
||||||
|
<p>Neue Services-ID anlegen, z. B. <code>de.sanamare.login</code>. Danach „Sign in with Apple“ ankreuzen, auf „Configure“ klicken, die App-ID aus Schritt 2 wählen und diese Werte eintragen:</p>
|
||||||
|
<OpenLink href="https://developer.apple.com/account/resources/identifiers/add/serviceId">Services-ID anlegen</OpenLink>
|
||||||
|
<CopyValue label="Domain" value={domain} />
|
||||||
|
<CopyValue label="Return-URL" value={callbackUrl("apple")} />
|
||||||
|
<Field label="Services-ID" name="servicesId" defaultValue={c.servicesId} placeholder="de.sanamare.login" autoComplete="off" />
|
||||||
|
</Step>
|
||||||
|
<Step n={4} title="Schlüssel erstellen" done={ok && has}>
|
||||||
|
<p>Neuen Schlüssel mit „Sign in with Apple“ erstellen und mit der App-ID aus Schritt 2 verknüpfen. Die .p8-Datei lässt sich nur einmal herunterladen, also gut aufheben.</p>
|
||||||
|
<OpenLink href="https://developer.apple.com/account/resources/authkeys/add">Schlüssel erstellen</OpenLink>
|
||||||
|
<Field label="Key-ID" name="keyId" defaultValue={c.keyId} placeholder="XYZ987WVU6" autoComplete="off" />
|
||||||
|
<KeyFileInput name="privateKey" label="Schlüsseldatei (.p8)" accept=".p8,text/plain" saved={Boolean(c.privateKey)} hint="Die heruntergeladene Datei AuthKey_….p8 auswählen." />
|
||||||
|
</Step>
|
||||||
|
<Step n={5} title="Einschalten, speichern und testen">
|
||||||
|
<p>Ich prüfe die Angaben direkt bei Apple.</p>
|
||||||
|
<Switch name="enabled" label="„Mit Apple anmelden“ im Shop anbieten" defaultChecked={c.enabled || !has} />
|
||||||
|
</Step>
|
||||||
|
</Steps>
|
||||||
|
</Card>
|
||||||
|
</AdminForm>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const WIZARDS: Record<IntegrationKey, (p: { ok: boolean }) => Promise<React.ReactElement>> = {
|
||||||
|
stripe: StripeWizard,
|
||||||
|
paypal: PaypalWizard,
|
||||||
|
dhl: DhlWizard,
|
||||||
|
google: GoogleWizard,
|
||||||
|
apple: AppleWizard,
|
||||||
|
};
|
||||||
184
src/app/admin/(panel)/verbindungen/actions.ts
Normal file
184
src/app/admin/(panel)/verbindungen/actions.ts
Normal file
|
|
@ -0,0 +1,184 @@
|
||||||
|
"use server";
|
||||||
|
import { revalidatePath } from "next/cache";
|
||||||
|
import { assertPermission, audit } from "@/lib/auth";
|
||||||
|
import { fail, ok, type ActionResult } from "@/lib/action-result";
|
||||||
|
import { getCredentials, saveCredentials } from "@/lib/payments/credentials";
|
||||||
|
import { getDhlConfig, saveDhlConfig, splitStreet } from "@/lib/dhl";
|
||||||
|
import { getSettings } from "@/lib/settings";
|
||||||
|
import { getLoginProviders, saveLoginProviders } from "@/lib/social/config";
|
||||||
|
import { isValidApplePrivateKey } from "@/lib/social/oauth";
|
||||||
|
import { createStripeWebhook, detectPaypalMode, forgetTest, saveDetectedPaypal, testDhlConnection, testLogin, testPaypal, testStripe, type IntegrationKey } from "@/lib/integrations";
|
||||||
|
|
||||||
|
const str = (fd: FormData, k: string) => String(fd.get(k) ?? "").trim();
|
||||||
|
// Leere Geheimfelder behalten den gespeicherten Wert
|
||||||
|
const keep = (v: string, old: string) => (v ? v : old);
|
||||||
|
const done = (r: { ok: boolean; message: string }) => {
|
||||||
|
revalidatePath("/admin/verbindungen", "layout");
|
||||||
|
revalidatePath("/admin/zahlung");
|
||||||
|
revalidatePath("/admin/dhl");
|
||||||
|
return r.ok ? ok(r.message) : fail(r.message);
|
||||||
|
};
|
||||||
|
|
||||||
|
export async function saveStripe(_prev: ActionResult, fd: FormData): Promise<ActionResult> {
|
||||||
|
const user = await assertPermission("payments.edit");
|
||||||
|
const c = await getCredentials();
|
||||||
|
const secretKey = keep(str(fd, "secretKey"), c.stripe.secretKey);
|
||||||
|
if (!secretKey) return fail("Bitte füge den Geheimschlüssel aus Schritt 2 ein.", { secretKey: "Bitte einfügen" });
|
||||||
|
if (/^pk_/.test(secretKey)) return fail("Das ist der veröffentlichbare Schlüssel (pk_…). Gebraucht wird der Geheimschlüssel, er beginnt mit sk_live_ oder sk_test_.", { secretKey: "sk_… gesucht" });
|
||||||
|
if (!/^(sk|rk)_(test|live)_/.test(secretKey)) return fail("Der Geheimschlüssel beginnt mit sk_live_ oder sk_test_.", { secretKey: "Ungültiges Format" });
|
||||||
|
const changedKey = secretKey !== c.stripe.secretKey;
|
||||||
|
let webhookSecret = keep(str(fd, "webhookSecret"), changedKey ? "" : c.stripe.webhookSecret);
|
||||||
|
let note = "";
|
||||||
|
const next = { ...c, stripe: { ...c.stripe, secretKey, webhookSecret } };
|
||||||
|
const test = await testStripe(next);
|
||||||
|
if (!test.ok) return fail(test.message, { secretKey: "Wird abgelehnt" });
|
||||||
|
if (fd.get("autoWebhook") === "on" && (!webhookSecret || changedKey || fd.get("renewWebhook") === "on")) {
|
||||||
|
try {
|
||||||
|
webhookSecret = await createStripeWebhook(secretKey);
|
||||||
|
note = " Webhook automatisch eingerichtet.";
|
||||||
|
} catch (e) {
|
||||||
|
note = ` Den Webhook konnte ich nicht automatisch anlegen (${e instanceof Error ? e.message : e}). Richte ihn bitte von Hand ein, siehe unten.`;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
next.stripe.webhookSecret = webhookSecret;
|
||||||
|
await saveCredentials(next);
|
||||||
|
await audit(user, "Stripe eingerichtet", secretKey.includes("_test_") ? "Testmodus" : "Live");
|
||||||
|
const final = await testStripe(next);
|
||||||
|
return done({ ok: final.ok, message: final.message + note });
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function savePaypal(_prev: ActionResult, fd: FormData): Promise<ActionResult> {
|
||||||
|
const user = await assertPermission("payments.edit");
|
||||||
|
const c = await getCredentials();
|
||||||
|
const clientId = str(fd, "clientId");
|
||||||
|
const clientSecret = keep(str(fd, "clientSecret"), c.paypal.clientSecret);
|
||||||
|
if (!clientId || !clientSecret) return fail("Bitte füge Client-ID und Secret aus Schritt 2 ein.");
|
||||||
|
let sandbox: boolean | null;
|
||||||
|
try {
|
||||||
|
sandbox = await detectPaypalMode(clientId, clientSecret);
|
||||||
|
} catch (e) {
|
||||||
|
return fail(`PayPal ist nicht erreichbar: ${e instanceof Error ? e.message : e}`);
|
||||||
|
}
|
||||||
|
if (sandbox === null) return fail("PayPal kennt diese Zugangsdaten weder im Live- noch im Sandbox-Modus. Prüfe, ob Client-ID und Secret zur selben App gehören.", { clientSecret: "Wird abgelehnt" });
|
||||||
|
await saveDetectedPaypal(clientId, clientSecret, sandbox);
|
||||||
|
await audit(user, "PayPal eingerichtet", sandbox ? "Sandbox" : "Live");
|
||||||
|
return done({ ok: true, message: `PayPal verbunden. Erkannt: ${sandbox ? "Sandbox-Zugang (Testzahlungen)" : "Live-Zugang (echte Zahlungen)"}.` });
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function saveDhlConnection(_prev: ActionResult, fd: FormData): Promise<ActionResult> {
|
||||||
|
const user = await assertPermission("shipping.edit");
|
||||||
|
const c = await getDhlConfig();
|
||||||
|
const sandbox = fd.get("sandbox") === "on";
|
||||||
|
const ekp = str(fd, "ekp").replace(/\s/g, "");
|
||||||
|
if (ekp && !/^\d{10}$/.test(ekp)) return fail("Die EKP hat 10 Ziffern.", { ekp: "10 Ziffern" });
|
||||||
|
let billingNational = str(fd, "billingNational").replace(/\s/g, "");
|
||||||
|
let billingInternational = str(fd, "billingInternational").replace(/\s/g, "");
|
||||||
|
// Aus der EKP die üblichen Abrechnungsnummern bilden: Verfahren 01 (Paket) bzw. 53 (Paket International), Teilnahme 01
|
||||||
|
if (ekp && !billingNational) billingNational = `${ekp}0101`;
|
||||||
|
if (ekp && !billingInternational) billingInternational = `${ekp}5301`;
|
||||||
|
const errors: Record<string, string> = {};
|
||||||
|
if (billingNational && !/^\d{14}$/.test(billingNational)) errors.billingNational = "14 Ziffern";
|
||||||
|
if (billingInternational && !/^\d{14}$/.test(billingInternational)) errors.billingInternational = "14 Ziffern";
|
||||||
|
if (Object.keys(errors).length) return fail("Bitte prüfe die Abrechnungsnummern.", errors);
|
||||||
|
const apiKey = keep(str(fd, "apiKey"), c.apiKey);
|
||||||
|
if (!apiKey) return fail("Bitte füge den API-Schlüssel aus Schritt 2 ein.", { apiKey: "Bitte einfügen" });
|
||||||
|
const next = {
|
||||||
|
...c,
|
||||||
|
sandbox,
|
||||||
|
apiKey,
|
||||||
|
username: str(fd, "username"),
|
||||||
|
password: keep(str(fd, "password"), c.password),
|
||||||
|
billingNational,
|
||||||
|
billingInternational,
|
||||||
|
enabled: fd.get("enabled") === "on",
|
||||||
|
};
|
||||||
|
if (!sandbox && (!next.username || !next.password || !next.billingNational)) return fail("Für echte Labels fehlen Benutzername, Passwort oder Abrechnungsnummer. Zum Ausprobieren kannst du den Testmodus einschalten.");
|
||||||
|
// Absender beim ersten Mal aus den Shop-Angaben übernehmen, damit der Test sofort geht
|
||||||
|
if (!next.shipperName || !next.shipperStreet) {
|
||||||
|
const g = (await getSettings()).general;
|
||||||
|
const [street, house] = splitStreet(g.street);
|
||||||
|
const [zip, ...city] = g.zipCity.split(" ");
|
||||||
|
next.shipperName ||= g.company;
|
||||||
|
next.shipperStreet ||= street;
|
||||||
|
next.shipperHouse ||= house;
|
||||||
|
next.shipperZip ||= /^\d{5}$/.test(zip ?? "") ? zip : "";
|
||||||
|
next.shipperCity ||= city.join(" ");
|
||||||
|
next.shipperEmail ||= g.email;
|
||||||
|
next.shipperPhone ||= g.phone;
|
||||||
|
}
|
||||||
|
await saveDhlConfig(next);
|
||||||
|
await audit(user, "DHL eingerichtet", sandbox ? "Sandbox" : "Live");
|
||||||
|
const r = await testDhlConnection();
|
||||||
|
return done(r);
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function saveGoogle(_prev: ActionResult, fd: FormData): Promise<ActionResult> {
|
||||||
|
const user = await assertPermission("settings.edit");
|
||||||
|
const c = await getLoginProviders();
|
||||||
|
const clientId = str(fd, "clientId");
|
||||||
|
const clientSecret = keep(str(fd, "clientSecret"), c.google.clientSecret);
|
||||||
|
if (!clientId || !clientSecret) return fail("Bitte füge Client-ID und Client-Secret aus Schritt 4 ein.");
|
||||||
|
if (!clientId.endsWith(".apps.googleusercontent.com")) return fail("Die Client-ID endet auf .apps.googleusercontent.com.", { clientId: "Bitte prüfen" });
|
||||||
|
const next = { ...c, google: { enabled: fd.get("enabled") === "on", clientId, clientSecret } };
|
||||||
|
const r = await testLogin("google", next);
|
||||||
|
if (!r.ok) next.google.enabled = false;
|
||||||
|
await saveLoginProviders(next);
|
||||||
|
await audit(user, "Google-Anmeldung eingerichtet", next.google.enabled ? "an" : "aus");
|
||||||
|
return done(r.ok ? { ok: true, message: `${r.message}${next.google.enabled ? " Der Knopf erscheint jetzt im Shop." : " Schalte „Im Shop anbieten“ ein, damit der Knopf erscheint."}` } : { ok: false, message: `${r.message} Gespeichert, aber noch nicht im Shop angeboten.` });
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function saveApple(_prev: ActionResult, fd: FormData): Promise<ActionResult> {
|
||||||
|
const user = await assertPermission("settings.edit");
|
||||||
|
const c = await getLoginProviders();
|
||||||
|
const privateKey = keep(str(fd, "privateKey").replace(/\r\n/g, "\n"), c.apple.privateKey);
|
||||||
|
if (privateKey && !isValidApplePrivateKey(privateKey)) return fail("Der Schlüssel lässt sich nicht lesen. Wähle die heruntergeladene .p8-Datei aus.", { privateKey: "Ungültig" });
|
||||||
|
const next = {
|
||||||
|
...c,
|
||||||
|
apple: {
|
||||||
|
enabled: fd.get("enabled") === "on",
|
||||||
|
servicesId: str(fd, "servicesId"),
|
||||||
|
teamId: str(fd, "teamId").toUpperCase(),
|
||||||
|
keyId: str(fd, "keyId").toUpperCase(),
|
||||||
|
privateKey,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
if (!next.apple.servicesId || !next.apple.teamId || !next.apple.keyId || !privateKey) return fail("Es fehlen noch Angaben: Services-ID, Team-ID, Key-ID und die .p8-Datei.");
|
||||||
|
const r = await testLogin("apple", next);
|
||||||
|
if (!r.ok) next.apple.enabled = false;
|
||||||
|
await saveLoginProviders(next);
|
||||||
|
await audit(user, "Apple-Anmeldung eingerichtet", next.apple.enabled ? "an" : "aus");
|
||||||
|
return done(r.ok ? { ok: true, message: `${r.message}${next.apple.enabled ? " Der Knopf erscheint jetzt im Shop." : " Schalte „Im Shop anbieten“ ein, damit der Knopf erscheint."}` } : { ok: false, message: `${r.message} Gespeichert, aber noch nicht im Shop angeboten.` });
|
||||||
|
}
|
||||||
|
|
||||||
|
const PERMS: Record<IntegrationKey, "payments.edit" | "shipping.edit" | "settings.edit"> = { stripe: "payments.edit", paypal: "payments.edit", dhl: "shipping.edit", google: "settings.edit", apple: "settings.edit" };
|
||||||
|
|
||||||
|
export async function disconnect(fd: FormData) {
|
||||||
|
const key = str(fd, "provider") as IntegrationKey;
|
||||||
|
if (!(key in PERMS)) return;
|
||||||
|
const user = await assertPermission(PERMS[key]);
|
||||||
|
if (key === "stripe" || key === "paypal") {
|
||||||
|
const c = await getCredentials();
|
||||||
|
if (key === "stripe") c.stripe = { publishableKey: "", secretKey: "", webhookSecret: "" };
|
||||||
|
else c.paypal = { clientId: "", clientSecret: "", sandbox: true };
|
||||||
|
await saveCredentials(c);
|
||||||
|
} else if (key === "dhl") {
|
||||||
|
const c = await getDhlConfig();
|
||||||
|
await saveDhlConfig({ ...c, apiKey: "", password: "", enabled: false });
|
||||||
|
} else {
|
||||||
|
const c = await getLoginProviders();
|
||||||
|
if (key === "google") c.google = { enabled: false, clientId: "", clientSecret: "" };
|
||||||
|
else c.apple = { enabled: false, servicesId: "", teamId: "", keyId: "", privateKey: "" };
|
||||||
|
await saveLoginProviders(c);
|
||||||
|
}
|
||||||
|
await forgetTest(key);
|
||||||
|
await audit(user, "Verbindung entfernt", key);
|
||||||
|
revalidatePath("/admin/verbindungen", "layout");
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function retest(_prev: ActionResult, fd: FormData): Promise<ActionResult> {
|
||||||
|
const key = str(fd, "provider") as IntegrationKey;
|
||||||
|
if (!(key in PERMS)) return fail("Unbekannter Anbieter.");
|
||||||
|
await assertPermission(PERMS[key]);
|
||||||
|
const r = key === "stripe" ? await testStripe() : key === "paypal" ? await testPaypal() : key === "dhl" ? await testDhlConnection() : await testLogin(key);
|
||||||
|
return done(r);
|
||||||
|
}
|
||||||
32
src/app/admin/(panel)/verbindungen/page.tsx
Normal file
32
src/app/admin/(panel)/verbindungen/page.tsx
Normal file
|
|
@ -0,0 +1,32 @@
|
||||||
|
import Link from "next/link";
|
||||||
|
import { can, requireAdmin } from "@/lib/auth";
|
||||||
|
import { INTEGRATIONS, getStatuses } from "@/lib/integrations";
|
||||||
|
import { PageHead } from "@/components/admin/ui";
|
||||||
|
import { StatusPill } from "@/components/admin/IntegrationStatus";
|
||||||
|
|
||||||
|
export default async function IntegrationsPage() {
|
||||||
|
const user = await requireAdmin();
|
||||||
|
const statuses = await getStatuses();
|
||||||
|
const list = INTEGRATIONS.filter((i) => can(user, i.permission));
|
||||||
|
return (
|
||||||
|
<div className="ad-wrap">
|
||||||
|
<PageHead title="Verbindungen" lead="Zahlungsanbieter, Versand und Anmeldung einrichten. Jede Einrichtung führt dich Schritt für Schritt durch und prüft am Ende, ob alles funktioniert." />
|
||||||
|
<div className="ad-integrations">
|
||||||
|
{list.map((i) => {
|
||||||
|
const s = statuses[i.key];
|
||||||
|
return (
|
||||||
|
<Link key={i.key} className="ad-integration" href={`/admin/verbindungen/${i.key}`}>
|
||||||
|
<div className="ad-integration__head">
|
||||||
|
<h2>{i.name}</h2>
|
||||||
|
<StatusPill s={s} />
|
||||||
|
</div>
|
||||||
|
<p>{i.purpose}</p>
|
||||||
|
<small>{s.configured ? (s.lastTest ? s.lastTest.message : "Noch nicht getestet") : i.effort}</small>
|
||||||
|
<span className="sm-btn sm-btn--secondary sm-btn--sm" style={{ justifySelf: "start" }}>{s.configured ? "Ansehen" : "Einrichten"}</span>
|
||||||
|
</Link>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
@ -5,64 +5,9 @@ import { assertPermission, audit } from "@/lib/auth";
|
||||||
import { fail, ok, type ActionResult } from "@/lib/action-result";
|
import { fail, ok, type ActionResult } from "@/lib/action-result";
|
||||||
import { parsePrice } from "@/lib/money";
|
import { parsePrice } from "@/lib/money";
|
||||||
import { getDefinition } from "@/lib/payments/catalog";
|
import { getDefinition } from "@/lib/payments/catalog";
|
||||||
import { getCredentials, saveCredentials } from "@/lib/payments/credentials";
|
|
||||||
|
|
||||||
const str = (fd: FormData, k: string) => String(fd.get(k) ?? "").trim();
|
const str = (fd: FormData, k: string) => String(fd.get(k) ?? "").trim();
|
||||||
|
|
||||||
export async function saveProviderCredentials(_prev: ActionResult, fd: FormData): Promise<ActionResult> {
|
|
||||||
const user = await assertPermission("payments.edit");
|
|
||||||
const current = await getCredentials();
|
|
||||||
// Leere Geheimfelder behalten den gespeicherten Wert
|
|
||||||
const keep = (v: string, old: string) => (v ? v : old);
|
|
||||||
const stripeSecret = keep(str(fd, "stripeSecretKey"), current.stripe.secretKey);
|
|
||||||
if (stripeSecret && !/^(sk|rk)_(test|live)_/.test(stripeSecret)) return fail("Der Stripe-Geheimschlüssel beginnt mit sk_live_ oder sk_test_.", { stripeSecretKey: "Ungültiges Format" });
|
|
||||||
await saveCredentials({
|
|
||||||
stripe: {
|
|
||||||
publishableKey: str(fd, "stripePublishableKey"),
|
|
||||||
secretKey: fd.get("stripeClear") === "on" ? "" : stripeSecret,
|
|
||||||
webhookSecret: fd.get("stripeClear") === "on" ? "" : keep(str(fd, "stripeWebhookSecret"), current.stripe.webhookSecret),
|
|
||||||
},
|
|
||||||
paypal: {
|
|
||||||
clientId: str(fd, "paypalClientId"),
|
|
||||||
clientSecret: fd.get("paypalClear") === "on" ? "" : keep(str(fd, "paypalClientSecret"), current.paypal.clientSecret),
|
|
||||||
sandbox: fd.get("paypalSandbox") === "on",
|
|
||||||
},
|
|
||||||
});
|
|
||||||
await audit(user, "Zahlungs-Zugangsdaten geändert");
|
|
||||||
revalidatePath("/admin/zahlung");
|
|
||||||
return ok("Zugangsdaten gespeichert.");
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function testProvider(_prev: ActionResult, fd: FormData): Promise<ActionResult> {
|
|
||||||
await assertPermission("payments.edit");
|
|
||||||
const provider = str(fd, "provider");
|
|
||||||
const c = await getCredentials();
|
|
||||||
try {
|
|
||||||
if (provider === "stripe") {
|
|
||||||
if (!c.stripe.secretKey) return fail("Es ist noch kein Stripe-Schlüssel gespeichert.");
|
|
||||||
const res = await fetch("https://api.stripe.com/v1/balance", { headers: { Authorization: `Bearer ${c.stripe.secretKey}` }, cache: "no-store" });
|
|
||||||
const data = await res.json();
|
|
||||||
if (!res.ok) return fail(`Stripe lehnt ab: ${data?.error?.message ?? res.status}`);
|
|
||||||
return ok(`Stripe verbunden (${data.livemode ? "Live-Modus" : "Testmodus"}).`);
|
|
||||||
}
|
|
||||||
if (provider === "paypal") {
|
|
||||||
if (!c.paypal.clientId || !c.paypal.clientSecret) return fail("Es sind noch keine PayPal-Zugangsdaten gespeichert.");
|
|
||||||
const base = c.paypal.sandbox ? "https://api-m.sandbox.paypal.com" : "https://api-m.paypal.com";
|
|
||||||
const res = await fetch(`${base}/v1/oauth2/token`, {
|
|
||||||
method: "POST",
|
|
||||||
headers: { Authorization: "Basic " + Buffer.from(`${c.paypal.clientId}:${c.paypal.clientSecret}`).toString("base64"), "Content-Type": "application/x-www-form-urlencoded" },
|
|
||||||
body: "grant_type=client_credentials",
|
|
||||||
cache: "no-store",
|
|
||||||
});
|
|
||||||
if (!res.ok) return fail("PayPal lehnt die Zugangsdaten ab. Prüfe Client-ID, Secret und den Sandbox-Schalter.");
|
|
||||||
return ok(`PayPal verbunden (${c.paypal.sandbox ? "Sandbox" : "Live"}).`);
|
|
||||||
}
|
|
||||||
} catch (e) {
|
|
||||||
return fail(`Keine Verbindung: ${e instanceof Error ? e.message : e}`);
|
|
||||||
}
|
|
||||||
return fail("Unbekannter Anbieter.");
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function savePaymentMethod(_prev: ActionResult, fd: FormData): Promise<ActionResult> {
|
export async function savePaymentMethod(_prev: ActionResult, fd: FormData): Promise<ActionResult> {
|
||||||
const user = await assertPermission("payments.edit");
|
const user = await assertPermission("payments.edit");
|
||||||
const id = str(fd, "id");
|
const id = str(fd, "id");
|
||||||
|
|
|
||||||
|
|
@ -2,43 +2,32 @@ import { db } from "@/lib/db";
|
||||||
import { requireAdmin } from "@/lib/auth";
|
import { requireAdmin } from "@/lib/auth";
|
||||||
import { centsToInput, formatPrice } from "@/lib/money";
|
import { centsToInput, formatPrice } from "@/lib/money";
|
||||||
import { getDefinition } from "@/lib/payments/catalog";
|
import { getDefinition } from "@/lib/payments/catalog";
|
||||||
import { getCredentials, isProviderReady, mask } from "@/lib/payments/credentials";
|
import Link from "next/link";
|
||||||
|
import { getCredentials, isProviderReady } from "@/lib/payments/credentials";
|
||||||
|
import { getStatuses } from "@/lib/integrations";
|
||||||
|
import { StatusPill } from "@/components/admin/IntegrationStatus";
|
||||||
import { Field, TextareaField } from "@/components/Field";
|
import { Field, TextareaField } from "@/components/Field";
|
||||||
import { AdminForm } from "@/components/admin/AdminForm";
|
import { AdminForm } from "@/components/admin/AdminForm";
|
||||||
import { TestButton } from "@/components/admin/TestButton";
|
|
||||||
import { Card, PageHead, Pill, Switch } from "@/components/admin/ui";
|
import { Card, PageHead, Pill, Switch } from "@/components/admin/ui";
|
||||||
import { savePaymentMethod, saveProviderCredentials, testProvider } from "./actions";
|
import { savePaymentMethod } from "./actions";
|
||||||
|
|
||||||
export default async function PaymentsPage() {
|
export default async function PaymentsPage() {
|
||||||
await requireAdmin("payments.edit");
|
await requireAdmin("payments.edit");
|
||||||
const [methods, creds] = await Promise.all([db.paymentMethod.findMany({ orderBy: { sort: "asc" } }), getCredentials()]);
|
const [methods, creds, statuses] = await Promise.all([db.paymentMethod.findMany({ orderBy: { sort: "asc" } }), getCredentials(), getStatuses()]);
|
||||||
const appUrl = (process.env.APP_URL ?? "https://sanamare.maaxxs-coding.de").replace(/\/$/, "");
|
|
||||||
return (
|
return (
|
||||||
<div className="ad-wrap ad-wrap--narrow">
|
<div className="ad-wrap ad-wrap--narrow">
|
||||||
<PageHead title="Zahlungsarten" lead="Schalte Zahlungsarten ein und aus. Online-Zahlungen brauchen einmalig die Zugangsdaten des Anbieters." />
|
<PageHead title="Zahlungsarten" lead="Schalte Zahlungsarten ein und aus. Online-Zahlungen brauchen einmalig einen eingerichteten Anbieter." />
|
||||||
|
|
||||||
<h2 className="display-sm" style={{ margin: "0 0 var(--space-4)" }}>Zugangsdaten</h2>
|
<Card title="Zahlungsanbieter" lead="Online-Zahlungen laufen über Stripe und PayPal. Die Einrichtung führt dich Schritt für Schritt durch.">
|
||||||
<AdminForm action={saveProviderCredentials} submitLabel="Zugangsdaten speichern">
|
<ul className="ad-legal">
|
||||||
<Card title="Stripe" lead="Für Kreditkarte, Apple Pay, Google Pay, Klarna und SEPA-Lastschrift." action={<Pill tone={creds.stripe.secretKey ? "success" : "neutral"}>{creds.stripe.secretKey ? (creds.stripe.secretKey.includes("_test_") ? "Testmodus" : "Live") : "Nicht verbunden"}</Pill>}>
|
{(["stripe", "paypal"] as const).map((k) => (
|
||||||
<Field label="Veröffentlichbarer Schlüssel" optional name="stripePublishableKey" defaultValue={creds.stripe.publishableKey} placeholder="pk_live_…" />
|
<li key={k}>
|
||||||
<Field label="Geheimschlüssel" name="stripeSecretKey" type="password" autoComplete="off" placeholder={creds.stripe.secretKey ? mask(creds.stripe.secretKey) : "sk_live_… oder sk_test_…"} hint={creds.stripe.secretKey ? "Leer lassen, um den gespeicherten Schlüssel zu behalten." : "Findest du im Stripe-Dashboard unter Entwickler → API-Schlüssel."} />
|
<Link href={`/admin/verbindungen/${k}`}>{k === "stripe" ? "Stripe (Karte, Apple Pay, Google Pay, Klarna, SEPA)" : "PayPal"}</Link>
|
||||||
<Field label="Webhook-Signaturschlüssel" optional name="stripeWebhookSecret" type="password" autoComplete="off" placeholder={creds.stripe.webhookSecret ? mask(creds.stripe.webhookSecret) : "whsec_…"} />
|
<StatusPill s={statuses[k]} />
|
||||||
<div className="ad-help" style={{ marginTop: "var(--space-4)" }}>
|
</li>
|
||||||
Webhook in Stripe anlegen mit der Adresse <code>{appUrl}/api/webhooks/stripe</code> und den Ereignissen <code>checkout.session.completed</code>, <code>checkout.session.async_payment_succeeded</code> und <code>checkout.session.async_payment_failed</code>. Nötig vor allem für SEPA, weil die Bestätigung dort später kommt.
|
))}
|
||||||
</div>
|
</ul>
|
||||||
{creds.stripe.secretKey && <label className="sm-check" style={{ marginTop: "var(--space-3)" }}><input type="checkbox" name="stripeClear" /><span className="sm-check__text">Stripe-Verbindung entfernen</span></label>}
|
|
||||||
</Card>
|
</Card>
|
||||||
<Card title="PayPal" lead="Für die Zahlungsart PayPal." action={<Pill tone={creds.paypal.clientSecret ? "success" : "neutral"}>{creds.paypal.clientSecret ? (creds.paypal.sandbox ? "Sandbox" : "Live") : "Nicht verbunden"}</Pill>}>
|
|
||||||
<Field label="Client-ID" name="paypalClientId" defaultValue={creds.paypal.clientId} hint="Aus dem PayPal-Entwicklerbereich unter Apps & Zugangsdaten." />
|
|
||||||
<Field label="Secret" name="paypalClientSecret" type="password" autoComplete="off" placeholder={creds.paypal.clientSecret ? mask(creds.paypal.clientSecret) : ""} hint={creds.paypal.clientSecret ? "Leer lassen, um das gespeicherte Secret zu behalten." : undefined} />
|
|
||||||
<Switch name="paypalSandbox" label="Sandbox (Testmodus)" hint="Ausschalten, sobald echte Zahlungen ankommen sollen." defaultChecked={creds.paypal.sandbox} />
|
|
||||||
{creds.paypal.clientSecret && <label className="sm-check"><input type="checkbox" name="paypalClear" /><span className="sm-check__text">PayPal-Verbindung entfernen</span></label>}
|
|
||||||
</Card>
|
|
||||||
</AdminForm>
|
|
||||||
<div style={{ display: "flex", gap: "var(--space-5)", flexWrap: "wrap", margin: "var(--space-2) 0 var(--space-8)" }}>
|
|
||||||
<div><span className="label">Stripe</span><TestButton action={testProvider} provider="stripe" /></div>
|
|
||||||
<div><span className="label">PayPal</span><TestButton action={testProvider} provider="paypal" /></div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<h2 className="display-sm" style={{ margin: "0 0 var(--space-4)" }}>Zahlungsarten im Shop</h2>
|
<h2 className="display-sm" style={{ margin: "0 0 var(--space-4)" }}>Zahlungsarten im Shop</h2>
|
||||||
{methods.map((m) => {
|
{methods.map((m) => {
|
||||||
|
|
@ -57,7 +46,7 @@ export default async function PaymentsPage() {
|
||||||
<div className="ad-card__body">
|
<div className="ad-card__body">
|
||||||
<AdminForm action={savePaymentMethod}>
|
<AdminForm action={savePaymentMethod}>
|
||||||
<input type="hidden" name="id" value={m.id} />
|
<input type="hidden" name="id" value={m.id} />
|
||||||
<Switch name="enabled" label="Im Shop anbieten" hint={ready ? undefined : "Wird erst angezeigt, wenn die Zugangsdaten oben gespeichert sind."} defaultChecked={m.enabled} />
|
<Switch name="enabled" label="Im Shop anbieten" hint={ready ? undefined : "Wird erst angezeigt, wenn der Anbieter oben eingerichtet ist."} defaultChecked={m.enabled} />
|
||||||
<Field label="Name im Shop" name="name" defaultValue={m.name} />
|
<Field label="Name im Shop" name="name" defaultValue={m.name} />
|
||||||
<TextareaField label="Beschreibung" name="description" defaultValue={m.description} rows={2} />
|
<TextareaField label="Beschreibung" name="description" defaultValue={m.description} rows={2} />
|
||||||
{def?.fields.map((f) =>
|
{def?.fields.map((f) =>
|
||||||
|
|
|
||||||
34
src/components/admin/CopyValue.tsx
Normal file
34
src/components/admin/CopyValue.tsx
Normal file
|
|
@ -0,0 +1,34 @@
|
||||||
|
"use client";
|
||||||
|
import { useState } from "react";
|
||||||
|
import { Icon } from "../Icon";
|
||||||
|
|
||||||
|
/** Wert zum Übernehmen beim Anbieter, mit Kopieren-Knopf. */
|
||||||
|
export function CopyValue({ label, value }: { label: string; value: string }) {
|
||||||
|
const [copied, setCopied] = useState(false);
|
||||||
|
const copy = async () => {
|
||||||
|
try {
|
||||||
|
await navigator.clipboard.writeText(value);
|
||||||
|
} catch {
|
||||||
|
// Fallback für Browser ohne Clipboard-API (z. B. ohne HTTPS)
|
||||||
|
const t = document.createElement("textarea");
|
||||||
|
t.value = value;
|
||||||
|
document.body.appendChild(t);
|
||||||
|
t.select();
|
||||||
|
document.execCommand("copy");
|
||||||
|
t.remove();
|
||||||
|
}
|
||||||
|
setCopied(true);
|
||||||
|
setTimeout(() => setCopied(false), 2000);
|
||||||
|
};
|
||||||
|
return (
|
||||||
|
<div className="ad-copy">
|
||||||
|
<span className="ad-copy__label">{label}</span>
|
||||||
|
<div className="ad-copy__row">
|
||||||
|
<code>{value}</code>
|
||||||
|
<button type="button" className="sm-btn sm-btn--secondary sm-btn--sm" onClick={copy}>
|
||||||
|
{copied ? <><Icon name="check" size="sm" /> Kopiert</> : "Kopieren"}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
10
src/components/admin/IntegrationStatus.tsx
Normal file
10
src/components/admin/IntegrationStatus.tsx
Normal file
|
|
@ -0,0 +1,10 @@
|
||||||
|
import type { IntegrationStatus } from "@/lib/integrations";
|
||||||
|
import { Pill } from "./ui";
|
||||||
|
|
||||||
|
export function StatusPill({ s }: { s: IntegrationStatus }) {
|
||||||
|
if (!s.configured) return <Pill tone="neutral">Nicht eingerichtet</Pill>;
|
||||||
|
if (s.lastTest && !s.lastTest.ok) return <Pill tone="danger">Fehler</Pill>;
|
||||||
|
if (!s.active) return <Pill tone="gold">Eingerichtet, aus</Pill>;
|
||||||
|
if (s.mode && s.mode !== "Live") return <Pill tone="gold">{s.mode}</Pill>;
|
||||||
|
return <Pill tone="success">Verbunden</Pill>;
|
||||||
|
}
|
||||||
30
src/components/admin/KeyFileInput.tsx
Normal file
30
src/components/admin/KeyFileInput.tsx
Normal file
|
|
@ -0,0 +1,30 @@
|
||||||
|
"use client";
|
||||||
|
import { useState } from "react";
|
||||||
|
|
||||||
|
/** Liest eine Schlüsseldatei (z. B. Apples .p8) im Browser und schickt ihren Inhalt als Formularfeld mit. */
|
||||||
|
export function KeyFileInput({ name, label, accept, saved, hint }: { name: string; label: string; accept: string; saved: boolean; hint?: string }) {
|
||||||
|
const [content, setContent] = useState("");
|
||||||
|
const [file, setFile] = useState("");
|
||||||
|
const [error, setError] = useState("");
|
||||||
|
const onChange = async (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||||
|
const f = e.target.files?.[0];
|
||||||
|
setError("");
|
||||||
|
if (!f) return;
|
||||||
|
const text = await f.text();
|
||||||
|
if (!text.includes("PRIVATE KEY")) {
|
||||||
|
setError("Das ist keine Schlüsseldatei. Gesucht ist die .p8-Datei von Apple.");
|
||||||
|
setContent("");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
setFile(f.name);
|
||||||
|
setContent(text);
|
||||||
|
};
|
||||||
|
return (
|
||||||
|
<div className="sm-field">
|
||||||
|
<span className="sm-field__label">{label}</span>
|
||||||
|
<input type="hidden" name={name} value={content} />
|
||||||
|
<input className="ad-file" type="file" accept={accept} onChange={onChange} aria-label={label} />
|
||||||
|
{error ? <span className="sm-field__error">{error}</span> : <span className="sm-field__hint">{file ? `${file} wird beim Speichern übernommen.` : saved ? "Ein Schlüssel ist gespeichert. Nur auswählen, wenn du ihn ersetzen willst." : hint}</span>}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
27
src/components/admin/Setup.tsx
Normal file
27
src/components/admin/Setup.tsx
Normal file
|
|
@ -0,0 +1,27 @@
|
||||||
|
import { Icon } from "../Icon";
|
||||||
|
|
||||||
|
/** Nummerierte Schritte einer geführten Einrichtung. */
|
||||||
|
export function Steps({ children }: { children: React.ReactNode }) {
|
||||||
|
return <ol className="ad-steps">{children}</ol>;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function Step({ n, title, done, children }: { n: number; title: string; done?: boolean; children: React.ReactNode }) {
|
||||||
|
return (
|
||||||
|
<li className={`ad-step${done ? " is-done" : ""}`}>
|
||||||
|
<span className="ad-step__num" aria-hidden="true">{done ? <Icon name="check" size="sm" /> : n}</span>
|
||||||
|
<div className="ad-step__body">
|
||||||
|
<h3>{title}{done && <span className="sr-only"> (erledigt)</span>}</h3>
|
||||||
|
{children}
|
||||||
|
</div>
|
||||||
|
</li>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Link zur passenden Seite beim Anbieter, öffnet in neuem Tab. */
|
||||||
|
export function OpenLink({ href, children }: { href: string; children: React.ReactNode }) {
|
||||||
|
return (
|
||||||
|
<a className="ad-openlink" href={href} target="_blank" rel="noopener noreferrer">
|
||||||
|
{children} <Icon name="external" size="sm" />
|
||||||
|
</a>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
@ -38,10 +38,10 @@ export const ADMIN_NAV: { group: string; items: NavItem[] }[] = [
|
||||||
group: "Einstellungen",
|
group: "Einstellungen",
|
||||||
items: [
|
items: [
|
||||||
{ href: "/admin/einstellungen", label: "Allgemein & Kasse", icon: "settings", permission: "settings.edit" },
|
{ href: "/admin/einstellungen", label: "Allgemein & Kasse", icon: "settings", permission: "settings.edit" },
|
||||||
|
{ href: "/admin/verbindungen", label: "Verbindungen", icon: "external", permission: "settings.edit" },
|
||||||
{ href: "/admin/zahlung", label: "Zahlungsarten", icon: "card", permission: "payments.edit" },
|
{ href: "/admin/zahlung", label: "Zahlungsarten", icon: "card", permission: "payments.edit" },
|
||||||
{ href: "/admin/versand", label: "Versand", icon: "truck", permission: "shipping.edit" },
|
{ href: "/admin/versand", label: "Versand", icon: "truck", permission: "shipping.edit" },
|
||||||
{ href: "/admin/dhl", label: "DHL-Versand", icon: "box", permission: "shipping.edit" },
|
{ href: "/admin/dhl", label: "DHL-Versand", icon: "box", permission: "shipping.edit" },
|
||||||
{ href: "/admin/anmeldung", label: "Anmeldung", icon: "lock", permission: "settings.edit" },
|
|
||||||
{ href: "/admin/team", label: "Team", icon: "users", permission: "users.manage" },
|
{ href: "/admin/team", label: "Team", icon: "users", permission: "users.manage" },
|
||||||
{ href: "/admin/rollen", label: "Rollen & Rechte", icon: "shield", permission: "roles.manage" },
|
{ href: "/admin/rollen", label: "Rollen & Rechte", icon: "shield", permission: "roles.manage" },
|
||||||
{ href: "/admin/protokoll", label: "Protokoll", icon: "history", permission: "audit.view" },
|
{ href: "/admin/protokoll", label: "Protokoll", icon: "history", permission: "audit.view" },
|
||||||
|
|
|
||||||
177
src/lib/integrations.ts
Normal file
177
src/lib/integrations.ts
Normal file
|
|
@ -0,0 +1,177 @@
|
||||||
|
import "server-only";
|
||||||
|
import { db } from "./db";
|
||||||
|
import { getCredentials, saveCredentials, type PaymentCredentials } from "./payments/credentials";
|
||||||
|
import { stripeRequest } from "./payments/stripe";
|
||||||
|
import { getDhlConfig, testConnection } from "./dhl";
|
||||||
|
import { appUrl, getLoginProviders, isConfigured, type LoginProviders } from "./social/config";
|
||||||
|
import { appleClientSecret } from "./social/oauth";
|
||||||
|
import type { Permission } from "./permissions";
|
||||||
|
|
||||||
|
export type IntegrationKey = "stripe" | "paypal" | "dhl" | "google" | "apple";
|
||||||
|
export type TestResult = { ok: boolean; message: string; at: string };
|
||||||
|
export type IntegrationStatus = { key: IntegrationKey; configured: boolean; mode: string; active: boolean; lastTest: TestResult | null };
|
||||||
|
|
||||||
|
export const INTEGRATIONS: { key: IntegrationKey; name: string; purpose: string; permission: Permission; effort: string }[] = [
|
||||||
|
{ key: "stripe", name: "Stripe", purpose: "Kreditkarte, Apple Pay, Google Pay, Klarna und SEPA-Lastschrift", permission: "payments.edit", effort: "ca. 5 Minuten, ein Schlüssel" },
|
||||||
|
{ key: "paypal", name: "PayPal", purpose: "Bezahlen mit PayPal", permission: "payments.edit", effort: "ca. 5 Minuten, zwei Werte" },
|
||||||
|
{ key: "dhl", name: "DHL", purpose: "Versandlabels aus der Bestellung und Sendungsverfolgung", permission: "shipping.edit", effort: "ca. 15 Minuten, Geschäftskundenkonto nötig" },
|
||||||
|
{ key: "google", name: "Google", purpose: "„Mit Google anmelden“ für Kunden und Team", permission: "settings.edit", effort: "ca. 10 Minuten, zwei Werte" },
|
||||||
|
{ key: "apple", name: "Apple", purpose: "„Mit Apple anmelden“ für Kunden und Team", permission: "settings.edit", effort: "ca. 15 Minuten, Apple-Developer-Konto nötig" },
|
||||||
|
];
|
||||||
|
|
||||||
|
const TESTS_KEY = "integration_tests";
|
||||||
|
|
||||||
|
export async function getLastTests(): Promise<Partial<Record<IntegrationKey, TestResult>>> {
|
||||||
|
const row = await db.setting.findUnique({ where: { key: TESTS_KEY } });
|
||||||
|
return (row?.value ?? {}) as Partial<Record<IntegrationKey, TestResult>>;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function remember(key: IntegrationKey, r: { ok: boolean; message: string } | null) {
|
||||||
|
const current = await getLastTests();
|
||||||
|
const value = { ...current } as Record<string, TestResult>;
|
||||||
|
if (r) value[key] = { ...r, at: new Date().toISOString() };
|
||||||
|
else delete value[key];
|
||||||
|
await db.setting.upsert({ where: { key: TESTS_KEY }, create: { key: TESTS_KEY, value }, update: { value } });
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function forgetTest(key: IntegrationKey) {
|
||||||
|
await remember(key, null);
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function getStatuses(): Promise<Record<IntegrationKey, IntegrationStatus>> {
|
||||||
|
const [creds, dhl, login, tests] = await Promise.all([getCredentials(), getDhlConfig(), getLoginProviders(), getLastTests()]);
|
||||||
|
const s = (key: IntegrationKey, configured: boolean, mode: string, active: boolean): IntegrationStatus => ({ key, configured, mode, active, lastTest: configured ? (tests[key] ?? null) : null });
|
||||||
|
return {
|
||||||
|
stripe: s("stripe", Boolean(creds.stripe.secretKey), creds.stripe.secretKey.includes("_test_") ? "Testmodus" : "Live", Boolean(creds.stripe.secretKey)),
|
||||||
|
paypal: s("paypal", Boolean(creds.paypal.clientId && creds.paypal.clientSecret), creds.paypal.sandbox ? "Sandbox" : "Live", Boolean(creds.paypal.clientSecret)),
|
||||||
|
dhl: s("dhl", Boolean(dhl.apiKey), dhl.sandbox ? "Sandbox" : "Live", dhl.enabled),
|
||||||
|
google: s("google", isConfigured("google", login), "", login.google.enabled),
|
||||||
|
apple: s("apple", isConfigured("apple", login), "", login.apple.enabled),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------- Stripe ----------
|
||||||
|
|
||||||
|
export const STRIPE_WEBHOOK_EVENTS = ["checkout.session.completed", "checkout.session.async_payment_succeeded", "checkout.session.async_payment_failed"];
|
||||||
|
export const stripeWebhookUrl = () => `${appUrl()}/api/webhooks/stripe`;
|
||||||
|
|
||||||
|
export async function testStripe(c?: PaymentCredentials) {
|
||||||
|
const creds = c ?? (await getCredentials());
|
||||||
|
let r: { ok: boolean; message: string };
|
||||||
|
if (!creds.stripe.secretKey) r = { ok: false, message: "Es ist noch kein Stripe-Schlüssel gespeichert." };
|
||||||
|
else {
|
||||||
|
try {
|
||||||
|
const data = await stripeRequest<{ livemode: boolean }>(creds.stripe.secretKey, "/balance", undefined, "GET");
|
||||||
|
r = { ok: true, message: `Stripe verbunden (${data.livemode ? "Live" : "Testmodus"}).${creds.stripe.webhookSecret ? " Zahlungsbestätigungen kommen per Webhook an." : " Webhook fehlt noch."}` };
|
||||||
|
} catch (e) {
|
||||||
|
const msg = e instanceof Error ? e.message : String(e);
|
||||||
|
r = { ok: false, message: msg === "fetch failed" ? "Stripe ist gerade nicht erreichbar. Bitte später noch einmal testen." : `Stripe lehnt ab: ${msg}` };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
await remember("stripe", r);
|
||||||
|
return r;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Legt den Webhook in Stripe an (oder ersetzt unseren alten) und gibt den Signaturschlüssel zurück. */
|
||||||
|
export async function createStripeWebhook(secretKey: string) {
|
||||||
|
const url = stripeWebhookUrl();
|
||||||
|
const list = await stripeRequest<{ data: { id: string; url: string }[] }>(secretKey, "/webhook_endpoints?limit=100", undefined, "GET");
|
||||||
|
// Den Signaturschlüssel zeigt Stripe nur beim Anlegen, deshalb einen vorhandenen Endpunkt für diese Adresse ersetzen
|
||||||
|
for (const ep of list.data.filter((e) => e.url === url)) await stripeRequest(secretKey, `/webhook_endpoints/${ep.id}`, undefined, "DELETE");
|
||||||
|
const p = new URLSearchParams({ url, description: "Sanamare Shop" });
|
||||||
|
for (const e of STRIPE_WEBHOOK_EVENTS) p.append("enabled_events[]", e);
|
||||||
|
const created = await stripeRequest<{ secret: string }>(secretKey, "/webhook_endpoints", p);
|
||||||
|
return created.secret;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------- PayPal ----------
|
||||||
|
|
||||||
|
async function paypalToken(clientId: string, secret: string, sandbox: boolean) {
|
||||||
|
const res = await fetch(`${sandbox ? "https://api-m.sandbox.paypal.com" : "https://api-m.paypal.com"}/v1/oauth2/token`, {
|
||||||
|
method: "POST",
|
||||||
|
headers: { Authorization: "Basic " + Buffer.from(`${clientId}:${secret}`).toString("base64"), "Content-Type": "application/x-www-form-urlencoded" },
|
||||||
|
body: "grant_type=client_credentials",
|
||||||
|
cache: "no-store",
|
||||||
|
});
|
||||||
|
return res.ok;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Erkennt selbst, ob die Zugangsdaten zu Live oder Sandbox gehören. null = passt zu keinem. */
|
||||||
|
export async function detectPaypalMode(clientId: string, secret: string): Promise<boolean | null> {
|
||||||
|
if (await paypalToken(clientId, secret, false)) return false;
|
||||||
|
if (await paypalToken(clientId, secret, true)) return true;
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function testPaypal() {
|
||||||
|
const c = await getCredentials();
|
||||||
|
let r: { ok: boolean; message: string };
|
||||||
|
if (!c.paypal.clientId || !c.paypal.clientSecret) r = { ok: false, message: "Es sind noch keine PayPal-Zugangsdaten gespeichert." };
|
||||||
|
else {
|
||||||
|
try {
|
||||||
|
r = (await paypalToken(c.paypal.clientId, c.paypal.clientSecret, c.paypal.sandbox))
|
||||||
|
? { ok: true, message: `PayPal verbunden (${c.paypal.sandbox ? "Sandbox" : "Live"}).` }
|
||||||
|
: { ok: false, message: "PayPal lehnt Client-ID oder Secret ab." };
|
||||||
|
} catch (e) {
|
||||||
|
r = { ok: false, message: `PayPal ist nicht erreichbar: ${e instanceof Error ? e.message : e}` };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
await remember("paypal", r);
|
||||||
|
return r;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function saveDetectedPaypal(clientId: string, clientSecret: string, sandbox: boolean) {
|
||||||
|
const c = await getCredentials();
|
||||||
|
await saveCredentials({ ...c, paypal: { clientId, clientSecret, sandbox } });
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------- DHL ----------
|
||||||
|
|
||||||
|
export async function testDhlConnection() {
|
||||||
|
const r = await testConnection(await getDhlConfig());
|
||||||
|
await remember("dhl", r);
|
||||||
|
return r;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------- Google & Apple ----------
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Prüft Client-ID und Secret, ohne dass sich jemand anmelden muss: Wir tauschen einen
|
||||||
|
* absichtlich ungültigen Code. "invalid_grant" heißt, der Anbieter kennt den Client.
|
||||||
|
*/
|
||||||
|
async function probeToken(url: string, body: URLSearchParams) {
|
||||||
|
const res = await fetch(url, { method: "POST", headers: { "Content-Type": "application/x-www-form-urlencoded", Accept: "application/json" }, body, cache: "no-store" });
|
||||||
|
const data = (await res.json().catch(() => ({}))) as { error?: string; error_description?: string };
|
||||||
|
return data.error ?? (res.ok ? "ok" : `HTTP ${res.status}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function testLogin(provider: "google" | "apple", login?: LoginProviders) {
|
||||||
|
const c = login ?? (await getLoginProviders());
|
||||||
|
let r: { ok: boolean; message: string };
|
||||||
|
if (!isConfigured(provider, c)) r = { ok: false, message: "Es fehlen noch Angaben." };
|
||||||
|
else {
|
||||||
|
try {
|
||||||
|
if (provider === "google") {
|
||||||
|
const err = await probeToken("https://oauth2.googleapis.com/token", new URLSearchParams({ code: "sanamare-test", client_id: c.google.clientId, client_secret: c.google.clientSecret, redirect_uri: `${appUrl()}/api/auth/google/callback`, grant_type: "authorization_code" }));
|
||||||
|
r = err === "invalid_grant"
|
||||||
|
? { ok: true, message: "Google kennt Client-ID und Secret. Die Anmeldung ist bereit." }
|
||||||
|
: err === "invalid_client" || err === "unauthorized_client"
|
||||||
|
? { ok: false, message: "Google lehnt Client-ID oder Secret ab. Prüfe, ob beide aus demselben OAuth-Client stammen." }
|
||||||
|
: err === "redirect_uri_mismatch"
|
||||||
|
? { ok: false, message: "Die Weiterleitungs-URI ist bei Google nicht eingetragen. Kopiere sie aus Schritt 3." }
|
||||||
|
: { ok: false, message: `Google meldet: ${err}` };
|
||||||
|
} else {
|
||||||
|
const err = await probeToken("https://appleid.apple.com/auth/token", new URLSearchParams({ code: "sanamare-test", client_id: c.apple.servicesId, client_secret: appleClientSecret(c.apple), redirect_uri: `${appUrl()}/api/auth/apple/callback`, grant_type: "authorization_code" }));
|
||||||
|
r = err === "invalid_grant"
|
||||||
|
? { ok: true, message: "Apple kennt Services-ID, Team-ID und Schlüssel. Die Anmeldung ist bereit." }
|
||||||
|
: err === "invalid_client"
|
||||||
|
? { ok: false, message: "Apple lehnt die Angaben ab. Meist passt die Services-ID, die Team-ID oder die Key-ID nicht zum Schlüssel." }
|
||||||
|
: { ok: false, message: `Apple meldet: ${err}` };
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
r = { ok: false, message: `Keine Verbindung: ${e instanceof Error ? e.message : e}` };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
await remember(provider, r);
|
||||||
|
return r;
|
||||||
|
}
|
||||||
|
|
@ -4,7 +4,7 @@ import type { Order } from "@prisma/client";
|
||||||
|
|
||||||
const API = "https://api.stripe.com/v1";
|
const API = "https://api.stripe.com/v1";
|
||||||
|
|
||||||
async function stripeRequest<T>(secretKey: string, path: string, params?: URLSearchParams, method = "POST"): Promise<T> {
|
export async function stripeRequest<T>(secretKey: string, path: string, params?: URLSearchParams, method = "POST"): Promise<T> {
|
||||||
const res = await fetch(`${API}${path}`, {
|
const res = await fetch(`${API}${path}`, {
|
||||||
method,
|
method,
|
||||||
headers: {
|
headers: {
|
||||||
|
|
|
||||||
|
|
@ -52,7 +52,7 @@ export function isValidApplePrivateKey(pem: string) {
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Apple verlangt als Client-Secret ein mit dem .p8-Schlüssel signiertes JWT (ES256). */
|
/** Apple verlangt als Client-Secret ein mit dem .p8-Schlüssel signiertes JWT (ES256). */
|
||||||
function appleClientSecret(c: LoginProviders["apple"]) {
|
export function appleClientSecret(c: LoginProviders["apple"]) {
|
||||||
const now = Math.floor(Date.now() / 1000);
|
const now = Math.floor(Date.now() / 1000);
|
||||||
const header = b64url(JSON.stringify({ alg: "ES256", kid: c.keyId }));
|
const header = b64url(JSON.stringify({ alg: "ES256", kid: c.keyId }));
|
||||||
const claims = b64url(JSON.stringify({ iss: c.teamId, iat: now, exp: now + 300, aud: "https://appleid.apple.com", sub: c.servicesId }));
|
const claims = b64url(JSON.stringify({ iss: c.teamId, iat: now, exp: now + 300, aud: "https://appleid.apple.com", sub: c.servicesId }));
|
||||||
|
|
|
||||||
|
|
@ -187,3 +187,32 @@ a.ad-kpi:hover { border-color: var(--line-strong); }
|
||||||
.ad-template__confirm { display: flex; flex-wrap: wrap; gap: 8px; align-items: center; }
|
.ad-template__confirm { display: flex; flex-wrap: wrap; gap: 8px; align-items: center; }
|
||||||
.ad-legal { list-style: none; margin: 0; padding: 0; display: grid; gap: var(--space-3); }
|
.ad-legal { list-style: none; margin: 0; padding: 0; display: grid; gap: var(--space-3); }
|
||||||
.ad-legal li { display: flex; justify-content: space-between; align-items: center; gap: var(--space-3); font-size: 14px; }
|
.ad-legal li { display: flex; justify-content: space-between; align-items: center; gap: var(--space-3); font-size: 14px; }
|
||||||
|
|
||||||
|
/* Geführte Einrichtung */
|
||||||
|
.ad-steps { list-style: none; margin: 0; padding: 0; display: grid; gap: var(--space-6); counter-reset: step; }
|
||||||
|
.ad-step { display: grid; grid-template-columns: 32px 1fr; gap: var(--space-4); }
|
||||||
|
.ad-step__num { width: 32px; height: 32px; border-radius: 50%; border: 1px solid var(--line); display: grid; place-items: center; font-size: 14px; font-weight: 600; background: var(--surface-raised, #fff); }
|
||||||
|
.ad-step.is-done .ad-step__num { background: var(--gold); border-color: var(--gold); color: var(--ink); }
|
||||||
|
.ad-step__body h3 { margin: 4px 0 var(--space-2); font-size: 16px; font-weight: 600; }
|
||||||
|
.ad-step__body p { margin: 0 0 var(--space-3); font-size: 14px; line-height: 21px; color: var(--ink-muted); }
|
||||||
|
.ad-step__body ol, .ad-step__body ul { margin: 0 0 var(--space-3); padding-left: 20px; font-size: 14px; line-height: 21px; color: var(--ink-muted); }
|
||||||
|
.ad-step__body .sm-field { margin-top: var(--space-3); }
|
||||||
|
.ad-openlink { display: inline-flex; align-items: center; gap: 6px; font-size: 14px; font-weight: 500; color: var(--link); text-decoration: underline; text-underline-offset: 3px; margin: 0 var(--space-4) var(--space-3) 0; }
|
||||||
|
.ad-copy { margin: 0 0 var(--space-3); }
|
||||||
|
.ad-copy__label { display: block; font-size: 12px; color: var(--ink-subtle); margin-bottom: 4px; }
|
||||||
|
.ad-copy__row { display: flex; gap: 8px; align-items: center; }
|
||||||
|
.ad-copy__row code { flex: 1; min-width: 0; overflow-wrap: anywhere; padding: 8px 10px; border: 1px solid var(--line); border-radius: var(--radius-md); background: var(--surface); font-size: 13px; }
|
||||||
|
.ad-file { font-size: 14px; }
|
||||||
|
.ad-result { display: flex; gap: 8px; align-items: flex-start; padding: var(--space-4) var(--space-5); border-radius: var(--radius-md); font-size: 14px; line-height: 20px; margin-bottom: var(--space-5); border: 1px solid var(--line); }
|
||||||
|
.ad-result--ok { border-color: var(--success, #2f7a52); }
|
||||||
|
.ad-result--err { border-color: var(--danger); }
|
||||||
|
.ad-result small { display: block; color: var(--ink-subtle); }
|
||||||
|
|
||||||
|
/* Übersicht Verbindungen */
|
||||||
|
.ad-integrations { display: grid; grid-template-columns: repeat(auto-fill, minmax(260px, 1fr)); gap: var(--space-4); }
|
||||||
|
.ad-integration { display: grid; gap: var(--space-3); padding: var(--space-5); border: 1px solid var(--line); border-radius: var(--radius-md); background: var(--surface-raised, #fff); text-decoration: none; color: inherit; }
|
||||||
|
.ad-integration:hover { border-color: var(--gold); }
|
||||||
|
.ad-integration__head { display: flex; justify-content: space-between; align-items: center; gap: var(--space-3); }
|
||||||
|
.ad-integration h2 { margin: 0; font-size: 18px; font-weight: 600; }
|
||||||
|
.ad-integration p { margin: 0; font-size: 14px; line-height: 20px; color: var(--ink-muted); }
|
||||||
|
.ad-integration small { font-size: 12px; color: var(--ink-subtle); }
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue