Neuer Zahlungsweg PAYMENT_DRIVER=stripe: Checkout Session über die Stripe-API (Http-Client, kein SDK), Freischaltung nur durch die signierte Meldung an POST /stripe/webhook (Signatur und Zeittoleranz geprüft, Betrag und Währung gegen die Bestellung, wiederholte Meldung wirkungslos). Nur Testschlüssel (sk_test_), nie in Produktion; Standard bleibt der Testweg. Die Freischaltung nutzt denselben Weg wie die Testzahlung (Checkout::settle). Die Schaltfläche „Widerrufen“ ist im Stripe-Modus ausgeblendet, weil sie kein Geld zurückbucht. Betrieb: docs/betrieb/DEPLOYMENT.md. Bestandstests geändert: ShopProductPageTest und CmsSectionRenderingTest (2 Stellen) nutzten „stripe“ als Beispiel für einen nicht freigegebenen Zahlungsweg. Stripe ist jetzt freigegeben, die Tests nehmen den unbekannten Treiber „unbekannt“; die Assertions bleiben unverändert. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
604e1791c5
commit
9f7c645baf
15 files changed
+752
-15
No files matched your search
@@ -140,6 +140,27 @@ private function createOrder(User $user, Party $holder, array $pairs): Order
|
||||
public function confirmTestPayment(Order $order, string $reference): Order
|
||||
{
|
||||
$this->assertTestDriver();
|
||||
|
||||
return $this->settle($order, 'test', $reference);
|
||||
}
|
||||
|
||||
/**
|
||||
* Zahlung eines Anbieters (Stripe): wie die Testzahlung, aber erst nach Prüfung von Betrag und Währung gegen die
|
||||
* Bestellung. Wiederholte Meldungen sind wirkungslos.
|
||||
*/
|
||||
public function confirmProviderPayment(Order $order, string $provider, string $reference, int $amountCents, string $currency): Order
|
||||
{
|
||||
$expected = (int) ($order->total_cents ?? $order->lines()->sum('price_cents'));
|
||||
|
||||
if ($amountCents !== $expected || strtoupper($currency) !== strtoupper((string) ($order->currency ?? 'EUR'))) {
|
||||
throw new DomainRuleException('Der gezahlte Betrag weicht von der Bestellung ab.');
|
||||
}
|
||||
|
||||
return $this->settle($order, $provider, $reference);
|
||||
}
|
||||
|
||||
private function settle(Order $order, string $provider, string $reference): Order
|
||||
{
|
||||
$reference = trim($reference);
|
||||
|
||||
if ($reference === '') {
|
||||
@@ -147,7 +168,7 @@ public function confirmTestPayment(Order $order, string $reference): Order
|
||||
}
|
||||
|
||||
$paidNow = false;
|
||||
$order = DB::transaction(function () use ($order, $reference, &$paidNow): Order {
|
||||
$order = DB::transaction(function () use ($order, $provider, $reference, &$paidNow): Order {
|
||||
$order = Order::query()->lockForUpdate()->findOrFail($order->id);
|
||||
|
||||
if ($order->status === 'bezahlt') {
|
||||
@@ -158,11 +179,11 @@ public function confirmTestPayment(Order $order, string $reference): Order
|
||||
throw new DomainRuleException('Diese Bestellung nimmt keine Zahlung mehr an.');
|
||||
}
|
||||
|
||||
$order->payments()->create([
|
||||
'provider' => 'test',
|
||||
'status' => 'bestaetigt',
|
||||
'provider_reference' => $reference,
|
||||
]);
|
||||
// Eine bei Stripe angelegte offene Zahlung mit derselben Referenz wird bestätigt statt doppelt geführt.
|
||||
$order->payments()->updateOrCreate(
|
||||
['provider_reference' => $reference],
|
||||
['provider' => $provider, 'status' => 'bestaetigt'],
|
||||
);
|
||||
$order->status = 'bezahlt';
|
||||
$order->save();
|
||||
$paidNow = true;
|
||||
|
||||
@@ -9,8 +9,19 @@
|
||||
*/
|
||||
final class Shop
|
||||
{
|
||||
public static function driver(): string
|
||||
{
|
||||
return (string) config('services.payment.driver');
|
||||
}
|
||||
|
||||
public static function enabled(): bool
|
||||
{
|
||||
return ! app()->isProduction() && config('services.payment.driver') === 'test';
|
||||
return ! app()->isProduction() && in_array(self::driver(), ['test', 'stripe'], true);
|
||||
}
|
||||
|
||||
/** Stripe-Kasse (Etappe 1: nur Testmodus, nie in Produktion). */
|
||||
public static function stripe(): bool
|
||||
{
|
||||
return ! app()->isProduction() && self::driver() === 'stripe';
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,145 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Commerce\Stripe;
|
||||
|
||||
use App\Domain\Catalog\DomainRuleException;
|
||||
use App\Domain\Commerce\Order;
|
||||
use Illuminate\Http\Client\ConnectionException;
|
||||
use Illuminate\Http\Client\PendingRequest;
|
||||
use Illuminate\Http\Client\Response;
|
||||
use Illuminate\Support\Facades\Http;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
|
||||
/**
|
||||
* Stripe-Kasse (Checkout Session) für die Testzahlung in Etappe 1. Ausschließlich Testschlüssel: Ein Live-Schlüssel
|
||||
* oder die Produktionsumgebung werden abgewiesen, bevor ein Aufruf an Stripe geht. Bezahlt wird bei Stripe; Kartendaten
|
||||
* berühren diese Anwendung nie. Die Freischaltung erfolgt allein über die signierte Meldung (StripeWebhook).
|
||||
*/
|
||||
class StripeGateway
|
||||
{
|
||||
/**
|
||||
* Legt für die Bestellung eine Checkout Session an oder liefert die noch offene wieder.
|
||||
*
|
||||
* @return array{id: string, url: string}
|
||||
*/
|
||||
public function checkoutFor(Order $order): array
|
||||
{
|
||||
$this->assertSandbox();
|
||||
$order->loadMissing('lines', 'user');
|
||||
|
||||
if ($order->status !== 'offen') {
|
||||
throw new DomainRuleException('Diese Bestellung nimmt keine Zahlung mehr an.');
|
||||
}
|
||||
|
||||
$open = $this->reusableSession($order);
|
||||
|
||||
if ($open !== null) {
|
||||
return $open;
|
||||
}
|
||||
|
||||
$attempt = $order->payments()->where('provider', 'stripe')->count() + 1;
|
||||
$params = [
|
||||
'mode' => 'payment',
|
||||
'client_reference_id' => (string) $order->id,
|
||||
'customer_email' => $order->user->email,
|
||||
'locale' => 'de',
|
||||
'success_url' => route('member.order', $order).'?zahlung=zurueck',
|
||||
'cancel_url' => route('member.order', $order).'?zahlung=abbruch',
|
||||
'metadata' => ['order_id' => (string) $order->id],
|
||||
'payment_intent_data' => ['metadata' => ['order_id' => (string) $order->id]],
|
||||
];
|
||||
|
||||
foreach ($order->lines->values() as $index => $line) {
|
||||
$params['line_items'][$index] = [
|
||||
'quantity' => 1,
|
||||
'price_data' => [
|
||||
'currency' => strtolower((string) ($line->currency ?? $order->currency ?? 'EUR')),
|
||||
'unit_amount' => (int) $line->price_cents,
|
||||
'product_data' => ['name' => filled($line->offer_name) ? (string) $line->offer_name : 'Lizenz'],
|
||||
],
|
||||
];
|
||||
}
|
||||
|
||||
$response = $this->request()
|
||||
->withHeaders(['Idempotency-Key' => 'luf-order-'.$order->id.'-'.$attempt])
|
||||
->post('/v1/checkout/sessions', $params);
|
||||
|
||||
$this->assertOk($response, 'angelegt');
|
||||
$id = (string) $response->json('id');
|
||||
$url = (string) $response->json('url');
|
||||
|
||||
if ($id === '' || $url === '') {
|
||||
throw new DomainRuleException('Stripe hat keine Kasse geliefert. Bitte versuche es später noch einmal.');
|
||||
}
|
||||
|
||||
$order->payments()->create(['provider' => 'stripe', 'status' => 'offen', 'provider_reference' => $id]);
|
||||
|
||||
return ['id' => $id, 'url' => $url];
|
||||
}
|
||||
|
||||
public function assertSandbox(): void
|
||||
{
|
||||
$secret = (string) config('services.stripe.secret');
|
||||
|
||||
if (app()->isProduction()) {
|
||||
throw new DomainRuleException('Stripe ist in Produktion nicht freigegeben.');
|
||||
}
|
||||
|
||||
if ($secret === '') {
|
||||
throw new DomainRuleException('Stripe ist nicht eingerichtet: Der Schlüssel fehlt.');
|
||||
}
|
||||
|
||||
if (! str_starts_with($secret, 'sk_test_') && ! str_starts_with($secret, 'rk_test_')) {
|
||||
throw new DomainRuleException('Etappe 1 erlaubt nur den Stripe-Testmodus (Schlüssel sk_test_).');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array{id: string, url: string}|null
|
||||
*/
|
||||
private function reusableSession(Order $order): ?array
|
||||
{
|
||||
$payment = $order->payments()->where('provider', 'stripe')->where('status', 'offen')->latest('id')->first();
|
||||
|
||||
if ($payment === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
$response = $this->request()->get('/v1/checkout/sessions/'.$payment->provider_reference);
|
||||
} catch (ConnectionException) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if ($response->successful() && $response->json('status') === 'open' && filled($response->json('url'))) {
|
||||
return ['id' => (string) $payment->provider_reference, 'url' => (string) $response->json('url')];
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
private function request(): PendingRequest
|
||||
{
|
||||
return Http::baseUrl(rtrim((string) config('services.stripe.api_base'), '/'))
|
||||
->withToken((string) config('services.stripe.secret'))
|
||||
->asForm()
|
||||
->acceptJson()
|
||||
->timeout(15);
|
||||
}
|
||||
|
||||
private function assertOk(Response $response, string $what): void
|
||||
{
|
||||
if ($response->successful()) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Nur Statuscode und Fehlertyp ins Log, nie Schlüssel oder Kundendaten.
|
||||
Log::warning('Stripe-Anfrage fehlgeschlagen', [
|
||||
'status' => $response->status(),
|
||||
'type' => $response->json('error.type'),
|
||||
'code' => $response->json('error.code'),
|
||||
]);
|
||||
|
||||
throw new DomainRuleException('Die Zahlung konnte bei Stripe nicht '.$what.' werden. Bitte versuche es später noch einmal.');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domain\Commerce\Stripe;
|
||||
|
||||
use App\Domain\Catalog\DomainRuleException;
|
||||
|
||||
/**
|
||||
* Prüft die Signatur einer Stripe-Meldung (Header „Stripe-Signature“: t=Zeit, v1=HMAC-SHA256 über „t.Nutzlast“).
|
||||
* Eine Meldung ohne gültige Signatur oder außerhalb der Zeittoleranz wird abgewiesen.
|
||||
*/
|
||||
class StripeSignature
|
||||
{
|
||||
public const TOLERANCE_SECONDS = 300;
|
||||
|
||||
public function verify(string $payload, ?string $header, ?int $now = null): void
|
||||
{
|
||||
$secret = (string) config('services.stripe.webhook_secret');
|
||||
|
||||
if ($secret === '') {
|
||||
throw new DomainRuleException('Das Webhook-Geheimnis ist nicht eingerichtet.');
|
||||
}
|
||||
|
||||
if ($header === null || trim($header) === '') {
|
||||
throw new DomainRuleException('Die Signatur fehlt.');
|
||||
}
|
||||
|
||||
$timestamp = null;
|
||||
$signatures = [];
|
||||
|
||||
foreach (explode(',', $header) as $part) {
|
||||
[$key, $value] = array_pad(explode('=', trim($part), 2), 2, '');
|
||||
|
||||
if ($key === 't') {
|
||||
$timestamp = ctype_digit($value) ? (int) $value : null;
|
||||
} elseif ($key === 'v1' && $value !== '') {
|
||||
$signatures[] = $value;
|
||||
}
|
||||
}
|
||||
|
||||
if ($timestamp === null || $signatures === []) {
|
||||
throw new DomainRuleException('Die Signatur ist unvollständig.');
|
||||
}
|
||||
|
||||
$expected = hash_hmac('sha256', $timestamp.'.'.$payload, $secret);
|
||||
$valid = false;
|
||||
|
||||
foreach ($signatures as $signature) {
|
||||
$valid = hash_equals($expected, $signature) || $valid;
|
||||
}
|
||||
|
||||
if (! $valid) {
|
||||
throw new DomainRuleException('Die Signatur stimmt nicht.');
|
||||
}
|
||||
|
||||
if (abs(($now ?? now()->getTimestamp()) - $timestamp) > self::TOLERANCE_SECONDS) {
|
||||
throw new DomainRuleException('Die Meldung ist zu alt.');
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -9,7 +9,9 @@
|
||||
use App\Domain\Commerce\Checkout;
|
||||
use App\Domain\Commerce\Order;
|
||||
use App\Domain\Commerce\OrderHolders;
|
||||
use App\Domain\Commerce\Shop;
|
||||
use App\Domain\Commerce\StaleOverview;
|
||||
use App\Domain\Commerce\Stripe\StripeGateway;
|
||||
use App\Domain\Entitlement\GrantIssuer;
|
||||
use App\Http\Controllers\Controller;
|
||||
use Illuminate\Http\RedirectResponse;
|
||||
@@ -99,9 +101,26 @@ public function show(Request $request, Order $order): View
|
||||
return view('member.order', [
|
||||
'order' => $order,
|
||||
'testPayment' => ! app()->isProduction() && config('services.payment.driver') === 'test',
|
||||
'stripePayment' => Shop::stripe(),
|
||||
'zahlung' => $request->query('zahlung'),
|
||||
]);
|
||||
}
|
||||
|
||||
/** Leitet zur Stripe-Kasse (Testmodus). Freigeschaltet wird erst durch die signierte Meldung von Stripe. */
|
||||
public function pay(Request $request, Order $order, StripeGateway $stripe): RedirectResponse
|
||||
{
|
||||
abort_unless($order->user_id === $request->user()->id, 403);
|
||||
abort_unless(Shop::stripe(), 404);
|
||||
|
||||
try {
|
||||
$session = $stripe->checkoutFor($order);
|
||||
} catch (DomainRuleException $exception) {
|
||||
return back()->withErrors(['payment' => $exception->getMessage()]);
|
||||
}
|
||||
|
||||
return redirect()->away($session['url']);
|
||||
}
|
||||
|
||||
public function confirm(Request $request, Order $order, Checkout $checkout): RedirectResponse
|
||||
{
|
||||
abort_unless($order->user_id === $request->user()->id, 403);
|
||||
|
||||
@@ -0,0 +1,114 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers;
|
||||
|
||||
use App\Domain\Catalog\DomainRuleException;
|
||||
use App\Domain\Commerce\Checkout;
|
||||
use App\Domain\Commerce\Order;
|
||||
use App\Domain\Commerce\Payment;
|
||||
use App\Domain\Commerce\Shop;
|
||||
use App\Domain\Commerce\Stripe\StripeSignature;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
|
||||
/**
|
||||
* Empfängt die signierten Meldungen von Stripe (Etappe 1: Testmodus). Ohne gültige Signatur geschieht nichts. Die
|
||||
* Freischaltung nutzt denselben geprüften Weg wie die Testzahlung und ist bei Wiederholung wirkungslos.
|
||||
* Antworten: 404 wenn Stripe nicht aktiv ist, 400 bei ungültiger Signatur, sonst 200 (Stripe wiederholt sonst).
|
||||
*/
|
||||
class StripeWebhookController extends Controller
|
||||
{
|
||||
public function __invoke(Request $request, StripeSignature $signature, Checkout $checkout): JsonResponse
|
||||
{
|
||||
abort_unless(Shop::stripe(), 404);
|
||||
|
||||
$payload = $request->getContent();
|
||||
|
||||
try {
|
||||
$signature->verify($payload, $request->header('Stripe-Signature'));
|
||||
} catch (DomainRuleException $exception) {
|
||||
Log::warning('Stripe-Meldung abgewiesen', ['grund' => $exception->getMessage()]);
|
||||
|
||||
return response()->json(['error' => 'Ungültige Signatur.'], 400);
|
||||
}
|
||||
|
||||
$event = json_decode($payload, true);
|
||||
|
||||
if (! is_array($event) || ! isset($event['type'])) {
|
||||
return response()->json(['error' => 'Ungültige Nutzlast.'], 400);
|
||||
}
|
||||
|
||||
$session = (array) ($event['data']['object'] ?? []);
|
||||
|
||||
return match ($event['type']) {
|
||||
'checkout.session.completed', 'checkout.session.async_payment_succeeded' => $this->paid($session, $checkout),
|
||||
'checkout.session.expired', 'checkout.session.async_payment_failed' => $this->notPaid($session, (string) $event['type']),
|
||||
default => response()->json(['received' => true, 'handled' => false]),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $session
|
||||
*/
|
||||
private function paid(array $session, Checkout $checkout): JsonResponse
|
||||
{
|
||||
if (($session['payment_status'] ?? null) !== 'paid') {
|
||||
return response()->json(['received' => true, 'handled' => false]);
|
||||
}
|
||||
|
||||
$order = $this->orderOf($session);
|
||||
$reference = (string) ($session['id'] ?? '');
|
||||
|
||||
if ($order === null || $reference === '') {
|
||||
Log::warning('Stripe-Zahlung ohne zugehörige Bestellung', ['session' => $reference]);
|
||||
|
||||
return response()->json(['received' => true, 'handled' => false]);
|
||||
}
|
||||
|
||||
try {
|
||||
$checkout->confirmProviderPayment(
|
||||
$order,
|
||||
'stripe',
|
||||
$reference,
|
||||
(int) ($session['amount_total'] ?? -1),
|
||||
(string) ($session['currency'] ?? ''),
|
||||
);
|
||||
} catch (DomainRuleException $exception) {
|
||||
// Dauerhafter Fehler (Betragsabweichung, Bestellung nicht mehr offen): nichts freischalten, Zahlung zur
|
||||
// Prüfung festhalten und 200 antworten, damit Stripe nicht endlos wiederholt.
|
||||
Log::warning('Stripe-Zahlung nicht übernommen', ['order' => $order->id, 'session' => $reference, 'grund' => $exception->getMessage()]);
|
||||
$order->payments()->updateOrCreate(['provider_reference' => $reference], ['provider' => 'stripe', 'status' => 'zu_pruefen']);
|
||||
|
||||
return response()->json(['received' => true, 'handled' => false]);
|
||||
}
|
||||
|
||||
return response()->json(['received' => true, 'handled' => true]);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $session
|
||||
*/
|
||||
private function notPaid(array $session, string $type): JsonResponse
|
||||
{
|
||||
$payment = Payment::query()->where('provider', 'stripe')->where('provider_reference', (string) ($session['id'] ?? ''))->first();
|
||||
|
||||
// Die Bestellung bleibt offen und lässt sich erneut bezahlen; nur diese Kasse gilt nicht mehr.
|
||||
if ($payment !== null && $payment->status === 'offen') {
|
||||
$payment->status = $type === 'checkout.session.expired' ? 'abgelaufen' : 'fehlgeschlagen';
|
||||
$payment->save();
|
||||
}
|
||||
|
||||
return response()->json(['received' => true, 'handled' => $payment !== null]);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $session
|
||||
*/
|
||||
private function orderOf(array $session): ?Order
|
||||
{
|
||||
$id = $session['client_reference_id'] ?? ($session['metadata']['order_id'] ?? null);
|
||||
|
||||
return is_numeric($id) ? Order::query()->find((int) $id) : null;
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user