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>
This commit is contained in:
Kevin 2026-06-10 13:42:45 +00:00
parent 1668e5a879
commit ccc6f85809
31 changed files with 3420 additions and 717 deletions

View file

@ -0,0 +1,86 @@
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use function Laravel\Prompts\confirm;
use function Laravel\Prompts\password;
class PayoneHashKey extends Command
{
protected $signature = 'payone:hash-key
{--write : Schreibt den erzeugten Hash als PAYONE_KEY_HASH in die .env}';
protected $description = 'Erzeugt aus dem PAYONE-Portal-Key (Klartext) den benötigten MD5-Hash für PAYONE_KEY_HASH';
public function handle(): int
{
$this->components->info('Der Klartext-Key wird nur flüchtig zur Hash-Erzeugung verwendet und nirgends gespeichert oder geloggt.');
$plainKey = trim((string) password(
label: 'PAYONE-Portal-Key (Klartext, verdeckte Eingabe)',
required: true,
));
if ($plainKey === '') {
$this->components->error('Es wurde kein Key eingegeben.');
return self::FAILURE;
}
$hash = hash('md5', $plainKey);
$this->newLine();
$this->components->twoColumnDetail('PAYONE_KEY_HASH', $hash);
$this->newLine();
if (! $this->option('write')) {
$this->line(' Ohne <comment>--write</comment>: Wert manuell als <comment>PAYONE_KEY_HASH</comment> in die .env übernehmen.');
return self::SUCCESS;
}
if (! confirm("PAYONE_KEY_HASH in {$this->envPath()} schreiben/aktualisieren?", default: true)) {
$this->components->warn('Abgebrochen – .env wurde nicht verändert.');
return self::SUCCESS;
}
if (! $this->writeHashToEnv($hash)) {
return self::FAILURE;
}
$this->components->info('PAYONE_KEY_HASH in die .env geschrieben.');
$this->line(' Danach <comment>php artisan config:clear</comment> ausführen (bzw. config neu cachen).');
return self::SUCCESS;
}
private function envPath(): string
{
return base_path('.env');
}
private function writeHashToEnv(string $hash): bool
{
$path = $this->envPath();
if (! is_file($path) || ! is_writable($path)) {
$this->components->error(".env nicht gefunden oder nicht beschreibbar: {$path}");
return false;
}
$contents = (string) file_get_contents($path);
$line = 'PAYONE_KEY_HASH='.$hash;
if (preg_match('/^PAYONE_KEY_HASH=.*$/m', $contents)) {
$contents = preg_replace('/^PAYONE_KEY_HASH=.*$/m', $line, $contents);
} else {
$contents = rtrim($contents, "\n")."\n".$line."\n";
}
return file_put_contents($path, $contents) !== false;
}
}

View file

@ -3,11 +3,11 @@
namespace App\Cron;
use App\Http\Controllers\Pay\PayoneController;
use App\Models\PaymentTransaction;
use App\Models\ShoppingOrder;
use App\Models\ShoppingOrderItem;
use App\Models\UserAbo;
use App\Services\AboOrderCart;
use App\Services\Payment\Payone\PayoneTransactionRecorder;
use Illuminate\Support\Facades\Log;
use Yard;
@ -79,7 +79,7 @@ class UserMakeOrder
\Log::info('Response: '.json_encode($response));
// $response = $this->pay->ResponseData(true);
Log::info('Zahlungsvorgang abgeschlossen für UserAbo ID: '.$this->userAbo->id.', Status: '.($response->status ?? 'unbekannt'));
Log::info('Zahlungsvorgang abgeschlossen für UserAbo ID: '.$this->userAbo->id.', Status: '.(is_array($response) ? ($response['status'] ?? 'unbekannt') : 'unbekannt'));
return $response;
} catch (\Exception $e) {
@ -100,19 +100,12 @@ class UserMakeOrder
return;
}
PaymentTransaction::create([
'shopping_payment_id' => $shoppingPayment->id,
'request' => 'authorization',
'txid' => $responseData['txid'] ?? 0,
'userid' => $responseData['userid'] ?? $this->userAbo->payone_userid ?? 0,
'status' => $responseData['status'],
'txaction' => $responseData['txaction'] ?? null,
'transmitted_data' => $responseData,
'errorcode' => $responseData['errorcode'] ?? null,
'errormessage' => $responseData['errormessage'] ?? null,
'customermessage' => $responseData['customermessage'] ?? null,
'mode' => $shoppingPayment->mode,
]);
PayoneTransactionRecorder::recordFromResponse(
$shoppingPayment,
'authorization',
$responseData,
(int) ($this->userAbo->payone_userid ?? 0),
);
}
public function getShoppingPayment()

View file

@ -2,12 +2,14 @@
namespace App\Exceptions;
use Throwable;
use App\Services\Payment\Payone\Exceptions\PayoneTransportException;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Mail;
use Symfony\Component\ErrorHandler\Exception\FlattenException;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Symfony\Component\ErrorHandler\ErrorRenderer\HtmlErrorRenderer;
use Symfony\Component\ErrorHandler\Exception\FlattenException;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Throwable;
class Handler extends ExceptionHandler
{
@ -17,7 +19,9 @@ class Handler extends ExceptionHandler
* @var array
*/
protected $dontReport = [
//
// PAYONE-Transportfehler werden bereits via MyLog protokolliert (inkl. Mail);
// kein zusätzlicher Exception-Report nötig (entspricht dem alten abort(403)-Verhalten).
PayoneTransportException::class,
];
/**
@ -33,7 +37,6 @@ class Handler extends ExceptionHandler
/**
* Report or log an exception.
*
* @param \Throwable $exception
* @return void
*
* @throws \Exception
@ -51,13 +54,18 @@ class Handler extends ExceptionHandler
* Render an exception into an HTTP response.
*
* @param \Illuminate\Http\Request $request
* @param \Throwable $exception
* @return \Symfony\Component\HttpFoundation\Response
*
* @throws \Throwable
*/
public function render($request, Throwable $exception)
{
// Fallback für nicht im Checkout abgefangene PAYONE-Transportfehler:
// identisch zum früheren abort(403, $message) in Payone::sendRequest.
if ($exception instanceof PayoneTransportException) {
$exception = new HttpException(403, $exception->getMessage(), $exception);
}
return parent::render($request, $exception);
}
@ -65,7 +73,6 @@ class Handler extends ExceptionHandler
* Convert an authentication exception into a response.
*
* @param \Illuminate\Http\Request $request
* @param \Illuminate\Auth\AuthenticationException $exception
* @return \Symfony\Component\HttpFoundation\Response
*/
protected function unauthenticated($request, \Illuminate\Auth\AuthenticationException $exception)
@ -83,12 +90,12 @@ class Handler extends ExceptionHandler
// 'crm' => 'login', // CRM hat eine eigene login route
// default => 'login'
// };
// Temporär: Verwende Standard-Login-Route
return redirect()->guest(route('login'));
} catch (\Exception $e) {
// Fallback: Weiterleitung zur Hauptdomain
return redirect()->guest('https://' . config('app.domain') . config('app.tld_care') . '/login');
return redirect()->guest('https://'.config('app.domain').config('app.tld_care').'/login');
}
}
@ -99,24 +106,23 @@ class Handler extends ExceptionHandler
$handler = new HtmlErrorRenderer(true); // boolean, true raises debug flag...
$css = $handler->getStylesheet();
$content = $handler->getBody($e);
//Mail::to(config('app.exception_mail'))->send(new MailContact($contact));
// Mail::to(config('app.exception_mail'))->send(new MailContact($contact));
// Verwende normale Mail-Klasse statt Facade, um Probleme bei der Initialisierung zu vermeiden
$to = config('app.exception_mail');
$subject = 'mivita Exception: ' . \Request::fullUrl();
$subject = 'mivita Exception: '.\Request::fullUrl();
if ($to) {
\Mail::send('emails.exception', compact('css', 'content'), function ($message) use ($to, $subject) {
$message
->to($to)
->subject($subject)
;
->subject($subject);
});
}
} catch (Throwable $ex) {
// Einfache Fehlerprotokollierung ohne Facade
file_put_contents(
storage_path('logs/laravel-' . date('Y-m-d') . '.log'),
'[' . date('Y-m-d H:i:s') . '] exception-handler-error: ' . $ex->getMessage() . "\n",
storage_path('logs/laravel-'.date('Y-m-d').'.log'),
'['.date('Y-m-d H:i:s').'] exception-handler-error: '.$ex->getMessage()."\n",
FILE_APPEND
);
}

