init
This commit is contained in:
@@ -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;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user