Eine Bestellung auf Rechnung lässt sich auch mit dem Stripe-Treiber nicht per Karte bezahlen; der Betreiber, der den Zahlungseingang bestätigt, wird an der Zahlung festgehalten; im Livebetrieb ist der alte Einzelkauf ohne Pflichtangaben gesperrt und placeFromCart verlangt die Zustimmungen. ADR-47, Domänenmodell, Lizenzlogik, Kernabläufe, Szenarien, Fachanforderungen und DEPLOYMENT nachgeführt. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
237 lines
9.0 KiB
PHP
237 lines
9.0 KiB
PHP
<?php
|
|
|
|
namespace App\Domain\Commerce\Stripe;
|
|
|
|
use App\Domain\Catalog\DomainRuleException;
|
|
use App\Domain\Commerce\Money;
|
|
use App\Domain\Commerce\Order;
|
|
use App\Domain\Commerce\Payment;
|
|
use App\Domain\Commerce\Shop;
|
|
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). Außerhalb der Produktion nur mit Testschlüsseln; ein Live-Schlüssel wird dort
|
|
* abgewiesen. In Produktion nur nach der Produktivfreigabe (Shop::live) und nur mit Live-Schlüssel; in jedem anderen
|
|
* Fall wird 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). Der Betrag je Position ist der
|
|
* Preis nach Rabatt, damit die Summe bei Stripe genau dem gespeicherten Zahlbetrag der Bestellung entspricht.
|
|
*/
|
|
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->assertAllowed();
|
|
$order->loadMissing('lines', 'user');
|
|
$taxRate = $this->taxRate();
|
|
|
|
if ($order->status !== 'offen') {
|
|
throw new DomainRuleException('Diese Bestellung nimmt keine Zahlung mehr an.');
|
|
}
|
|
|
|
if ($order->payment_method === 'rechnung') {
|
|
throw new DomainRuleException('Diese Bestellung wird auf Rechnung bezahlt, nicht bei Stripe.');
|
|
}
|
|
|
|
$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) {
|
|
$productData = ['name' => filled($line->offer_name) ? (string) $line->offer_name : 'Lizenz'];
|
|
|
|
if ((int) $line->discount_cents > 0) {
|
|
$productData['description'] = 'Listenpreis '.Money::format((int) $line->price_cents).', Rabatt '.Money::format((int) $line->discount_cents);
|
|
}
|
|
|
|
$params['line_items'][$index] = [
|
|
'quantity' => 1,
|
|
'price_data' => [
|
|
'currency' => strtolower((string) ($line->currency ?? $order->currency ?? 'EUR')),
|
|
'unit_amount' => $line->payable(),
|
|
'product_data' => $productData,
|
|
],
|
|
];
|
|
|
|
if ($taxRate !== null) {
|
|
$params['line_items'][$index]['tax_rates'] = [$taxRate];
|
|
}
|
|
}
|
|
|
|
$response = $this->request()
|
|
->withHeaders(['Idempotency-Key' => $this->idempotencyKey($order, $attempt, $params)])
|
|
->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 assertAllowed(): void
|
|
{
|
|
$secret = (string) config('services.stripe.secret');
|
|
|
|
if ($secret === '') {
|
|
throw new DomainRuleException('Stripe ist nicht eingerichtet: Der Schlüssel fehlt.');
|
|
}
|
|
|
|
if (app()->isProduction()) {
|
|
if (! Shop::live()) {
|
|
throw new DomainRuleException('Stripe ist in Produktion nicht freigegeben.');
|
|
}
|
|
|
|
return;
|
|
}
|
|
|
|
if (! str_starts_with($secret, 'sk_test_') && ! str_starts_with($secret, 'rk_test_')) {
|
|
throw new DomainRuleException('Außerhalb der Produktion erlaubt Stripe nur den Testmodus (Schlüssel sk_test_).');
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Vollerstattung der bezahlten Bestellung bei Stripe. Der Betrag ist der gespeicherte Zahlbetrag. Der
|
|
* Idempotenzschlüssel verhindert eine doppelte Rückzahlung bei Wiederholung. Schlägt sie fehl, wird nichts
|
|
* entzogen (Aufrufer: Checkout::refund).
|
|
*/
|
|
public function refund(Order $order, Payment $payment, string $reason): void
|
|
{
|
|
$this->assertAllowed();
|
|
$intent = (string) $payment->provider_payment_ref;
|
|
|
|
if ($intent === '') {
|
|
$session = $this->request()->get('/v1/checkout/sessions/'.$payment->provider_reference);
|
|
$this->assertOk($session, 'abgefragt');
|
|
$intent = (string) $session->json('payment_intent');
|
|
}
|
|
|
|
if ($intent === '') {
|
|
throw new DomainRuleException('Zu dieser Zahlung gibt es bei Stripe keinen Zahlungsvorgang. Erstatte sie im Stripe-Dashboard und prüfe den Fall.');
|
|
}
|
|
|
|
$response = $this->request()
|
|
->withHeaders(['Idempotency-Key' => 'luf-refund-'.$order->id.'-'.$payment->id])
|
|
->post('/v1/refunds', [
|
|
'payment_intent' => $intent,
|
|
'amount' => $order->payable(),
|
|
'reason' => 'requested_by_customer',
|
|
'metadata' => ['order_id' => (string) $order->id, 'grund' => mb_substr($reason, 0, 200)],
|
|
]);
|
|
|
|
$this->assertOk($response, 'erstattet');
|
|
$payment->provider_payment_ref = $intent;
|
|
$payment->save();
|
|
}
|
|
|
|
/**
|
|
* Stripe bindet einen Schlüssel an die Parameter der ersten Anfrage und lehnt dieselbe Kennung mit anderen
|
|
* Parametern ab. Der Schlüssel enthält deshalb einen Fingerabdruck der Parameter und die Minute: Ein
|
|
* doppelter Klick bleibt wirkungslos, eine geänderte Anfrage oder ein Neuversuch nach einer Korrektur nicht.
|
|
*
|
|
* @param array<string, mixed> $params
|
|
*/
|
|
private function idempotencyKey(Order $order, int $attempt, array $params): string
|
|
{
|
|
$fingerprint = substr(sha1(json_encode([$params, now()->format('YmdHi')], JSON_THROW_ON_ERROR)), 0, 12);
|
|
|
|
return 'luf-order-'.$order->id.'-'.$attempt.'-'.$fingerprint;
|
|
}
|
|
|
|
/** Konfigurierter Steuersatz oder null; eine ungültige ID wird abgewiesen, statt geraten zu werden. */
|
|
private function taxRate(): ?string
|
|
{
|
|
$id = trim((string) config('services.stripe.tax_rate'));
|
|
|
|
if ($id === '') {
|
|
return null;
|
|
}
|
|
|
|
if (! preg_match('/^txr_[A-Za-z0-9]+$/', $id)) {
|
|
throw new DomainRuleException('Die Steuersatz-ID für Stripe ist ungültig (erwartet txr_...).');
|
|
}
|
|
|
|
return $id;
|
|
}
|
|
|
|
/**
|
|
* @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;
|
|
}
|
|
|
|
// Statuscode, Fehlertyp, Code, betroffener Parameter und Begründung von Stripe, damit die Ursache lesbar ist.
|
|
// Nie Schlüssel oder Kundendaten; die Begründung wird gekürzt.
|
|
Log::warning('Stripe-Anfrage fehlgeschlagen', [
|
|
'status' => $response->status(),
|
|
'type' => $response->json('error.type'),
|
|
'code' => $response->json('error.code'),
|
|
'param' => $response->json('error.param'),
|
|
'message' => mb_substr((string) $response->json('error.message'), 0, 300),
|
|
]);
|
|
|
|
throw new DomainRuleException('Die Zahlung konnte bei Stripe nicht '.$what.' werden. Bitte versuche es später noch einmal.');
|
|
}
|
|
}
|