This commit is contained in:
2026-09-15 10:35:56 +08:00
commit 782f8ea7aa
4086 changed files with 631288 additions and 0 deletions
@@ -0,0 +1,178 @@
<?php
declare(strict_types=1);
namespace Esun\OceanpaymentKlarna\Model\Callback;
use Esun\OceanpaymentKlarna\Model\Config;
use Esun\OceanpaymentKlarna\Model\OrderStatusManager;
use Esun\OceanpaymentKlarna\Model\Signature;
use Magento\Framework\Exception\LocalizedException;
use Magento\Sales\Api\OrderRepositoryInterface;
use Magento\Sales\Model\Order;
use Magento\Sales\Model\OrderFactory;
use Psr\Log\LoggerInterface;
class Processor
{
public const SUCCESS = 'success';
public const FAILURE = 'failure';
public const PENDING = 'pending';
public function __construct(
private readonly Config $config,
private readonly Signature $signature,
private readonly OrderFactory $orderFactory,
private readonly OrderRepositoryInterface $orderRepository,
private readonly OrderStatusManager $statusManager,
private readonly LoggerInterface $logger
) {
}
public function process(array $data, bool $isAsync): string
{
$orderNumber = (string)($data['order_number'] ?? '');
if ($orderNumber === '' || (string)($data['payment_id'] ?? '') === '') {
throw new LocalizedException(__('Oceanpayment callback is missing required fields.'));
}
/** @var Order $order */
$order = $this->orderFactory->create()->loadByIncrementId($orderNumber);
if (!$order->getEntityId()
|| (string)$order->getPayment()->getMethod() !== Config::METHOD_CODE
) {
throw new LocalizedException(__('The Oceanpayment Klarna order could not be found.'));
}
$this->validate($order, $data);
$payment = $order->getPayment();
$paymentId = (string)$data['payment_id'];
$status = (string)$data['payment_status'];
if ((string)$payment->getAdditionalInformation('oceanpayment_klarna_processed_payment_id') === $paymentId
&& (string)$payment->getAdditionalInformation('oceanpayment_klarna_processed_status') === $status
) {
return $this->mapStatus($status);
}
$payment->setAdditionalInformation('oceanpayment_klarna_payment_id', $paymentId);
$payment->setAdditionalInformation('oceanpayment_klarna_processed_payment_id', $paymentId);
$payment->setAdditionalInformation('oceanpayment_klarna_processed_status', $status);
$payment->setAdditionalInformation('oceanpayment_klarna_payment_details', (string)$data['payment_details']);
$payment->setAdditionalInformation('oceanpayment_klarna_auth_type', (string)$data['payment_authType']);
$payment->setTransactionId($paymentId);
$payment->setLastTransId($paymentId);
$result = $this->mapStatus($status);
if ($result === self::SUCCESS) {
$this->processSuccess($order, $data);
} elseif ($result === self::PENDING) {
$this->processPending($order, $data);
} else {
$this->processFailure($order, $data, $isAsync);
}
$this->orderRepository->save($order);
if ($this->config->isDebug((int)$order->getStoreId())) {
$this->logger->debug('Oceanpayment Klarna callback processed', [
'order_number' => $orderNumber,
'payment_id' => $paymentId,
'payment_status' => $status,
'async' => $isAsync,
]);
}
return $result;
}
private function validate(Order $order, array $data): void
{
$storeId = (int)$order->getStoreId();
if (!hash_equals($this->config->getSecret('account', $storeId), (string)$data['account'])
|| !hash_equals($this->config->getSecret('terminal', $storeId), (string)$data['terminal'])
) {
throw new LocalizedException(__('Oceanpayment callback account verification failed.'));
}
if (!hash_equals(
strtoupper((string)$order->getOrderCurrencyCode()),
strtoupper((string)$data['order_currency'])
)
|| abs((float)$order->getGrandTotal() - (float)$data['order_amount']) >= 0.005
) {
throw new LocalizedException(__('Oceanpayment callback amount verification failed.'));
}
if (!$this->signature->verifyCallback($data, $this->config->getSecret('secure_code', $storeId))) {
throw new LocalizedException(__('Oceanpayment callback signature verification failed.'));
}
$expectedPaymentId = (string)$order->getPayment()
->getAdditionalInformation('oceanpayment_klarna_payment_id');
if ($expectedPaymentId !== '' && !hash_equals($expectedPaymentId, (string)$data['payment_id'])) {
throw new LocalizedException(__('Oceanpayment callback payment ID verification failed.'));
}
if ((string)$data['methods'] !== Config::METHODS_VALUE) {
throw new LocalizedException(__('Oceanpayment callback payment method verification failed.'));
}
if (!in_array((string)$data['payment_status'], ['-1', '0', '1'], true)) {
throw new LocalizedException(__('Oceanpayment returned an unknown payment status.'));
}
}
private function processSuccess(Order $order, array $data): void
{
$payment = $order->getPayment();
$payment->setIsTransactionClosed(true);
if ($order->canInvoice() && (float)$order->getTotalDue() > 0.0001) {
$payment->registerCaptureNotification((float)$data['order_amount'], true);
}
$this->statusManager->apply(
$order,
$this->config->getValue('success_order_status', (int)$order->getStoreId()),
Order::STATE_PROCESSING
);
$order->addCommentToStatusHistory(
__('Oceanpayment Klarna payment approved. Payment ID: %1', $data['payment_id'])
);
}
private function processPending(Order $order, array $data): void
{
$order->getPayment()->setIsTransactionClosed(false)->setIsTransactionPending(true);
$this->statusManager->apply(
$order,
$this->config->getValue('pending_order_status', (int)$order->getStoreId()),
Order::STATE_PAYMENT_REVIEW
);
$order->addCommentToStatusHistory(
__('Oceanpayment Klarna authorization is pending. Payment ID: %1', $data['payment_id'])
);
}
private function processFailure(Order $order, array $data, bool $isAsync): void
{
$order->getPayment()->setIsTransactionClosed(true);
if ($isAsync && $order->canCancel()) {
$order->cancel();
$this->statusManager->apply(
$order,
$this->config->getValue('failure_order_status', (int)$order->getStoreId()),
Order::STATE_CANCELED
);
}
$order->addCommentToStatusHistory(
__(
'Oceanpayment Klarna payment failed. Payment ID: %1. Details: %2',
$data['payment_id'],
$data['payment_details']
)
);
}
private function mapStatus(string $status): string
{
return match ($status) {
'1' => self::SUCCESS,
'-1' => self::PENDING,
default => self::FAILURE,
};
}
}