mivita/app/Http/Controllers/Pay/PayoneController.php
Kevin 8593dbe65d Payment Phase R: PAYONE-Integration entflechten (R1–R7 + Review)
Strangler-Refactoring der PAYONE-Zahlungslogik in eine testbare
Service-Schicht, ohne Verhalten in Checkout/Cron/IPN zu ändern.

Neue Services (app/Services/Payment/Payone):
- PayonePaymentService (+ PayonePaymentResult-DTO) für CC-/SEPA-Check
  und Abo-Abbuchung
- PayoneRequestBuilder, PaymentMethodResolver, PayoneMethodConfig
- PayoneTransactionRecorder: zentrale PaymentTransaction-Erstellung
  (API-Response, Invoice, Webhook) inkl. PCI-Redaction (cardpan/cardcvc2)
- PayoneWebhookHandler (+ PayoneWebhookResult): IPN/TSOK-Logik aus
  Api\PayoneController; response('TSOK') statt echo/exit
- PayoneTransportException + Handler-Mapping (403) statt abort() im Service

Hotfixes (R1): var_dump/exit & bare exit() entfernt, Log-Redaction.

Security (R-Review):
- PAYONE_KEY_HASH (MD5-Hash, kein Klartext) mit Boot-Hard-Fail; schließt
  zugleich die ''-Webhook-Bypass-Lücke. Artisan-Command payone:hash-key
  (verdeckte Eingabe, optional --write) zur Hash-Erzeugung.
- Webhook: txaction Pflichtfeld, mode-Fallback auf payment->mode.

Pay\PayoneController ist @deprecated-Fassade (614 → 328 Zeilen),
delegiert an Services via Container-Singleton.

Migration: fehlende Spalte shopping_payments.carddata nachgezogen.

Tests: 47 grün (PayonePaymentService, Recorder, Webhook, Resolver,
TransportException, hash-key). End-to-End im Test-System verifiziert
(siehe dev/2026-06-09-payments).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-10 13:42:45 +00:00

328 lines
12 KiB
PHP

