Files
laraundfelix/tests/Feature/StripeSandboxTest.php
T
StommerandClaude Sonnet 5.5 9f7c645baf
CI Feature / test (push) Successful in 1m53s
Binde Stripe im Testmodus an die Kasse an
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>
2026-11-21 22:26:09 +01:00

315 lines
15 KiB
PHP

<?php
namespace Tests\Feature;
use App\Domain\Commerce\Order;
use App\Domain\Commerce\Shop;
use App\Domain\Entitlement\Acquisition;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Http\Client\Request as HttpRequest;
use Illuminate\Support\Facades\Http;
use Illuminate\Testing\TestResponse;
use Tests\Support\BuildsShop;
use Tests\TestCase;
/**
* Stripe-Sandbox (Etappe 1): Kasse über eine Checkout Session, Freischaltung nur durch die signierte Meldung.
* Alle Aufrufe an Stripe sind gefälscht (Http::fake); es geht nie ein echter Aufruf hinaus.
*/
class StripeSandboxTest extends TestCase
{
use BuildsShop;
use RefreshDatabase;
private const WEBHOOK_SECRET = 'whsec_testgeheimnis_nur_fuer_tests';
protected function setUp(): void
{
parent::setUp();
$this->seedShop();
config([
'services.payment.driver' => 'stripe',
'services.stripe.secret' => 'sk_test_nur_fuer_tests',
'services.stripe.webhook_secret' => self::WEBHOOK_SECRET,
'services.stripe.api_base' => 'https://stripe.test',
]);
$this->travelTo('2026-11-22 10:00:00');
}
public function test_stripe_is_a_shop_driver_but_never_in_production(): void
{
$this->assertTrue(Shop::enabled());
$this->assertTrue(Shop::stripe());
$this->app['env'] = 'production';
$this->assertFalse(Shop::enabled());
$this->assertFalse(Shop::stripe());
}
public function test_the_order_page_offers_stripe_and_not_the_test_buttons(): void
{
$order = $this->orderOf($this->tina(), [$this->privateKonflikte()]);
$this->actingAs($this->tina())->get(route('member.order', $order))
->assertOk()
->assertSee('Jetzt bezahlen (Stripe-Testmodus)')
->assertDontSee('Testzahlung bestätigen')
->assertDontSee('Testzahlung ablehnen');
}
public function test_paying_creates_a_checkout_session_with_the_order_amounts_and_redirects(): void
{
$order = $this->orderOf($this->tina(), [$this->privateKonflikte(), $this->privateGrenzen()]);
Http::fake(['stripe.test/v1/checkout/sessions' => Http::response(['id' => 'cs_test_1', 'url' => 'https://checkout.stripe.test/c/pay/cs_test_1'])]);
$this->actingAs($this->tina())->post(route('member.order.pay', $order))
->assertRedirect('https://checkout.stripe.test/c/pay/cs_test_1');
Http::assertSent(function (HttpRequest $request) use ($order): bool {
parse_str($request->body(), $body);
return $request->url() === 'https://stripe.test/v1/checkout/sessions'
&& $request->hasHeader('Authorization', 'Bearer sk_test_nur_fuer_tests')
&& $request->hasHeader('Idempotency-Key', 'luf-order-'.$order->id.'-1')
&& $body['mode'] === 'payment'
&& $body['client_reference_id'] === (string) $order->id
&& $body['metadata']['order_id'] === (string) $order->id
&& $body['line_items'][0]['price_data']['currency'] === 'eur'
&& (int) $body['line_items'][0]['price_data']['unit_amount'] === 4900
&& (int) $body['line_items'][1]['price_data']['unit_amount'] === 2900
&& str_ends_with($body['success_url'], '?zahlung=zurueck')
&& str_ends_with($body['cancel_url'], '?zahlung=abbruch');
});
$this->assertSame('offen', $order->payments()->where('provider', 'stripe')->value('status'));
$this->assertSame('offen', $order->fresh()->status, 'Bezahlt wird erst durch die signierte Meldung.');
}
public function test_an_open_session_is_reused(): void
{
$order = $this->orderOf($this->tina(), [$this->privateKonflikte()]);
$order->payments()->create(['provider' => 'stripe', 'status' => 'offen', 'provider_reference' => 'cs_test_alt']);
Http::fake(['stripe.test/v1/checkout/sessions/cs_test_alt' => Http::response(['id' => 'cs_test_alt', 'status' => 'open', 'url' => 'https://checkout.stripe.test/alt'])]);
$this->actingAs($this->tina())->post(route('member.order.pay', $order))->assertRedirect('https://checkout.stripe.test/alt');
Http::assertNotSent(fn (HttpRequest $request): bool => $request->method() === 'POST');
}
public function test_an_expired_session_is_replaced_by_a_new_one(): void
{
$order = $this->orderOf($this->tina(), [$this->privateKonflikte()]);
$order->payments()->create(['provider' => 'stripe', 'status' => 'offen', 'provider_reference' => 'cs_test_alt']);
Http::fake([
'stripe.test/v1/checkout/sessions/cs_test_alt' => Http::response(['id' => 'cs_test_alt', 'status' => 'expired']),
'stripe.test/v1/checkout/sessions' => Http::response(['id' => 'cs_test_neu', 'url' => 'https://checkout.stripe.test/neu']),
]);
$this->actingAs($this->tina())->post(route('member.order.pay', $order))->assertRedirect('https://checkout.stripe.test/neu');
Http::assertSent(fn (HttpRequest $request): bool => $request->hasHeader('Idempotency-Key', 'luf-order-'.$order->id.'-2'));
}
public function test_only_the_buyer_pays_and_only_an_open_order(): void
{
$order = $this->orderOf($this->tina(), [$this->privateKonflikte()]);
Http::fake();
$this->actingAs($this->max())->post(route('member.order.pay', $order))->assertForbidden();
Http::assertNothingSent();
$order->forceFill(['status' => 'bezahlt'])->save();
$this->actingAs($this->tina())->post(route('member.order.pay', $order))
->assertSessionHasErrors('payment');
Http::assertNothingSent();
}
public function test_only_test_keys_reach_stripe(): void
{
$order = $this->orderOf($this->tina(), [$this->privateKonflikte()]);
Http::fake();
foreach (['sk_live_abc', '', 'pk_test_abc'] as $secret) {
config(['services.stripe.secret' => $secret]);
$this->actingAs($this->tina())->post(route('member.order.pay', $order))->assertSessionHasErrors('payment');
}
Http::assertNothingSent();
}
public function test_a_stripe_error_leaves_the_order_open_and_shows_a_plain_message(): void
{
$order = $this->orderOf($this->tina(), [$this->privateKonflikte()]);
Http::fake(['stripe.test/*' => Http::response(['error' => ['type' => 'api_error']], 500)]);
$this->actingAs($this->tina())->post(route('member.order.pay', $order))
->assertSessionHasErrors(['payment' => 'Die Zahlung konnte bei Stripe nicht angelegt werden. Bitte versuche es später noch einmal.']);
$this->assertSame('offen', $order->fresh()->status);
$this->assertSame(0, $order->payments()->count());
}
public function test_a_signed_paid_event_grants_every_line_once_even_when_repeated(): void
{
$order = $this->orderOf($this->tina(), [$this->privateKonflikte(), $this->privateGrenzen()]);
$payload = $this->sessionEvent('checkout.session.completed', $order, 'cs_test_bezahlt', 7800);
$this->webhook($payload)->assertOk()->assertJson(['handled' => true]);
$this->webhook($payload)->assertOk();
$this->assertSame('bezahlt', $order->fresh()->status);
$this->assertSame(2, Acquisition::query()->where('reference_type', 'order_line')->whereIn('reference_id', $order->lines()->pluck('id'))->count(), 'Je Position genau ein Erwerb.');
$this->assertSame(1, $order->payments()->count());
$payment = $order->payments()->first();
$this->assertSame('stripe', $payment->provider);
$this->assertSame('bestaetigt', $payment->status);
$this->assertSame('cs_test_bezahlt', $payment->provider_reference);
}
public function test_a_paid_event_confirms_the_open_payment_row_instead_of_adding_one(): void
{
$order = $this->orderOf($this->tina(), [$this->privateKonflikte()]);
$order->payments()->create(['provider' => 'stripe', 'status' => 'offen', 'provider_reference' => 'cs_test_zeile']);
$this->webhook($this->sessionEvent('checkout.session.completed', $order, 'cs_test_zeile', 4900))->assertOk();
$this->assertSame(1, $order->payments()->count());
$this->assertSame('bestaetigt', $order->payments()->first()->status);
}
public function test_an_unsigned_wrongly_signed_or_stale_message_does_nothing(): void
{
$order = $this->orderOf($this->tina(), [$this->privateKonflikte()]);
$payload = $this->sessionEvent('checkout.session.completed', $order, 'cs_test_x', 4900);
$before = Acquisition::query()->count();
$this->call('POST', route('stripe.webhook'), [], [], [], ['CONTENT_TYPE' => 'application/json'], $payload)->assertStatus(400);
$this->webhook($payload, 'sig-falsch')->assertStatus(400);
$this->webhook($payload, 't='.now()->getTimestamp().',v1=abc')->assertStatus(400);
$this->webhook($payload, $this->signature($payload, now()->subMinutes(10)->getTimestamp()))->assertStatus(400);
$this->webhook($payload.' ', $this->signature($payload))->assertStatus(400);
$this->assertSame('offen', $order->fresh()->status);
$this->assertSame($before, Acquisition::query()->count(), 'Es wird nichts freigeschaltet.');
}
public function test_a_wrong_amount_or_currency_grants_nothing_and_is_marked_for_review(): void
{
$order = $this->orderOf($this->tina(), [$this->privateKonflikte()]);
$this->webhook($this->sessionEvent('checkout.session.completed', $order, 'cs_test_zuwenig', 100))->assertOk()->assertJson(['handled' => false]);
$this->webhook($this->sessionEvent('checkout.session.completed', $order, 'cs_test_usd', 4900, 'usd'))->assertOk()->assertJson(['handled' => false]);
$this->assertSame('offen', $order->fresh()->status);
$this->assertSame(['zu_pruefen', 'zu_pruefen'], $order->payments()->orderBy('id')->pluck('status')->all());
}
public function test_an_unpaid_session_an_unknown_order_and_unknown_events_are_ignored(): void
{
$order = $this->orderOf($this->tina(), [$this->privateKonflikte()]);
$this->webhook($this->sessionEvent('checkout.session.completed', $order, 'cs_test_offen', 4900, 'eur', 'unpaid'))->assertOk()->assertJson(['handled' => false]);
$this->webhook($this->event('checkout.session.completed', ['id' => 'cs_x', 'client_reference_id' => '999999', 'payment_status' => 'paid', 'amount_total' => 1, 'currency' => 'eur']))->assertOk()->assertJson(['handled' => false]);
$this->webhook($this->event('customer.created', ['id' => 'cus_1']))->assertOk()->assertJson(['handled' => false]);
$this->assertSame('offen', $order->fresh()->status);
}
public function test_an_expired_session_keeps_the_order_open_and_payable(): void
{
$order = $this->orderOf($this->tina(), [$this->privateKonflikte()]);
$order->payments()->create(['provider' => 'stripe', 'status' => 'offen', 'provider_reference' => 'cs_test_abgelaufen']);
$this->webhook($this->sessionEvent('checkout.session.expired', $order, 'cs_test_abgelaufen', 4900, 'eur', 'unpaid'))->assertOk();
$this->assertSame('offen', $order->fresh()->status);
$this->assertSame('abgelaufen', $order->payments()->first()->status);
}
public function test_a_payment_for_an_order_that_is_no_longer_open_is_not_applied(): void
{
$order = $this->orderOf($this->tina(), [$this->privateKonflikte()]);
$order->forceFill(['status' => 'fehlgeschlagen'])->save();
$this->webhook($this->sessionEvent('checkout.session.completed', $order, 'cs_test_spaet', 4900))->assertOk()->assertJson(['handled' => false]);
$this->assertSame('fehlgeschlagen', $order->fresh()->status);
$this->assertSame('zu_pruefen', $order->payments()->first()->status);
}
public function test_the_webhook_does_not_exist_outside_stripe_mode_or_in_production(): void
{
$order = $this->orderOf($this->tina(), [$this->privateKonflikte()]);
$payload = $this->sessionEvent('checkout.session.completed', $order, 'cs_test_x', 4900);
config(['services.payment.driver' => 'test']);
$this->webhook($payload)->assertNotFound();
config(['services.payment.driver' => 'stripe']);
$this->app['env'] = 'production';
$this->webhook($payload)->assertNotFound();
$this->assertSame('offen', $order->fresh()->status);
}
public function test_without_a_webhook_secret_every_message_is_refused(): void
{
$order = $this->orderOf($this->tina(), [$this->privateKonflikte()]);
$payload = $this->sessionEvent('checkout.session.completed', $order, 'cs_test_x', 4900);
$header = $this->signature($payload);
config(['services.stripe.webhook_secret' => '']);
$this->webhook($payload, $header)->assertStatus(400);
$this->assertSame('offen', $order->fresh()->status);
}
public function test_the_return_page_explains_waiting_and_cancelling(): void
{
$order = $this->orderOf($this->tina(), [$this->privateKonflikte()]);
$this->actingAs($this->tina())->get(route('member.order', $order).'?zahlung=zurueck')->assertSee('Wir warten auf die Bestätigung von Stripe');
$this->actingAs($this->tina())->get(route('member.order', $order).'?zahlung=abbruch')->assertSee('Es wurde nichts abgebucht');
}
public function test_a_paid_order_offers_the_library_and_no_withdrawal_that_would_not_refund_money(): void
{
$order = $this->orderOf($this->tina(), [$this->privateKonflikte()]);
$this->webhook($this->sessionEvent('checkout.session.completed', $order, 'cs_test_ok', 4900))->assertOk();
$this->actingAs($this->tina())->get(route('member.order', $order))
->assertSee('Zur Bibliothek')
->assertDontSee('Widerrufen');
}
/**
* @param array<string, mixed> $object
*/
private function event(string $type, array $object): string
{
return json_encode(['id' => 'evt_'.$type, 'object' => 'event', 'type' => $type, 'data' => ['object' => $object]], JSON_THROW_ON_ERROR);
}
private function sessionEvent(string $type, Order $order, string $sessionId, int $amount, string $currency = 'eur', string $paymentStatus = 'paid'): string
{
return $this->event($type, [
'id' => $sessionId,
'object' => 'checkout.session',
'client_reference_id' => (string) $order->id,
'payment_status' => $paymentStatus,
'amount_total' => $amount,
'currency' => $currency,
'metadata' => ['order_id' => (string) $order->id],
]);
}
private function signature(string $payload, ?int $timestamp = null): string
{
$timestamp ??= now()->getTimestamp();
return 't='.$timestamp.',v1='.hash_hmac('sha256', $timestamp.'.'.$payload, self::WEBHOOK_SECRET);
}
private function webhook(string $payload, ?string $signature = null): TestResponse
{
return $this->call('POST', route('stripe.webhook'), [], [], [], [
'CONTENT_TYPE' => 'application/json',
'HTTP_STRIPE_SIGNATURE' => $signature ?? $this->signature($payload),
], $payload);
}
}