View file

@ -3,247 +3,17 @@
namespace App\Http\Controllers\Api;
use App\Http\Controllers\Controller;
use App\Models\PaymentTransaction;
use App\Models\ShoppingOrder;
use App\Models\ShoppingPayment;
use App\Services\CheckoutFunnelTracker;
use App\Services\MyLog;
use App\Services\Payment;
use App\Services\ShoppingUserService;
use App\Services\Util;
use App\Services\Payment\Payone\PayoneWebhookHandler;
use Illuminate\Http\Response;
class PayoneController extends Controller
{
public function __construct() {}
public function __construct(private readonly PayoneWebhookHandler $webhookHandler) {}
public function paymentStatus()
public function paymentStatus(): Response
{
$result = $this->webhookHandler->handle(\Request::all());
$data = \Request::all();
// test para
/* $data = [
'key' => '698fb2555f8b2efc74f60b2121421f45',
'txaction' => 'paid',
'clearingtype' => 'wlt',
'userid' => '158723953',
'txid' => '321623031',
'price' => '89.00',
'param' => '1', //$this->shopping_order->id,
'reference' => '15c83aee2766c3',
];
*/
if (! isset($data['key']) || ! isset($data['param']) || ! isset($data['userid']) || ! isset($data['txid']) || ! isset($data['reference']) || ! isset($data['price'])) {
MyLog::writeLog(
'payone',
'error',
'Error:2001 App\Http\Controllers\Api\PayoneController::paymentStatus parameter incomplete',
$data
);
echo 'TSOK';
exit;
}
if ($data['key'] != config('payone.defaults.key')) {
MyLog::writeLog(
'payone',
'error',
'Error:2002 App\Http\Controllers\Api\PayoneController::paymentStatus Key error',
$data
);
echo 'TSOK';
exit;
}
$shopping_order = ShoppingOrder::find($data['param']);
if (! $shopping_order) {
MyLog::writeLog(
'payone',
'error',
'Error:2003 App\Http\Controllers\Api\PayoneController::paymentStatus ShoppingOrder not found:',
$data
);
echo 'TSOK';
exit;
}
$shopping_payment = ShoppingPayment::where('reference', $data['reference'])->first();
if (! $shopping_payment) {
MyLog::writeLog(
'payone',
'error',
'Error:2004 App\Http\Controllers\Api\PayoneController::paymentStatus ShoppingPayment not found',
$data
);
echo 'TSOK';
exit;
}
if ($shopping_payment->shopping_order_id != $shopping_order->id) {
MyLog::writeLog(
'payone',
'error',
'Error:2005 App\Http\Controllers\Api\PayoneController::paymentStatus ShoppingPayment no realation ShoppingOrder',
$data
);
echo 'TSOK';
exit;
}
$price = number_format((round($data['price'], 2) * 100), 0, '.', '');
$price_amount = number_format($shopping_payment->amount, 0, '.', '');
if ($price_amount != $price) {
$data['shopping_payment-amount'] = $price_amount;
$data['price-amount'] = $price;
MyLog::writeLog(
'payone',
'error',
'Error:2006 App\Http\Controllers\Api\PayoneController::paymentStatus Price error',
$data
);
echo 'TSOK';
exit;
}
/*
* Payone sendet dieselbe txaction oft mehrfach (v. a. "appointed"). War der Status
* bereits auf ShoppingPayment gespeichert, ist das ein Duplikat: TSOK, keine Doppel-Verarbeitung.
* Ausnahme: erneutes "paid", obwohl die Bestellung noch nicht als bezahlt gefuehrt wird (Recovery).
*/
if ($shopping_payment->txaction == $data['txaction']) {
if ($data['txaction'] === 'paid' && $shopping_order->txaction === 'paid') {
MyLog::writeLog(
'payone',
'notice',
'App\Http\Controllers\Api\PayoneController::paymentStatus duplicate callback ignored (already paid)',
$data,
false
);
echo 'TSOK';
exit;
}
if (in_array($data['txaction'], ['appointed', 'failed', 'pending'], true)) {
MyLog::writeLog(
'payone',
'info',
'App\Http\Controllers\Api\PayoneController::paymentStatus duplicate callback ignored (same txaction)',
[
'reference' => $data['reference'] ?? null,
'param' => $data['param'] ?? null,
'txaction' => $data['txaction'],
'txid' => $data['txid'] ?? null,
],
false
);
echo 'TSOK';
exit;
}
}
// create transaction
PaymentTransaction::create([
'shopping_payment_id' => $shopping_payment->id,
'request' => 'transaction',
'txid' => $data['txid'],
'userid' => $data['userid'],
'status' => 'PAYONE',
'key' => $data['key'],
'txaction' => $data['txaction'],
'transmitted_data' => Util::utf8ize($data),
'mode' => $data['mode'],
'errorcode' => $data['errorcode'] ?? null,
'errormessage' => $data['errormessage'] ?? null,
'customermessage' => $data['customermessage'] ?? null,
]);
// Define txaction priority (higher number = higher priority)
$txaction_priority = [
'appointed' => 1,
'pending' => 2,
'failed' => 3,
'paid' => 10, // highest priority - final state
];
$current_priority = isset($txaction_priority[$shopping_order->txaction]) ? $txaction_priority[$shopping_order->txaction] : 0;
$new_priority = isset($txaction_priority[$data['txaction']]) ? $txaction_priority[$data['txaction']] : 0;
// Only update txaction if new priority is higher than current
if ($new_priority > $current_priority) {
$shopping_order->txaction = $data['txaction'];
$shopping_order->save();
$shopping_payment->txaction = $data['txaction'];
$shopping_payment->save();
} else {
MyLog::writeLog(
'payone',
'info',
'App\Http\Controllers\Api\PayoneController::paymentStatus - txaction not updated (current: '.$shopping_order->txaction.' has higher/equal priority than new: '.$data['txaction'].')',
$data,
false
);
}
$send_link = false;
$send_mail = true;
if ($data['txaction'] === 'failed') {
$shopping_order->setUserHistoryValue(['status' => 6]);
Util::setInstanceStatusByPayment($shopping_payment, 5);
}
if ($data['txaction'] === 'appointed') {
$shopping_order->setUserHistoryValue(['status' => 7]);
ShoppingUserService::snycOrdersByShoppingOrder($shopping_order);
Util::setInstanceStatusByPayment($shopping_payment, 4);
}
if ($data['txaction'] === 'paid') {
// Use DB transaction and row locking to prevent race conditions
\DB::beginTransaction();
try {
// Lock the shopping order row to prevent concurrent processing
$locked_order = ShoppingOrder::where('id', $shopping_order->id)
->lockForUpdate()
->first();
// Double-check if payment was already processed
if (! $locked_order->paid) {
$send_link = Payment::paymentStatusPaidAction($locked_order, true, $shopping_payment);
\DB::commit();
} else {
$send_mail = false;
\DB::commit();
}
} catch (\Exception $e) {
\DB::rollBack();
MyLog::writeLog(
'payone',
'error',
'Error:2008 App\Http\Controllers\Api\PayoneController::paymentStatus Transaction failed',
['error' => $e->getMessage(), 'data' => $data]
);
throw $e;
}
CheckoutFunnelTracker::confirmedPayment(
shoppingPaymentId: $shopping_payment->id,
txaction: 'paid',
metadata: ['mode' => $data['mode'] ?? null, 'txid' => $data['txid'] ?? null],
);
}
if ($data['txaction'] === 'appointed') {
CheckoutFunnelTracker::confirmedPayment(
shoppingPaymentId: $shopping_payment->id,
txaction: 'appointed',
metadata: ['mode' => $data['mode'] ?? null],
);
}
$data['send_link'] = $send_link;
if ($send_mail) {
Payment::paymentStatusSendMail($shopping_order, $shopping_payment, $data);
}
echo 'TSOK';
exit;
return response($result->response);
}
}

View file