<?php
namespace App\Http\Controllers\Pay;
use App\Http\Controllers\Controller;
use App\Models\ShoppingPayment;
use App\Services\CheckoutFunnelTracker;
use App\Services\MyLog;
use App\Services\Payment\Payone\DTOs\PayonePaymentResult;
use App\Services\Payment\Payone\PaymentMethodResolver;
use App\Services\Payment\Payone\PayonePaymentService;
use App\Services\Payment\Payone\PayoneRequestBuilder;
use App\Services\Payment\Payone\PayoneTransactionRecorder;
use App\Services\Payone;
use Util;
/**
* @deprecated Legacy stateful PAYONE payment facade. New code should depend on
* {@see PayonePaymentService} (Checkout-/Abo-/CC-Check) plus the extracted helpers
* {@see PayoneRequestBuilder}, {@see PaymentMethodResolver} and
* {@see PayoneTransactionRecorder} directly. This controller stays only as a thin
* facade for existing callers (CheckoutController, UserMakeOrder, PaymentHelper)
* and is migrated away in Phase 1.
*
* clearingtype reference (resolved in {@see PaymentMethodResolver}):
* cc = credit card, elv = SEPA debit, vor = prepayment, rec = invoice,
* sb = online bank transfer, wlt = e-wallet, fnc = financing.
*/
class PayoneController extends Controller
{
const PREAUTHORIZATION = 'preauthorization';
const AUTHORIZATION = 'authorization';
const CAPTURE = 'capture';
const REFUND = 'refund';
const DEBIT = 'debit';
private $default = [];
private $personalData = [];
private $aboInitPayment = [];
private $method = [];
private $prepayment = [];
private $deliveryData = [];
private $urls = [];
private $shopping_user;
private $shopping_order;
private $shopping_payment;
private $reference;
private PayonePaymentService $paymentService;
private ?PayonePaymentResult $lastPaymentResult = null;
public function __construct()
{
$this->default = \Config::get('payone.defaults');
$this->paymentService = app(PayonePaymentService::class);
}
public function init($shopping_user, $shopping_order)
{
$this->shopping_user = $shopping_user;
$this->shopping_order = $shopping_order;
$this->default['mode'] = $this->shopping_order->mode;
}
public function getShoppingPayment()
{
return $this->shopping_payment;
}
public function setAboPayment($user_abo, $amount, $currency): void
{
$this->lastPaymentResult = $this->paymentService->chargeAbo(
$user_abo,
$this->shopping_order,
$this->shopping_user,
intval($amount),
$currency,
);
$this->shopping_payment = $this->lastPaymentResult->shoppingPayment;
}
// make Payone payment
public function setPrePayment($payment_method, $amount, $currency, $ret = [])
{
$amount = intval($amount);
$this->reference = substr(uniqid('m', false), 0, 16);
$this->setMethod($payment_method, $ret);
$this->urls = [
'successurl' => route('checkout.transaction_status', ['success', $this->reference]),
'errorurl' => route('checkout.transaction_status', ['error', $this->reference]),
'backurl' => route('checkout.transaction_status', ['cancel', $this->reference]),
];
$this->prepayment = [
'reference' => $this->reference, // a unique reference, e.g. order number
'amount' => $amount, // amount in smallest currency unit, i.e. cents
'currency' => $currency,
'param' => $this->shopping_order->id,
];
// init Abo
if ($this->shopping_order->is_abo) {
if ($this->method['clearingtype'] === 'cc') {
$this->aboInitPayment = [
'recurrence' => 'recurring',
'customer_is_present' => 'yes',
'request' => 'authorization',
'amount' => $amount,
];
$this->method['request'] = 'authorization';
}
if ($this->method['clearingtype'] === 'wlt') {
// payment for Abo PayPal
$this->aboInitPayment = [
'recurrence' => 'recurring',
'customer_is_present' => 'yes',
'request' => 'authorization',
'amount' => $amount,
'add_paydata[redirection_mode]' => 'DIRECT_TO_MERCHANT',
];
$this->setDeliverylData($this->shopping_user);
$this->method['request'] = 'authorization';
}
}
$this->shopping_payment = ShoppingPayment::create([
'shopping_order_id' => $this->shopping_order->id,
'clearingtype' => $this->method['clearingtype'],
'wallettype' => $this->method['wallettype'],
'onlinebanktransfertype' => $this->method['onlinebanktransfertype'],
'carddata' => isset($ret['cc']) ? $ret['cc'] : null,
'reference' => $this->reference,
'amount' => $amount,
'currency' => $currency,
'is_abo' => $this->shopping_order->is_abo,
'abo_interval' => $this->shopping_order->abo_interval,
'identifier' => Util::getUserShopIdentifier(),
'mode' => $this->shopping_order->mode,
]);
CheckoutFunnelTracker::initiatedPayment(
shoppingUserId: $this->shopping_user->id,
shoppingOrderId: $this->shopping_order->id,
shoppingPaymentId: $this->shopping_payment->id,
consultantUserId: $this->shopping_user->auth_user_id ?? null,
paymentMethod: $payment_method,
amountCents: $amount,
);
$this->default['mode'] = $this->shopping_order->mode;
return $this->reference;
}
public function setPersonalData()
{
$this->personalData = PayoneRequestBuilder::buildPersonalData($this->shopping_user);
}
private function setMethod($payment_method, $ret = [])
{
if ($payment_method) {
$this->method = PaymentMethodResolver::resolve($payment_method, $ret)->toArray();
}
}
public function onlyPaymentResponse(): array
{
// Abo path: chargeAbo (called from setAboPayment) already fetched the response.
if ($this->lastPaymentResult !== null) {
return $this->lastPaymentResult->toArray();
}
// Checkout path: state was set by setPrePayment + setPersonalData + setDeliverylData.
$request = PayoneRequestBuilder::buildRequest(
$this->default, $this->personalData, $this->deliveryData,
$this->method, $this->prepayment, $this->aboInitPayment, $this->urls,
);
return Payone::sendRequest($request);
}
public function ResponseData($is_abo = false)
{
$request = PayoneRequestBuilder::buildRequest($this->default, $this->personalData, $this->deliveryData, $this->method, $this->prepayment, $this->aboInitPayment, $this->urls);
if ($this->shopping_payment->clearingtype === 'fnc' && $this->shopping_payment->onlinebanktransfertype === 'MIV') {
$payt = PayoneTransactionRecorder::recordInvoicePayment(
$this->shopping_payment,
$this->method['request'],
$request,
);
Util::setUserHistoryValue(['status' => 5]);
if ($is_abo) {
return $this->reference;
}
return redirect(route('checkout.transaction_approved', [$payt->id, $this->reference]));
}
$response = Payone::sendRequest($request);
/*
* status APPROVED / REDIRECT / ERROR / PENDING
*/
if ($response['status'] === 'ERROR') {
MyLog::writeLog(
'payone',
'error',
'PayPal Preauthorization Fehler: '.$response['errormessage'],
$response
);
PayoneTransactionRecorder::recordFromResponse(
$this->shopping_payment,
$this->method['request'],
$response,
);
Util::setUserHistoryValue(['status' => 3]);
if ($is_abo) {
return $response;
}
\Session::flash('errormessage', $response['errormessage']);
\Session::flash('customermessage', $response['customermessage']);
return redirect(route('checkout.checkout_card'));
}
if ($response['status'] === 'REDIRECT') {
PayoneTransactionRecorder::recordFromResponse(
$this->shopping_payment,
$this->method['request'],
$response,
);
Util::setUserHistoryValue(['status' => 4]);
if ($is_abo) {
return $response;
}
return redirect()->away($response['redirecturl']);
}
if ($response['status'] === 'APPROVED') {
$payt = PayoneTransactionRecorder::recordFromResponse(
$this->shopping_payment,
$this->method['request'],
$response,
);
Util::setUserHistoryValue(['status' => 5]);
if ($is_abo) {
return $response;
}
if ($payt->shopping_payment->clearingtype === 'vor') {
// vorkasse
return redirect(route('checkout.transaction_approved', [$payt->id, $this->reference]));
}
if ($payt->shopping_payment->clearingtype === 'cc') {
// creditcard
return redirect(route('checkout.transaction_approved', [$payt->id, $this->reference]));
}
if ($payt->shopping_payment->clearingtype === 'elv') {
// sepa
return redirect(route('checkout.transaction_approved', [$payt->id, $this->reference]));
}
MyLog::writeLog(
'payone',
'error',
'Error:1002 Unbekannter clearingtype bei APPROVED-Status. App\Http\Controllers\Pay\PayoneController::ResponseData',
['clearingtype' => $payt->shopping_payment->clearingtype ?? null, 'txid' => $response['txid'] ?? null]
);
abort(403, 'Zahlung konnte nicht abgeschlossen werden. Unbekannte Zahlungsart. Fehlercode: 1002');
}
if ($response['status'] === 'PENDING') {
MyLog::writeLog(
'payone',
'error',
'Error:1000 Status PENDING App\Http\Controllers\Pay\PayoneController::ResponseData response status PENDING',
$response
);
abort(503, 'Ihre Zahlung wird noch verarbeitet. Bitte haben Sie einen Moment Geduld. Fehlercode: 1000');
}
MyLog::writeLog(
'payone',
'error',
'Error:1001 Der Zahlungsanbieter ist nicht erreichbar, die Zahlung konnte nicht durchgeführt werden. App\Http\Controllers\Pay\PayoneController::ResponseData error no response status',
$response
);
abort(403, 'Der Zahlungsanbieter ist nicht erreichbar, die Zahlung konnte nicht durchgeführt werden. Bitte versuchen Sie es später erneut. Fehlercode: 1001');
}
public function checkCreditCard($data): array
{
return $this->paymentService
->checkCreditCard($data, $this->default['mode'] ?? 'test')
->toArray();
}
public function checkBankAccount($data, $amount, $currency, $shopping_user): array
{
return $this->paymentService
->checkBankAccount($data, (int) $amount, $currency, $shopping_user, $this->default['mode'] ?? 'test')
->toArray();
}
public function setDeliverylData($shopping_user)
{
$this->deliveryData = PayoneRequestBuilder::buildDeliveryData($shopping_user);
}
}