Compare commits
2 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 794322d346 | |||
| 9511d67c15 |
@@ -46,16 +46,23 @@ Hermes gibt die HSI-Schnittstellendoku nur an Vertragskunden heraus. Ohne die
|
|||||||
Unterlagen lässt sich nichts schreiben, das mehr als geraten wäre. Sobald die
|
Unterlagen lässt sich nichts schreiben, das mehr als geraten wäre. Sobald die
|
||||||
Doku da ist, sagen Sie Bescheid.
|
Doku da ist, sagen Sie Bescheid.
|
||||||
|
|
||||||
### Mollie — Code fertig, ungetestet
|
### Mollie — im Testmodus durchgespielt (26.10.2026)
|
||||||
|
|
||||||
- `MOLLIE_API_KEY` — erst `test_…`, später `live_…`
|
Läuft für Abos und für normale Bestellungen ("Online bezahlen" an der
|
||||||
- Im Mollie-Dashboard freischalten: **SEPA-Lastschrift, Kreditkarte, PayPal**
|
Kasse). Getestet: Kauf, Abbruch, Teilerstattung im Admin, Storno mit
|
||||||
|
Resterstattung, Folgezahlung, gescheiterte Folgezahlung (nachgestellt).
|
||||||
|
|
||||||
|
- `MOLLIE_API_KEY` — jetzt `test_…`, zum Livegang `live_…`
|
||||||
|
- Im Mollie-Dashboard noch freischalten: **PayPal, SEPA-Lastschrift**. Dann
|
||||||
|
den Text der Zahlart in `src/api/store/payment-methods/route.ts` ergänzen.
|
||||||
- Webhook-URL muss von außen erreichbar sein: `https://<domain>/hooks/mollie`
|
- Webhook-URL muss von außen erreichbar sein: `https://<domain>/hooks/mollie`
|
||||||
(lokal geht das nur über einen Tunnel, z. B. ngrok)
|
(lokal über einen Tunnel, z. B. cloudflared)
|
||||||
|
|
||||||
Achtung: Mollie ist **kein** registriertes Medusa-Payment-Modul, sondern wird
|
Mollie ist **kein** Medusa-Zahlungsanbieter, sondern wird direkt über
|
||||||
direkt über `src/lib/mollie.ts` angesprochen. Registriert sind aktuell nur
|
`src/lib/mollie.ts` angesprochen. In Medusa laufen die Zahlungen über den
|
||||||
PayPal und PayPal-Card.
|
manuellen Anbieter; die Mollie-Zahlung steht als `mollie_payment_id` an der
|
||||||
|
Bestellung. Erstattungen im Admin (auch per Storno) gehen automatisch an
|
||||||
|
Mollie (`src/lib/mollie-erstattung.ts`).
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
|||||||
@@ -1,16 +1,15 @@
|
|||||||
import { MedusaRequest, MedusaResponse } from "@medusajs/framework/http";
|
import { MedusaRequest, MedusaResponse } from "@medusajs/framework/http";
|
||||||
import {
|
|
||||||
completeCartWorkflow,
|
|
||||||
createPaymentCollectionForCartWorkflow,
|
|
||||||
createPaymentSessionsWorkflow,
|
|
||||||
capturePaymentWorkflow,
|
|
||||||
} from "@medusajs/core-flows";
|
|
||||||
import { getPayment, findValidMandate } from "../../../lib/mollie";
|
import { getPayment, findValidMandate } from "../../../lib/mollie";
|
||||||
|
import { createSubscriptionsFromOrder } from "../../../lib/subscription-from-order";
|
||||||
import {
|
import {
|
||||||
createSubscriptionsFromOrder,
|
bezahltenWarenkorbAbschliessen,
|
||||||
SUBSCRIPTION_CART_FIELDS,
|
bestellungsZahlungErfassen,
|
||||||
} from "../../../lib/subscription-from-order";
|
mollieZahlungMerken,
|
||||||
import { SUBSCRIPTION_MODULE } from "../../../modules/subscription";
|
} from "../../../lib/mollie-bestellung";
|
||||||
|
import { aboAbbuchungGescheitert } from "../../../lib/abo-zahlung";
|
||||||
|
|
||||||
|
/** Endgültig gescheitert — "open" und "pending" können noch klappen. */
|
||||||
|
const GESCHEITERT = ["failed", "canceled", "expired"];
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Mollie-Webhook.
|
* Mollie-Webhook.
|
||||||
@@ -18,10 +17,12 @@ import { SUBSCRIPTION_MODULE } from "../../../modules/subscription";
|
|||||||
* Mollie schickt nur die Zahlungs-ID; den Zustand holen wir selbst ab, damit
|
* Mollie schickt nur die Zahlungs-ID; den Zustand holen wir selbst ab, damit
|
||||||
* ein gefälschter Aufruf nichts auslösen kann.
|
* ein gefälschter Aufruf nichts auslösen kann.
|
||||||
*
|
*
|
||||||
* Zwei Fälle:
|
* Drei Fälle:
|
||||||
* - Erstzahlung eines Abos ("first"): Warenkorb abschließen, Abo anlegen
|
* - Erstzahlung eines Abos ("first"): Warenkorb abschließen, Abo anlegen
|
||||||
* - Folgezahlung ("recurring"): nur die Zahlung der Bestellung erfassen,
|
* - normale Bestellung ("oneoff"): Warenkorb abschließen
|
||||||
* wodurch der Label-Subscriber greift
|
* - Folgezahlung eines Abos ("recurring"): Zahlung der schon angelegten
|
||||||
|
* Bestellung erfassen, wodurch der Label-Subscriber greift — oder, wenn
|
||||||
|
* die Abbuchung scheitert, Lieferung stornieren und Kunden informieren
|
||||||
*
|
*
|
||||||
* Mollie ruft den Webhook mehrfach auf. Alles hier muss also mehrfach
|
* Mollie ruft den Webhook mehrfach auf. Alles hier muss also mehrfach
|
||||||
* ausführbar sein, ohne doppelte Bestellungen oder Abos zu erzeugen.
|
* ausführbar sein, ohne doppelte Bestellungen oder Abos zu erzeugen.
|
||||||
@@ -41,113 +42,82 @@ export async function POST(req: MedusaRequest, res: MedusaResponse) {
|
|||||||
try {
|
try {
|
||||||
const payment: any = await getPayment(paymentId);
|
const payment: any = await getPayment(paymentId);
|
||||||
logger.info(`[mollie] ${paymentId}: ${payment.status} (${payment.sequenceType})`);
|
logger.info(`[mollie] ${paymentId}: ${payment.status} (${payment.sequenceType})`);
|
||||||
|
const meta = payment.metadata ?? {};
|
||||||
|
|
||||||
|
if (payment.sequenceType === "recurring") {
|
||||||
|
if (payment.status === "paid" && meta.order_id) {
|
||||||
|
await mollieZahlungMerken(req.scope, meta.order_id, payment.id);
|
||||||
|
await bestellungsZahlungErfassen(req.scope, meta.order_id, logger);
|
||||||
|
} else if (GESCHEITERT.includes(payment.status)) {
|
||||||
|
await aboAbbuchungGescheitert(req.scope, payment, logger);
|
||||||
|
}
|
||||||
|
return res.status(200).send("ok");
|
||||||
|
}
|
||||||
|
|
||||||
if (payment.status !== "paid") {
|
if (payment.status !== "paid") {
|
||||||
return res.status(200).send("ok");
|
return res.status(200).send("ok");
|
||||||
}
|
}
|
||||||
|
|
||||||
const meta = payment.metadata ?? {};
|
// --- Normale Bestellung ---
|
||||||
|
if (payment.sequenceType === "oneoff") {
|
||||||
if (payment.sequenceType === "recurring") {
|
const ergebnis = await bezahltenWarenkorbAbschliessen(req.scope, payment, logger);
|
||||||
await captureOrderPayment(req.scope, query, meta.order_id, logger);
|
if (ergebnis?.neu) {
|
||||||
|
logger.info(`[mollie] Bestellung zu Warenkorb ${meta.cart_id} angelegt.`);
|
||||||
|
}
|
||||||
|
await bestellungsZahlungErfassen(req.scope, ergebnis?.orderId, logger);
|
||||||
return res.status(200).send("ok");
|
return res.status(200).send("ok");
|
||||||
}
|
}
|
||||||
|
|
||||||
// --- Erstzahlung: Warenkorb abschließen und Abo anlegen ---
|
// --- Erstzahlung: Warenkorb abschließen und Abo anlegen ---
|
||||||
const cartId = meta.cart_id;
|
const mandateId = payment.mandateId ?? (await findValidMandate(payment.customerId));
|
||||||
if (!cartId) {
|
|
||||||
logger.warn(`[mollie] ${paymentId}: keine cart_id in den Metadaten.`);
|
|
||||||
return res.status(200).send("ok");
|
|
||||||
}
|
|
||||||
|
|
||||||
const { data: carts } = await query.graph({
|
|
||||||
entity: "cart",
|
|
||||||
fields: [
|
|
||||||
...SUBSCRIPTION_CART_FIELDS,
|
|
||||||
"completed_at",
|
|
||||||
"payment_collection.id",
|
|
||||||
"payment_collection.payment_sessions.id",
|
|
||||||
],
|
|
||||||
filters: { id: cartId },
|
|
||||||
});
|
|
||||||
const cart: any = carts?.[0];
|
|
||||||
if (!cart) {
|
|
||||||
logger.warn(`[mollie] Warenkorb ${cartId} nicht gefunden.`);
|
|
||||||
return res.status(200).send("ok");
|
|
||||||
}
|
|
||||||
if (cart.completed_at) {
|
|
||||||
logger.info(`[mollie] Warenkorb ${cartId} war schon abgeschlossen, nichts zu tun.`);
|
|
||||||
return res.status(200).send("ok");
|
|
||||||
}
|
|
||||||
|
|
||||||
const mandateId =
|
|
||||||
payment.mandateId ?? (await findValidMandate(payment.customerId));
|
|
||||||
if (!mandateId) {
|
if (!mandateId) {
|
||||||
logger.error(
|
logger.error(`[mollie] ${paymentId}: bezahlt, aber kein gültiges Mandat — ohne Mandat kein Abo.`);
|
||||||
`[mollie] ${paymentId}: bezahlt, aber kein gültiges Mandat — ohne Mandat kein Abo.`
|
|
||||||
);
|
|
||||||
return res.status(200).send("ok");
|
return res.status(200).send("ok");
|
||||||
}
|
}
|
||||||
|
|
||||||
// Ein früherer Aufruf kann Sammlung und Sitzung schon angelegt haben und
|
const ergebnis = await bezahltenWarenkorbAbschliessen(req.scope, payment, logger);
|
||||||
// erst danach gescheitert sein — dann weiterverwenden statt neu anlegen.
|
if (!ergebnis) return res.status(200).send("ok");
|
||||||
let collectionId = cart.payment_collection?.id;
|
|
||||||
if (!collectionId) {
|
if (ergebnis.neu) {
|
||||||
const { result: sammlung } = await createPaymentCollectionForCartWorkflow(req.scope).run({
|
const { data: orders } = await query.graph({
|
||||||
input: { cart_id: cartId },
|
entity: "order",
|
||||||
|
fields: [
|
||||||
|
"id",
|
||||||
|
"display_id",
|
||||||
|
"email",
|
||||||
|
"customer_id",
|
||||||
|
"region_id",
|
||||||
|
"currency_code",
|
||||||
|
"sales_channel_id",
|
||||||
|
"shipping_address.*",
|
||||||
|
"shipping_methods.shipping_option_id",
|
||||||
|
"items.id",
|
||||||
|
"items.quantity",
|
||||||
|
"items.metadata",
|
||||||
|
"items.variant_id",
|
||||||
|
"items.variant.id",
|
||||||
|
"items.variant.metadata",
|
||||||
|
"items.variant.product.metadata",
|
||||||
|
],
|
||||||
|
filters: { id: ergebnis.orderId },
|
||||||
});
|
});
|
||||||
collectionId = (sammlung as any).id;
|
const order: any = orders?.[0];
|
||||||
}
|
|
||||||
// Ohne Zahlungssitzung lässt sich der Warenkorb nicht abschließen. Wie im
|
const subscriptions = await createSubscriptionsFromOrder({
|
||||||
// Abo-Job über den manuellen Anbieter: Das Geld hat Mollie schon.
|
container: req.scope,
|
||||||
if (!cart.payment_collection?.payment_sessions?.length) {
|
order,
|
||||||
await createPaymentSessionsWorkflow(req.scope).run({
|
mollieCustomerId: payment.customerId,
|
||||||
input: { payment_collection_id: collectionId, provider_id: "pp_system_default" },
|
mollieMandateId: mandateId,
|
||||||
|
paymentMethod: payment.method,
|
||||||
});
|
});
|
||||||
|
|
||||||
|
logger.info(
|
||||||
|
`[mollie] Bestellung ${order.display_id} angelegt, ${subscriptions.length} Abo(s): ` +
|
||||||
|
subscriptions.map((s: any) => `${s.id} (${s.interval}, ${s.size})`).join(", ")
|
||||||
|
);
|
||||||
}
|
}
|
||||||
const { result: completed } = await completeCartWorkflow(req.scope).run({
|
|
||||||
input: { id: cartId },
|
|
||||||
});
|
|
||||||
const orderId = (completed as any)?.id;
|
|
||||||
|
|
||||||
const { data: orders } = await query.graph({
|
await bestellungsZahlungErfassen(req.scope, ergebnis.orderId, logger);
|
||||||
entity: "order",
|
|
||||||
fields: [
|
|
||||||
"id",
|
|
||||||
"display_id",
|
|
||||||
"email",
|
|
||||||
"customer_id",
|
|
||||||
"region_id",
|
|
||||||
"currency_code",
|
|
||||||
"sales_channel_id",
|
|
||||||
"shipping_address.*",
|
|
||||||
"shipping_methods.shipping_option_id",
|
|
||||||
"items.id",
|
|
||||||
"items.quantity",
|
|
||||||
"items.metadata",
|
|
||||||
"items.variant_id",
|
|
||||||
"items.variant.id",
|
|
||||||
"items.variant.metadata",
|
|
||||||
"items.variant.product.metadata",
|
|
||||||
],
|
|
||||||
filters: { id: orderId },
|
|
||||||
});
|
|
||||||
const order: any = orders?.[0];
|
|
||||||
|
|
||||||
const subscriptions = await createSubscriptionsFromOrder({
|
|
||||||
container: req.scope,
|
|
||||||
order,
|
|
||||||
mollieCustomerId: payment.customerId,
|
|
||||||
mollieMandateId: mandateId,
|
|
||||||
paymentMethod: payment.method,
|
|
||||||
});
|
|
||||||
|
|
||||||
logger.info(
|
|
||||||
`[mollie] Bestellung ${order.display_id} angelegt, ${subscriptions.length} Abo(s): ` +
|
|
||||||
subscriptions.map((s: any) => `${s.id} (${s.interval}, ${s.size})`).join(", ")
|
|
||||||
);
|
|
||||||
|
|
||||||
await captureOrderPayment(req.scope, query, orderId, logger);
|
|
||||||
res.status(200).send("ok");
|
res.status(200).send("ok");
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
logger.error(
|
logger.error(
|
||||||
@@ -162,30 +132,3 @@ export async function POST(req: MedusaRequest, res: MedusaResponse) {
|
|||||||
res.status(200).send("ok");
|
res.status(200).send("ok");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* Erfasst die Zahlung der Bestellung in Medusa. Das löst `payment.captured`
|
|
||||||
* aus, worauf der Subscriber das Versandlabel erzeugt.
|
|
||||||
*/
|
|
||||||
async function captureOrderPayment(scope: any, query: any, orderId: string | undefined, logger: any) {
|
|
||||||
if (!orderId) return;
|
|
||||||
const { data: orders } = await query.graph({
|
|
||||||
entity: "order",
|
|
||||||
fields: [
|
|
||||||
"id",
|
|
||||||
"display_id",
|
|
||||||
"payment_collections.payments.id",
|
|
||||||
"payment_collections.payments.amount",
|
|
||||||
"payment_collections.payments.captured_at",
|
|
||||||
],
|
|
||||||
filters: { id: orderId },
|
|
||||||
});
|
|
||||||
const payments = orders?.[0]?.payment_collections?.flatMap((c: any) => c.payments ?? []) ?? [];
|
|
||||||
for (const payment of payments) {
|
|
||||||
if (payment.captured_at) continue;
|
|
||||||
await capturePaymentWorkflow(scope).run({
|
|
||||||
input: { payment_id: payment.id, amount: payment.amount },
|
|
||||||
});
|
|
||||||
logger.info(`[mollie] Zahlung ${payment.id} erfasst — Label wird erzeugt.`);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -0,0 +1,76 @@
|
|||||||
|
import { MedusaRequest, MedusaResponse } from "@medusajs/framework/http";
|
||||||
|
import { updateCartWorkflow } from "@medusajs/core-flows";
|
||||||
|
import { createOneOffPayment, isMollieConfigured } from "../../../../lib/mollie";
|
||||||
|
import { hasSubscriptionLines, SUBSCRIPTION_CART_FIELDS } from "../../../../lib/subscription-from-order";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Startet die Online-Zahlung einer normalen Bestellung bei Mollie.
|
||||||
|
*
|
||||||
|
* Wie beim Abo wird der Warenkorb hier NICHT abgeschlossen. Das macht der
|
||||||
|
* Webhook, sobald Mollie die Zahlung bestätigt — bricht jemand bei Mollie ab,
|
||||||
|
* entsteht keine unbezahlte Bestellung. Adresse und Versandart setzt die
|
||||||
|
* Kasse vorher wie bei jeder anderen Zahlart.
|
||||||
|
*/
|
||||||
|
export async function POST(req: MedusaRequest, res: MedusaResponse) {
|
||||||
|
const query = req.scope.resolve("query");
|
||||||
|
const cartId = (req.body as { cart_id?: string })?.cart_id;
|
||||||
|
|
||||||
|
if (!isMollieConfigured()) {
|
||||||
|
return res.status(503).json({ message: "Online-Zahlung ist gerade nicht verfügbar." });
|
||||||
|
}
|
||||||
|
if (!cartId) {
|
||||||
|
return res.status(400).json({ message: "cart_id fehlt." });
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const { data: carts } = await query.graph({
|
||||||
|
entity: "cart",
|
||||||
|
fields: [
|
||||||
|
...SUBSCRIPTION_CART_FIELDS,
|
||||||
|
"completed_at",
|
||||||
|
"metadata",
|
||||||
|
"total",
|
||||||
|
// Ohne Preise der Posten und Versandarten rechnet Medusa total = 0.
|
||||||
|
"items.*",
|
||||||
|
"shipping_methods.*",
|
||||||
|
],
|
||||||
|
filters: { id: cartId },
|
||||||
|
});
|
||||||
|
const cart: any = carts?.[0];
|
||||||
|
if (!cart || cart.completed_at) {
|
||||||
|
return res.status(404).json({ message: "Warenkorb nicht gefunden." });
|
||||||
|
}
|
||||||
|
if (hasSubscriptionLines(cart)) {
|
||||||
|
return res.status(400).json({ message: "Ein Abo läuft über die Abo-Kasse." });
|
||||||
|
}
|
||||||
|
if (!cart.email || !cart.shipping_address) {
|
||||||
|
return res.status(400).json({ message: "E-Mail-Adresse und Lieferadresse fehlen." });
|
||||||
|
}
|
||||||
|
const betrag = Math.round(Number(cart.total) * 100) / 100;
|
||||||
|
if (!(betrag > 0)) {
|
||||||
|
return res.status(400).json({ message: "Es ist nichts zu bezahlen." });
|
||||||
|
}
|
||||||
|
|
||||||
|
const storefront = process.env.STOREFRONT_URL ?? "http://localhost:4321";
|
||||||
|
const payment = await createOneOffPayment({
|
||||||
|
amount: betrag,
|
||||||
|
currency: String(cart.currency_code ?? "eur").toUpperCase(),
|
||||||
|
description: "place4bees Bestellung",
|
||||||
|
redirectUrl: `${storefront}/bestellung/zahlung?cart=${cart.id}`,
|
||||||
|
webhookUrl: process.env.MOLLIE_WEBHOOK_URL,
|
||||||
|
// Der Webhook findet den Warenkorb nur hierüber wieder.
|
||||||
|
metadata: { cart_id: cart.id },
|
||||||
|
});
|
||||||
|
|
||||||
|
// Für die Rückkehrseite: woran sie erkennt, ob die Zahlung abgebrochen wurde.
|
||||||
|
await updateCartWorkflow(req.scope).run({
|
||||||
|
input: { id: cart.id, metadata: { ...(cart.metadata ?? {}), mollie_payment_id: payment.id } } as any,
|
||||||
|
});
|
||||||
|
|
||||||
|
res.json({ checkout_url: payment.getCheckoutUrl?.() ?? (payment as any)._links?.checkout?.href });
|
||||||
|
} catch (error) {
|
||||||
|
const message = error instanceof Error ? error.message : "Online-Zahlung konnte nicht gestartet werden.";
|
||||||
|
req.scope.resolve("logger").error(`[mollie-kasse] ${message}`);
|
||||||
|
res.status(400).json({ message: "Online-Zahlung konnte nicht gestartet werden. Bitte versuchen Sie es erneut." });
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,67 @@
|
|||||||
|
import { MedusaRequest, MedusaResponse } from "@medusajs/framework/http";
|
||||||
|
import { getPayment } from "../../../../lib/mollie";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Stand einer Online-Zahlung für die Rückkehrseite.
|
||||||
|
*
|
||||||
|
* abgeschlossen — der Webhook hat die Bestellung angelegt
|
||||||
|
* wartet — Mollie hat noch nicht bestätigt (bei Überweisung dauert
|
||||||
|
* das Tage)
|
||||||
|
* abgebrochen — die Zahlung ist gescheitert oder wurde abgebrochen; der
|
||||||
|
* Warenkorb ist noch da und kann neu bezahlt werden
|
||||||
|
*/
|
||||||
|
export async function GET(req: MedusaRequest, res: MedusaResponse) {
|
||||||
|
const query = req.scope.resolve("query");
|
||||||
|
const cartId = req.query.cart_id as string | undefined;
|
||||||
|
if (!cartId) return res.status(400).json({ message: "cart_id fehlt." });
|
||||||
|
|
||||||
|
const { data: carts } = await query.graph({
|
||||||
|
entity: "cart",
|
||||||
|
fields: [
|
||||||
|
"id",
|
||||||
|
"completed_at",
|
||||||
|
"metadata",
|
||||||
|
"order.id",
|
||||||
|
"order.display_id",
|
||||||
|
"order.email",
|
||||||
|
// Für die Dankeseite (Kaufmeldung an Analytics, nur mit Einwilligung).
|
||||||
|
"order.total",
|
||||||
|
"order.shipping_total",
|
||||||
|
"order.tax_total",
|
||||||
|
"order.currency_code",
|
||||||
|
"order.items.title",
|
||||||
|
"order.items.variant_id",
|
||||||
|
"order.items.unit_price",
|
||||||
|
"order.items.quantity",
|
||||||
|
],
|
||||||
|
filters: { id: cartId },
|
||||||
|
});
|
||||||
|
const cart: any = carts?.[0];
|
||||||
|
if (!cart) return res.status(404).json({ message: "Warenkorb nicht gefunden." });
|
||||||
|
|
||||||
|
if (cart.completed_at && cart.order) {
|
||||||
|
return res.json({
|
||||||
|
status: "abgeschlossen",
|
||||||
|
order: {
|
||||||
|
id: cart.order.id,
|
||||||
|
display_id: cart.order.display_id,
|
||||||
|
email: cart.order.email,
|
||||||
|
total: Number(cart.order.total ?? 0),
|
||||||
|
shipping_total: Number(cart.order.shipping_total ?? 0),
|
||||||
|
tax_total: Number(cart.order.tax_total ?? 0),
|
||||||
|
currency_code: cart.order.currency_code,
|
||||||
|
items: (cart.order.items ?? []).map((i: any) => ({
|
||||||
|
title: i.title,
|
||||||
|
variant_id: i.variant_id,
|
||||||
|
unit_price: Number(i.unit_price ?? 0),
|
||||||
|
quantity: Number(i.quantity ?? 1),
|
||||||
|
})),
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
const molliePaymentId = cart.metadata?.mollie_payment_id;
|
||||||
|
if (!molliePaymentId) return res.json({ status: "abgebrochen" });
|
||||||
|
const payment: any = await getPayment(molliePaymentId);
|
||||||
|
res.json({ status: ["failed", "canceled", "expired"].includes(payment.status) ? "abgebrochen" : "wartet" });
|
||||||
|
}
|
||||||
@@ -1,4 +1,5 @@
|
|||||||
import { MedusaRequest, MedusaResponse } from "@medusajs/framework/http";
|
import { MedusaRequest, MedusaResponse } from "@medusajs/framework/http";
|
||||||
|
import { isMollieConfigured } from "../../../lib/mollie";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Die Zahlungsarten, die der Shop anbieten darf.
|
* Die Zahlungsarten, die der Shop anbieten darf.
|
||||||
@@ -61,10 +62,28 @@ export async function GET(req: MedusaRequest, res: MedusaResponse) {
|
|||||||
.map((provider: any) => provider.id)
|
.map((provider: any) => provider.id)
|
||||||
);
|
);
|
||||||
|
|
||||||
|
// Mollie ist kein Medusa-Zahlungsanbieter an der Region, sondern läuft über
|
||||||
|
// /store/mollie/checkout — deshalb hier gesondert und nur mit Schlüssel.
|
||||||
|
const online = isMollieConfigured()
|
||||||
|
? [
|
||||||
|
{
|
||||||
|
id: "mollie",
|
||||||
|
label: "Online bezahlen",
|
||||||
|
description:
|
||||||
|
// Nur nennen, was Mollie an der Kasse tatsächlich anbietet (Stand
|
||||||
|
// 26.10.2026). Klarna ist im Profil freigeschaltet, erscheint aber
|
||||||
|
// nicht: Es braucht die einzelnen Bestellposten, die eine einfache
|
||||||
|
// Zahlung nicht mitschickt. Kommt PayPal dazu, hier ergänzen.
|
||||||
|
"Kreditkarte, Sofortüberweisung oder Überweisung — die Auswahl folgt auf der sicheren Seite unseres Zahlungsdienstleisters Mollie.",
|
||||||
|
},
|
||||||
|
]
|
||||||
|
: [];
|
||||||
|
|
||||||
res.json({
|
res.json({
|
||||||
payment_methods: ZAHLUNGSARTEN.filter(
|
payment_methods: [
|
||||||
(art) => art.bereit && anDerRegion.has(art.id)
|
...online,
|
||||||
).map(({ bereit, ...rest }) => rest),
|
...ZAHLUNGSARTEN.filter((art) => art.bereit && anDerRegion.has(art.id)).map(({ bereit, ...rest }) => rest),
|
||||||
|
],
|
||||||
// Für die Einrichtung sichtbar: was angeschlossen, aber noch nicht
|
// Für die Einrichtung sichtbar: was angeschlossen, aber noch nicht
|
||||||
// fertig ist. Der Shop zeigt das nicht an.
|
// fertig ist. Der Shop zeigt das nicht an.
|
||||||
not_ready: ZAHLUNGSARTEN.filter((art) => !art.bereit).map((art) => art.id),
|
not_ready: ZAHLUNGSARTEN.filter((art) => !art.bereit).map((art) => art.id),
|
||||||
|
|||||||
@@ -0,0 +1,80 @@
|
|||||||
|
import { cancelOrderWorkflow } from "@medusajs/core-flows";
|
||||||
|
import { Modules } from "@medusajs/framework/utils";
|
||||||
|
import { aboZahlungFehlgeschlagenMail } from "./order-emails";
|
||||||
|
import { SUBSCRIPTION_MODULE } from "../modules/subscription";
|
||||||
|
|
||||||
|
/** Nach so vielen gescheiterten Abbuchungen wird das Abo pausiert. */
|
||||||
|
const MAX_FEHLVERSUCHE = 3;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Die Abbuchung für eine Abo-Lieferung ist gescheitert. Der Abo-Job hat die
|
||||||
|
* Bestellung schon angelegt — sie wird storniert, damit keine unbezahlte
|
||||||
|
* Lieferung im Admin liegt. Das Abo versucht es in drei Tagen erneut und
|
||||||
|
* pausiert nach dem dritten Fehlversuch. Der Kunde bekommt jedes Mal Bescheid.
|
||||||
|
*/
|
||||||
|
export async function aboAbbuchungGescheitert(scope: any, payment: any, logger: any) {
|
||||||
|
const { order_id: orderId, subscription_id: aboId } = payment.metadata ?? {};
|
||||||
|
if (!orderId || !aboId) return;
|
||||||
|
|
||||||
|
const orders: any = scope.resolve(Modules.ORDER);
|
||||||
|
const order = await orders.retrieveOrder(orderId, {
|
||||||
|
select: ["id", "display_id", "status", "metadata"],
|
||||||
|
relations: ["shipping_address"],
|
||||||
|
});
|
||||||
|
// Mollie meldet denselben Zustand mehrfach — nur einmal verarbeiten.
|
||||||
|
if (order.metadata?.mollie_fehlgeschlagen === payment.id) return;
|
||||||
|
|
||||||
|
await orders.updateOrders(orderId, {
|
||||||
|
// storno_grund sagt dem Storno-Subscriber, dass hier eine eigene Mail
|
||||||
|
// rausgeht und keine zweite nötig ist.
|
||||||
|
metadata: { ...(order.metadata ?? {}), mollie_fehlgeschlagen: payment.id, storno_grund: "abo_abbuchung" },
|
||||||
|
});
|
||||||
|
if (order.status !== "canceled") {
|
||||||
|
await cancelOrderWorkflow(scope).run({ input: { order_id: orderId } });
|
||||||
|
}
|
||||||
|
|
||||||
|
const subscriptions: any = scope.resolve(SUBSCRIPTION_MODULE);
|
||||||
|
const [abo] = await subscriptions.listSubscriptions({ id: aboId });
|
||||||
|
if (!abo) return;
|
||||||
|
const versuche = (abo.failed_attempts ?? 0) + 1;
|
||||||
|
const pausiert = versuche >= MAX_FEHLVERSUCHE;
|
||||||
|
await subscriptions.updateSubscriptions({
|
||||||
|
id: abo.id,
|
||||||
|
failed_attempts: versuche,
|
||||||
|
last_error: `Abbuchung ${payment.id}: ${payment.status}`,
|
||||||
|
...(pausiert
|
||||||
|
? { status: "paused", paused_at: new Date() }
|
||||||
|
: { next_order_at: new Date(Date.now() + 3 * 24 * 60 * 60 * 1000) }),
|
||||||
|
});
|
||||||
|
logger.warn(
|
||||||
|
`[mollie] Abo ${abo.id}: Abbuchung ${payment.id} ${payment.status}, Bestellung ${order.display_id} storniert` +
|
||||||
|
(pausiert ? ", Abo pausiert." : `, neuer Versuch in 3 Tagen (Versuch ${versuche}).`)
|
||||||
|
);
|
||||||
|
|
||||||
|
try {
|
||||||
|
const storefront = process.env.STOREFRONT_URL ?? "http://localhost:4321";
|
||||||
|
const rhythmus: Record<string, string> = {
|
||||||
|
monthly: "monatlich",
|
||||||
|
quarterly: "vierteljährlich",
|
||||||
|
biannual: "halbjährlich",
|
||||||
|
};
|
||||||
|
await scope.resolve(Modules.NOTIFICATION).createNotifications({
|
||||||
|
to: abo.email,
|
||||||
|
channel: "email",
|
||||||
|
template: pausiert ? "subscription-paused" : "subscription-payment-failed",
|
||||||
|
content: aboZahlungFehlgeschlagenMail({
|
||||||
|
shipping_address: order.shipping_address ?? null,
|
||||||
|
beschreibung: `${abo.size}, ${rhythmus[abo.interval] ?? abo.interval}`,
|
||||||
|
pausiert,
|
||||||
|
kontoLink: `${storefront}/konto/abos`,
|
||||||
|
}),
|
||||||
|
data: { subscription_id: abo.id, order_id: orderId },
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
logger.error(
|
||||||
|
`[mail] Hinweis zur gescheiterten Abbuchung für ${abo.id} nicht verschickt: ${
|
||||||
|
error instanceof Error ? error.message : String(error)
|
||||||
|
}`
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,130 @@
|
|||||||
|
import {
|
||||||
|
capturePaymentWorkflow,
|
||||||
|
completeCartWorkflow,
|
||||||
|
createPaymentCollectionForCartWorkflow,
|
||||||
|
createPaymentSessionsWorkflow,
|
||||||
|
} from "@medusajs/core-flows";
|
||||||
|
import { Modules } from "@medusajs/framework/utils";
|
||||||
|
import { SUBSCRIPTION_CART_FIELDS } from "./subscription-from-order";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Schließt einen Warenkorb ab, den der Kunde bei Mollie bezahlt hat — für
|
||||||
|
* Abo-Erstzahlung und normale Bestellung gleich.
|
||||||
|
*
|
||||||
|
* Das Geld liegt schon bei Mollie. In Medusa läuft die Zahlung deshalb über
|
||||||
|
* den manuellen Anbieter; die Mollie-Zahlung steht als `mollie_payment_id`
|
||||||
|
* an der Bestellung, damit Erstattungen sie finden.
|
||||||
|
*
|
||||||
|
* Mehrfach aufrufbar: Ist der Warenkorb schon abgeschlossen, kommt die
|
||||||
|
* vorhandene Bestellung mit `neu: false` zurück — so legt ein wiederholter
|
||||||
|
* Webhook kein zweites Abo an.
|
||||||
|
*
|
||||||
|
* Gibt `null` zurück, wenn nicht abgeschlossen werden darf — dann steht der
|
||||||
|
* Grund im Log.
|
||||||
|
*/
|
||||||
|
export async function bezahltenWarenkorbAbschliessen(
|
||||||
|
scope: any,
|
||||||
|
payment: any,
|
||||||
|
logger: any
|
||||||
|
): Promise<{ orderId: string; neu: boolean } | null> {
|
||||||
|
const query = scope.resolve("query");
|
||||||
|
const cartId = payment.metadata?.cart_id;
|
||||||
|
if (!cartId) {
|
||||||
|
logger.warn(`[mollie] ${payment.id}: keine cart_id in den Metadaten.`);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
const { data: carts } = await query.graph({
|
||||||
|
entity: "cart",
|
||||||
|
fields: [
|
||||||
|
...SUBSCRIPTION_CART_FIELDS,
|
||||||
|
"completed_at",
|
||||||
|
"total",
|
||||||
|
// Ohne Preise der Posten und Versandarten rechnet Medusa total = 0.
|
||||||
|
"items.*",
|
||||||
|
"shipping_methods.*",
|
||||||
|
"payment_collection.id",
|
||||||
|
"payment_collection.payment_sessions.id",
|
||||||
|
"order.id",
|
||||||
|
],
|
||||||
|
filters: { id: cartId },
|
||||||
|
});
|
||||||
|
const cart: any = carts?.[0];
|
||||||
|
if (!cart) {
|
||||||
|
logger.warn(`[mollie] Warenkorb ${cartId} nicht gefunden.`);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
if (cart.completed_at) {
|
||||||
|
logger.info(`[mollie] Warenkorb ${cartId} war schon abgeschlossen.`);
|
||||||
|
return cart.order?.id ? { orderId: cart.order.id, neu: false } : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Der Warenkorb ließe sich nach dem Anlegen der Zahlung noch ändern. Passt
|
||||||
|
// der bezahlte Betrag nicht mehr, wird nichts abgeschlossen — sonst gäbe es
|
||||||
|
// Ware, die niemand bezahlt hat.
|
||||||
|
const bezahlt = Number(payment.amount?.value);
|
||||||
|
const soll = Math.round(Number(cart.total) * 100) / 100;
|
||||||
|
if (Math.abs(bezahlt - soll) > 0.005) {
|
||||||
|
logger.error(
|
||||||
|
`[mollie] ${payment.id}: bezahlt ${bezahlt.toFixed(2)} €, Warenkorb ${cartId} steht bei ${soll.toFixed(2)} € — ` +
|
||||||
|
"nicht abgeschlossen. Bitte prüfen und den Betrag bei Mollie erstatten."
|
||||||
|
);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Ein früherer Aufruf kann Sammlung und Sitzung schon angelegt haben und
|
||||||
|
// erst danach gescheitert sein — dann weiterverwenden statt neu anlegen.
|
||||||
|
let collectionId = cart.payment_collection?.id;
|
||||||
|
if (!collectionId) {
|
||||||
|
const { result: sammlung } = await createPaymentCollectionForCartWorkflow(scope).run({
|
||||||
|
input: { cart_id: cartId },
|
||||||
|
});
|
||||||
|
collectionId = (sammlung as any).id;
|
||||||
|
}
|
||||||
|
if (!cart.payment_collection?.payment_sessions?.length) {
|
||||||
|
await createPaymentSessionsWorkflow(scope).run({
|
||||||
|
input: { payment_collection_id: collectionId, provider_id: "pp_system_default" },
|
||||||
|
});
|
||||||
|
}
|
||||||
|
const { result: bestellung } = await completeCartWorkflow(scope).run({ input: { id: cartId } });
|
||||||
|
const orderId = (bestellung as any)?.id;
|
||||||
|
await mollieZahlungMerken(scope, orderId, payment.id);
|
||||||
|
return { orderId, neu: true };
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Hält die Mollie-Zahlung an der Bestellung fest — für spätere Erstattungen. */
|
||||||
|
export async function mollieZahlungMerken(scope: any, orderId: string, molliePaymentId: string) {
|
||||||
|
const orders: any = scope.resolve(Modules.ORDER);
|
||||||
|
const order = await orders.retrieveOrder(orderId, { select: ["id", "metadata"] });
|
||||||
|
if (order.metadata?.mollie_payment_id === molliePaymentId) return;
|
||||||
|
await orders.updateOrders(orderId, {
|
||||||
|
metadata: { ...(order.metadata ?? {}), mollie_payment_id: molliePaymentId },
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Erfasst die Zahlung der Bestellung in Medusa. Das löst `payment.captured`
|
||||||
|
* aus, worauf der Subscriber das Versandlabel erzeugt.
|
||||||
|
*/
|
||||||
|
export async function bestellungsZahlungErfassen(scope: any, orderId: string | undefined, logger: any) {
|
||||||
|
if (!orderId) return;
|
||||||
|
const query = scope.resolve("query");
|
||||||
|
const { data: orders } = await query.graph({
|
||||||
|
entity: "order",
|
||||||
|
fields: [
|
||||||
|
"id",
|
||||||
|
"payment_collections.payments.id",
|
||||||
|
"payment_collections.payments.amount",
|
||||||
|
"payment_collections.payments.captured_at",
|
||||||
|
],
|
||||||
|
filters: { id: orderId },
|
||||||
|
});
|
||||||
|
const zahlungen = orders?.[0]?.payment_collections?.flatMap((c: any) => c.payments ?? []) ?? [];
|
||||||
|
for (const zahlung of zahlungen) {
|
||||||
|
if (zahlung.captured_at) continue;
|
||||||
|
await capturePaymentWorkflow(scope).run({
|
||||||
|
input: { payment_id: zahlung.id, amount: zahlung.amount },
|
||||||
|
});
|
||||||
|
logger.info(`[mollie] Zahlung ${zahlung.id} erfasst — Label wird erzeugt.`);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,57 @@
|
|||||||
|
import { getPayment, isMollieConfigured, refundMolliePayment } from "./mollie";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Bringt Mollie auf den Stand der Erstattungen in Medusa.
|
||||||
|
*
|
||||||
|
* Medusa bucht Erstattungen nur — bezahlt wurde aber bei Mollie, also muss
|
||||||
|
* das Geld auch dort zurück. Verglichen wird die Summe aller Erstattungen in
|
||||||
|
* Medusa mit dem, was Mollie schon zurückgezahlt hat; erstattet wird nur die
|
||||||
|
* Differenz. So ist es egal, ob die Erstattung über "Refund" im Admin kam
|
||||||
|
* (payment.refunded) oder über ein Storno (dort löst Medusa kein Ereignis
|
||||||
|
* pro Zahlung aus), und ein doppelter Aufruf erstattet nichts doppelt.
|
||||||
|
*
|
||||||
|
* Gibt den bei Mollie neu erstatteten Betrag zurück, 0 wenn nichts zu tun war.
|
||||||
|
*/
|
||||||
|
export async function erstattungenMitMollieAbgleichen(scope: any, orderId: string, logger: any): Promise<number> {
|
||||||
|
const query = scope.resolve("query");
|
||||||
|
const { data: orders } = await query.graph({
|
||||||
|
entity: "order",
|
||||||
|
fields: [
|
||||||
|
"id",
|
||||||
|
"display_id",
|
||||||
|
"currency_code",
|
||||||
|
"metadata",
|
||||||
|
"payment_collections.payments.refunds.amount",
|
||||||
|
],
|
||||||
|
filters: { id: orderId },
|
||||||
|
});
|
||||||
|
const order: any = orders?.[0];
|
||||||
|
const molliePaymentId = order?.metadata?.mollie_payment_id;
|
||||||
|
if (!molliePaymentId) return 0; // nicht über Mollie bezahlt, z. B. Rechnung
|
||||||
|
if (!isMollieConfigured()) {
|
||||||
|
logger.error(`[erstattung] Bestellung ${order.display_id}: MOLLIE_API_KEY fehlt — bitte bei Mollie von Hand erstatten.`);
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
const inMedusa = (order.payment_collections ?? [])
|
||||||
|
.flatMap((c: any) => c.payments ?? [])
|
||||||
|
.flatMap((p: any) => p.refunds ?? [])
|
||||||
|
.reduce((summe: number, r: any) => summe + Number(r.amount ?? 0), 0);
|
||||||
|
|
||||||
|
// Nicht amountRefunded: Eine gerade angelegte Erstattung steht dort erst,
|
||||||
|
// wenn Mollie sie ausgeführt hat — bis dahin würde ein zweiter Aufruf sie
|
||||||
|
// doppelt anlegen. amountRemaining sinkt dagegen sofort.
|
||||||
|
const mollie: any = await getPayment(molliePaymentId);
|
||||||
|
const beiMollie = Number(mollie.amount?.value ?? 0) - Number(mollie.amountRemaining?.value ?? mollie.amount?.value ?? 0);
|
||||||
|
const offen = Math.round((inMedusa - beiMollie) * 100) / 100;
|
||||||
|
if (offen <= 0) return 0;
|
||||||
|
|
||||||
|
await refundMolliePayment({
|
||||||
|
paymentId: molliePaymentId,
|
||||||
|
amount: offen,
|
||||||
|
currency: String(order.currency_code ?? "eur").toUpperCase(),
|
||||||
|
description: `place4bees Erstattung Bestellung ${order.display_id}`,
|
||||||
|
});
|
||||||
|
logger.info(`[erstattung] Bestellung ${order.display_id}: ${offen.toFixed(2)} € bei Mollie erstattet (${molliePaymentId}).`);
|
||||||
|
return offen;
|
||||||
|
}
|
||||||
@@ -123,3 +123,38 @@ export async function chargeRecurring(params: {
|
|||||||
export async function getPayment(paymentId: string) {
|
export async function getPayment(paymentId: string) {
|
||||||
return getMollie().payments.get(paymentId);
|
return getMollie().payments.get(paymentId);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Einmalige Zahlung für eine normale Bestellung. Ohne Kunde und Mandat —
|
||||||
|
* die Zahlart wählt der Kunde auf Mollies Seite.
|
||||||
|
*/
|
||||||
|
export async function createOneOffPayment(params: {
|
||||||
|
amount: number;
|
||||||
|
description: string;
|
||||||
|
redirectUrl: string;
|
||||||
|
webhookUrl?: string;
|
||||||
|
metadata?: Record<string, unknown>;
|
||||||
|
currency?: string;
|
||||||
|
}) {
|
||||||
|
return getMollie().payments.create({
|
||||||
|
amount: money(params.amount, params.currency ?? "EUR"),
|
||||||
|
description: params.description,
|
||||||
|
redirectUrl: params.redirectUrl,
|
||||||
|
...(params.webhookUrl ? { webhookUrl: params.webhookUrl } : {}),
|
||||||
|
metadata: params.metadata as any,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Erstattet einen Betrag auf das Zahlungsmittel, mit dem gezahlt wurde. */
|
||||||
|
export async function refundMolliePayment(params: {
|
||||||
|
paymentId: string;
|
||||||
|
amount: number;
|
||||||
|
description: string;
|
||||||
|
currency?: string;
|
||||||
|
}) {
|
||||||
|
return getMollie().paymentRefunds.create({
|
||||||
|
paymentId: params.paymentId,
|
||||||
|
amount: money(params.amount, params.currency ?? "EUR"),
|
||||||
|
description: params.description,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|||||||
@@ -545,6 +545,126 @@ export function passwortZuruecksetzenMail(link: string) {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Schlusszeile für Mails, auf die man eine Rückfrage haben könnte. */
|
||||||
|
const RUECKFRAGE = `Fragen? Schreiben Sie uns an ${SHOP.email}.`;
|
||||||
|
|
||||||
|
/** Storno einer Bestellung. `erstattet` ist der Betrag, der zurückgeht. */
|
||||||
|
export function stornoMail(s: {
|
||||||
|
display_id: number | string;
|
||||||
|
shipping_address: Record<string, any> | null;
|
||||||
|
erstattet: number;
|
||||||
|
waehrung: string;
|
||||||
|
}) {
|
||||||
|
const geld =
|
||||||
|
s.erstattet > 0
|
||||||
|
? `Den bereits gezahlten Betrag von ${euro(s.erstattet, s.waehrung)} erstatten wir auf das Zahlungsmittel, mit dem Sie bezahlt haben. Je nach Bank dauert die Gutschrift einige Tage.`
|
||||||
|
: "Sie müssen nichts bezahlen.";
|
||||||
|
|
||||||
|
const htmlInhalt = RAHMEN(`
|
||||||
|
<h1 style="${STIL.h1}">Bestellung storniert</h1>
|
||||||
|
<p style="margin:0;color:${FARBE.text}">Bestellnummer ${s.display_id}</p>
|
||||||
|
<p style="margin:24px 0 0">${anrede(s.shipping_address)}</p>
|
||||||
|
<p style="margin:12px 0 0">wir haben Ihre Bestellung ${s.display_id} storniert. Sie wird nicht verschickt.</p>
|
||||||
|
<p style="${STIL.kasten}">${geld}</p>
|
||||||
|
<p style="margin:24px 0 0;color:${FARBE.text};font-size:13px">${RUECKFRAGE}</p>`);
|
||||||
|
|
||||||
|
const text = [
|
||||||
|
`Bestellung ${s.display_id} storniert`,
|
||||||
|
"",
|
||||||
|
anrede(s.shipping_address),
|
||||||
|
"",
|
||||||
|
`wir haben Ihre Bestellung ${s.display_id} storniert. Sie wird nicht verschickt.`,
|
||||||
|
"",
|
||||||
|
geld,
|
||||||
|
"",
|
||||||
|
RUECKFRAGE,
|
||||||
|
"",
|
||||||
|
`${SHOP.name} · ${SHOP.web} · ${SHOP.email}`,
|
||||||
|
].join("\n");
|
||||||
|
|
||||||
|
return { subject: `Ihre Bestellung ${s.display_id} wurde storniert`, html: htmlInhalt, text };
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Erstattung eines Betrags zu einer Bestellung. */
|
||||||
|
export function erstattungMail(e: {
|
||||||
|
display_id: number | string;
|
||||||
|
shipping_address: Record<string, any> | null;
|
||||||
|
betrag: number;
|
||||||
|
waehrung: string;
|
||||||
|
}) {
|
||||||
|
const betrag = euro(e.betrag, e.waehrung);
|
||||||
|
const htmlInhalt = RAHMEN(`
|
||||||
|
<h1 style="${STIL.h1}">Geld ist unterwegs</h1>
|
||||||
|
<p style="margin:0;color:${FARBE.text}">Bestellnummer ${e.display_id}</p>
|
||||||
|
<p style="margin:24px 0 0">${anrede(e.shipping_address)}</p>
|
||||||
|
<p style="margin:12px 0 0">
|
||||||
|
wir haben Ihnen zu Ihrer Bestellung ${e.display_id} <strong>${betrag}</strong> erstattet —
|
||||||
|
auf das Zahlungsmittel, mit dem Sie bezahlt haben.
|
||||||
|
</p>
|
||||||
|
<p style="${STIL.kasten}">Je nach Bank und Zahlart dauert es einige Tage, bis die Gutschrift auf Ihrem Konto erscheint.</p>
|
||||||
|
<p style="margin:24px 0 0;color:${FARBE.text};font-size:13px">${RUECKFRAGE}</p>`);
|
||||||
|
|
||||||
|
const text = [
|
||||||
|
`Erstattung zu Bestellung ${e.display_id}`,
|
||||||
|
"",
|
||||||
|
anrede(e.shipping_address),
|
||||||
|
"",
|
||||||
|
`wir haben Ihnen zu Ihrer Bestellung ${e.display_id} ${betrag} erstattet —`,
|
||||||
|
"auf das Zahlungsmittel, mit dem Sie bezahlt haben.",
|
||||||
|
"Je nach Bank und Zahlart dauert es einige Tage, bis die Gutschrift erscheint.",
|
||||||
|
"",
|
||||||
|
RUECKFRAGE,
|
||||||
|
"",
|
||||||
|
`${SHOP.name} · ${SHOP.web} · ${SHOP.email}`,
|
||||||
|
].join("\n");
|
||||||
|
|
||||||
|
return { subject: `Erstattung zu Ihrer Bestellung ${e.display_id}`, html: htmlInhalt, text };
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Abbuchung für eine Abo-Lieferung ist fehlgeschlagen. Nach mehreren
|
||||||
|
* Fehlversuchen ist das Abo pausiert — dann sagt die Mail das.
|
||||||
|
*/
|
||||||
|
export function aboZahlungFehlgeschlagenMail(a: {
|
||||||
|
shipping_address: Record<string, any> | null;
|
||||||
|
beschreibung: string;
|
||||||
|
pausiert: boolean;
|
||||||
|
kontoLink: string;
|
||||||
|
}) {
|
||||||
|
const titel = a.pausiert ? "Ihr Abo ist pausiert" : "Abbuchung hat nicht geklappt";
|
||||||
|
const absatz = a.pausiert
|
||||||
|
? `die Abbuchung für Ihr Honig-Abo (${a.beschreibung}) ist mehrmals fehlgeschlagen. Wir haben das Abo deshalb pausiert — es wird nichts geliefert und nichts abgebucht.`
|
||||||
|
: `die Abbuchung für die nächste Lieferung Ihres Honig-Abos (${a.beschreibung}) ist fehlgeschlagen. Die Lieferung geht deshalb noch nicht raus. In drei Tagen versuchen wir es erneut.`;
|
||||||
|
const hinweis = a.pausiert
|
||||||
|
? "Sobald Ihr Zahlungsmittel wieder funktioniert, können Sie das Abo im Kundenkonto fortsetzen."
|
||||||
|
: "Bitte prüfen Sie, ob Ihr Zahlungsmittel noch gültig und das Konto gedeckt ist.";
|
||||||
|
|
||||||
|
const htmlInhalt = RAHMEN(`
|
||||||
|
<h1 style="${STIL.h1}">${titel}</h1>
|
||||||
|
<p style="margin:24px 0 0">${anrede(a.shipping_address)}</p>
|
||||||
|
<p style="margin:12px 0 0">${absatz}</p>
|
||||||
|
<p style="${STIL.kasten}">${hinweis}</p>
|
||||||
|
<p style="margin:24px 0 0"><a href="${html(a.kontoLink)}" style="${STIL.knopf}">Abo im Kundenkonto ansehen</a></p>
|
||||||
|
<p style="margin:24px 0 0;color:${FARBE.text};font-size:13px">${RUECKFRAGE}</p>`);
|
||||||
|
|
||||||
|
const text = [
|
||||||
|
titel,
|
||||||
|
"",
|
||||||
|
anrede(a.shipping_address),
|
||||||
|
"",
|
||||||
|
absatz,
|
||||||
|
"",
|
||||||
|
hinweis,
|
||||||
|
a.kontoLink,
|
||||||
|
"",
|
||||||
|
RUECKFRAGE,
|
||||||
|
"",
|
||||||
|
`${SHOP.name} · ${SHOP.web} · ${SHOP.email}`,
|
||||||
|
].join("\n");
|
||||||
|
|
||||||
|
return { subject: `${titel} – place4bees Honig-Abo`, html: htmlInhalt, text };
|
||||||
|
}
|
||||||
|
|
||||||
/** Versandnachricht an den Beschenkten — dieselbe Sendung, ohne Beträge. */
|
/** Versandnachricht an den Beschenkten — dieselbe Sendung, ohne Beträge. */
|
||||||
export function geschenkVersandnachricht(
|
export function geschenkVersandnachricht(
|
||||||
empfaengerName: string,
|
empfaengerName: string,
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
/**
|
/**
|
||||||
* Alle Mails, die der Shop verschicken kann, mit Beispieldaten — um nach
|
* Alle Mails, die der Shop verschicken kann (18), mit Beispieldaten — um nach
|
||||||
* einer Änderung an Text oder Gestaltung alles auf einmal anzusehen.
|
* einer Änderung an Text oder Gestaltung alles auf einmal anzusehen.
|
||||||
*
|
*
|
||||||
* npx medusa exec ./src/scripts/mail-muster.ts
|
* npx medusa exec ./src/scripts/mail-muster.ts
|
||||||
@@ -25,6 +25,9 @@ import {
|
|||||||
kuendigungsbestaetigung,
|
kuendigungsbestaetigung,
|
||||||
emailBestaetigenMail,
|
emailBestaetigenMail,
|
||||||
passwortZuruecksetzenMail,
|
passwortZuruecksetzenMail,
|
||||||
|
stornoMail,
|
||||||
|
erstattungMail,
|
||||||
|
aboZahlungFehlgeschlagenMail,
|
||||||
} from "../lib/order-emails";
|
} from "../lib/order-emails";
|
||||||
import { anfrageMail } from "../lib/contact-email";
|
import { anfrageMail } from "../lib/contact-email";
|
||||||
import { MAIL_LOGO_PNG_BASE64 } from "../lib/mail-logo";
|
import { MAIL_LOGO_PNG_BASE64 } from "../lib/mail-logo";
|
||||||
@@ -98,6 +101,16 @@ const muster: [string, { subject: string; html: string; text: string }][] = [
|
|||||||
})],
|
})],
|
||||||
["E-Mail bestätigen", emailBestaetigenMail("https://place4bees.com/konto/bestaetigen?code=MUSTER")],
|
["E-Mail bestätigen", emailBestaetigenMail("https://place4bees.com/konto/bestaetigen?code=MUSTER")],
|
||||||
["Passwort zurücksetzen", passwortZuruecksetzenMail("https://place4bees.com/konto/passwort-neu?token=MUSTER")],
|
["Passwort zurücksetzen", passwortZuruecksetzenMail("https://place4bees.com/konto/passwort-neu?token=MUSTER")],
|
||||||
|
["Storno", stornoMail({ display_id: 1042, shipping_address: adresse, erstattet: 58.29, waehrung: "eur" })],
|
||||||
|
["Erstattung", erstattungMail({ display_id: 1042, shipping_address: adresse, betrag: 6.9, waehrung: "eur" })],
|
||||||
|
["Abo: Abbuchung fehlgeschlagen", aboZahlungFehlgeschlagenMail({
|
||||||
|
shipping_address: adresse, beschreibung: "250 Gramm, monatlich", pausiert: false,
|
||||||
|
kontoLink: "https://place4bees.com/konto/abos",
|
||||||
|
})],
|
||||||
|
["Abo: pausiert nach Fehlversuchen", aboZahlungFehlgeschlagenMail({
|
||||||
|
shipping_address: adresse, beschreibung: "250 Gramm, monatlich", pausiert: true,
|
||||||
|
kontoLink: "https://place4bees.com/konto/abos",
|
||||||
|
})],
|
||||||
["Kontaktanfrage (intern)", anfrageMail({
|
["Kontaktanfrage (intern)", anfrageMail({
|
||||||
name: "Erika Mustermann", email: "erika@example.com", quelle: "Ihr Projekt", seite: "/business/kontakt",
|
name: "Erika Mustermann", email: "erika@example.com", quelle: "Ihr Projekt", seite: "/business/kontakt",
|
||||||
nachricht: "Hallo,\nwir würden gern zwei Bienenvölker auf unserem Firmendach aufstellen. Wie läuft das ab?\n\nViele Grüße",
|
nachricht: "Hallo,\nwir würden gern zwei Bienenvölker auf unserem Firmendach aufstellen. Wie läuft das ab?\n\nViele Grüße",
|
||||||
|
|||||||
@@ -0,0 +1,68 @@
|
|||||||
|
import type { SubscriberArgs, SubscriberConfig } from "@medusajs/framework";
|
||||||
|
import { Modules } from "@medusajs/framework/utils";
|
||||||
|
import { stornoMail } from "../lib/order-emails";
|
||||||
|
import { erstattungenMitMollieAbgleichen } from "../lib/mollie-erstattung";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Storno einer Bestellung: Geld bei Mollie zurück und Kunde informieren.
|
||||||
|
*
|
||||||
|
* Beim Storno erstattet Medusa erfasste Zahlungen selbst, löst dabei aber
|
||||||
|
* kein payment.refunded aus — deshalb wird hier mit Mollie abgeglichen.
|
||||||
|
*
|
||||||
|
* Keine Mail, wenn die Bestellung wegen einer gescheiterten Abo-Abbuchung
|
||||||
|
* storniert wurde: Dazu geht schon eine eigene Mail raus.
|
||||||
|
*/
|
||||||
|
export default async function orderCanceledEmail({ event, container }: SubscriberArgs<{ id: string }>) {
|
||||||
|
const logger = container.resolve("logger");
|
||||||
|
const orderId = event.data.id;
|
||||||
|
|
||||||
|
try {
|
||||||
|
const erstattetBeiMollie = await erstattungenMitMollieAbgleichen(container, orderId, logger);
|
||||||
|
|
||||||
|
const query = container.resolve("query");
|
||||||
|
const { data: orders } = await query.graph({
|
||||||
|
entity: "order",
|
||||||
|
fields: [
|
||||||
|
"id",
|
||||||
|
"display_id",
|
||||||
|
"email",
|
||||||
|
"currency_code",
|
||||||
|
"metadata",
|
||||||
|
"shipping_address.*",
|
||||||
|
"payment_collections.payments.refunds.amount",
|
||||||
|
],
|
||||||
|
filters: { id: orderId },
|
||||||
|
});
|
||||||
|
const order: any = orders?.[0];
|
||||||
|
if (!order?.email || order.metadata?.storno_grund === "abo_abbuchung") return;
|
||||||
|
|
||||||
|
// Alles, was zu dieser Bestellung erstattet ist — auch per Rechnung
|
||||||
|
// bezahltes, das im Admin als erstattet verbucht wurde.
|
||||||
|
const erstattet = (order.payment_collections ?? [])
|
||||||
|
.flatMap((c: any) => c.payments ?? [])
|
||||||
|
.flatMap((p: any) => p.refunds ?? [])
|
||||||
|
.reduce((summe: number, r: any) => summe + Number(r.amount ?? 0), 0);
|
||||||
|
|
||||||
|
await container.resolve<any>(Modules.NOTIFICATION).createNotifications({
|
||||||
|
to: order.email,
|
||||||
|
channel: "email",
|
||||||
|
template: "order-canceled",
|
||||||
|
content: stornoMail({
|
||||||
|
display_id: order.display_id,
|
||||||
|
shipping_address: order.shipping_address ?? null,
|
||||||
|
erstattet: Math.max(erstattet, erstattetBeiMollie),
|
||||||
|
waehrung: order.currency_code,
|
||||||
|
}),
|
||||||
|
data: { order_id: order.id, display_id: order.display_id },
|
||||||
|
});
|
||||||
|
logger.info(`[mail] Stornomail ${order.display_id} an ${order.email}.`);
|
||||||
|
} catch (error) {
|
||||||
|
logger.error(
|
||||||
|
`[storno] Bestellung ${orderId}: ${error instanceof Error ? error.message : (error as any)?.message ?? String(error)}`
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export const config: SubscriberConfig = {
|
||||||
|
event: "order.canceled",
|
||||||
|
};
|
||||||
@@ -0,0 +1,65 @@
|
|||||||
|
import type { SubscriberArgs, SubscriberConfig } from "@medusajs/framework";
|
||||||
|
import { Modules } from "@medusajs/framework/utils";
|
||||||
|
import { erstattungMail } from "../lib/order-emails";
|
||||||
|
import { erstattungenMitMollieAbgleichen } from "../lib/mollie-erstattung";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Erstattung über "Refund" im Admin: Geld bei Mollie zurück und Kunde
|
||||||
|
* informieren — mit dem Betrag genau dieser Erstattung.
|
||||||
|
*/
|
||||||
|
export default async function paymentRefundedEmail({ event, container }: SubscriberArgs<{ id: string }>) {
|
||||||
|
const logger = container.resolve("logger");
|
||||||
|
const paymentId = event.data.id;
|
||||||
|
|
||||||
|
try {
|
||||||
|
const query = container.resolve("query");
|
||||||
|
const { data: zahlungen } = await query.graph({
|
||||||
|
entity: "payment",
|
||||||
|
fields: ["id", "currency_code", "refunds.amount", "refunds.created_at", "payment_collection.order.id"],
|
||||||
|
filters: { id: paymentId },
|
||||||
|
});
|
||||||
|
const zahlung: any = zahlungen?.[0];
|
||||||
|
const orderId = zahlung?.payment_collection?.order?.id;
|
||||||
|
if (!orderId) {
|
||||||
|
logger.warn(`[erstattung] Zahlung ${paymentId} gehört zu keiner Bestellung.`);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
await erstattungenMitMollieAbgleichen(container, orderId, logger);
|
||||||
|
|
||||||
|
const letzte = [...(zahlung.refunds ?? [])].sort(
|
||||||
|
(a: any, b: any) => new Date(b.created_at).getTime() - new Date(a.created_at).getTime()
|
||||||
|
)[0];
|
||||||
|
if (!letzte) return;
|
||||||
|
|
||||||
|
const { data: orders } = await query.graph({
|
||||||
|
entity: "order",
|
||||||
|
fields: ["id", "display_id", "email", "shipping_address.*"],
|
||||||
|
filters: { id: orderId },
|
||||||
|
});
|
||||||
|
const order: any = orders?.[0];
|
||||||
|
if (!order?.email) return;
|
||||||
|
|
||||||
|
await container.resolve<any>(Modules.NOTIFICATION).createNotifications({
|
||||||
|
to: order.email,
|
||||||
|
channel: "email",
|
||||||
|
template: "payment-refunded",
|
||||||
|
content: erstattungMail({
|
||||||
|
display_id: order.display_id,
|
||||||
|
shipping_address: order.shipping_address ?? null,
|
||||||
|
betrag: Number(letzte.amount),
|
||||||
|
waehrung: zahlung.currency_code,
|
||||||
|
}),
|
||||||
|
data: { order_id: order.id, payment_id: paymentId },
|
||||||
|
});
|
||||||
|
logger.info(`[mail] Erstattungsmail ${order.display_id} an ${order.email} (${Number(letzte.amount).toFixed(2)} €).`);
|
||||||
|
} catch (error) {
|
||||||
|
logger.error(
|
||||||
|
`[erstattung] Zahlung ${paymentId}: ${error instanceof Error ? error.message : (error as any)?.message ?? String(error)}`
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export const config: SubscriberConfig = {
|
||||||
|
event: "payment.refunded",
|
||||||
|
};
|
||||||
@@ -55,6 +55,7 @@ const currentPath = Astro.url.pathname;
|
|||||||
{layer === "shop" && (
|
{layer === "shop" && (
|
||||||
<div class="ml-auto flex items-center gap-4">
|
<div class="ml-auto flex items-center gap-4">
|
||||||
<a
|
<a
|
||||||
|
id="konto-link"
|
||||||
href={loggedIn ? "/konto" : "/konto/anmelden"}
|
href={loggedIn ? "/konto" : "/konto/anmelden"}
|
||||||
class="text-[0.9375rem] text-white/70 transition-colors hover:text-white"
|
class="text-[0.9375rem] text-white/70 transition-colors hover:text-white"
|
||||||
>
|
>
|
||||||
@@ -126,6 +127,17 @@ const currentPath = Astro.url.pathname;
|
|||||||
<script>
|
<script>
|
||||||
import { getCart } from "../lib/cart";
|
import { getCart } from "../lib/cart";
|
||||||
import { getCartIdClient } from "../lib/cartCookie";
|
import { getCartIdClient } from "../lib/cartCookie";
|
||||||
|
import { getCustomerTokenClient } from "../lib/customerCookie";
|
||||||
|
|
||||||
|
// Statisch erzeugte Seiten (z. B. die Dankeseite) kennen beim Bauen kein
|
||||||
|
// Cookie und zeigen deshalb immer "Anmelden". Im Browser nachziehen.
|
||||||
|
function refreshKontoLink() {
|
||||||
|
const link = document.getElementById("konto-link") as HTMLAnchorElement | null;
|
||||||
|
if (!link) return;
|
||||||
|
const angemeldet = Boolean(getCustomerTokenClient());
|
||||||
|
link.textContent = angemeldet ? "Mein Konto" : "Anmelden";
|
||||||
|
link.href = angemeldet ? "/konto" : "/konto/anmelden";
|
||||||
|
}
|
||||||
|
|
||||||
async function refreshCartBadge(animate = false) {
|
async function refreshCartBadge(animate = false) {
|
||||||
const badge = document.getElementById("cart-badge");
|
const badge = document.getElementById("cart-badge");
|
||||||
@@ -159,6 +171,9 @@ const currentPath = Astro.url.pathname;
|
|||||||
|
|
||||||
// Beim Seitenaufbau still setzen, sonst poppt der Zähler bei jeder
|
// Beim Seitenaufbau still setzen, sonst poppt der Zähler bei jeder
|
||||||
// Navigation. Nur eine echte Warenkorbänderung darf ihn anspringen lassen.
|
// Navigation. Nur eine echte Warenkorbänderung darf ihn anspringen lassen.
|
||||||
document.addEventListener("astro:page-load", () => refreshCartBadge(false));
|
document.addEventListener("astro:page-load", () => {
|
||||||
|
refreshKontoLink();
|
||||||
|
refreshCartBadge(false);
|
||||||
|
});
|
||||||
window.addEventListener("cart:updated", () => refreshCartBadge(true));
|
window.addEventListener("cart:updated", () => refreshCartBadge(true));
|
||||||
</script>
|
</script>
|
||||||
|
|||||||
@@ -201,6 +201,22 @@ export async function startSubscriptionCheckout(payload: {
|
|||||||
return data;
|
return data;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Startet die Online-Zahlung einer normalen Bestellung bei Mollie. */
|
||||||
|
export async function startMollieCheckout(cartId: string): Promise<{ checkout_url: string }> {
|
||||||
|
return medusaFetch("/store/mollie/checkout", {
|
||||||
|
method: "POST",
|
||||||
|
body: JSON.stringify({ cart_id: cartId }),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Stand der Online-Zahlung, für die Rückkehrseite. */
|
||||||
|
export async function getMollieStatus(cartId: string): Promise<{
|
||||||
|
status: "abgeschlossen" | "wartet" | "abgebrochen";
|
||||||
|
order?: { id: string; display_id: number; email: string };
|
||||||
|
}> {
|
||||||
|
return medusaFetch(`/store/mollie/status?cart_id=${encodeURIComponent(cartId)}`);
|
||||||
|
}
|
||||||
|
|
||||||
export async function addLineItem(
|
export async function addLineItem(
|
||||||
cartId: string,
|
cartId: string,
|
||||||
variantId: string,
|
variantId: string,
|
||||||
|
|||||||
@@ -0,0 +1,96 @@
|
|||||||
|
---
|
||||||
|
export const prerender = false;
|
||||||
|
|
||||||
|
import Layout from "../../layouts/Layout.astro";
|
||||||
|
|
||||||
|
// Mollie schickt den Kunden nach der Online-Zahlung hierher zurück. Die
|
||||||
|
// Bestellung entsteht im Webhook, nicht hier — die Seite wartet darauf und
|
||||||
|
// leitet dann auf die gewohnte Dankeseite weiter.
|
||||||
|
const cartId = Astro.url.searchParams.get("cart") ?? "";
|
||||||
|
---
|
||||||
|
|
||||||
|
<Layout title="Zahlung" description="Ihre Zahlung bei place4bees wird bestätigt.">
|
||||||
|
<section class="honeycomb-bg pt-24 pb-[var(--section-y)] sm:pt-28">
|
||||||
|
<div class="mx-auto max-w-[46rem] px-[var(--gutter)]">
|
||||||
|
<div class="surface p-9 shadow-xs sm:p-14" data-cart={cartId}>
|
||||||
|
<img src="/images/bee-single.png" alt="" class="h-10 w-auto opacity-70" />
|
||||||
|
|
||||||
|
<div id="zahlung-pending">
|
||||||
|
<h1 class="mt-7 max-w-[18ch]">Ihre Zahlung wird bestätigt</h1>
|
||||||
|
<p class="mt-5 text-[1.0625rem] leading-relaxed text-brand-text">
|
||||||
|
Das dauert meist nur wenige Sekunden.
|
||||||
|
</p>
|
||||||
|
<div class="mt-8 flex flex-col gap-2" aria-hidden="true">
|
||||||
|
<div class="skeleton h-4 w-2/3"></div>
|
||||||
|
<div class="skeleton h-4 w-1/2"></div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div id="zahlung-abgebrochen" hidden>
|
||||||
|
<h1 class="mt-7 max-w-[20ch]">Die Zahlung wurde nicht abgeschlossen</h1>
|
||||||
|
<p class="mt-5 text-[1.0625rem] leading-relaxed text-brand-text">
|
||||||
|
Es wurde nichts abgebucht, und Ihr Warenkorb ist noch da. Sie können es noch einmal
|
||||||
|
versuchen oder eine andere Zahlungsart wählen.
|
||||||
|
</p>
|
||||||
|
<a href="/kasse" class="btn btn-primary mt-9">Zurück zur Kasse</a>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div id="zahlung-langsam" hidden>
|
||||||
|
<h1 class="mt-7 max-w-[20ch]">Zahlung wird noch geprüft</h1>
|
||||||
|
<p class="mt-5 text-[1.0625rem] leading-relaxed text-brand-text">
|
||||||
|
Bei einer Überweisung kann das ein bis zwei Bankarbeitstage dauern. Sobald die Zahlung
|
||||||
|
bestätigt ist, bekommen Sie die Bestellbestätigung per E-Mail. Sie müssen nichts weiter tun.
|
||||||
|
</p>
|
||||||
|
<a href="/shop" class="link-underline mt-8">
|
||||||
|
Weiter einkaufen
|
||||||
|
<svg viewBox="0 0 20 20" class="h-4 w-4 text-brand-primary" fill="none" stroke="currentColor" stroke-width="1.75" aria-hidden="true">
|
||||||
|
<path d="M4 10h12M11 5l5 5-5 5" stroke-linecap="round" stroke-linejoin="round" />
|
||||||
|
</svg>
|
||||||
|
</a>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
</Layout>
|
||||||
|
|
||||||
|
<script>
|
||||||
|
import { getMollieStatus } from "../../lib/cart";
|
||||||
|
import { clearCartIdClient } from "../../lib/cartCookie";
|
||||||
|
|
||||||
|
// astro:page-load feuert beim ersten Laden und nach jedem
|
||||||
|
// View-Transition-Wechsel.
|
||||||
|
document.addEventListener("astro:page-load", async () => {
|
||||||
|
const wrap = document.querySelector<HTMLElement>("[data-cart]");
|
||||||
|
const cartId = wrap?.dataset.cart;
|
||||||
|
if (!wrap || !cartId) return;
|
||||||
|
|
||||||
|
const zeige = (id: string) => {
|
||||||
|
document.getElementById("zahlung-pending")!.hidden = true;
|
||||||
|
document.getElementById(id)!.hidden = false;
|
||||||
|
};
|
||||||
|
|
||||||
|
// Höchstens 30 Sekunden warten, danach die ehrliche Auskunft.
|
||||||
|
const deadline = Date.now() + 30_000;
|
||||||
|
while (Date.now() < deadline) {
|
||||||
|
try {
|
||||||
|
const stand = await getMollieStatus(cartId);
|
||||||
|
if (stand.status === "abgeschlossen" && stand.order) {
|
||||||
|
// Wie nach jeder anderen Bestellung: Die Dankeseite liest sie von hier.
|
||||||
|
sessionStorage.setItem("last_order", JSON.stringify(stand.order));
|
||||||
|
clearCartIdClient();
|
||||||
|
window.dispatchEvent(new CustomEvent("cart:updated"));
|
||||||
|
window.location.replace("/bestellung/danke");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (stand.status === "abgebrochen") {
|
||||||
|
zeige("zahlung-abgebrochen");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
// Kurzer Aussetzer — weiter versuchen bis zur Frist.
|
||||||
|
}
|
||||||
|
await new Promise((resolve) => setTimeout(resolve, 2000));
|
||||||
|
}
|
||||||
|
zeige("zahlung-langsam");
|
||||||
|
});
|
||||||
|
</script>
|
||||||
@@ -374,6 +374,7 @@ const money = (amount: number) =>
|
|||||||
createPaymentSession,
|
createPaymentSession,
|
||||||
completeCart,
|
completeCart,
|
||||||
startSubscriptionCheckout,
|
startSubscriptionCheckout,
|
||||||
|
startMollieCheckout,
|
||||||
getCart,
|
getCart,
|
||||||
applyGiftCard,
|
applyGiftCard,
|
||||||
removeGiftCard,
|
removeGiftCard,
|
||||||
@@ -535,6 +536,15 @@ const money = (amount: number) =>
|
|||||||
const providerId = String(data.get("payment_provider_id") || "");
|
const providerId = String(data.get("payment_provider_id") || "");
|
||||||
if (!providerId) throw new Error("Bitte wählen Sie eine Zahlungsart.");
|
if (!providerId) throw new Error("Bitte wählen Sie eine Zahlungsart.");
|
||||||
|
|
||||||
|
// Online-Zahlung: Weiter zu Mollie. Abgeschlossen wird erst, wenn
|
||||||
|
// Mollie die Zahlung bestätigt — wie beim Abo.
|
||||||
|
if (providerId === "mollie") {
|
||||||
|
const { checkout_url } = await startMollieCheckout(cartId);
|
||||||
|
if (!checkout_url) throw new Error("Zahlungsanbieter lieferte keine Weiterleitung.");
|
||||||
|
window.location.href = checkout_url;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
const paymentCollection = await createPaymentCollection(cartId);
|
const paymentCollection = await createPaymentCollection(cartId);
|
||||||
await createPaymentSession(paymentCollection.id, providerId);
|
await createPaymentSession(paymentCollection.id, providerId);
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user