@ -1,36 +1,31 @@
<?php
/*
* clearingtype
elv Debit payment
cc Credit card
rec Invoice
cod Cash on delivery
vor Prepayment
sb Online Bank Transfer
wlt e-wallet
fnc Financing
*/
/*private $payment_methods= [
'wlt#PPE' => 'PayPal',
'cc' => 'CreditCard',
'sb#GPY' => 'giropay',
'sb#PNT' => 'Sofort',
'wlt#PDT' => 'paydirekt',
'fnc' => 'Rechnungskauf',
'pref' => 'Vorauskasse',
];*/
namespace App\Http\Controllers\Pay;
use App\Http\Controllers\Controller;
use App\Models\PaymentTransaction;
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';
@ -53,11 +48,8 @@ class PayoneController extends Controller
private $prepayment = [];
/* private $onlineTransfer = [];
private $creditCard = []; */
private $deliveryData = [];
// private $payment_method;
private $urls = [];
private $shopping_user;
@ -68,10 +60,14 @@ class PayoneController extends Controller
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)
@ -86,47 +82,16 @@ class PayoneController extends Controller
return $this->shopping_payment;
}
public function setAboPayment($user_abo, $amount, $currency)
public function setAboPayment($user_abo, $amount, $currency): void
{
$this->reference = substr(uniqid('m', false), 0, 16);
$amount = intval($amount);
$this->method = [
'clearingtype' => $user_abo->clearingtype,
'wallettype' => $user_abo->wallettype,
'pseudocardpan' => isset($user_abo->carddata['pseudocardpan']) ? $user_abo->carddata['pseudocardpan'] : '',
'cardexpiredate' => isset($user_abo->carddata['cardexpiredate']) ? $user_abo->carddata['cardexpiredate'] : '',
'userid' => $user_abo->payone_userid,
'onlinebanktransfertype' => '',
'request' => 'authorization',
];
$this->aboInitPayment = [
'recurrence' => 'recurring',
'customer_is_present' => 'no',
'request' => 'authorization',
'amount' => $amount,
];
$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,
];
$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' => $user_abo->carddata,
'reference' => $this->reference,
'amount' => $amount,
'currency' => $currency,
'is_abo' => $this->shopping_order->is_abo,
'abo_interval' => 0,
'mode' => $this->shopping_order->mode,
]);
$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
@ -206,150 +171,48 @@ class PayoneController extends Controller
public function setPersonalData()
{
$this->personalData = [
'firstname' => $this->shopping_user->billing_firstname,
'lastname' => $this->shopping_user->billing_lastname, // mandatory
'street' => $this->shopping_user->billing_address,
'zip' => $this->shopping_user->billing_zipcode,
'city' => $this->shopping_user->billing_city,
'country' => ($this->shopping_user->billing_country) ? $this->shopping_user->billing_country->code : 'DE', // mandatory
'email' => $this->shopping_user->billing_email,
// "language" => ($this->shopping_user->billing_country) ? strtoupper($this->shopping_user->billing_country->code) : "DE", // mandatory
'language' => 'DE',
];
/**
* Paydirekt requires both, personal data and shipping data
*/
/* $this->deliveryData = array(
"shipping_firstname" => "Paul",
"shipping_lastname" => "Neverpayer",
"shipping_street" => "Hamburger Allee 26-28",
"shipping_zip" => "60486",
"shipping_city" => "Frankfurt am Main",
"shipping_country" => "DE"
);*/
$this->personalData = PayoneRequestBuilder::buildPersonalData($this->shopping_user);
}
private function setMethod($payment_method, $ret = [])
{
if ($payment_method) {
if (strpos($payment_method, '#')) {
$payment_method = explode('#', $payment_method);
// wallet Paypal
if ($payment_method[0] === 'wlt') {
$this->method = [
'clearingtype' => 'wlt',
'wallettype' => $payment_method[1],
'onlinebanktransfertype' => '',
'request' => 'authorization',
];
}
// Online-Überweisung
if ($payment_method[0] === 'sb') {
$this->method = [
'clearingtype' => 'sb',
'wallettype' => '',
'onlinebanktransfertype' => $payment_method[1], // this is the type for Sofort.com
'bankcountry' => 'DE', // we need to know the country of the customer's bank, i.e. of the invoice address
'request' => 'authorization',
];
}
// Rechnungskauf
if ($payment_method[0] === 'fnc') {
// MIVITA
if (isset($payment_method[1]) && $payment_method[1] === 'MIV') {
$this->method = [
'clearingtype' => 'fnc',
'wallettype' => '',
'onlinebanktransfertype' => 'MIV',
'request' => 'authorization',
];
}
// PAYONE
/* $this->method = [
"clearingtype" => "fnc",
"wallettype" => "",
'onlinebanktransfertype' => "",
"financingtype" => "PYV",
"request" => "genericpayment",
"add_paydata[action]" => "pre_check",
"add_paydata[payment_type]" => "Payolution-Invoicing",
];*/
}
}
// vorkasse
if ($payment_method === 'elv') {
$this->method = [
'clearingtype' => 'elv',
'wallettype' => '',
'onlinebanktransfertype' => '',
'request' => 'authorization',
'mandate_identification' => $ret['elv']['mandate_identification'],
'iban' => $ret['elv']['iban'],
'bic' => $ret['elv']['bic'],
'bankaccountholder' => $ret['elv']['bankaccountholder'],
// "bankcountry" => "DE",
];
}
// vorkasse
if ($payment_method === 'vor') {
$this->method = [
'clearingtype' => 'vor',
'wallettype' => '',
'onlinebanktransfertype' => '',
'request' => 'authorization',
];
}
// CreditCard
if ($payment_method === 'cc') {
// need the $cc_ret
$this->method = [
'clearingtype' => 'cc',
'wallettype' => '',
'onlinebanktransfertype' => '',
'request' => 'authorization',
'pseudocardpan' => $ret['cc']['pseudocardpan'],
// "xid" => "3-D Secure transaction ID"
];
}
$this->method = PaymentMethodResolver::resolve($payment_method, $ret)->toArray();
}
}
public function onlyPaymentResponse()
public function onlyPaymentResponse(): array
{
$request = array_merge($this->default, $this->personalData, $this->deliveryData, $this->method, $this->prepayment, $this->aboInitPayment, $this->urls);
$response = Payone::sendRequest($request);
// Abo path: chargeAbo (called from setAboPayment) already fetched the response.
if ($this->lastPaymentResult !== null) {
return $this->lastPaymentResult->toArray();
}
return $response;
// 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 = array_merge($this->default, $this->personalData, $this->deliveryData, $this->method, $this->prepayment, $this->aboInitPayment, $this->urls);
$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 = PaymentTransaction::create([
'shopping_payment_id' => $this->shopping_payment->id,
'request' => $this->method['request'],
'txid' => 0,
'userid' => 0,
'status' => 'FNCMIV',
'transmitted_data' => $request,
'txaction' => 'invoice_open',
'mode' => $this->shopping_payment->mode,
]);
$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]));
exit;
}
$response = Payone::sendRequest($request);
/*
@ -362,16 +225,11 @@ class PayoneController extends Controller
'PayPal Preauthorization Fehler: '.$response['errormessage'],
$response
);
PaymentTransaction::create([
'shopping_payment_id' => $this->shopping_payment->id,
'request' => $this->method['request'],
'errorcode' => $response['errorcode'],
'errormessage' => $response['errormessage'],
'customermessage' => $response['customermessage'],
'transmitted_data' => $request,
'status' => $response['status'],
'mode' => $this->shopping_payment->mode,
]);
PayoneTransactionRecorder::recordFromResponse(
$this->shopping_payment,
$this->method['request'],
$response,
);
Util::setUserHistoryValue(['status' => 3]);
if ($is_abo) {
return $response;
@ -383,36 +241,25 @@ class PayoneController extends Controller
}
if ($response['status'] === 'REDIRECT') {
PaymentTransaction::create([
'shopping_payment_id' => $this->shopping_payment->id,
'request' => $this->method['request'],
'txid' => $response['txid'],
'userid' => $response['userid'],
'status' => $response['status'],
'mode' => $this->shopping_payment->mode,
]);
PayoneTransactionRecorder::recordFromResponse(
$this->shopping_payment,
$this->method['request'],
$response,
);
Util::setUserHistoryValue(['status' => 4]);
if ($is_abo) {
return $response;
}
return redirect()->away($response['redirecturl']);
exit;
}
if ($response['status'] === 'APPROVED') {
// header("Location: " . $response["redirecturl"]); // or other redirect method
$payt = PaymentTransaction::create([
'shopping_payment_id' => $this->shopping_payment->id,
'request' => $this->method['request'],
'txid' => $response['txid'],
'userid' => $response['userid'],
'status' => $response['status'],
'transmitted_data' => $response,
'mode' => $this->shopping_payment->mode,
]);
$payt = PayoneTransactionRecorder::recordFromResponse(
$this->shopping_payment,
$this->method['request'],
$response,
);
Util::setUserHistoryValue(['status' => 5]);
if ($is_abo) {
return $response;
@ -421,27 +268,25 @@ class PayoneController extends Controller
if ($payt->shopping_payment->clearingtype === 'vor') {
// vorkasse
return redirect(route('checkout.transaction_approved', [$payt->id, $this->reference]));
exit;
}
if ($payt->shopping_payment->clearingtype === 'cc') {
// creditcard
return redirect(route('checkout.transaction_approved', [$payt->id, $this->reference]));
exit;
}
if ($payt->shopping_payment->clearingtype === 'elv') {
// sepa
return redirect(route('checkout.transaction_approved', [$payt->id, $this->reference]));
exit;
}
var_dump($response);
exit();
// txid
// Payment process ID (PAYONE)
// userid
// Debtor ID (PAYONE)
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') {
@ -451,11 +296,7 @@ class PayoneController extends Controller
'Error:1000 Status PENDING App\Http\Controllers\Pay\PayoneController::ResponseData response status PENDING',
$response
);
exit();
// txid
// Payment process ID (PAYONE)
// userid
// Debtor ID (PAYONE)
abort(503, 'Ihre Zahlung wird noch verarbeitet. Bitte haben Sie einen Moment Geduld. Fehlercode: 1000');
}
MyLog::writeLog(
'payone',
@ -466,148 +307,22 @@ class PayoneController extends Controller
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)
public function checkCreditCard($data): array
{
$this->prepayment = [
'request' => 'creditcardcheck', // create account receivable and instantly book the amount
'cardholder' => $data['cc_cardholder_first'].' '.$data['cc_cardholder_last'],
'cardpan' => $data['cc_cardpan'],
'cardexpiredate' => substr($data['cc_cardexpireyear'], -2).$data['cc_cardexpiremonth'],
'cardtype' => $data['cc_cardtype'],
'cardcvc2' => $data['cc_cardcvc2'],
'storecarddata' => 'yes',
'language' => 'de',
];
$request = array_merge($this->default, $this->prepayment);
return Payone::sendRequest($request);
return $this->paymentService
->checkCreditCard($data, $this->default['mode'] ?? 'test')
->toArray();
}
public function checkBankAccount($data, $amount, $currency, $shopping_user)
public function checkBankAccount($data, $amount, $currency, $shopping_user): array
{
$this->shopping_user = $shopping_user;
$this->setPersonalData();
$this->prepayment = [
'clearingtype' => 'elv',
'amount' => $amount, // amount in smallest currency unit, i.e. cents
'currency' => $currency,
'request' => 'managemandate', // create account receivable and instantly book the amount
'bankaccountholder' => $data['elv_bankaccountholder'],
'iban' => $data['elv_iban'],
'bic' => $data['elv_bic'],
// "language" => 'de',
];
$request = array_merge($this->default, $this->personalData, $this->deliveryData, $this->method, $this->prepayment, $this->urls);
return Payone::sendRequest($request);
return $this->paymentService
->checkBankAccount($data, (int) $amount, $currency, $shopping_user, $this->default['mode'] ?? 'test')
->toArray();
}
public function setDeliverylData($shopping_user)
{
if ($shopping_user->same_as_billing == true) {
$this->deliveryData = [
'shipping_firstname' => $shopping_user->billing_firstname,
'shipping_lastname' => $shopping_user->billing_lastname,
'shipping_zip' => $shopping_user->billing_zipcode,
'shipping_city' => $shopping_user->billing_city,
'shipping_country' => $shopping_user->billing_country->code,
'shipping_street' => $shopping_user->billing_address,
];
} else {
$this->deliveryData = [
'shipping_firstname' => $shopping_user->shipping_firstname,
'shipping_lastname' => $shopping_user->shipping_lastname,
'shipping_zip' => $shopping_user->shipping_zipcode,
'shipping_city' => $shopping_user->shipping_city,
'shipping_country' => $shopping_user->shipping_country->code,
'shipping_street' => $shopping_user->shipping_address,
];
}
$this->deliveryData = PayoneRequestBuilder::buildDeliveryData($shopping_user);
}
/* public function getPDFFile($mandateId)
{
$params['file_reference'] = $mandateId;//"XX-T0000000";
$params['file_type'] = 'SEPA_MANDATE';
$params['file_format'] = 'PDF';
$request = array_merge($this->default, $params);
return Payone::sendRequest($request);
}
*/
/* public function checkStatus(){
// again, the default values will be needed
$capture = array(
"request" => "capture",
"txid" => "your_txid",
"sequencenumber" => "previous_sequencenumber_plus_one", // get this from the last received transactionsstatus
"amount" => "your_amount", // you can either capture the full amount of the tx, or less
"currency" => "EUR"
);
$request = array_merge($this->default, $capture);
$response = Payone::sendRequest($request);
} */
// set for clearingtype
// debit payment
/*
*
*
* $params['bankaccountholder'] = $paymentData['mopt_payone__debit_bankaccountholder'];
$params['iban'] = $this->removeWhitespaces($paymentData['mopt_payone__debit_iban']);
$params['bic'] = $this->removeWhitespaces($paymentData['mopt_payone__debit_bic']);
* $params['bankcountry'] = $paymentData['mopt_payone__debit_bankcountry'];
$params['bankaccount'] = $this->removeWhitespaces($paymentData['mopt_payone__debit_bankaccount']);
$params['bankcode'] = $this->removeWhitespaces($paymentData['mopt_payone__debit_bankcode']);
if (Shopware()->Session()->moptMandateData) {
$params['mandate_identification'] = Shopware()->Session()->moptMandateData['mopt_payone__mandateIdentification'];
}
*
* ["clearing_bankaccount"]=> string(10) "2599100003"
["clearing_bankcode"]=> string(8) "12345678"
["clearing_bankcountry"]=> string(2) "DE"
["clearing_bankname"]=> string(8) "Testbank"
["clearing_bankaccountholder"]=> string(11) "Test Nutzer"
["clearing_bankcity"]=> string(4) "Kiel"
["clearing_bankiban"]=> string(22) "DE00123456782599100003"
["clearing_bankbic"]=> string(8) "TESTTEST" }
*/
/*
* PNT Sofortbanking (DE, AT, CH, NL)
GPY giropay (DE)
EPS eps – online transfer (AT)
PFF PostFinance E-Finance (CH)
PFC PostFinance Card (CH)
IDL iDEAL (NL)
P24 Przelewy24 (PL)
BCT Bancontact*/
/*
* iban
* bic
* bankcountry*/
/* * Card type
V Visa
M MasterCard
A American Express
D Diners / Discover
J JCB
O Maestro International
*/
}

