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,73 @@
<?php
declare(strict_types=1);
namespace Esun\Oceanpayment\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,227 @@
<?php
declare(strict_types=1);
namespace Esun\Oceanpayment\Model\Callback;
use Esun\Oceanpayment\Model\Config;
use Esun\Oceanpayment\Model\OrderStatusManager;
use Esun\Oceanpayment\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()
|| !Config::isSupportedMethod((string)$order->getPayment()->getMethod())
) {
throw new LocalizedException(__('The Oceanpayment order could not be found.'));
}
$this->validate($order, $data);
$payment = $order->getPayment();
$paymentId = (string)$data['payment_id'];
$status = (string)$data['payment_status'];
$method = (string)$payment->getMethod();
if ((string)$payment->getAdditionalInformation('qianhai_processed_payment_id') === $paymentId
&& (string)$payment->getAdditionalInformation('qianhai_processed_status') === $status
) {
return $this->mapStatus($status);
}
$payment->setAdditionalInformation('qianhai_payment_id', $paymentId);
$payment->setAdditionalInformation('qianhai_processed_payment_id', $paymentId);
$payment->setAdditionalInformation('qianhai_processed_status', $status);
$payment->setAdditionalInformation('qianhai_payment_details', (string)$data['payment_details']);
$payment->setAdditionalInformation('qianhai_payment_method', (string)$data['methods']);
$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(), $method)) {
$this->logger->debug('Oceanpayment 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();
$method = (string)$order->getPayment()->getMethod();
if (!hash_equals($this->config->getSecret('account', $storeId, $method), (string)$data['account'])
|| !hash_equals($this->config->getSecret('terminal', $storeId, $method), (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.'));
}
$secureCode = $this->config->getSecret('secure_code', $storeId, $method);
if (!$this->signature->verifyCallback($data, $secureCode)) {
if ($this->config->isDebug($storeId, $method)) {
$this->logger->warning(
'Oceanpayment callback signature verification failed',
$this->getSignatureDiagnostics($data, $secureCode)
);
}
throw new LocalizedException(__('Oceanpayment callback signature verification failed.'));
}
$expectedPaymentId = (string)$order->getPayment()
->getAdditionalInformation('qianhai_payment_id');
if ($expectedPaymentId !== ''
&& !hash_equals($expectedPaymentId, (string)$data['payment_id'])
) {
throw new LocalizedException(__('Oceanpayment callback payment ID verification failed.'));
}
if (!in_array((string)$data['payment_status'], ['-1', '0', '1'], true)) {
throw new LocalizedException(__('Oceanpayment returned an unknown payment status.'));
}
}
private function getSignatureDiagnostics(array $data, string $secureCode): array
{
$provided = strtolower(trim((string)($data['signValue'] ?? '')));
$expected = $this->signature->createCallback($data, $secureCode);
return [
'account' => $this->mask((string)($data['account'] ?? '')),
'terminal' => $this->mask((string)($data['terminal'] ?? '')),
'order_number' => (string)($data['order_number'] ?? ''),
'order_currency' => (string)($data['order_currency'] ?? ''),
'order_amount' => (string)($data['order_amount'] ?? ''),
'order_notes_length' => strlen((string)($data['order_notes'] ?? '')),
'card_number' => $this->mask((string)($data['card_number'] ?? '')),
'payment_id' => (string)($data['payment_id'] ?? ''),
'payment_auth_type' => (string)($data['payment_authType'] ?? ''),
'payment_status' => (string)($data['payment_status'] ?? ''),
'payment_details' => mb_substr((string)($data['payment_details'] ?? ''), 0, 200),
'payment_risk' => mb_substr((string)($data['payment_risk'] ?? ''), 0, 200),
'provided_sign_prefix' => substr($provided, 0, 12),
'provided_sign_length' => strlen($provided),
'expected_sign_prefix' => substr($expected, 0, 12),
];
}
private function mask(string $value): string
{
$length = strlen($value);
if ($length <= 4) {
return str_repeat('*', $length);
}
return str_repeat('*', $length - 4) . substr($value, -4);
}
private function processSuccess(Order $order, array $data): void
{
$payment = $order->getPayment();
$method = (string)$payment->getMethod();
$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(), $method),
Order::STATE_PROCESSING
);
$order->addCommentToStatusHistory(
__('Oceanpayment payment approved. Payment ID: %1', $data['payment_id'])
);
}
private function processPending(Order $order, array $data): void
{
$method = (string)$order->getPayment()->getMethod();
$order->getPayment()->setIsTransactionClosed(false)->setIsTransactionPending(true);
$this->statusManager->apply(
$order,
$this->config->getValue('pending_order_status', (int)$order->getStoreId(), $method),
Order::STATE_PAYMENT_REVIEW
);
$order->addCommentToStatusHistory(
__('Oceanpayment payment is pending. Payment ID: %1', $data['payment_id'])
);
}
private function processFailure(Order $order, array $data, bool $isAsync): void
{
$method = (string)$order->getPayment()->getMethod();
$order->getPayment()->setIsTransactionClosed(true);
if ($isAsync && $order->canCancel()) {
$order->cancel();
$this->statusManager->apply(
$order,
$this->config->getValue('failure_order_status', (int)$order->getStoreId(), $method),
Order::STATE_CANCELED
);
}
$order->addCommentToStatusHistory(
__(
'Oceanpayment 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,
};
}
}
+122
View File
@@ -0,0 +1,122 @@
<?php
declare(strict_types=1);
namespace Esun\Oceanpayment\Model;
use Magento\Framework\App\Config\ScopeConfigInterface;
use Magento\Framework\Encryption\EncryptorInterface;
use Magento\Store\Model\ScopeInterface;
class Config
{
public const METHOD_CODE = 'esun_oceanpayment';
public const ONEPAGE_METHOD_CODE = 'esun_oceanpayment_onepage';
public const LEGACY_METHOD_CODE = 'evebit_paymentqianhai';
public const SANDBOX_ENDPOINT = 'https://test-secure.oceanpayment.com/gateway/service/sendTrade';
public const PRODUCTION_ENDPOINT = 'https://secure.oceanpayment.com/gateway/service/sendTrade';
public static function isSupportedMethod(string $method): bool
{
return in_array(
$method,
[self::METHOD_CODE, self::ONEPAGE_METHOD_CODE, self::LEGACY_METHOD_CODE],
true
);
}
private const PATH_PREFIX = 'payment/';
public function __construct(
private readonly ScopeConfigInterface $scopeConfig,
private readonly EncryptorInterface $encryptor
) {
}
public function getValue(
string $field,
?int $storeId = null,
string $method = self::METHOD_CODE
): string {
return trim((string)$this->scopeConfig->getValue(
$this->getPath($method, $field),
ScopeInterface::SCOPE_STORE,
$storeId
));
}
public function getSecret(
string $field,
?int $storeId = null,
string $method = self::METHOD_CODE
): string {
$value = $this->getValue($field, $storeId, $method);
if ($value === '') {
return '';
}
// Magento's current encrypted config format starts with key/cipher version segments.
// Values supplied through environment deployment configuration remain plaintext.
if (!preg_match('/^\d+:\d+:/', $value)) {
return $value;
}
try {
$decrypted = $this->encryptor->decrypt($value);
return $decrypted !== '' ? $decrypted : $value;
} catch (\Throwable) {
// Environment-provided sensitive values may already be plaintext.
return $value;
}
}
public function isActive(?int $storeId = null, string $method = self::METHOD_CODE): bool
{
return $this->scopeConfig->isSetFlag(
$this->getPath($method, 'active'),
ScopeInterface::SCOPE_STORE,
$storeId
);
}
public function isSandbox(?int $storeId = null, string $method = self::METHOD_CODE): bool
{
return $this->scopeConfig->isSetFlag(
$this->getPath($method, 'sandbox'),
ScopeInterface::SCOPE_STORE,
$storeId
);
}
public function isDebug(?int $storeId = null, string $method = self::METHOD_CODE): bool
{
return $this->scopeConfig->isSetFlag(
$this->getPath($method, 'debug'),
ScopeInterface::SCOPE_STORE,
$storeId
);
}
public function getEndpoint(?int $storeId = null, string $method = self::METHOD_CODE): string
{
return $this->isSandbox($storeId, $method) ? self::SANDBOX_ENDPOINT : self::PRODUCTION_ENDPOINT;
}
public function isConfigured(?int $storeId = null, string $method = self::METHOD_CODE): bool
{
return $this->getSecret('account', $storeId, $method) !== ''
&& $this->getSecret('terminal', $storeId, $method) !== ''
&& $this->getSecret('secure_code', $storeId, $method) !== ''
&& ($method !== self::ONEPAGE_METHOD_CODE
|| $this->getSecret('public_key', $storeId, $method) !== '');
}
private function getPath(string $method, string $field): string
{
$method = $method === self::LEGACY_METHOD_CODE ? self::METHOD_CODE : $method;
if (!in_array($method, [self::METHOD_CODE, self::ONEPAGE_METHOD_CODE], true)) {
throw new \InvalidArgumentException('Unsupported Oceanpayment method code.');
}
return self::PATH_PREFIX . $method . '/' . $field;
}
}
@@ -0,0 +1,50 @@
<?php
declare(strict_types=1);
namespace Esun\Oceanpayment\Model;
use Magento\Checkout\Model\ConfigProviderInterface;
use Magento\Framework\UrlInterface;
class ConfigProvider implements ConfigProviderInterface
{
public function __construct(
private readonly UrlInterface $urlBuilder,
private readonly Config $config
) {
}
public function getConfig(): array
{
return [
'payment' => [
Config::METHOD_CODE => [
'redirectUrl' => $this->urlBuilder->getUrl(
'oceanpayment/payment/redirect',
['_secure' => true, '_nosid' => true]
),
],
Config::ONEPAGE_METHOD_CODE => [
'prepareUrl' => $this->urlBuilder->getUrl(
'oceanpayment/payment/onepage',
['_secure' => true, '_nosid' => true]
),
'resultUrl' => $this->urlBuilder->getUrl(
'oceanpayment/payment/onepageResult',
['_secure' => true, '_nosid' => true]
),
'successUrl' => $this->urlBuilder->getUrl(
'checkout/onepage/success',
['_secure' => true, '_nosid' => true]
),
'sandbox' => $this->config->isSandbox(null, Config::ONEPAGE_METHOD_CODE),
'language' => $this->config->getValue(
'language',
null,
Config::ONEPAGE_METHOD_CODE
),
],
],
];
}
}
@@ -0,0 +1,122 @@
<?php
declare(strict_types=1);
namespace Esun\Oceanpayment\Model\Gateway;
use Esun\Oceanpayment\Model\Config;
use Esun\Oceanpayment\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();
$method = (string)$order->getPayment()->getMethod();
if (!$this->config->isConfigured($storeId, $method)) {
throw new LocalizedException(__('Oceanpayment 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 create request', [
'order_number' => $request['order_number'],
'endpoint' => $this->config->getEndpoint($storeId, $method),
'sandbox' => $this->config->isSandbox($storeId, $method),
]);
}
try {
$curl->post($this->config->getEndpoint($storeId, $method), $request);
} catch (\Throwable $exception) {
$this->logger->error('Oceanpayment gateway request failed', [
'order_number' => $order->getIncrementId(),
'exception' => $exception,
]);
throw new LocalizedException(__('Unable to connect to Oceanpayment.'), $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('qianhai_payment_id', $response['payment_id']);
$payment->setAdditionalInformation('qianhai_pay_url', $response['pay_url']);
$payment->setAdditionalInformation('qianhai_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();
$method = (string)$order->getPayment()->getMethod();
$account = $this->config->getSecret('account', $storeId, $method);
$terminal = $this->config->getSecret('terminal', $storeId, $method);
if (!hash_equals($account, $response['account'])
|| !hash_equals($terminal, $response['terminal'])
|| !hash_equals((string)$order->getIncrementId(), $response['order_number'])
|| !hash_equals(strtoupper((string)$order->getOrderCurrencyCode()), strtoupper($response['order_currency']))
|| !$this->amountsEqual((float)$order->getGrandTotal(), $response['order_amount'])
) {
throw new LocalizedException(__('Oceanpayment response did not match the Magento order.'));
}
if (!$this->signature->verifyCreateResponse(
$response,
$this->config->getSecret('secure_code', $storeId, $method)
)) {
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.'));
}
}
private function amountsEqual(float $expected, string $actual): bool
{
return abs($expected - (float)$actual) < 0.005;
}
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,161 @@
<?php
declare(strict_types=1);
namespace Esun\Oceanpayment\Model\Gateway;
use Esun\Oceanpayment\Model\Config;
use Esun\Oceanpayment\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
) {
}
public function build(Order $order): array
{
$method = (string)$order->getPayment()->getMethod();
if ($method !== Config::METHOD_CODE && $method !== Config::LEGACY_METHOD_CODE) {
throw new \InvalidArgumentException('The order does not use Oceanpayment Hosted.');
}
$data = $this->buildBase($order, $method);
$data['backUrl'] = $this->urlBuilder->getUrl(
'oceanpayment/payment/back',
['_secure' => true, '_nosid' => true]
);
$data['signValue'] = $this->signature->createRequest(
$data,
$this->config->getSecret('secure_code', (int)$order->getStoreId(), $method)
);
return array_filter($data, static fn ($value): bool => $value !== '');
}
public function buildEmbedded(Order $order): array
{
$method = (string)$order->getPayment()->getMethod();
if ($method !== Config::ONEPAGE_METHOD_CODE) {
throw new \InvalidArgumentException('The order does not use Oceanpayment OnePage.');
}
$data = $this->buildBase($order, $method);
$data['backUrl'] = $this->urlBuilder->getUrl(
'oceanpayment/payment/back',
['_secure' => true, '_nosid' => true]
);
$data['signValue'] = $this->signature->createEmbeddedRequest(
$data,
$this->config->getSecret('secure_code', (int)$order->getStoreId(), $method)
);
return array_filter($data, static fn ($value): bool => $value !== '');
}
private function buildBase(Order $order, string $method): 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, $method),
'terminal' => $this->config->getSecret('terminal', $storeId, $method),
'noticeUrl' => $this->urlBuilder->getUrl(
'oceanpayment/payment/notify',
['_secure' => true, '_nosid' => true]
),
'methods' => $this->clean($this->config->getValue('methods', $storeId, $method), 50),
'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' => '',
];
$data += $this->getProductData($order);
$language = $this->clean($this->config->getValue('language', $storeId, $method), 50);
if ($language !== '') {
$data['language'] = $language;
}
$key = $this->config->getSecret('public_key', $storeId, $method);
if ($key !== '') {
$data['key'] = $key;
}
return $data;
}
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, '.', '');
}
if ($names === []) {
$names[] = 'Magento Order';
$quantities[] = '1';
$skus[] = (string)$order->getIncrementId();
$prices[] = number_format((float)$order->getGrandTotal(), 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\Oceanpayment\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,17 @@
<?php
declare(strict_types=1);
namespace Esun\Oceanpayment\Model;
use Magento\Quote\Api\Data\CartInterface;
class OnepagePaymentMethod extends PaymentMethod
{
protected $_code = Config::ONEPAGE_METHOD_CODE;
public function isAvailable(?CartInterface $quote = null): bool
{
return parent::isAvailable($quote)
&& trim((string)$this->getConfigData('public_key')) !== '';
}
}
@@ -0,0 +1,43 @@
<?php
declare(strict_types=1);
namespace Esun\Oceanpayment\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,51 @@
<?php
declare(strict_types=1);
namespace Esun\Oceanpayment\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 = [
'account',
'terminal',
'secure_code',
'public_key',
'key',
'signValue',
];
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;
}
return trim((string)$this->getConfigData('account')) !== ''
&& trim((string)$this->getConfigData('terminal')) !== ''
&& trim((string)$this->getConfigData('secure_code')) !== '';
}
}
@@ -0,0 +1,111 @@
<?php
declare(strict_types=1);
namespace Esun\Oceanpayment\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 createEmbeddedRequest(array $data, string $secureCode): string
{
$plain = (string)($data['account'] ?? '')
. (string)($data['terminal'] ?? '')
. (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);
}
}