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,27 @@
<?php
declare(strict_types=1);
namespace Esun\OceanpaymentKlarna\Block\Adminhtml\System\Config\Form\Field;
use Esun\OceanpaymentKlarna\Model\SecretValueDecoder;
use Magento\Backend\Block\Template\Context;
use Magento\Config\Block\System\Config\Form\Field;
use Magento\Framework\Data\Form\Element\AbstractElement;
class DecryptedText extends Field
{
public function __construct(
Context $context,
private readonly SecretValueDecoder $secretValueDecoder,
array $data = []
) {
parent::__construct($context, $data);
}
protected function _getElementHtml(AbstractElement $element): string
{
$element->setValue($this->secretValueDecoder->decode((string)$element->getValue()));
return parent::_getElementHtml($element);
}
}
@@ -0,0 +1,22 @@
<?php
declare(strict_types=1);
namespace Esun\OceanpaymentKlarna\Controller\Payment;
use Magento\Framework\App\Action\Action;
use Magento\Framework\App\CsrfAwareActionInterface;
use Magento\Framework\App\Request\InvalidRequestException;
use Magento\Framework\App\RequestInterface;
abstract class AbstractCallback extends Action implements CsrfAwareActionInterface
{
public function createCsrfValidationException(RequestInterface $request): ?InvalidRequestException
{
return null;
}
public function validateForCsrf(RequestInterface $request): ?bool
{
return true;
}
}
@@ -0,0 +1,55 @@
<?php
declare(strict_types=1);
namespace Esun\OceanpaymentKlarna\Controller\Payment;
use Esun\OceanpaymentKlarna\Model\Callback\Parser;
use Esun\OceanpaymentKlarna\Model\Callback\Processor;
use Magento\Framework\App\Action\Context;
use Magento\Framework\App\Action\HttpGetActionInterface;
use Magento\Framework\App\Action\HttpPostActionInterface;
use Magento\Framework\Controller\Result\Redirect as ResultRedirect;
use Psr\Log\LoggerInterface;
class Back extends AbstractCallback implements HttpGetActionInterface, HttpPostActionInterface
{
public function __construct(
Context $context,
private readonly Parser $parser,
private readonly Processor $processor,
private readonly LoggerInterface $logger
) {
parent::__construct($context);
}
public function execute(): ResultRedirect
{
/** @var ResultRedirect $result */
$result = $this->resultRedirectFactory->create();
try {
$data = $this->parser->parse(
(string)$this->getRequest()->getContent(),
(array)$this->getRequest()->getParams()
);
$paymentResult = $this->processor->process($data, false);
if ($paymentResult === Processor::FAILURE) {
$this->messageManager->addErrorMessage(
__('Klarna payment was not completed: %1', $data['payment_details'])
);
} elseif ($paymentResult === Processor::PENDING) {
$this->messageManager->addNoticeMessage(
__('Your Klarna authorization is being confirmed. The order will update automatically.')
);
}
} catch (\Throwable $exception) {
$this->logger->warning('Oceanpayment Klarna browser callback was rejected', [
'exception' => $exception,
]);
$this->messageManager->addErrorMessage(
__('The Klarna payment result could not be verified. Please contact customer service if charged.')
);
}
return $result->setPath('checkout/onepage/success');
}
}
@@ -0,0 +1,44 @@
<?php
declare(strict_types=1);
namespace Esun\OceanpaymentKlarna\Controller\Payment;
use Esun\OceanpaymentKlarna\Model\Callback\Parser;
use Esun\OceanpaymentKlarna\Model\Callback\Processor;
use Magento\Framework\App\Action\Context;
use Magento\Framework\App\Action\HttpPostActionInterface;
use Magento\Framework\Controller\Result\Raw;
use Magento\Framework\Controller\Result\RawFactory;
use Psr\Log\LoggerInterface;
class Notify extends AbstractCallback implements HttpPostActionInterface
{
public function __construct(
Context $context,
private readonly Parser $parser,
private readonly Processor $processor,
private readonly RawFactory $rawFactory,
private readonly LoggerInterface $logger
) {
parent::__construct($context);
}
public function execute(): Raw
{
$result = $this->rawFactory->create();
try {
$data = $this->parser->parse(
(string)$this->getRequest()->getContent(),
(array)$this->getRequest()->getParams()
);
$this->processor->process($data, true);
return $result->setContents('receive-ok');
} catch (\Throwable $exception) {
$this->logger->warning('Oceanpayment Klarna asynchronous callback was rejected', [
'exception' => $exception,
]);
$this->getResponse()->setHttpResponseCode(400);
return $result->setContents('invalid');
}
}
}
@@ -0,0 +1,66 @@
<?php
declare(strict_types=1);
namespace Esun\OceanpaymentKlarna\Controller\Payment;
use Esun\OceanpaymentKlarna\Model\Config;
use Esun\OceanpaymentKlarna\Model\Gateway\Client;
use Magento\Checkout\Model\Session as CheckoutSession;
use Magento\Framework\App\Action\Action;
use Magento\Framework\App\Action\Context;
use Magento\Framework\App\Action\HttpGetActionInterface;
use Magento\Framework\Controller\Result\Redirect as ResultRedirect;
use Magento\Sales\Api\OrderRepositoryInterface;
use Psr\Log\LoggerInterface;
class Redirect extends Action implements HttpGetActionInterface
{
public function __construct(
Context $context,
private readonly CheckoutSession $checkoutSession,
private readonly Client $client,
private readonly OrderRepositoryInterface $orderRepository,
private readonly LoggerInterface $logger
) {
parent::__construct($context);
}
public function execute(): ResultRedirect
{
/** @var ResultRedirect $result */
$result = $this->resultRedirectFactory->create();
$order = $this->checkoutSession->getLastRealOrder();
if (!$order->getEntityId()
|| (string)$order->getPayment()->getMethod() !== Config::METHOD_CODE
) {
$this->messageManager->addErrorMessage(__('The Oceanpayment Klarna order is no longer available.'));
return $result->setPath('checkout/cart');
}
try {
$cachedUrl = (string)$order->getPayment()
->getAdditionalInformation('oceanpayment_klarna_pay_url');
$paymentUrl = $cachedUrl !== '' && $this->client->isAllowedPaymentUrl($cachedUrl)
? $cachedUrl
: $this->client->createPaymentUrl($order);
return $result->setUrl($paymentUrl);
} catch (\Throwable $exception) {
$this->logger->error('Oceanpayment Klarna initialization failed', [
'order_number' => $order->getIncrementId(),
'exception' => $exception,
]);
if ($order->canCancel()) {
$order->cancel();
$order->addCommentToStatusHistory(__('Oceanpayment Klarna initialization failed.'));
$this->orderRepository->save($order);
}
$this->checkoutSession->restoreQuote();
$this->messageManager->addErrorMessage(
__('Klarna payment initialization failed. Please try again or choose another payment method.')
);
return $result->setPath('checkout/cart');
}
}
}
@@ -0,0 +1,13 @@
<?php
declare(strict_types=1);
namespace Esun\OceanpaymentKlarna\Logger;
use Magento\Framework\Logger\Handler\Base;
use Monolog\Logger;
class Handler extends Base
{
protected $fileName = '/var/log/oceanpayment-klarna.log';
protected $loggerType = Logger::DEBUG;
}
@@ -0,0 +1,14 @@
<?php
declare(strict_types=1);
namespace Esun\OceanpaymentKlarna\Logger;
use Monolog\Logger as MonologLogger;
class Logger extends MonologLogger
{
public function __construct(Handler $handler)
{
parent::__construct('oceanpayment-klarna', [$handler]);
}
}
@@ -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);
}
}
@@ -0,0 +1,39 @@
# Esun_OceanpaymentKlarna
Magento 2 钱海 Oceanpayment Klarna 独立支付模块。模块使用 Oceanpayment Hosted Checkout,
不采集消费者的 Klarna 凭据,也不依赖或修改 `Esun_Oceanpayment`。
## 配置
后台路径:`Stores > Configuration > Sales > Payment Methods > 钱海支付 - Klarna`。
分别在网站范围配置测试和正式环境对应的 `Account`、`Terminal`、`Secure Code`。后台仍可保存钱海提供的 `Key`,但 Klarna Hosted Checkout 不会把它发送到支付接口。
凭据通过 Magento 加密配置保存,请勿写入源码或提交到 Git。
沙盒测试时启用“沙盒模式”;上线时关闭沙盒模式即可自动使用正式凭据。支付方式代码固定为
`Klarna`,无需在后台修改。
默认只向 Oceanpayment 文档列出的 Klarna 国家开放。实际国家、币种及业务类型仍以对应钱海
终端的开通范围为准。
## 支付流程
1. Magento 创建 `pending_payment` 订单;
2. 模块生成 Klarna 必需的 `itemList`,并验证明细金额等于订单总额;
3. 服务端调用 Oceanpayment `sendTrade`;
4. 用户跳转至 Oceanpayment/Klarna 完成支付;
5. 独立的同步返回和异步通知完成验签及幂等处理;
6. `payment_status=-1` 进入支付审核,`payment_status=1` 时登记收款并开票。
当前模块兼容由 Oceanpayment 开通的 Auto Capture。若商户使用 Manual Capture,需要另外接入
Oceanpayment 的预授权完成/撤销接口后再启用生产支付。
## 安装
```bash
php bin/magento module:enable Esun_OceanpaymentKlarna
php bin/magento setup:upgrade
php bin/magento cache:flush
```
生产模式还需重新执行 DI 编译和静态资源部署。
@@ -0,0 +1,52 @@
<?php
declare(strict_types=1);
namespace Esun\OceanpaymentKlarna\Test\Unit\Model;
use Esun\OceanpaymentKlarna\Model\Config;
use Esun\OceanpaymentKlarna\Model\SecretValueDecoder;
use Magento\Framework\App\Config\ScopeConfigInterface;
use Magento\Store\Model\ScopeInterface;
use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\TestCase;
class EnvironmentCredentialsTest extends TestCase
{
public static function environmentProvider(): array
{
return [
'sandbox' => [true, 'sandbox_account', 'sandbox-value'],
'production' => [false, 'production_account', 'production-value'],
];
}
#[DataProvider('environmentProvider')]
public function testSelectsCredentialsForTheActiveEnvironment(
bool $sandbox,
string $field,
string $expected
): void {
$scopeConfig = $this->createMock(ScopeConfigInterface::class);
$scopeConfig->method('isSetFlag')
->with(
'payment/' . Config::METHOD_CODE . '/sandbox',
ScopeInterface::SCOPE_STORE,
1
)
->willReturn($sandbox);
$scopeConfig->method('getValue')
->with(
'payment/' . Config::METHOD_CODE . '/' . $field,
ScopeInterface::SCOPE_STORE,
1
)
->willReturn($expected);
$config = new Config(
$scopeConfig,
new SecretValueDecoder($this->createMock(\Magento\Framework\Encryption\EncryptorInterface::class))
);
self::assertSame($expected, $config->getSecret('account', 1));
}
}
@@ -0,0 +1,70 @@
<?php
declare(strict_types=1);
namespace Esun\OceanpaymentKlarna\Test\Unit\Model\Gateway;
use Esun\OceanpaymentKlarna\Model\Gateway\ItemListBuilder;
use Magento\Sales\Model\Order;
use Magento\Sales\Model\Order\Item;
use PHPUnit\Framework\TestCase;
class ItemListBuilderTest extends TestCase
{
public function testBuildsOceanpaymentCompatibleFixedNodes(): void
{
$item = $this->createMock(Item::class);
$item->method('getName')->willReturn('PLA Basic');
$item->method('getSku')->willReturn('PLA-BASIC');
$order = $this->createMock(Order::class);
$order->method('getAllVisibleItems')->willReturn([$item]);
$order->method('getShippingAmount')->willReturn(5.0);
$order->method('getTaxAmount')->willReturn(2.0);
$order->method('getDiscountAmount')->willReturn(-3.0);
$order->method('getGrandTotal')->willReturn(24.0);
$payload = json_decode((new ItemListBuilder())->build($order), true, 512, JSON_THROW_ON_ERROR);
self::assertCount(4, $payload);
self::assertSame('1', $payload[0]['type']);
self::assertSame('17.00', $payload[0]['price']);
self::assertSame('17.00', $payload[0]['total_amount']);
self::assertSame('0.12', $payload[0]['taxRate']);
self::assertSame('2.00', $payload[0]['taxPrice']);
self::assertArrayHasKey('image_url', $payload[0]);
self::assertArrayHasKey('product_url', $payload[0]);
self::assertArrayHasKey('remark', $payload[0]);
self::assertSame('3', $payload[1]['type']);
self::assertSame('4', $payload[2]['type']);
self::assertSame('5', $payload[3]['type']);
}
public function testAggregatesProductsAndZeroValueGiftIntoOneNetMerchandiseNode(): void
{
$item = $this->createMock(Item::class);
$item->method('getName')->willReturn('Product');
$item->method('getSku')->willReturn('SKU');
$gift = $this->createMock(Item::class);
$gift->method('getName')->willReturn('Free Gift');
$gift->method('getSku')->willReturn('GIFT');
$order = $this->createMock(Order::class);
$order->method('getAllVisibleItems')->willReturn([$item, $gift]);
$order->method('getShippingAmount')->willReturn(0.0);
$order->method('getTaxAmount')->willReturn(0.0);
$order->method('getDiscountAmount')->willReturn(0.0);
$order->method('getGrandTotal')->willReturn(11.5);
$payload = json_decode((new ItemListBuilder())->build($order), true, 512, JSON_THROW_ON_ERROR);
self::assertCount(4, $payload);
self::assertSame('Product;Free Gift', $payload[0]['title']);
self::assertSame('SKU;GIFT', $payload[0]['sku']);
self::assertSame('1', $payload[0]['quantity']);
self::assertSame('11.50', $payload[0]['total_amount']);
self::assertSame('0.00', $payload[1]['total_amount']);
self::assertSame('0.00', $payload[2]['total_amount']);
self::assertSame('0.00', $payload[3]['total_amount']);
}
}
@@ -0,0 +1,43 @@
<?php
declare(strict_types=1);
namespace Esun\OceanpaymentKlarna\Test\Unit\Model;
use Esun\OceanpaymentKlarna\Model\SecretValueDecoder;
use Magento\Framework\Encryption\EncryptorInterface;
use PHPUnit\Framework\TestCase;
class SecretValueDecoderTest extends TestCase
{
public function testLeavesPlainTextValueUnchanged(): void
{
$encryptor = $this->createMock(EncryptorInterface::class);
$encryptor->expects(self::never())->method('decrypt');
self::assertSame('214127', (new SecretValueDecoder($encryptor))->decode('214127'));
}
public function testDecodesSingleEncryptedValue(): void
{
$encryptor = $this->createMock(EncryptorInterface::class);
$encryptor->expects(self::once())
->method('decrypt')
->with('0:3:encrypted')
->willReturn('214127');
self::assertSame('214127', (new SecretValueDecoder($encryptor))->decode('0:3:encrypted'));
}
public function testRecoversDoubleEncryptedValue(): void
{
$encryptor = $this->createMock(EncryptorInterface::class);
$encryptor->expects(self::exactly(2))
->method('decrypt')
->willReturnMap([
['0:3:outer', '0:3:inner'],
['0:3:inner', '214127'],
]);
self::assertSame('214127', (new SecretValueDecoder($encryptor))->decode('0:3:outer'));
}
}
@@ -0,0 +1,32 @@
<?php
declare(strict_types=1);
namespace Esun\OceanpaymentKlarna\Test\Unit\Model;
use Esun\OceanpaymentKlarna\Model\Signature;
use PHPUnit\Framework\TestCase;
class SignatureTest extends TestCase
{
public function testCreatesHostedRequestSignatureInOceanpaymentFieldOrder(): void
{
$data = [
'account' => 'account',
'terminal' => 'terminal',
'backUrl' => 'https://example.com/back',
'order_number' => 'ORDER-1',
'order_currency' => 'USD',
'order_amount' => '10.00',
'billing_firstName' => 'Jane',
'billing_lastName' => 'Doe',
'billing_email' => 'jane@example.com',
];
$plain = implode('', array_values($data)) . 'secure-code';
self::assertSame(
hash('sha256', $plain),
(new Signature())->createRequest($data, 'secure-code')
);
}
}
@@ -0,0 +1,20 @@
{
"name": "esun/module-oceanpayment-klarna",
"description": "Oceanpayment Klarna Hosted Checkout integration for Magento 2",
"type": "magento2-module",
"version": "1.0.0",
"license": ["OSL-3.0", "AFL-3.0"],
"require": {
"php": "^8.1 || ^8.2 || ^8.3 || ^8.4",
"magento/framework": "^103.0",
"magento/module-checkout": "^100.4",
"magento/module-payment": "^100.4",
"magento/module-sales": "^103.0"
},
"autoload": {
"files": ["registration.php"],
"psr-4": {
"Esun\\OceanpaymentKlarna\\": ""
}
}
}
@@ -0,0 +1,148 @@
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Config:etc/system_file.xsd">
<system>
<section id="payment">
<group id="esun_oceanpayment_klarna" translate="label" type="text" sortOrder="820"
showInDefault="1" showInWebsite="1" showInStore="1">
<label>钱海支付 - Klarna</label>
<field id="active" translate="label" type="select" sortOrder="10"
showInDefault="1" showInWebsite="1" showInStore="1">
<label>启用</label>
<source_model>Magento\Config\Model\Config\Source\Yesno</source_model>
</field>
<field id="title" translate="label comment" type="text" sortOrder="20"
showInDefault="1" showInWebsite="1" showInStore="1">
<label>结账页标题</label>
<comment>默认 Pay with Klarna;可按 Store View 配置 Klarna 官方认可的当地语言名称。</comment>
</field>
<field id="sandbox" translate="label comment" type="select" sortOrder="30"
showInDefault="1" showInWebsite="1" showInStore="1">
<label>沙盒模式</label>
<comment>启用时使用测试凭据及 test-secure.oceanpayment.com。</comment>
<source_model>Magento\Config\Model\Config\Source\Yesno</source_model>
</field>
<field id="sandbox_account" translate="label comment" type="text" sortOrder="40"
showInDefault="1" showInWebsite="1" showInStore="0">
<label>测试 Account</label>
<comment>完整显示,便于核对当前配置的测试商户号。</comment>
<frontend_model>Esun\OceanpaymentKlarna\Block\Adminhtml\System\Config\Form\Field\DecryptedText</frontend_model>
<backend_model>Magento\Config\Model\Config\Backend\Encrypted</backend_model>
<depends>
<field id="sandbox">1</field>
</depends>
</field>
<field id="sandbox_terminal" translate="label comment" type="text" sortOrder="50"
showInDefault="1" showInWebsite="1" showInStore="0">
<label>测试 Terminal</label>
<comment>完整显示,便于核对当前配置的测试终端号。</comment>
<frontend_model>Esun\OceanpaymentKlarna\Block\Adminhtml\System\Config\Form\Field\DecryptedText</frontend_model>
<backend_model>Magento\Config\Model\Config\Backend\Encrypted</backend_model>
<depends>
<field id="sandbox">1</field>
</depends>
</field>
<field id="sandbox_secure_code" translate="label comment" type="obscure" sortOrder="60"
showInDefault="1" showInWebsite="1" showInStore="0">
<label>测试 Secure Code</label>
<comment>仅在服务器端参与签名,不会发送到浏览器。</comment>
<backend_model>Magento\Config\Model\Config\Backend\Encrypted</backend_model>
<depends>
<field id="sandbox">1</field>
</depends>
</field>
<field id="sandbox_public_key" translate="label comment" type="obscure" sortOrder="70"
showInDefault="1" showInWebsite="1" showInStore="0">
<label>测试 Key</label>
<comment>保留 Oceanpayment 提供的 Key;Hosted Checkout 请求不使用此字段。</comment>
<backend_model>Magento\Config\Model\Config\Backend\Encrypted</backend_model>
<depends>
<field id="sandbox">1</field>
</depends>
</field>
<field id="production_account" translate="label comment" type="text" sortOrder="80"
showInDefault="1" showInWebsite="1" showInStore="0">
<label>正式 Account</label>
<comment>完整显示,便于核对当前配置的正式商户号。</comment>
<frontend_model>Esun\OceanpaymentKlarna\Block\Adminhtml\System\Config\Form\Field\DecryptedText</frontend_model>
<backend_model>Magento\Config\Model\Config\Backend\Encrypted</backend_model>
<depends>
<field id="sandbox">0</field>
</depends>
</field>
<field id="production_terminal" translate="label comment" type="text" sortOrder="90"
showInDefault="1" showInWebsite="1" showInStore="0">
<label>正式 Terminal</label>
<comment>完整显示,便于核对当前配置的正式终端号。</comment>
<frontend_model>Esun\OceanpaymentKlarna\Block\Adminhtml\System\Config\Form\Field\DecryptedText</frontend_model>
<backend_model>Magento\Config\Model\Config\Backend\Encrypted</backend_model>
<depends>
<field id="sandbox">0</field>
</depends>
</field>
<field id="production_secure_code" translate="label comment" type="obscure" sortOrder="100"
showInDefault="1" showInWebsite="1" showInStore="0">
<label>正式 Secure Code</label>
<comment>仅在服务器端参与签名,不会发送到浏览器。</comment>
<backend_model>Magento\Config\Model\Config\Backend\Encrypted</backend_model>
<depends>
<field id="sandbox">0</field>
</depends>
</field>
<field id="production_public_key" translate="label comment" type="obscure" sortOrder="110"
showInDefault="1" showInWebsite="1" showInStore="0">
<label>正式 Key</label>
<comment>保留 Oceanpayment 提供的 Key;Hosted Checkout 请求不使用此字段。</comment>
<backend_model>Magento\Config\Model\Config\Backend\Encrypted</backend_model>
<depends>
<field id="sandbox">0</field>
</depends>
</field>
<field id="new_order_status" translate="label" type="select" sortOrder="120"
showInDefault="1" showInWebsite="1" showInStore="1">
<label>新订单状态</label>
<source_model>Magento\Sales\Model\Config\Source\Order\Status</source_model>
</field>
<field id="success_order_status" translate="label" type="select" sortOrder="130"
showInDefault="1" showInWebsite="1" showInStore="1">
<label>支付成功状态</label>
<source_model>Magento\Sales\Model\Config\Source\Order\Status</source_model>
</field>
<field id="failure_order_status" translate="label" type="select" sortOrder="140"
showInDefault="1" showInWebsite="1" showInStore="1">
<label>支付失败状态</label>
<source_model>Magento\Sales\Model\Config\Source\Order\Status</source_model>
</field>
<field id="pending_order_status" translate="label comment" type="select" sortOrder="150"
showInDefault="1" showInWebsite="1" showInStore="1">
<label>预授权/待确认状态</label>
<comment>Klarna 返回 payment_status=-1 时使用。</comment>
<source_model>Magento\Sales\Model\Config\Source\Order\Status</source_model>
</field>
<field id="allowspecific" translate="label" type="allowspecific" sortOrder="160"
showInDefault="1" showInWebsite="1" showInStore="1">
<label>适用国家</label>
<source_model>Magento\Payment\Model\Config\Source\Allspecificcountries</source_model>
</field>
<field id="specificcountry" translate="label comment" type="multiselect" sortOrder="170"
showInDefault="1" showInWebsite="1" showInStore="1">
<label>指定国家</label>
<comment>默认使用 Oceanpayment 文档列出的 Klarna 支持国家,请以商户终端实际开通范围为准。</comment>
<source_model>Magento\Directory\Model\Config\Source\Country</source_model>
<can_be_empty>1</can_be_empty>
</field>
<field id="sort_order" translate="label" type="text" sortOrder="180"
showInDefault="1" showInWebsite="1" showInStore="1">
<label>排序</label>
<validate>validate-number</validate>
</field>
<field id="debug" translate="label comment" type="select" sortOrder="190"
showInDefault="1" showInWebsite="1" showInStore="1">
<label>调试日志</label>
<comment>日志会脱敏,不记录凭据、itemList 或完整签名原文。</comment>
<source_model>Magento\Config\Model\Config\Source\Yesno</source_model>
</field>
</group>
</section>
</system>
</config>
@@ -0,0 +1,23 @@
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Store:etc/config.xsd">
<default>
<payment>
<esun_oceanpayment_klarna>
<active>0</active>
<model>Esun\OceanpaymentKlarna\Model\PaymentMethod</model>
<title>Pay with Klarna</title>
<sandbox>1</sandbox>
<methods>Klarna</methods>
<new_order_status>pending_payment</new_order_status>
<success_order_status>processing</success_order_status>
<failure_order_status>canceled</failure_order_status>
<pending_order_status>payment_review</pending_order_status>
<allowspecific>1</allowspecific>
<specificcountry>AT,BE,CZ,DK,FI,IE,PL,RO,ES,SE,GB,FR,DE,GR,HU,IT,NL,NO,PT,CH,US</specificcountry>
<sort_order>82</sort_order>
<debug>0</debug>
</esun_oceanpayment_klarna>
</payment>
</default>
</config>
@@ -0,0 +1,46 @@
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
<type name="Esun\OceanpaymentKlarna\Model\Gateway\Client">
<arguments>
<argument name="logger" xsi:type="object">Esun\OceanpaymentKlarna\Logger\Logger</argument>
</arguments>
</type>
<type name="Esun\OceanpaymentKlarna\Model\Callback\Processor">
<arguments>
<argument name="logger" xsi:type="object">Esun\OceanpaymentKlarna\Logger\Logger</argument>
</arguments>
</type>
<type name="Esun\OceanpaymentKlarna\Controller\Payment\Redirect">
<arguments>
<argument name="logger" xsi:type="object">Esun\OceanpaymentKlarna\Logger\Logger</argument>
</arguments>
</type>
<type name="Esun\OceanpaymentKlarna\Controller\Payment\Back">
<arguments>
<argument name="logger" xsi:type="object">Esun\OceanpaymentKlarna\Logger\Logger</argument>
</arguments>
</type>
<type name="Esun\OceanpaymentKlarna\Controller\Payment\Notify">
<arguments>
<argument name="logger" xsi:type="object">Esun\OceanpaymentKlarna\Logger\Logger</argument>
</arguments>
</type>
<type name="Magento\Config\Model\Config\TypePool">
<arguments>
<argument name="sensitive" xsi:type="array">
<item name="payment/esun_oceanpayment_klarna/sandbox_account" xsi:type="string">1</item>
<item name="payment/esun_oceanpayment_klarna/sandbox_terminal" xsi:type="string">1</item>
<item name="payment/esun_oceanpayment_klarna/sandbox_secure_code" xsi:type="string">1</item>
<item name="payment/esun_oceanpayment_klarna/sandbox_public_key" xsi:type="string">1</item>
<item name="payment/esun_oceanpayment_klarna/production_account" xsi:type="string">1</item>
<item name="payment/esun_oceanpayment_klarna/production_terminal" xsi:type="string">1</item>
<item name="payment/esun_oceanpayment_klarna/production_secure_code" xsi:type="string">1</item>
<item name="payment/esun_oceanpayment_klarna/production_public_key" xsi:type="string">1</item>
</argument>
<argument name="environment" xsi:type="array">
<item name="payment/esun_oceanpayment_klarna/sandbox" xsi:type="string">1</item>
</argument>
</arguments>
</type>
</config>
@@ -0,0 +1,11 @@
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
<type name="Magento\Checkout\Model\CompositeConfigProvider">
<arguments>
<argument name="configProviders" xsi:type="array">
<item name="esun_oceanpayment_klarna" xsi:type="object">Esun\OceanpaymentKlarna\Model\ConfigProvider</item>
</argument>
</arguments>
</type>
</config>
@@ -0,0 +1,9 @@
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="urn:magento:framework:App/etc/routes.xsd">
<router id="standard">
<route id="oceanpaymentklarna" frontName="oceanpaymentklarna">
<module name="Esun_OceanpaymentKlarna"/>
</route>
</router>
</config>
@@ -0,0 +1,11 @@
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
<module name="Esun_OceanpaymentKlarna">
<sequence>
<module name="Magento_Checkout"/>
<module name="Magento_Payment"/>
<module name="Magento_Sales"/>
</sequence>
</module>
</config>
@@ -0,0 +1,5 @@
"Pay with Klarna","使用 Klarna 灵活付款"
"You will be redirected to Klarna to securely complete your payment.","下单后将跳转至 Klarna 安全页面完成付款。"
"Klarna requires at least one order item.","Klarna 订单必须至少包含一个商品。"
"Klarna requires a positive merchandise amount.","Klarna 订单的商品金额必须大于零。"
"Klarna item total does not match the order total.","Klarna 商品明细金额与订单总额不一致。"
1 Pay with Klarna 使用 Klarna 灵活付款
2 You will be redirected to Klarna to securely complete your payment. 下单后将跳转至 Klarna 安全页面完成付款。
3 Klarna requires at least one order item. Klarna 订单必须至少包含一个商品。
4 Klarna requires a positive merchandise amount. Klarna 订单的商品金额必须大于零。
5 Klarna item total does not match the order total. Klarna 商品明细金额与订单总额不一致。
@@ -0,0 +1,8 @@
<?php
use Magento\Framework\Component\ComponentRegistrar;
ComponentRegistrar::register(
ComponentRegistrar::MODULE,
'Esun_OceanpaymentKlarna',
__DIR__
);
@@ -0,0 +1,42 @@
<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
<body>
<referenceBlock name="checkout.root">
<arguments>
<argument name="jsLayout" xsi:type="array">
<item name="components" xsi:type="array">
<item name="checkout" xsi:type="array">
<item name="children" xsi:type="array">
<item name="steps" xsi:type="array">
<item name="children" xsi:type="array">
<item name="billing-step" xsi:type="array">
<item name="children" xsi:type="array">
<item name="payment" xsi:type="array">
<item name="children" xsi:type="array">
<item name="renders" xsi:type="array">
<item name="children" xsi:type="array">
<item name="esun_oceanpayment_klarna" xsi:type="array">
<item name="component" xsi:type="string">Esun_OceanpaymentKlarna/js/view/payment/klarna</item>
<item name="methods" xsi:type="array">
<item name="esun_oceanpayment_klarna" xsi:type="array">
<item name="isBillingAddressRequired" xsi:type="boolean">true</item>
</item>
</item>
</item>
</item>
</item>
</item>
</item>
</item>
</item>
</item>
</item>
</item>
</item>
</item>
</argument>
</arguments>
</referenceBlock>
</body>
</page>
@@ -0,0 +1,13 @@
define([
'uiComponent',
'Magento_Checkout/js/model/payment/renderer-list'
], function (Component, rendererList) {
'use strict';
rendererList.push({
type: 'esun_oceanpayment_klarna',
component: 'Esun_OceanpaymentKlarna/js/view/payment/method-renderer/klarna-method'
});
return Component.extend({});
});
@@ -0,0 +1,19 @@
define([
'Magento_Checkout/js/view/payment/default'
], function (Component) {
'use strict';
return Component.extend({
defaults: {
template: 'Esun_OceanpaymentKlarna/payment/klarna'
},
redirectAfterPlaceOrder: false,
afterPlaceOrder: function () {
window.location.replace(
window.checkoutConfig.payment.esun_oceanpayment_klarna.redirectUrl
);
}
});
});
@@ -0,0 +1,36 @@
<div class="payment-method" data-bind="css: {'_active': (getCode() === isChecked())}">
<div class="payment-method-title field choice">
<input type="radio"
name="payment[method]"
class="radio"
data-bind="attr: {'id': getCode()}, value: getCode(), checked: isChecked, click: selectPaymentMethod, visible: isRadioButtonVisible()">
<label class="label" data-bind="attr: {'for': getCode()}">
<span data-bind="text: getTitle()"></span>
</label>
</div>
<div class="payment-method-content">
<!-- ko foreach: getRegion('messages') -->
<!-- ko template: getTemplate() --><!-- /ko -->
<!-- /ko -->
<div class="payment-method-billing-address">
<!-- ko foreach: $parent.getRegion(getBillingAddressFormName()) -->
<!-- ko template: getTemplate() --><!-- /ko -->
<!-- /ko -->
</div>
<p data-bind="i18n: 'You will be redirected to Klarna to securely complete your payment.'"></p>
<div class="checkout-agreements-block">
<!-- ko foreach: $parent.getRegion('before-place-order') -->
<!-- ko template: getTemplate() --><!-- /ko -->
<!-- /ko -->
</div>
<div class="actions-toolbar">
<div class="primary">
<button class="action primary checkout"
type="submit"
data-bind="click: placeOrder, attr: {title: $t('Place Order and Pay')}, css: {disabled: !isPlaceOrderActionAllowed()}, enable: isPlaceOrderActionAllowed()">
<span data-bind="i18n: 'Place Order and Pay'"></span>
</button>
</div>
</div>
</div>
</div>