View file

@ -13,6 +13,7 @@ use App\Services\AboHelper;
use App\Services\CheckoutFunnelTracker;
use App\Services\CustomerPriority;
use App\Services\Payment;
use App\Services\Payment\Payone\Exceptions\PayoneTransportException;
use App\Services\Shop;
use App\Services\Util;
use App\User;
@ -258,31 +259,39 @@ class CheckoutController extends Controller
$result = [];
$payment_method = Request::get('payment_method');
// Kreditkarte prüfen
if ($payment_method === 'cc') {
$result = $this->checkCreditCard($data, $shopping_user, $shopping_order);
if (! is_array($result) || ! isset($result['returnstatus']) || $result['returnstatus'] !== 'VALID') {
return $result;
try {
// Kreditkarte prüfen
if ($payment_method === 'cc') {
$result = $this->checkCreditCard($data, $shopping_user, $shopping_order);
if (! is_array($result) || ! isset($result['returnstatus']) || $result['returnstatus'] !== 'VALID') {
return $result;
}
}
}
// SEPA prüfen
if ($payment_method === 'elv') {
$result = $this->checkSepaAccount($data, $shopping_user, $shopping_order);
if (! is_array($result) || ! isset($result['returnstatus']) || $result['returnstatus'] !== 'VALID') {
return $result;
// SEPA prüfen
if ($payment_method === 'elv') {
$result = $this->checkSepaAccount($data, $shopping_user, $shopping_order);
if (! is_array($result) || ! isset($result['returnstatus']) || $result['returnstatus'] !== 'VALID') {
return $result;
}
}
// Zahlung vorbereiten
$pay = new PayoneController;
$pay->init($shopping_user, $shopping_order);
$amount = Yard::instance($this->instance)->totalWithShipping(2, '.', '') * 100;
$reference = $pay->setPrePayment($payment_method, $amount, 'EUR', $result);
$this->checkoutRepo->putSessionPayments('payment_reference', $reference);
$pay->setPersonalData();
return $pay->ResponseData();
} catch (PayoneTransportException $e) {
// Zahlungsanbieter nicht erreichbar: zurück zur Zahlungsseite mit Fehlermeldung
// (statt 403-Fehlerseite wie früher beim abort()).
Session::flash('errormessage', $e->getMessage());
return redirect(route('checkout.checkout_card'))->withInput(Request::all());
}
// Zahlung vorbereiten
$pay = new PayoneController;
$pay->init($shopping_user, $shopping_order);
$amount = Yard::instance($this->instance)->totalWithShipping(2, '.', '') * 100;
$reference = $pay->setPrePayment($payment_method, $amount, 'EUR', $result);
$this->checkoutRepo->putSessionPayments('payment_reference', $reference);
$pay->setPersonalData();
return $pay->ResponseData();
}
/**

View file

@ -2,6 +2,7 @@
namespace App\Providers;
use App\Services\Payment\Payone\PayonePaymentService;
use Illuminate\Pagination\Paginator;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Facades\URL;
@ -53,6 +54,12 @@ class AppServiceProvider extends ServiceProvider
*/
public function register()
{
// PAYONE payment service: built from merchant defaults, real Guzzle client at runtime.
// The per-request `mode` is always passed explicitly to the service methods, so the
// shared singleton needs only the base defaults from config.
$this->app->singleton(PayonePaymentService::class, function () {
return new PayonePaymentService(config('payone.defaults'));
});
if ($this->app->environment() !== 'production' && class_exists(\Barryvdh\LaravelIdeHelper\IdeHelperServiceProvider::class)) {
$this->app->register(\Barryvdh\LaravelIdeHelper\IdeHelperServiceProvider::class);

View file

@ -0,0 +1,67 @@
<?php
namespace App\Services\Payment\Payone\DTOs;
use App\Models\ShoppingPayment;
class PayonePaymentResult
{
/**
* @param array<string, mixed> $rawResponse
*/
public function __construct(
public readonly string $status,
public readonly array $rawResponse,
public readonly string $txid = '',
public readonly int $userid = 0,
public readonly ?string $redirectUrl = null,
public readonly ?string $errorMessage = null,
public readonly ?string $customerMessage = null,
public readonly ?string $errorCode = null,
public readonly ?ShoppingPayment $shoppingPayment = null,
) {}
public function isApproved(): bool
{
return $this->status === 'APPROVED';
}
public function isRedirect(): bool
{
return $this->status === 'REDIRECT';
}
public function isError(): bool
{
return $this->status === 'ERROR';
}
public function isValid(): bool
{
return $this->status === 'VALID';
}
/** @return array<string, mixed> */
public function toArray(): array
{
return $this->rawResponse;
}
/**
* @param array<string, mixed> $response
*/
public static function fromResponse(array $response, ?ShoppingPayment $shoppingPayment = null): self
{
return new self(
status: $response['status'] ?? 'UNKNOWN',
rawResponse: $response,
txid: (string) ($response['txid'] ?? ''),
userid: (int) ($response['userid'] ?? 0),
redirectUrl: $response['redirecturl'] ?? null,
errorMessage: $response['errormessage'] ?? null,
customerMessage: $response['customermessage'] ?? null,
errorCode: $response['errorcode'] ?? null,
shoppingPayment: $shoppingPayment,
);
}
}

View file

@ -0,0 +1,49 @@
<?php
namespace App\Services\Payment\Payone\DTOs;
class PayoneWebhookResult
{
private function __construct(
public readonly string $response,
public readonly bool $processed,
public readonly ?string $rejectionCode = null,
public readonly bool $duplicate = false,
public readonly ?string $txaction = null,
public readonly bool $paid = false,
public readonly bool $mailSent = false,
public readonly bool $sendLink = false,
) {}
/**
* Webhook was rejected before processing (validation/key/price/relation error).
* PAYONE still receives "TSOK" so it stops retrying the malformed callback.
*/
public static function rejected(string $code): self
{
return new self(response: 'TSOK', processed: false, rejectionCode: $code);
}
/**
* Webhook is a duplicate of an already-processed txaction; ignored.
*/
public static function duplicateIgnored(string $txaction): self
{
return new self(response: 'TSOK', processed: false, duplicate: true, txaction: $txaction);
}
/**
* Webhook was processed: transaction recorded, status updated, side effects applied.
*/
public static function processed(string $txaction, bool $paid, bool $mailSent, bool $sendLink): self
{
return new self(
response: 'TSOK',
processed: true,
txaction: $txaction,
paid: $paid,
mailSent: $mailSent,
sendLink: $sendLink,
);
}
}

View file

@ -0,0 +1,18 @@
<?php
namespace App\Services\Payment\Payone\Exceptions;
use RuntimeException;
class PayoneDeclinedException extends RuntimeException
{
public function __construct(
public readonly string $errorCode,
public readonly string $errorMessage,
public readonly string $customerMessage = '',
int $code = 0,
?\Throwable $previous = null,
) {
parent::__construct($errorMessage, $code, $previous);
}
}

View file

@ -0,0 +1,7 @@
<?php
namespace App\Services\Payment\Payone\Exceptions;
use RuntimeException;
class PayoneTransportException extends RuntimeException {}

View file

@ -0,0 +1,79 @@
<?php
namespace App\Services\Payment\Payone;
use InvalidArgumentException;
class PaymentMethodResolver
{
/**
* Resolves a payment method string into PAYONE method parameters.
*
* Supported formats:
* Simple: 'cc' | 'elv' | 'vor'
* Compound: 'wlt#PPE' | 'wlt#PDT' | 'sb#GPY' | 'sb#PNT' | 'fnc#MIV'
*
* @param array<string, mixed> $context Extra data required for specific methods (e.g. cc.pseudocardpan, elv.iban).
*
* @throws InvalidArgumentException for unknown method strings.
*/
public static function resolve(string $paymentMethod, array $context = []): PayoneMethodConfig
{
if (str_contains($paymentMethod, '#')) {
[$type, $subtype] = explode('#', $paymentMethod, 2);
return match ($type) {
'wlt' => new PayoneMethodConfig([
'clearingtype' => 'wlt',
'wallettype' => $subtype,
'onlinebanktransfertype' => '',
'request' => 'authorization',
]),
'sb' => new PayoneMethodConfig([
'clearingtype' => 'sb',
'wallettype' => '',
'onlinebanktransfertype' => $subtype,
'bankcountry' => 'DE',
'request' => 'authorization',
]),
'fnc' => match ($subtype) {
'MIV' => new PayoneMethodConfig([
'clearingtype' => 'fnc',
'wallettype' => '',
'onlinebanktransfertype' => 'MIV',
'request' => 'authorization',
]),
default => throw new InvalidArgumentException("Unknown fnc subtype: {$subtype}"),
},
default => throw new InvalidArgumentException("Unknown compound payment method type: {$type}"),
};
}
return match ($paymentMethod) {
'cc' => new PayoneMethodConfig([
'clearingtype' => 'cc',
'wallettype' => '',
'onlinebanktransfertype' => '',
'request' => 'authorization',
'pseudocardpan' => $context['cc']['pseudocardpan'] ?? '',
]),
'elv' => new PayoneMethodConfig([
'clearingtype' => 'elv',
'wallettype' => '',
'onlinebanktransfertype' => '',
'request' => 'authorization',
'mandate_identification' => $context['elv']['mandate_identification'] ?? '',
'iban' => $context['elv']['iban'] ?? '',
'bic' => $context['elv']['bic'] ?? '',
'bankaccountholder' => $context['elv']['bankaccountholder'] ?? '',
]),
'vor' => new PayoneMethodConfig([
'clearingtype' => 'vor',
'wallettype' => '',
'onlinebanktransfertype' => '',
'request' => 'authorization',
]),
default => throw new InvalidArgumentException("Unknown payment method: {$paymentMethod}"),
};
}
}

View file

@ -0,0 +1,19 @@
<?php
namespace App\Services\Payment\Payone;
class PayoneMethodConfig
{
/**
* @param array<string, mixed> $params
*/
public function __construct(private readonly array $params) {}
/**
* @return array<string, mixed>
*/
public function toArray(): array
{
return $this->params;
}
}

View file

@ -0,0 +1,128 @@
<?php
namespace App\Services\Payment\Payone;
use App\Models\ShoppingOrder;
use App\Models\ShoppingPayment;
use App\Models\ShoppingUser;
use App\Models\UserAbo;
use App\Services\Payment\Payone\DTOs\PayonePaymentResult;
use App\Services\Payone;
use GuzzleHttp\Client;
class PayonePaymentService
{
/**
* @param array<string, mixed> $defaults PAYONE merchant defaults from config('payone.defaults')
* @param Client|null $client Optional Guzzle client; inject a MockHandler client in tests.
*/
public function __construct(
private readonly array $defaults,
private readonly ?Client $client = null,
) {}
public function checkCreditCard(array $data, string $mode): PayonePaymentResult
{
$request = array_merge($this->defaults, ['mode' => $mode], [
'request' => 'creditcardcheck',
'cardholder' => $data['cc_cardholder_first'].' '.$data['cc_cardholder_last'],
'cardpan' => $data['cc_cardpan'],
'cardexpiredate' => substr($data['cc_cardexpireyear'], -2).$data['cc_cardexpiremonth'],
'cardtype' => $data['cc_cardtype'],
'cardcvc2' => $data['cc_cardcvc2'],
'storecarddata' => 'yes',
'language' => 'de',
]);
return PayonePaymentResult::fromResponse(Payone::sendRequest($request, '', $this->client));
}
public function checkBankAccount(
array $data,
int $amount,
string $currency,
ShoppingUser $shoppingUser,
string $mode,
): PayonePaymentResult {
$defaults = array_merge($this->defaults, ['mode' => $mode]);
$personalData = PayoneRequestBuilder::buildPersonalData($shoppingUser);
$methodParams = [
'clearingtype' => 'elv',
'request' => 'managemandate',
'bankaccountholder' => $data['elv_bankaccountholder'],
'iban' => $data['elv_iban'],
'bic' => $data['elv_bic'],
];
$prepayment = [
'amount' => $amount,
'currency' => $currency,
];
$request = PayoneRequestBuilder::buildRequest($defaults, $personalData, [], $methodParams, $prepayment);
return PayonePaymentResult::fromResponse(Payone::sendRequest($request, '', $this->client));
}
/**
* Charges a recurring abo payment: creates the ShoppingPayment record, builds the
* PAYONE authorization request, and returns the result with the ShoppingPayment attached.
*/
public function chargeAbo(
UserAbo $userAbo,
ShoppingOrder $shoppingOrder,
ShoppingUser $shoppingUser,
int $amountCents,
string $currency,
): PayonePaymentResult {
$reference = substr(uniqid('m', false), 0, 16);
$method = [
'clearingtype' => $userAbo->clearingtype,
'wallettype' => $userAbo->wallettype ?? '',
'pseudocardpan' => $userAbo->carddata['pseudocardpan'] ?? '',
'cardexpiredate' => $userAbo->carddata['cardexpiredate'] ?? '',
'userid' => $userAbo->payone_userid,
'onlinebanktransfertype' => '',
'request' => 'authorization',
];
$aboInitPayment = [
'recurrence' => 'recurring',
'customer_is_present' => 'no',
'request' => 'authorization',
'amount' => $amountCents,
];
$prepayment = [
'reference' => $reference,
'amount' => $amountCents,
'currency' => $currency,
'param' => $shoppingOrder->id,
];
$shoppingPayment = ShoppingPayment::create([
'shopping_order_id' => $shoppingOrder->id,
'clearingtype' => $method['clearingtype'],
'wallettype' => $method['wallettype'],
'onlinebanktransfertype' => $method['onlinebanktransfertype'],
'carddata' => $userAbo->carddata,
'reference' => $reference,
'amount' => $amountCents,
'currency' => $currency,
'is_abo' => $shoppingOrder->is_abo,
'abo_interval' => 0,
'mode' => $shoppingOrder->mode,
]);
$defaults = array_merge($this->defaults, ['mode' => $shoppingOrder->mode]);
$personalData = PayoneRequestBuilder::buildPersonalData($shoppingUser);
$request = PayoneRequestBuilder::buildRequest(
$defaults, $personalData, [], $method, $prepayment, $aboInitPayment,
);
$response = Payone::sendRequest($request, '', $this->client);
return PayonePaymentResult::fromResponse($response, $shoppingPayment);
}
}

View file

@ -0,0 +1,81 @@
<?php
namespace App\Services\Payment\Payone;
use App\Models\ShoppingUser;
class PayoneRequestBuilder
{
/**
* Builds the personal/billing data block for a PAYONE request.
*
* @return array<string, mixed>
*/
public static function buildPersonalData(ShoppingUser $shoppingUser): array
{
return [
'firstname' => $shoppingUser->billing_firstname,
'lastname' => $shoppingUser->billing_lastname,
'street' => $shoppingUser->billing_address,
'zip' => $shoppingUser->billing_zipcode,
'city' => $shoppingUser->billing_city,
'country' => $shoppingUser->billing_country?->code ?? 'DE',
'email' => $shoppingUser->billing_email,
'language' => 'DE',
];
}
/**
* Builds the shipping/delivery data block for a PAYONE request.
* When same_as_billing is true, billing address is used for shipping.
*
* @return array<string, mixed>
*/
public static function buildDeliveryData(ShoppingUser $shoppingUser): array
{
if ($shoppingUser->same_as_billing) {
return [
'shipping_firstname' => $shoppingUser->billing_firstname,
'shipping_lastname' => $shoppingUser->billing_lastname,
'shipping_zip' => $shoppingUser->billing_zipcode,
'shipping_city' => $shoppingUser->billing_city,
'shipping_country' => $shoppingUser->billing_country?->code ?? 'DE',
'shipping_street' => $shoppingUser->billing_address,
];
}
return [
'shipping_firstname' => $shoppingUser->shipping_firstname,
'shipping_lastname' => $shoppingUser->shipping_lastname,
'shipping_zip' => $shoppingUser->shipping_zipcode,
'shipping_city' => $shoppingUser->shipping_city,
'shipping_country' => $shoppingUser->shipping_country?->code ?? 'DE',
'shipping_street' => $shoppingUser->shipping_address,
];
}
/**
* Merges all PAYONE request segments into one flat array, in the correct
* precedence order (later segments override earlier ones on key collision).
*
* @param array<string, mixed> $defaults
* @param array<string, mixed> $personalData
* @param array<string, mixed> $deliveryData
* @param array<string, mixed> $methodParams
* @param array<string, mixed> $prepayment
* @param array<string, mixed> $aboInitPayment
* @param array<string, mixed> $urls
* @return array<string, mixed>
*/
public static function buildRequest(
array $defaults,
array $personalData,
array $deliveryData,
array $methodParams,
array $prepayment,
array $aboInitPayment = [],
array $urls = [],
): array {
return array_merge($defaults, $personalData, $deliveryData, $methodParams, $prepayment, $aboInitPayment, $urls);
}
}

View file

@ -0,0 +1,101 @@
<?php
namespace App\Services\Payment\Payone;
use App\Models\PaymentTransaction;
use App\Models\ShoppingPayment;
use App\Services\Util;
class PayoneTransactionRecorder
{
/**
* PCI-sensitive keys that must never be persisted in transmitted_data.
*
* @var list<string>
*/
private const REDACTED_KEYS = ['cardpan', 'cardcvc2'];
/**
* Records a PaymentTransaction from a PAYONE API response (ERROR, REDIRECT, APPROVED, …).
*
* @param array<string, mixed> $response
*/
public static function recordFromResponse(
ShoppingPayment $payment,
string $requestType,
array $response,
int $useridFallback = 0,
): PaymentTransaction {
return PaymentTransaction::create([
'shopping_payment_id' => $payment->id,
'request' => $requestType,
'txid' => $response['txid'] ?? 0,
'userid' => $response['userid'] ?? $useridFallback,
'status' => $response['status'] ?? 'UNKNOWN',
'txaction' => $response['txaction'] ?? null,
'transmitted_data' => self::redactPayload($response),
'errorcode' => $response['errorcode'] ?? null,
'errormessage' => $response['errormessage'] ?? null,
'customermessage' => $response['customermessage'] ?? null,
'mode' => $payment->mode,
]);
}
/**
* Records a synthetic transaction for FNC/MIV invoice payments (no PAYONE API call made).
*
* @param array<string, mixed> $requestPayload
*/
public static function recordInvoicePayment(
ShoppingPayment $payment,
string $requestType,
array $requestPayload,
): PaymentTransaction {
return PaymentTransaction::create([
'shopping_payment_id' => $payment->id,
'request' => $requestType,
'txid' => 0,
'userid' => 0,
'status' => 'FNCMIV',
'transmitted_data' => self::redactPayload($requestPayload),
'txaction' => 'invoice_open',
'mode' => $payment->mode,
]);
}
/**
* Records a transaction for an incoming PAYONE IPN/TSOK webhook callback.
*
* @param array<string, mixed> $data Raw callback payload (\Request::all()).
*/
public static function recordWebhookCallback(
ShoppingPayment $payment,
array $data,
): PaymentTransaction {
return PaymentTransaction::create([
'shopping_payment_id' => $payment->id,
'request' => 'transaction',
'txid' => $data['txid'] ?? 0,
'userid' => $data['userid'] ?? 0,
'status' => 'PAYONE',
'key' => $data['key'] ?? null,
'txaction' => $data['txaction'] ?? null,
'transmitted_data' => self::redactPayload(Util::utf8ize($data)),
'mode' => $data['mode'] ?? $payment->mode,
'errorcode' => $data['errorcode'] ?? null,
'errormessage' => $data['errormessage'] ?? null,
'customermessage' => $data['customermessage'] ?? null,
]);
}
/**
* Strips PCI-sensitive fields before persisting a payload.
*
* @param array<string, mixed> $payload
* @return array<string, mixed>
*/
private static function redactPayload(array $payload): array
{
return array_diff_key($payload, array_flip(self::REDACTED_KEYS));
}
}

View file

@ -0,0 +1,233 @@
<?php
namespace App\Services\Payment\Payone;
use App\Models\ShoppingOrder;
use App\Models\ShoppingPayment;
use App\Services\CheckoutFunnelTracker;
use App\Services\MyLog;
use App\Services\Payment;
use App\Services\Payment\Payone\DTOs\PayoneWebhookResult;
use App\Services\ShoppingUserService;
use App\Services\Util;
class PayoneWebhookHandler
{
/**
* Txaction priority (higher number = higher priority); 'paid' is the final state.
*
* @var array<string, int>
*/
private const TXACTION_PRIORITY = [
'appointed' => 1,
'pending' => 2,
'failed' => 3,
'paid' => 10,
];
/**
* Processes a PAYONE IPN/TSOK callback. Always returns a result whose `response`
* is sent verbatim to PAYONE. A thrown exception (paid-path transaction failure)
* propagates so PAYONE retries the callback.
*
* @param array<string, mixed> $data
*/
public function handle(array $data): PayoneWebhookResult
{
if (! isset($data['key'], $data['param'], $data['userid'], $data['txid'], $data['reference'], $data['price'], $data['txaction'])) {
MyLog::writeLog(
'payone',
'error',
'Error:2001 App\Http\Controllers\Api\PayoneController::paymentStatus parameter incomplete',
$data
);
return PayoneWebhookResult::rejected('2001');
}
if ($data['key'] != config('payone.defaults.key')) {
MyLog::writeLog(
'payone',
'error',
'Error:2002 App\Http\Controllers\Api\PayoneController::paymentStatus Key error',
$data
);
return PayoneWebhookResult::rejected('2002');
}
$shopping_order = ShoppingOrder::find($data['param']);
if (! $shopping_order) {
MyLog::writeLog(
'payone',
'error',
'Error:2003 App\Http\Controllers\Api\PayoneController::paymentStatus ShoppingOrder not found:',
$data
);
return PayoneWebhookResult::rejected('2003');
}
$shopping_payment = ShoppingPayment::where('reference', $data['reference'])->first();
if (! $shopping_payment) {
MyLog::writeLog(
'payone',
'error',
'Error:2004 App\Http\Controllers\Api\PayoneController::paymentStatus ShoppingPayment not found',
$data
);
return PayoneWebhookResult::rejected('2004');
}
if ($shopping_payment->shopping_order_id != $shopping_order->id) {
MyLog::writeLog(
'payone',
'error',
'Error:2005 App\Http\Controllers\Api\PayoneController::paymentStatus ShoppingPayment no realation ShoppingOrder',
$data
);
return PayoneWebhookResult::rejected('2005');
}
$price = number_format((round($data['price'], 2) * 100), 0, '.', '');
$price_amount = number_format($shopping_payment->amount, 0, '.', '');
if ($price_amount != $price) {
$data['shopping_payment-amount'] = $price_amount;
$data['price-amount'] = $price;
MyLog::writeLog(
'payone',
'error',
'Error:2006 App\Http\Controllers\Api\PayoneController::paymentStatus Price error',
$data
);
return PayoneWebhookResult::rejected('2006');
}
/*
* Payone sendet dieselbe txaction oft mehrfach (v. a. "appointed"). War der Status
* bereits auf ShoppingPayment gespeichert, ist das ein Duplikat: TSOK, keine Doppel-Verarbeitung.
* Ausnahme: erneutes "paid", obwohl die Bestellung noch nicht als bezahlt gefuehrt wird (Recovery).
*/
if ($shopping_payment->txaction == $data['txaction']) {
if ($data['txaction'] === 'paid' && $shopping_order->txaction === 'paid') {
MyLog::writeLog(
'payone',
'notice',
'App\Http\Controllers\Api\PayoneController::paymentStatus duplicate callback ignored (already paid)',
$data,
false
);
return PayoneWebhookResult::duplicateIgnored($data['txaction']);
}
if (in_array($data['txaction'], ['appointed', 'failed', 'pending'], true)) {
MyLog::writeLog(
'payone',
'info',
'App\Http\Controllers\Api\PayoneController::paymentStatus duplicate callback ignored (same txaction)',
[
'reference' => $data['reference'] ?? null,
'param' => $data['param'] ?? null,
'txaction' => $data['txaction'],
'txid' => $data['txid'] ?? null,
],
false
);
return PayoneWebhookResult::duplicateIgnored($data['txaction']);
}
}
// create transaction (centralised in the recorder, incl. PCI redaction + utf8ize)
PayoneTransactionRecorder::recordWebhookCallback($shopping_payment, $data);
$current_priority = self::TXACTION_PRIORITY[$shopping_order->txaction] ?? 0;
$new_priority = self::TXACTION_PRIORITY[$data['txaction']] ?? 0;
// Only update txaction if new priority is higher than current
if ($new_priority > $current_priority) {
$shopping_order->txaction = $data['txaction'];
$shopping_order->save();
$shopping_payment->txaction = $data['txaction'];
$shopping_payment->save();
} else {
MyLog::writeLog(
'payone',
'info',
'App\Http\Controllers\Api\PayoneController::paymentStatus - txaction not updated (current: '.$shopping_order->txaction.' has higher/equal priority than new: '.$data['txaction'].')',
$data,
false
);
}
$send_link = false;
$send_mail = true;
if ($data['txaction'] === 'failed') {
$shopping_order->setUserHistoryValue(['status' => 6]);
Util::setInstanceStatusByPayment($shopping_payment, 5);
}
if ($data['txaction'] === 'appointed') {
$shopping_order->setUserHistoryValue(['status' => 7]);
ShoppingUserService::snycOrdersByShoppingOrder($shopping_order);
Util::setInstanceStatusByPayment($shopping_payment, 4);
}
if ($data['txaction'] === 'paid') {
// Use DB transaction and row locking to prevent race conditions
\DB::beginTransaction();
try {
// Lock the shopping order row to prevent concurrent processing
$locked_order = ShoppingOrder::where('id', $shopping_order->id)
->lockForUpdate()
->first();
// Double-check if payment was already processed
if (! $locked_order->paid) {
$send_link = Payment::paymentStatusPaidAction($locked_order, true, $shopping_payment);
\DB::commit();
} else {
$send_mail = false;
\DB::commit();
}
} catch (\Exception $e) {
\DB::rollBack();
MyLog::writeLog(
'payone',
'error',
'Error:2008 App\Http\Controllers\Api\PayoneController::paymentStatus Transaction failed',
['error' => $e->getMessage(), 'data' => $data]
);
throw $e;
}
CheckoutFunnelTracker::confirmedPayment(
shoppingPaymentId: $shopping_payment->id,
txaction: 'paid',
metadata: ['mode' => $data['mode'] ?? null, 'txid' => $data['txid'] ?? null],
);
}
if ($data['txaction'] === 'appointed') {
CheckoutFunnelTracker::confirmedPayment(
shoppingPaymentId: $shopping_payment->id,
txaction: 'appointed',
metadata: ['mode' => $data['mode'] ?? null],
);
}
$data['send_link'] = $send_link;
if ($send_mail) {
Payment::paymentStatusSendMail($shopping_order, $shopping_payment, $data);
}
return PayoneWebhookResult::processed(
txaction: $data['txaction'],
paid: $data['txaction'] === 'paid',
mailSent: $send_mail,
sendLink: (bool) $send_link,
);
}
}

View file

@ -3,11 +3,11 @@
namespace App\Services;
use App\Http\Controllers\Pay\PayoneController;
use App\Models\PaymentTransaction;
use App\Models\ShoppingOrder;
use App\Models\ShoppingOrderItem;
use App\Models\ShoppingUser;
use App\Models\UserHistory;
use App\Services\Payment\Payone\PayoneTransactionRecorder;
use Yard;
class PaymentHelper
@ -39,41 +39,10 @@ class PaymentHelper
$pay->setPersonalData();
$response = $pay->onlyPaymentResponse();
$shopping_payment = $pay->getShoppingPayment();
if ($response['status'] === 'ERROR') {
$payT = PaymentTransaction::create([
'shopping_payment_id' => $shopping_payment->id,
'request' => 'authorization',
'errorcode' => $response['errorcode'],
'errormessage' => $response['errormessage'],
'customermessage' => $response['customermessage'],
'status' => $response['status'],
'mode' => $shopping_payment->mode,
]);
UserHistory::create(['user_id' => $user->id, 'shopping_order_id' => $shopping_order->id, 'action' => 'abo_open_payment', 'referenz' => $payT->id, 'identifier' => $user->payment_account, 'status' => 3]);
}
if ($response['status'] === 'REDIRECT') {
$payT = PaymentTransaction::create([
'shopping_payment_id' => $shopping_payment->id,
'request' => 'authorization',
'txid' => $response['txid'],
'userid' => $response['userid'],
'status' => $response['status'],
'mode' => $shopping_payment->mode,
]);
UserHistory::create(['user_id' => $user->id, 'shopping_order_id' => $shopping_order->id, 'action' => 'abo_open_payment', 'referenz' => $payT->id, 'identifier' => $user->payment_account, 'status' => 4]);
}
if ($response['status'] === 'APPROVED') {
$payT = PaymentTransaction::create([
'shopping_payment_id' => $shopping_payment->id,
'request' => 'authorization',
'txid' => $response['txid'],
'userid' => $response['userid'],
'status' => $response['status'],
'transmitted_data' => $response,
'mode' => $shopping_payment->mode,
]);
UserHistory::create(['user_id' => $user->id, 'shopping_order_id' => $shopping_order->id, 'action' => 'abo_open_payment', 'referenz' => $payT->id, 'identifier' => $user->payment_account, 'status' => 5]);
if (in_array($response['status'] ?? '', ['ERROR', 'REDIRECT', 'APPROVED'], true)) {
$statusMap = ['ERROR' => 3, 'REDIRECT' => 4, 'APPROVED' => 5];
$payT = PayoneTransactionRecorder::recordFromResponse($shopping_payment, 'authorization', $response);
UserHistory::create(['user_id' => $user->id, 'shopping_order_id' => $shopping_order->id, 'action' => 'abo_open_payment', 'referenz' => $payT->id, 'identifier' => $user->payment_account, 'status' => $statusMap[$response['status']]]);
}
}

View file

@ -28,6 +28,7 @@
namespace App\Services;
// require 'vendor/autoload.php';
use App\Services\Payment\Payone\Exceptions\PayoneTransportException;
use Exception;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\BadResponseException;
@ -86,9 +87,9 @@ class Payone
'payone',
'error',
'Error:1002 Der Zahlungsanbieter ist nicht erreichbar, die Zahlung konnte nicht durchgeführt werden. App\Services\Payone::sendRequest HTTP-Fehlerantwort (4xx/5xx).',
['error' => $error, 'responseBodyAsString' => $responseBodyAsString, 'request' => $request]
['error' => $error, 'responseBodyAsString' => $responseBodyAsString, 'request' => self::redactRequest($request)]
);
abort(403, $userMessage);
throw new PayoneTransportException($userMessage, 0, $e);
} catch (ConnectException $e) {
MyLog::writeLog(
'payone',
@ -96,10 +97,10 @@ class Payone
'Error:1002 Der Zahlungsanbieter ist nicht erreichbar, die Zahlung konnte nicht durchgeführt werden. App\Services\Payone::sendRequest Netzwerk-/Transportfehler (keine HTTP-Antwort).',
[
'exception' => $e->getMessage(),
'request' => $request,
'request' => self::redactRequest($request),
]
);
abort(403, $userMessage);
throw new PayoneTransportException($userMessage, 0, $e);
} catch (RequestException $e) {
if ($e->hasResponse()) {
$error = $e->getResponse();
@ -108,7 +109,7 @@ class Payone
'payone',
'error',
'Error:1002 Der Zahlungsanbieter ist nicht erreichbar, die Zahlung konnte nicht durchgeführt werden. App\Services\Payone::sendRequest HTTP-Fehlerantwort.',
['error' => $error, 'responseBodyAsString' => $responseBodyAsString, 'request' => $request]
['error' => $error, 'responseBodyAsString' => $responseBodyAsString, 'request' => self::redactRequest($request)]
);
} else {
MyLog::writeLog(
@ -117,12 +118,12 @@ class Payone
'Error:1002 Der Zahlungsanbieter ist nicht erreichbar, die Zahlung konnte nicht durchgeführt werden. App\Services\Payone::sendRequest Transportfehler (RequestException ohne Antwort).',
[
'exception' => $e->getMessage(),
'request' => $request,
'request' => self::redactRequest($request),
]
);
}
abort(403, $userMessage);
throw new PayoneTransportException($userMessage, 0, $e);
}
if (isset($response)) {
if (implode($response->getHeader('Content-Type')) == 'text/plain;charset=UTF-8') {
@ -137,7 +138,7 @@ class Payone
'payone',
'error',
'Error: App\Services\Payone::sendRequest content type is anything else',
['error' => $return, 'response' => $response, 'request' => $request]
['error' => $return, 'response' => $response, 'request' => self::redactRequest($request)]
);
}
} else {
@ -145,7 +146,7 @@ class Payone
'payone',
'error',
'Error: App\Services\Payone::sendRequest Something went wrong during the HTTP request',
['request' => $request]
['request' => self::redactRequest($request)]
);
throw new Exception('Something went wrong during the HTTP request.');
}
@ -157,9 +158,9 @@ class Payone
'payone',
'error',
'Error: 1003 App\Http\Controllers\Pay\PayoneController::ResponseData response is non array: return:',
['return' => $return, 'response' => $response, 'request' => $request]
['return' => $return, 'response' => $response, 'request' => self::redactRequest($request)]
);
abort(403, 'Der Zahlungsanbieter ist nicht erreichbar, die Zahlung konnte nicht durchgeführt werden. Bitte versuchen Sie es später erneut. Fehlercode: 1003');
throw new PayoneTransportException('Der Zahlungsanbieter ist nicht erreichbar, die Zahlung konnte nicht durchgeführt werden. Bitte versuchen Sie es später erneut. Fehlercode: 1003');
}
if (! isset($return['status'])) {
@ -167,9 +168,9 @@ class Payone
'payone',
'error',
'Error: 1004 App\Http\Controllers\Pay\PayoneController::ResponseData response has non status',
['return' => $return, 'response' => $response, 'request' => $request]
['return' => $return, 'response' => $response, 'request' => self::redactRequest($request)]
);
abort(403, 'Der Zahlungsanbieter ist nicht erreichbar, die Zahlung konnte nicht durchgeführt werden. Bitte versuchen Sie es später erneut. Fehlercode: 1004');
throw new PayoneTransportException('Der Zahlungsanbieter ist nicht erreichbar, die Zahlung konnte nicht durchgeführt werden. Bitte versuchen Sie es später erneut. Fehlercode: 1004');
}
/* echo "done.\n";
@ -179,6 +180,17 @@ class Payone
return $return;
}
/**
* Removes PCI-sensitive fields from a request array before logging.
*
* @param array<string, mixed> $request
* @return array<string, mixed>
*/
private static function redactRequest(array $request): array
{
return array_diff_key($request, array_flip(['cardpan', 'cardcvc2']));
}
/**
* gets response string an puts it into an array
*