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,50 @@
<?php
declare(strict_types=1);
namespace Esun\OceanpaymentKlarna\Model\Callback;
use Magento\Framework\Exception\LocalizedException;
class Parser
{
private const FIELDS = [
'notice_type', 'push_dateTime', 'response_type', 'account', 'terminal', 'signValue',
'methods', 'order_number', 'card_country', 'order_currency', 'order_amount', 'order_notes',
'card_number', 'card_type', 'payment_country', 'payment_id', 'payment_status',
'payment_authType', 'payment_details', 'payment_solutions', 'payment_risk', 'payment_amount',
'payment_exchangeRate', 'pay_barCode', 'auth_reason', 'order_operator', 'auth_code',
];
public function parse(string $body, array $parameters): array
{
if (strlen($body) > 1048576) {
throw new LocalizedException(__('Oceanpayment callback body is too large.'));
}
$source = $parameters;
if (str_starts_with(ltrim($body), '<')) {
$previous = libxml_use_internal_errors(true);
try {
$xml = simplexml_load_string($body, \SimpleXMLElement::class, LIBXML_NONET | LIBXML_NOCDATA);
} finally {
libxml_clear_errors();
libxml_use_internal_errors($previous);
}
if ($xml === false) {
throw new LocalizedException(__('Oceanpayment callback XML is invalid.'));
}
$source = [];
foreach (self::FIELDS as $field) {
$source[$field] = isset($xml->{$field}) ? (string)$xml->{$field} : '';
}
}
$result = [];
foreach (self::FIELDS as $field) {
$value = $source[$field] ?? '';
$result[$field] = is_scalar($value) ? trim((string)$value) : '';
}
return $result;
}
}
@@ -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,
};
}
}
@@ -0,0 +1,68 @@
<?php
declare(strict_types=1);
namespace Esun\OceanpaymentKlarna\Model;
use Magento\Framework\App\Config\ScopeConfigInterface;
use Magento\Store\Model\ScopeInterface;
class Config
{
public const METHOD_CODE = 'esun_oceanpayment_klarna';
public const METHODS_VALUE = 'Klarna';
public const SANDBOX_ENDPOINT = 'https://test-secure.oceanpayment.com/gateway/service/sendTrade';
public const PRODUCTION_ENDPOINT = 'https://secure.oceanpayment.com/gateway/service/sendTrade';
private const PATH_PREFIX = 'payment/' . self::METHOD_CODE . '/';
public function __construct(
private readonly ScopeConfigInterface $scopeConfig,
private readonly SecretValueDecoder $secretValueDecoder
) {
}
public function getValue(string $field, ?int $storeId = null): string
{
return trim((string)$this->scopeConfig->getValue(
self::PATH_PREFIX . $field,
ScopeInterface::SCOPE_STORE,
$storeId
));
}
public function getSecret(string $field, ?int $storeId = null): string
{
$prefix = $this->isSandbox($storeId) ? 'sandbox_' : 'production_';
return $this->secretValueDecoder->decode($this->getValue($prefix . $field, $storeId));
}
public function isSandbox(?int $storeId = null): bool
{
return $this->scopeConfig->isSetFlag(
self::PATH_PREFIX . 'sandbox',
ScopeInterface::SCOPE_STORE,
$storeId
);
}
public function isDebug(?int $storeId = null): bool
{
return $this->scopeConfig->isSetFlag(
self::PATH_PREFIX . 'debug',
ScopeInterface::SCOPE_STORE,
$storeId
);
}
public function getEndpoint(?int $storeId = null): string
{
return $this->isSandbox($storeId) ? self::SANDBOX_ENDPOINT : self::PRODUCTION_ENDPOINT;
}
public function isConfigured(?int $storeId = null): bool
{
return $this->getSecret('account', $storeId) !== ''
&& $this->getSecret('terminal', $storeId) !== ''
&& $this->getSecret('secure_code', $storeId) !== '';
}
}
@@ -0,0 +1,29 @@
<?php
declare(strict_types=1);
namespace Esun\OceanpaymentKlarna\Model;
use Magento\Checkout\Model\ConfigProviderInterface;
use Magento\Framework\UrlInterface;
class ConfigProvider implements ConfigProviderInterface
{
public function __construct(
private readonly UrlInterface $urlBuilder
) {
}
public function getConfig(): array
{
return [
'payment' => [
Config::METHOD_CODE => [
'redirectUrl' => $this->urlBuilder->getUrl(
'oceanpaymentklarna/payment/redirect',
['_secure' => true, '_nosid' => true]
),
],
],
];
}
}
@@ -0,0 +1,114 @@
<?php
declare(strict_types=1);
namespace Esun\OceanpaymentKlarna\Model\Gateway;
use Esun\OceanpaymentKlarna\Model\Config;
use Esun\OceanpaymentKlarna\Model\Signature;
use Magento\Framework\Exception\LocalizedException;
use Magento\Framework\HTTP\Client\CurlFactory;
use Magento\Sales\Api\OrderRepositoryInterface;
use Magento\Sales\Model\Order;
use Psr\Log\LoggerInterface;
class Client
{
public function __construct(
private readonly Config $config,
private readonly Signature $signature,
private readonly RequestBuilder $requestBuilder,
private readonly ResponseParser $responseParser,
private readonly CurlFactory $curlFactory,
private readonly OrderRepositoryInterface $orderRepository,
private readonly LoggerInterface $logger
) {
}
public function createPaymentUrl(Order $order): string
{
$storeId = (int)$order->getStoreId();
if (!$this->config->isConfigured($storeId)) {
throw new LocalizedException(__('Oceanpayment Klarna is not fully configured.'));
}
$request = $this->requestBuilder->build($order);
$curl = $this->curlFactory->create();
$curl->setTimeout(30);
$curl->addHeader('Accept', 'application/xml');
$curl->addHeader('Content-Type', 'application/x-www-form-urlencoded');
$curl->setOption(CURLOPT_FOLLOWLOCATION, false);
if ($this->config->isDebug($storeId)) {
$this->logger->debug('Oceanpayment Klarna create request', [
'order_number' => $request['order_number'],
'endpoint' => $this->config->getEndpoint($storeId),
'sandbox' => $this->config->isSandbox($storeId),
'currency' => $request['order_currency'],
'amount' => $request['order_amount'],
'billing_country' => $request['billing_country'],
'item_list_length' => strlen($request['itemList']),
]);
}
try {
$curl->post($this->config->getEndpoint($storeId), $request);
} catch (\Throwable $exception) {
$this->logger->error('Oceanpayment Klarna gateway request failed', [
'order_number' => $order->getIncrementId(),
'exception' => $exception,
]);
throw new LocalizedException(__('Unable to connect to Oceanpayment Klarna.'), $exception);
}
$status = $curl->getStatus();
if ($status < 200 || $status >= 300) {
throw new LocalizedException(__('Oceanpayment returned HTTP status %1.', $status));
}
$response = $this->responseParser->parse((string)$curl->getBody());
$this->validateResponse($order, $response);
$payment = $order->getPayment();
$payment->setAdditionalInformation('oceanpayment_klarna_payment_id', $response['payment_id']);
$payment->setAdditionalInformation('oceanpayment_klarna_pay_url', $response['pay_url']);
$payment->setAdditionalInformation('oceanpayment_klarna_create_result', $response['pay_details']);
$this->orderRepository->save($order);
return $response['pay_url'];
}
private function validateResponse(Order $order, array $response): void
{
$storeId = (int)$order->getStoreId();
if (!hash_equals($this->config->getSecret('account', $storeId), $response['account'])
|| !hash_equals($this->config->getSecret('terminal', $storeId), $response['terminal'])
|| !hash_equals((string)$order->getIncrementId(), $response['order_number'])
|| !hash_equals(strtoupper((string)$order->getOrderCurrencyCode()), strtoupper($response['order_currency']))
|| abs((float)$order->getGrandTotal() - (float)$response['order_amount']) >= 0.005
) {
throw new LocalizedException(__('Oceanpayment response did not match the Magento order.'));
}
if (!$this->signature->verifyCreateResponse(
$response,
$this->config->getSecret('secure_code', $storeId)
)) {
throw new LocalizedException(__('Oceanpayment response signature verification failed.'));
}
if ($response['pay_results'] !== '1') {
throw new LocalizedException(__('Oceanpayment rejected the order: %1', $response['pay_details']));
}
if (!$this->isAllowedPaymentUrl($response['pay_url'])) {
throw new LocalizedException(__('Oceanpayment returned an invalid payment URL.'));
}
}
public function isAllowedPaymentUrl(string $url): bool
{
$parts = parse_url($url);
$host = strtolower((string)($parts['host'] ?? ''));
return ($parts['scheme'] ?? '') === 'https'
&& ($host === 'oceanpayment.com' || str_ends_with($host, '.oceanpayment.com'));
}
}
@@ -0,0 +1,128 @@
<?php
declare(strict_types=1);
namespace Esun\OceanpaymentKlarna\Model\Gateway;
use Magento\Framework\Exception\LocalizedException;
use Magento\Sales\Model\Order;
class ItemListBuilder
{
public function build(Order $order): string
{
$items = $order->getAllVisibleItems();
if ($items === []) {
throw new LocalizedException(__('Klarna requires at least one order item.'));
}
$names = [];
$skus = [];
foreach ($items as $item) {
$names[] = (string)$item->getName();
$skus[] = (string)$item->getSku();
}
$shipping = max(0, $this->toCents((float)$order->getShippingAmount()));
$tax = max(0, $this->toCents((float)$order->getTaxAmount()));
$grandTotal = $this->toCents((float)$order->getGrandTotal());
$goods = $grandTotal - $shipping - $tax;
if ($goods <= 0) {
throw new LocalizedException(__('Klarna requires a positive merchandise amount.'));
}
// Match Oceanpayment's Magento Klarna payload: one net merchandise
// node plus fixed discount, shipping and tax nodes. This avoids sending
// zero-value gifts or synthetic overflow products to Klarna.
$nodes = [
$this->node(
'1',
implode(';', $names),
implode(';', $skus),
$goods,
'1',
$goods,
number_format($tax / $goods, 2, '.', ''),
$tax
),
$this->node('3', 'discount', 'discount', 0, '0', 0, '0', 0),
$this->node('4', 'shipping_fee', 'shipping', $shipping, '1', $shipping, '0', 0),
$this->node('5', 'sales_tax', 'tax', $tax, '1', $tax, '0', $tax),
];
$this->assertTotal($order, $nodes);
return $this->encode($nodes);
}
private function node(
string $type,
string $title,
string $sku,
int $price,
string $quantity,
int $total,
string $taxRate,
int $taxPrice
): array {
return [
'type' => $type,
'title' => $this->clean($title, 100),
'sku' => $this->clean($sku, 100),
'price' => $this->money($price),
'quantity' => $quantity,
'total_amount' => $this->money($total),
'taxRate' => $taxRate,
'taxPrice' => $this->money($taxPrice),
'image_url' => '',
'product_url' => '',
'remark' => '',
'_cents' => $total,
];
}
private function assertTotal(Order $order, array $nodes): void
{
$total = 0;
foreach ($nodes as $node) {
$total += $node['type'] === '3' ? -$node['_cents'] : $node['_cents'];
}
if ($total !== $this->toCents((float)$order->getGrandTotal())) {
throw new LocalizedException(__('Klarna item total does not match the order total.'));
}
}
private function encode(array $nodes): string
{
$payload = [];
foreach ($nodes as $index => $node) {
unset($node['_cents']);
$payload[(string)$index] = $node;
}
$json = json_encode((object)$payload, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
if ($json === false) {
throw new LocalizedException(__('Unable to encode Klarna item data.'));
}
return $json;
}
private function clean(string $value, int $length): string
{
$value = preg_replace('/[<>\'"\x00-\x1F]/u', ' ', trim($value)) ?? '';
$value = preg_replace('/\s+/u', ' ', $value) ?? '';
return mb_substr($value !== '' ? $value : '-', 0, $length);
}
private function toCents(float $amount): int
{
return (int)round($amount * 100);
}
private function money(int $cents): string
{
return number_format($cents / 100, 2, '.', '');
}
}
@@ -0,0 +1,127 @@
<?php
declare(strict_types=1);
namespace Esun\OceanpaymentKlarna\Model\Gateway;
use Esun\OceanpaymentKlarna\Model\Config;
use Esun\OceanpaymentKlarna\Model\Signature;
use Magento\Framework\UrlInterface;
use Magento\Sales\Model\Order;
use Magento\Sales\Model\Order\Address;
class RequestBuilder
{
public function __construct(
private readonly Config $config,
private readonly Signature $signature,
private readonly UrlInterface $urlBuilder,
private readonly ItemListBuilder $itemListBuilder
) {
}
public function build(Order $order): array
{
$method = (string)$order->getPayment()->getMethod();
if ($method !== Config::METHOD_CODE) {
throw new \InvalidArgumentException('The order does not use Oceanpayment Klarna.');
}
$data = $this->buildBase($order);
$data['itemList'] = $this->itemListBuilder->build($order);
$data['backUrl'] = $this->urlBuilder->getUrl(
'oceanpaymentklarna/payment/back',
['_secure' => true, '_nosid' => true]
);
$data['signValue'] = $this->signature->createRequest(
$data,
$this->config->getSecret('secure_code', (int)$order->getStoreId())
);
return array_filter($data, static fn ($value): bool => $value !== '');
}
private function buildBase(Order $order): array
{
$storeId = (int)$order->getStoreId();
$billing = $order->getBillingAddress();
if (!$billing) {
throw new \InvalidArgumentException('The order has no billing address.');
}
$shipping = $order->getShippingAddress() ?: $billing;
$data = [
'account' => $this->config->getSecret('account', $storeId),
'terminal' => $this->config->getSecret('terminal', $storeId),
'noticeUrl' => $this->urlBuilder->getUrl(
'oceanpaymentklarna/payment/notify',
['_secure' => true, '_nosid' => true]
),
'methods' => Config::METHODS_VALUE,
'order_number' => $this->clean((string)$order->getIncrementId(), 50),
'order_currency' => strtoupper($this->clean((string)$order->getOrderCurrencyCode(), 3)),
'order_amount' => number_format((float)$order->getGrandTotal(), 2, '.', ''),
'billing_firstName' => $this->clean((string)$billing->getFirstname(), 50),
'billing_lastName' => $this->clean((string)$billing->getLastname(), 50),
'billing_email' => $this->clean((string)$billing->getEmail(), 50),
'billing_phone' => $this->clean((string)$billing->getTelephone(), 50),
'billing_country' => strtoupper($this->clean((string)$billing->getCountryId(), 100)),
'billing_state' => $this->clean($this->getRegion($billing), 100),
'billing_city' => $this->clean((string)$billing->getCity(), 500),
'billing_address' => $this->clean(implode(' ', $billing->getStreet()), 500),
'billing_zip' => $this->clean((string)$billing->getPostcode(), 50),
'billing_ip' => $this->clean((string)$order->getRemoteIp(), 50),
'ship_firstName' => $this->clean((string)$shipping->getFirstname(), 50),
'ship_lastName' => $this->clean((string)$shipping->getLastname(), 50),
'ship_email' => $this->clean((string)$shipping->getEmail(), 50),
'ship_phone' => $this->clean((string)$shipping->getTelephone(), 50),
'ship_country' => strtoupper($this->clean((string)$shipping->getCountryId(), 100)),
'ship_state' => $this->clean($this->getRegion($shipping), 100),
'ship_city' => $this->clean((string)$shipping->getCity(), 500),
'ship_addr' => $this->clean(implode(' ', $shipping->getStreet()), 500),
'ship_zip' => $this->clean((string)$shipping->getPostcode(), 50),
'order_notes' => $this->clean((string)$order->getIncrementId(), 50),
'cart_info' => 'PC',
'cart_api' => 'V2.0',
'pages' => '0',
];
return $data + $this->getProductData($order);
}
private function getProductData(Order $order): array
{
$names = [];
$quantities = [];
$skus = [];
$prices = [];
foreach ($order->getAllVisibleItems() as $item) {
$names[] = $this->cleanListValue((string)$item->getName(), 120);
$quantities[] = $this->cleanListValue((string)(float)$item->getQtyOrdered(), 20);
$skus[] = $this->cleanListValue((string)$item->getSku(), 120);
$prices[] = number_format((float)$item->getPrice(), 2, '.', '');
}
return [
'productName' => mb_substr(implode(',', $names), 0, 500),
'productNum' => mb_substr(implode(',', $quantities), 0, 50),
'productSku' => mb_substr(implode(',', $skus), 0, 500),
'productPrice' => mb_substr(implode(',', $prices), 0, 500),
];
}
private function getRegion(Address $address): string
{
return (string)($address->getRegionCode() ?: $address->getRegion() ?: '-');
}
private function cleanListValue(string $value, int $length): string
{
return str_replace(',', ' ', $this->clean($value, $length));
}
private function clean(string $value, int $length): string
{
return mb_substr($this->signature->sanitize($value), 0, $length);
}
}
@@ -0,0 +1,45 @@
<?php
declare(strict_types=1);
namespace Esun\OceanpaymentKlarna\Model\Gateway;
use Magento\Framework\Exception\LocalizedException;
class ResponseParser
{
private const FIELDS = [
'account',
'terminal',
'signValue',
'order_number',
'order_currency',
'order_amount',
'order_notes',
'payment_id',
'pay_url',
'pay_results',
'pay_details',
];
public function parse(string $body): array
{
$previous = libxml_use_internal_errors(true);
try {
$xml = simplexml_load_string($body, \SimpleXMLElement::class, LIBXML_NONET | LIBXML_NOCDATA);
} finally {
libxml_clear_errors();
libxml_use_internal_errors($previous);
}
if ($xml === false) {
throw new LocalizedException(__('Oceanpayment returned an invalid XML response.'));
}
$result = [];
foreach (self::FIELDS as $field) {
$result[$field] = isset($xml->{$field}) ? trim((string)$xml->{$field}) : '';
}
return $result;
}
}
@@ -0,0 +1,43 @@
<?php
declare(strict_types=1);
namespace Esun\OceanpaymentKlarna\Model;
use Magento\Sales\Model\Order;
use Magento\Sales\Model\Order\Config as OrderConfig;
class OrderStatusManager
{
private const STATES = [
Order::STATE_NEW,
Order::STATE_PENDING_PAYMENT,
Order::STATE_PROCESSING,
Order::STATE_COMPLETE,
Order::STATE_CLOSED,
Order::STATE_CANCELED,
Order::STATE_HOLDED,
Order::STATE_PAYMENT_REVIEW,
];
public function __construct(private readonly OrderConfig $orderConfig)
{
}
public function apply(Order $order, string $status, string $fallbackState): void
{
$state = $this->findState($status) ?: $fallbackState;
$order->setState($state);
$order->setStatus($status ?: ($this->orderConfig->getStateDefaultStatus($state) ?: $state));
}
private function findState(string $status): ?string
{
foreach (self::STATES as $state) {
if (in_array($status, $this->orderConfig->getStateStatuses($state, false), true)) {
return $state;
}
}
return null;
}
}
@@ -0,0 +1,57 @@
<?php
declare(strict_types=1);
namespace Esun\OceanpaymentKlarna\Model;
use Magento\Framework\DataObject;
use Magento\Payment\Model\Method\AbstractMethod;
use Magento\Quote\Api\Data\CartInterface;
use Magento\Sales\Model\Order;
class PaymentMethod extends AbstractMethod
{
protected $_code = Config::METHOD_CODE;
protected $_isGateway = true;
protected $_isOffline = false;
protected $_canUseInternal = false;
protected $_canUseCheckout = true;
protected $_isInitializeNeeded = true;
protected $_debugReplacePrivateDataKeys = [
'sandbox_account',
'sandbox_terminal',
'sandbox_secure_code',
'sandbox_public_key',
'production_account',
'production_terminal',
'production_secure_code',
'production_public_key',
'signValue',
'itemList',
];
public function initialize($paymentAction, $stateObject): self
{
if ($stateObject instanceof DataObject) {
$stateObject->setState(Order::STATE_PENDING_PAYMENT);
$stateObject->setStatus(
$this->getConfigData('new_order_status') ?: Order::STATE_PENDING_PAYMENT
);
$stateObject->setIsNotified(false);
}
return $this;
}
public function isAvailable(?CartInterface $quote = null): bool
{
if (!parent::isAvailable($quote)) {
return false;
}
$prefix = $this->getConfigData('sandbox') ? 'sandbox_' : 'production_';
return trim((string)$this->getConfigData($prefix . 'account')) !== ''
&& trim((string)$this->getConfigData($prefix . 'terminal')) !== ''
&& trim((string)$this->getConfigData($prefix . 'secure_code')) !== '';
}
}
@@ -0,0 +1,43 @@
<?php
declare(strict_types=1);
namespace Esun\OceanpaymentKlarna\Model;
use Magento\Framework\Encryption\EncryptorInterface;
class SecretValueDecoder
{
private const MAX_DECRYPTION_DEPTH = 3;
public function __construct(private readonly EncryptorInterface $encryptor)
{
}
public function decode(string $value): string
{
$decoded = trim($value);
for ($depth = 0; $depth < self::MAX_DECRYPTION_DEPTH; $depth++) {
if (!$this->isEncrypted($decoded)) {
break;
}
try {
$next = $this->encryptor->decrypt($decoded);
} catch (\Throwable) {
break;
}
if ($next === '' || hash_equals($decoded, $next)) {
break;
}
$decoded = trim($next);
}
return $decoded;
}
private function isEncrypted(string $value): bool
{
return preg_match('/^\d+:\d+:/', $value) === 1;
}
}
@@ -0,0 +1,96 @@
<?php
declare(strict_types=1);
namespace Esun\OceanpaymentKlarna\Model;
class Signature
{
private const CALLBACK_FIELDS = [
'account',
'terminal',
'order_number',
'order_currency',
'order_amount',
'order_notes',
'card_number',
'payment_id',
'payment_authType',
'payment_status',
'payment_details',
'payment_risk',
];
private const CREATE_RESPONSE_FIELDS = [
'account',
'terminal',
'order_number',
'order_currency',
'order_amount',
'order_notes',
'payment_id',
'pay_url',
'pay_results',
'pay_details',
];
public function sanitize(string $value): string
{
return str_replace(['<', '>', "'", '"'], ' ', trim($value));
}
public function createRequest(array $data, string $secureCode): string
{
$plain = (string)($data['account'] ?? '')
. (string)($data['terminal'] ?? '')
. (string)($data['backUrl'] ?? '')
. (string)($data['order_number'] ?? '')
. (string)($data['order_currency'] ?? '')
. (string)($data['order_amount'] ?? '')
. (string)($data['billing_firstName'] ?? '')
. (string)($data['billing_lastName'] ?? '')
. (string)($data['billing_email'] ?? '')
. $secureCode;
return hash('sha256', $plain);
}
public function verifyCreateResponse(array $data, string $secureCode): bool
{
return $this->verifyFields($data, self::CREATE_RESPONSE_FIELDS, $secureCode);
}
public function verifyCallback(array $data, string $secureCode): bool
{
$provided = strtolower(trim((string)($data['signValue'] ?? '')));
if (!preg_match('/^[a-f0-9]{64}$/', $provided)) {
return false;
}
return hash_equals($this->createCallback($data, $secureCode), $provided);
}
public function createCallback(array $data, string $secureCode): string
{
return $this->createFields($data, self::CALLBACK_FIELDS, $secureCode);
}
private function verifyFields(array $data, array $fields, string $secureCode): bool
{
$provided = strtolower(trim((string)($data['signValue'] ?? '')));
if (!preg_match('/^[a-f0-9]{64}$/', $provided)) {
return false;
}
return hash_equals($this->createFields($data, $fields, $secureCode), $provided);
}
private function createFields(array $data, array $fields, string $secureCode): string
{
$plain = '';
foreach ($fields as $field) {
$plain .= (string)($data[$field] ?? '');
}
return hash('sha256', $plain . $secureCode);
}
}