Phase 9E (Backbone): Stripe-Produkt-Sync und Webhook-Verarbeitung mit STR-Spiegelung
- billing:sync-stripe-plans: legt die Tarife als Netto-Produkte/Preise
(tax_behavior exclusive, EUR) in Stripe an und pflegt die IDs zurueck
nach plans; idempotent, --dry-run. Gegen Stripe Test-Mode ausgefuehrt —
alle 4 Tiers verknuepft.
- ProcessStripeWebhook (Listener auf Cashier WebhookReceived):
- invoice.payment_succeeded -> Spiegelung in den lokalen STR-Kreis
(fortlaufende Nummer via InvoiceNumberGenerator, Adress-Snapshot
bevorzugt aus dem Stripe-Payload inkl. lokaler USt-ID, Status paid,
idempotent gegen doppelte Zustellung)
- checkout.session.completed -> markiert den referenzierten
single_purchases-Datensatz als bezahlt (Metadata single_purchase_id)
- CASHIER_CURRENCY=eur (+ Locale de_DE); Cashier-Webhook-Route aktiv
- Doku: Billing-Referenz §7 + Phase-9-Plan (9E-Backbone) aktualisiert
Offen fuer 9E-Rest: Checkout-Flows (Abo + Einmalkauf), Webhook-Endpoint
im Stripe-Dashboard + STRIPE_WEBHOOK_SECRET, Slot-Logik auf
Plan-Kontingent (fachliche Frage: Grandfathered = unbegrenzt?).
Tests: StripeWebhookProcessingTest (7, inkl. Event-Wiring).
Suite: 497 passed, 4 skipped. Pint clean.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
parent
62e6b7e70f
commit
38fab64e10
5 changed files with 400 additions and 6 deletions
96
app/Console/Commands/SyncStripePlans.php
Normal file
96
app/Console/Commands/SyncStripePlans.php
Normal file
|
|
@ -0,0 +1,96 @@
|
|||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use App\Models\Plan;
|
||||
use Illuminate\Console\Command;
|
||||
use Laravel\Cashier\Cashier;
|
||||
|
||||
/**
|
||||
* Legt die Tarife aus `plans` als Produkte/Preise in Stripe an und pflegt
|
||||
* die Stripe-IDs zurück (Phase 9E).
|
||||
*
|
||||
* Preise sind NETTO (`tax_behavior: exclusive`) — die Steuer wird im
|
||||
* Checkout ergänzt (Entscheidung 12.06.2026). Idempotent: vorhandene
|
||||
* IDs werden übersprungen; Preisänderungen erzeugen in Stripe bewusst
|
||||
* neue Price-Objekte (Stripe-Preise sind unveränderlich), der alte Preis
|
||||
* bleibt für Bestandsabos gültig.
|
||||
*/
|
||||
class SyncStripePlans extends Command
|
||||
{
|
||||
protected $signature = 'billing:sync-stripe-plans
|
||||
{--dry-run : Nur anzeigen, was angelegt würde}';
|
||||
|
||||
protected $description = 'Synchronisiert die Tarife aus plans als Netto-Produkte/Preise nach Stripe';
|
||||
|
||||
public function handle(): int
|
||||
{
|
||||
if (! config('cashier.secret')) {
|
||||
$this->error('STRIPE_SECRET ist nicht gesetzt.');
|
||||
|
||||
return self::FAILURE;
|
||||
}
|
||||
|
||||
$dryRun = (bool) $this->option('dry-run');
|
||||
$stripe = Cashier::stripe();
|
||||
|
||||
foreach (Plan::query()->active()->get() as $plan) {
|
||||
if ($plan->stripe_product_id && $plan->stripe_price_id_monthly && $plan->stripe_price_id_yearly) {
|
||||
$this->line("{$plan->slug}: vollständig verknüpft, übersprungen.");
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
if ($dryRun) {
|
||||
$this->line(sprintf(
|
||||
'[dry-run] %s: Produkt + Preise %s €/Monat, %s €/Jahr (netto) anlegen.',
|
||||
$plan->slug,
|
||||
number_format($plan->monthly_price_cents / 100, 2, ',', '.'),
|
||||
number_format($plan->yearly_price_cents / 100, 2, ',', '.'),
|
||||
));
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
$productId = $plan->stripe_product_id;
|
||||
|
||||
if (! $productId) {
|
||||
$product = $stripe->products->create([
|
||||
'name' => $plan->name,
|
||||
'metadata' => ['plan_slug' => $plan->slug],
|
||||
]);
|
||||
$productId = $product->id;
|
||||
}
|
||||
|
||||
$monthlyId = $plan->stripe_price_id_monthly
|
||||
?: $this->createPrice($stripe, $productId, $plan, $plan->monthly_price_cents, 'month');
|
||||
|
||||
$yearlyId = $plan->stripe_price_id_yearly
|
||||
?: $this->createPrice($stripe, $productId, $plan, $plan->yearly_price_cents, 'year');
|
||||
|
||||
$plan->update([
|
||||
'stripe_product_id' => $productId,
|
||||
'stripe_price_id_monthly' => $monthlyId,
|
||||
'stripe_price_id_yearly' => $yearlyId,
|
||||
]);
|
||||
|
||||
$this->info("{$plan->slug}: {$productId} · monatlich {$monthlyId} · jährlich {$yearlyId}");
|
||||
}
|
||||
|
||||
return self::SUCCESS;
|
||||
}
|
||||
|
||||
private function createPrice(object $stripe, string $productId, Plan $plan, int $unitAmount, string $interval): string
|
||||
{
|
||||
$price = $stripe->prices->create([
|
||||
'product' => $productId,
|
||||
'currency' => strtolower($plan->currency),
|
||||
'unit_amount' => $unitAmount,
|
||||
'tax_behavior' => 'exclusive',
|
||||
'recurring' => ['interval' => $interval],
|
||||
'metadata' => ['plan_slug' => $plan->slug],
|
||||
]);
|
||||
|
||||
return $price->id;
|
||||
}
|
||||
}
|
||||
145
app/Listeners/ProcessStripeWebhook.php
Normal file
145
app/Listeners/ProcessStripeWebhook.php
Normal file
|
|
@ -0,0 +1,145 @@
|
|||
<?php
|
||||
|
||||
namespace App\Listeners;
|
||||
|
||||
use App\Enums\InvoiceStatus;
|
||||
use App\Enums\SinglePurchaseStatus;
|
||||
use App\Models\Invoice;
|
||||
use App\Models\InvoiceBillingAddress;
|
||||
use App\Models\SinglePurchase;
|
||||
use App\Models\User;
|
||||
use App\Services\Billing\InvoiceNumberGenerator;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
use Laravel\Cashier\Cashier;
|
||||
use Laravel\Cashier\Events\WebhookReceived;
|
||||
|
||||
/**
|
||||
* Verarbeitet Stripe-Webhooks über das Cashier-Event (Phase 9E).
|
||||
*
|
||||
* Cashier selbst pflegt den Subscription-Zustand; dieser Listener ergänzt
|
||||
* die beiden projektspezifischen Schritte des hybriden Rechnungsmodells:
|
||||
*
|
||||
* 1. **STR-Spiegelung**: Jede bezahlte Stripe-Rechnung wird als lokale
|
||||
* Rechnung im STR-Kreis gespiegelt (fortlaufende Nummer aus dem
|
||||
* InvoiceNumberGenerator, Adress-Snapshot aus dem Stripe-Payload).
|
||||
* Stripe bleibt Zahlungs-/Beleg-Quelle, `invoices` der lückenlose
|
||||
* lokale Rechnungsausgang.
|
||||
* 2. **Einmalkauf-Erfüllung**: `checkout.session.completed` markiert den
|
||||
* referenzierten `single_purchases`-Datensatz als bezahlt
|
||||
* (Metadata-Schlüssel `single_purchase_id`, gesetzt beim Checkout).
|
||||
*/
|
||||
class ProcessStripeWebhook
|
||||
{
|
||||
public function __construct(private readonly InvoiceNumberGenerator $numbers) {}
|
||||
|
||||
public function handle(WebhookReceived $event): void
|
||||
{
|
||||
match ($event->payload['type'] ?? null) {
|
||||
'invoice.payment_succeeded' => $this->mirrorPaidInvoice($event->payload['data']['object'] ?? []),
|
||||
'checkout.session.completed' => $this->fulfillSinglePurchase($event->payload['data']['object'] ?? []),
|
||||
default => null,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $stripeInvoice
|
||||
*/
|
||||
private function mirrorPaidInvoice(array $stripeInvoice): void
|
||||
{
|
||||
$stripeInvoiceId = $stripeInvoice['id'] ?? null;
|
||||
|
||||
if (! $stripeInvoiceId) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Idempotent: Stripe liefert Webhooks mindestens einmal.
|
||||
if (Invoice::query()->where('stripe_invoice_id', $stripeInvoiceId)->exists()) {
|
||||
return;
|
||||
}
|
||||
|
||||
$user = Cashier::findBillable($stripeInvoice['customer'] ?? null);
|
||||
|
||||
if (! $user instanceof User) {
|
||||
Log::warning('STR-Spiegelung übersprungen: kein Billable zum Stripe-Customer.', [
|
||||
'stripe_invoice_id' => $stripeInvoiceId,
|
||||
'stripe_customer' => $stripeInvoice['customer'] ?? null,
|
||||
]);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$subtotal = (int) ($stripeInvoice['subtotal'] ?? 0);
|
||||
$tax = (int) ($stripeInvoice['tax'] ?? 0);
|
||||
$total = (int) ($stripeInvoice['total'] ?? $subtotal + $tax);
|
||||
|
||||
$invoice = Invoice::query()->create([
|
||||
'user_id' => $user->id,
|
||||
'invoice_billing_address_id' => $this->snapshotAddress($user, $stripeInvoice)->id,
|
||||
'number' => $this->numbers->nextStripeNumber(),
|
||||
'status' => InvoiceStatus::Paid->value,
|
||||
'amount_cents' => $subtotal,
|
||||
'tax_cents' => $tax,
|
||||
'total_cents' => $total,
|
||||
'currency' => strtoupper((string) ($stripeInvoice['currency'] ?? 'eur')),
|
||||
'is_netto' => $tax === 0,
|
||||
'invoice_date' => now()->toDateString(),
|
||||
'paid_at' => now(),
|
||||
'stripe_invoice_id' => $stripeInvoiceId,
|
||||
]);
|
||||
|
||||
Log::info('Stripe-Rechnung in den STR-Kreis gespiegelt.', [
|
||||
'number' => $invoice->number,
|
||||
'stripe_invoice_id' => $stripeInvoiceId,
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Adress-Snapshot pro Rechnung: bevorzugt die Adresse aus dem
|
||||
* Stripe-Payload (maßgeblich für genau diese Rechnung), sonst die
|
||||
* lokale Rechnungsadresse des Users.
|
||||
*
|
||||
* @param array<string, mixed> $stripeInvoice
|
||||
*/
|
||||
private function snapshotAddress(User $user, array $stripeInvoice): InvoiceBillingAddress
|
||||
{
|
||||
$stripeAddress = $stripeInvoice['customer_address'] ?? null;
|
||||
$local = $user->billingAddress;
|
||||
|
||||
return InvoiceBillingAddress::query()->create([
|
||||
'name' => $stripeInvoice['customer_name'] ?? $local?->name ?? $user->name,
|
||||
'address1' => $stripeAddress['line1'] ?? $local?->address1 ?? '',
|
||||
'address2' => $stripeAddress['line2'] ?? $local?->address2,
|
||||
'postal_code' => $stripeAddress['postal_code'] ?? $local?->postal_code ?? '',
|
||||
'city' => $stripeAddress['city'] ?? $local?->city ?? '',
|
||||
'country_code' => $stripeAddress['country'] ?? $local?->country_code ?? 'DE',
|
||||
'vat_id' => $local?->vat_id,
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $session
|
||||
*/
|
||||
private function fulfillSinglePurchase(array $session): void
|
||||
{
|
||||
$purchaseId = $session['metadata']['single_purchase_id'] ?? null;
|
||||
|
||||
if (! $purchaseId) {
|
||||
return;
|
||||
}
|
||||
|
||||
$purchase = SinglePurchase::query()->find((int) $purchaseId);
|
||||
|
||||
if (! $purchase || $purchase->status !== SinglePurchaseStatus::Pending) {
|
||||
return;
|
||||
}
|
||||
|
||||
$purchase->update([
|
||||
'status' => SinglePurchaseStatus::Paid->value,
|
||||
'paid_at' => now(),
|
||||
'stripe_checkout_session_id' => $session['id'] ?? $purchase->stripe_checkout_session_id,
|
||||
'stripe_payment_intent_id' => $session['payment_intent'] ?? null,
|
||||
]);
|
||||
|
||||
Log::info('Einmalkauf als bezahlt markiert.', ['single_purchase_id' => $purchase->id]);
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue