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,23 @@
<?php
declare(strict_types=1);
namespace Esun\Oceanpayment\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
{
// Oceanpayment cannot know the Magento form key; authenticity is checked by SHA-256 signature.
return true;
}
}
@@ -0,0 +1,54 @@
<?php
declare(strict_types=1);
namespace Esun\Oceanpayment\Controller\Payment;
use Esun\Oceanpayment\Model\Callback\Parser;
use Esun\Oceanpayment\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(
__('Payment was not completed: %1', $data['payment_details'])
);
} elseif ($paymentResult === Processor::PENDING) {
$this->messageManager->addNoticeMessage(
__('Your payment is being confirmed. The order will update automatically.')
);
}
} catch (\Throwable $exception) {
$this->logger->warning('Oceanpayment browser callback was rejected', ['exception' => $exception]);
$this->messageManager->addErrorMessage(
__('The payment result could not be verified. Please contact customer service if you were charged.')
);
}
return $result->setPath('checkout/onepage/success');
}
}
@@ -0,0 +1,44 @@
<?php
declare(strict_types=1);
namespace Esun\Oceanpayment\Controller\Payment;
use Esun\Oceanpayment\Model\Callback\Parser;
use Esun\Oceanpayment\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 asynchronous callback was rejected', [
'exception' => $exception,
]);
$this->getResponse()->setHttpResponseCode(400);
return $result->setContents('invalid');
}
}
}
@@ -0,0 +1,61 @@
<?php
declare(strict_types=1);
namespace Esun\Oceanpayment\Controller\Payment;
use Esun\Oceanpayment\Model\Config;
use Esun\Oceanpayment\Model\Gateway\RequestBuilder;
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\Json;
use Magento\Framework\Controller\Result\JsonFactory;
use Psr\Log\LoggerInterface;
class Onepage extends Action implements HttpGetActionInterface
{
public function __construct(
Context $context,
private readonly CheckoutSession $checkoutSession,
private readonly Config $config,
private readonly RequestBuilder $requestBuilder,
private readonly JsonFactory $jsonFactory,
private readonly LoggerInterface $logger
) {
parent::__construct($context);
}
public function execute(): Json
{
$result = $this->jsonFactory->create();
$order = $this->checkoutSession->getLastRealOrder();
if (!$order->getEntityId()
|| (string)$order->getPayment()->getMethod() !== Config::ONEPAGE_METHOD_CODE
) {
return $this->error($result, __('The Oceanpayment OnePage order is no longer available.'), 404);
}
$storeId = (int)$order->getStoreId();
if (!$this->config->isConfigured($storeId, Config::ONEPAGE_METHOD_CODE)) {
return $this->error($result, __('Oceanpayment OnePage is not fully configured.'), 503);
}
try {
return $result->setData(['success' => true, 'payload' => $this->requestBuilder->buildEmbedded($order)]);
} catch (\Throwable $exception) {
$this->logger->error('Oceanpayment OnePage initialization failed', [
'order_number' => $order->getIncrementId(),
'exception' => $exception,
]);
return $this->error($result, __('Payment initialization failed. Please try again.'), 500);
}
}
private function error(Json $result, \Magento\Framework\Phrase $message, int $status): Json
{
$this->getResponse()->setHttpResponseCode($status);
return $result->setData(['success' => false, 'message' => (string)$message]);
}
}
@@ -0,0 +1,52 @@
<?php
declare(strict_types=1);
namespace Esun\Oceanpayment\Controller\Payment;
use Esun\Oceanpayment\Model\Callback\Parser;
use Esun\Oceanpayment\Model\Callback\Processor;
use Magento\Framework\App\Action\Context;
use Magento\Framework\App\Action\HttpPostActionInterface;
use Magento\Framework\Controller\Result\Json;
use Magento\Framework\Controller\Result\JsonFactory;
use Psr\Log\LoggerInterface;
class OnepageResult extends AbstractCallback implements HttpPostActionInterface
{
public function __construct(
Context $context,
private readonly Parser $parser,
private readonly Processor $processor,
private readonly JsonFactory $jsonFactory,
private readonly LoggerInterface $logger
) {
parent::__construct($context);
}
public function execute(): Json
{
$result = $this->jsonFactory->create();
try {
$data = $this->parser->parse(
(string)$this->getRequest()->getContent(),
(array)$this->getRequest()->getParams()
);
$paymentResult = $this->processor->process($data, false);
return $result->setData([
'success' => $paymentResult !== Processor::FAILURE,
'status' => $paymentResult,
'message' => $paymentResult === Processor::FAILURE
? (string)__('Payment was not completed: %1', $data['payment_details'])
: '',
]);
} catch (\Throwable $exception) {
$this->logger->warning('Oceanpayment OnePage result was rejected', ['exception' => $exception]);
$this->getResponse()->setHttpResponseCode(400);
return $result->setData([
'success' => false,
'status' => Processor::FAILURE,
'message' => (string)__('The payment result could not be verified.'),
]);
}
}
}
@@ -0,0 +1,65 @@
<?php
declare(strict_types=1);
namespace Esun\Oceanpayment\Controller\Payment;
use Esun\Oceanpayment\Model\Config;
use Esun\Oceanpayment\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()
|| !Config::isSupportedMethod((string)$order->getPayment()->getMethod())
) {
$this->messageManager->addErrorMessage(__('The Oceanpayment order is no longer available.'));
return $result->setPath('checkout/cart');
}
try {
$cachedUrl = (string)$order->getPayment()->getAdditionalInformation('qianhai_pay_url');
$paymentUrl = $cachedUrl !== '' && $this->client->isAllowedPaymentUrl($cachedUrl)
? $cachedUrl
: $this->client->createPaymentUrl($order);
return $result->setUrl($paymentUrl);
} catch (\Throwable $exception) {
$this->logger->error('Oceanpayment initialization failed', [
'order_number' => $order->getIncrementId(),
'exception' => $exception,
]);
if ($order->canCancel()) {
$order->cancel();
$order->addCommentToStatusHistory(__('Oceanpayment initialization failed.'));
$this->orderRepository->save($order);
}
$this->checkoutSession->restoreQuote();
$this->messageManager->addErrorMessage(
__('Payment initialization failed. Please try again or choose another payment method.')
);
return $result->setPath('checkout/cart');
}
}
}
@@ -0,0 +1,14 @@
<?php
declare(strict_types=1);
namespace Esun\Oceanpayment\Logger;
use Magento\Framework\Logger\Handler\Base;
use Monolog\Logger;
class Handler extends Base
{
protected $fileName = '/var/log/oceanpayment.log';
protected $loggerType = Logger::DEBUG;
}
@@ -0,0 +1,14 @@
<?php
declare(strict_types=1);
namespace Esun\Oceanpayment\Logger;
use Monolog\Logger as MonologLogger;
class Logger extends MonologLogger
{
public function __construct(Handler $handler)
{
parent::__construct('oceanpayment', [$handler]);
}
}
@@ -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);
}
}
+108
View File
@@ -0,0 +1,108 @@
# Esun_Oceanpayment
Magento 2.4 钱海(Oceanpayment)支付模块,同时提供两个独立支付方式:Hosted Checkout
与 OnePage(Embedded)Checkout。客户可在 Magento 结账页直接选择跳转式付款或内嵌卡支付。
## 功能
- 沙盒/生产环境切换;
- Hosted Checkout(商户控制重定向);
- OnePage Checkout(钱海官方 iframe SDK,卡号/CVV 不经过 Magento);
- SHA-256 请求签名、建单响应验签和支付回调验签;
- 支持同步 `backUrl` 与异步 `noticeUrl`;
- 回调幂等处理,避免重复开票;
- 支付成功自动生成已付款发票和 Magento 支付交易;
- 成功、失败、待确认状态可配置;
- 敏感配置使用 Magento 加密后端,日志不记录密钥。
## 安装
```bash
php bin/magento module:enable Esun_Oceanpayment
php bin/magento setup:upgrade
php bin/magento cache:flush
```
生产模式还应执行:
```bash
php bin/magento setup:di:compile
php bin/magento setup:static-content:deploy -f
```
## 配置
后台路径:`Stores > Configuration > Sales > Payment Methods`,包含两个独立配置组:
- `钱海支付 - Hosted`:下单后跳转钱海托管支付页;
- `钱海支付 - OnePage`:卡支付框内嵌在 Magento checkout。
两种方式可分别启用、命名和排序,并分别保存终端配置。Hosted 必填 `Account`、`Terminal`、
`Secure Code`;OnePage 还必须填写 `Key`,且 `methods` 应为钱海已开通的 `Credit Card`。
沙盒地址固定为:
```text
https://test-secure.oceanpayment.com/gateway/service/sendTrade
```
生产地址固定为:
```text
https://secure.oceanpayment.com/gateway/service/sendTrade
```
推荐在 Magento 后台填写四项凭据。模块使用 Magento 的加密配置后端保存它们,不要把明文写入
Git、`config.xml`、部署脚本或工单。只有在执行 `app:config:dump`、敏感路径已经登记到
`app/etc/config.php` 后,才使用 `config:sensitive:set` 注入部署环境变量;否则该命令不会识别这些路径。
非敏感开关可以通过 CLI 设置:
```bash
php bin/magento config:set payment/esun_oceanpayment/sandbox 1
php bin/magento config:set payment/esun_oceanpayment/active 1
php bin/magento config:set payment/esun_oceanpayment_onepage/sandbox 1
php bin/magento config:set payment/esun_oceanpayment_onepage/active 1
```
## 回调地址
模块会为每笔订单自动提交以下 HTTPS 地址,无需在源码中配置:
```text
同步返回:https://你的域名/oceanpayment/payment/back
异步通知:https://你的域名/oceanpayment/payment/notify
```
为保证旧模块创建的在途订单仍可接收通知,新模块同时兼容旧的
`/paymentqianhai/payment/back` 和 `/paymentqianhai/payment/notify` 地址。
请确保上述路径可被公网访问,并且 CDN/WAF 不会拦截钱海的 POST 或 XML 请求。异步通知处理成功后返回
`receive-ok`;签名或订单校验失败时返回 HTTP 400,便于钱海按重试策略再次通知。
## 安全说明
- `secureCode` 只在服务器端用于 SHA-256,永远不会输出到结账页;
- OnePage 的 `signValue` 由服务器生成,使用文档规定的不含 `backUrl` 的字段顺序;
- OnePage 官方协议要求将 `key` 随单次支付请求交给 SDK,因此仅在下单后的会话绑定接口返回;
- 官方 SDK 仅从 `secure.oceanpayment.com` 加载,并通过钱海 iframe 采集卡资料;
- 支付跳转地址只接受 HTTPS 且域名必须是 `oceanpayment.com` 或其子域名;
- 浏览器返回不能绕过验签;异步通知作为最终支付状态来源;
- 模块不会记录卡号全文、`secureCode`、`key` 或签名明文。
## 测试
先在沙盒终端开通对应的 `methods`(默认 `Credit Card`),再用钱海文档提供的测试卡完成完整流程:
1. Magento 下单后跳转至钱海测试域名;
2. 支付成功后返回 Magento 成功页;
3. 订单变为配置的成功状态;
4. 订单中只生成一张已付款发票和一个支付交易;
5. 重放相同异步通知不会重复开票。
单元测试:
```bash
vendor/bin/phpunit app/code/Esun/Oceanpayment/Test/Unit
```
协议依据:Oceanpayment V4 Hosted Checkout、Parameters、Signature、Payment Status 与 Payments Webhook 文档。
@@ -0,0 +1,42 @@
<?php
declare(strict_types=1);
namespace Esun\Oceanpayment\Test\Unit\Model\Callback;
use Esun\Oceanpayment\Model\Callback\Parser;
use Magento\Framework\Exception\LocalizedException;
use PHPUnit\Framework\TestCase;
class ParserTest extends TestCase
{
public function testParsesOceanpaymentXmlNotification(): void
{
$xml = <<<'XML'
<?xml version="1.0" encoding="UTF-8"?>
<response>
<response_type>1</response_type>
<account>995149</account>
<terminal>99514901</terminal>
<order_number>100000001</order_number>
<order_currency>USD</order_currency>
<order_amount>1.00</order_amount>
<payment_id>PAY-123</payment_id>
<payment_status>1</payment_status>
<signValue>ABCDEF</signValue>
</response>
XML;
$result = (new Parser())->parse($xml, []);
self::assertSame('1', $result['response_type']);
self::assertSame('100000001', $result['order_number']);
self::assertSame('PAY-123', $result['payment_id']);
self::assertSame('', $result['payment_risk']);
}
public function testRejectsInvalidXml(): void
{
$this->expectException(LocalizedException::class);
(new Parser())->parse('<response><broken></response>', []);
}
}
@@ -0,0 +1,141 @@
<?php
declare(strict_types=1);
namespace Esun\Oceanpayment\Test\Unit\Model\Callback;
use Esun\Oceanpayment\Model\Callback\Processor;
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\Order\Payment;
use Magento\Sales\Model\OrderFactory;
use PHPUnit\Framework\TestCase;
use Psr\Log\LoggerInterface;
class ProcessorTest extends TestCase
{
public function testRejectsCallbackForDifferentPaymentId(): void
{
$config = $this->createMock(Config::class);
$config->method('getSecret')->willReturnMap([
['account', 1, Config::METHOD_CODE, 'account'],
['terminal', 1, Config::METHOD_CODE, 'terminal'],
['secure_code', 1, Config::METHOD_CODE, 'secure-code'],
]);
$signature = $this->createMock(Signature::class);
$signature->method('verifyCallback')->willReturn(true);
$payment = $this->createMock(Payment::class);
$payment->method('getMethod')->willReturn(Config::METHOD_CODE);
$payment->method('getAdditionalInformation')
->with('qianhai_payment_id')
->willReturn('expected-payment-id');
$order = $this->createMock(Order::class);
$order->method('loadByIncrementId')->willReturnSelf();
$order->method('getEntityId')->willReturn(1);
$order->method('getPayment')->willReturn($payment);
$order->method('getStoreId')->willReturn(1);
$order->method('getOrderCurrencyCode')->willReturn('USD');
$order->method('getGrandTotal')->willReturn(10.0);
$orderFactory = $this->createMock(OrderFactory::class);
$orderFactory->method('create')->willReturn($order);
$processor = new Processor(
$config,
$signature,
$orderFactory,
$this->createMock(OrderRepositoryInterface::class),
$this->createMock(OrderStatusManager::class),
$this->createMock(LoggerInterface::class)
);
$this->expectException(LocalizedException::class);
$this->expectExceptionMessage('Oceanpayment callback payment ID verification failed.');
$processor->process([
'account' => 'account',
'terminal' => 'terminal',
'order_number' => 'ORDER-1',
'order_currency' => 'USD',
'order_amount' => '10.00',
'payment_id' => 'different-payment-id',
'payment_status' => '1',
], true);
}
public function testSuccessfulCallbackRegistersCaptureTransaction(): void
{
$config = $this->createMock(Config::class);
$config->method('getSecret')->willReturnMap([
['account', 1, Config::METHOD_CODE, 'account'],
['terminal', 1, Config::METHOD_CODE, 'terminal'],
['secure_code', 1, Config::METHOD_CODE, 'secure-code'],
]);
$config->method('getValue')->willReturn('processing');
$signature = $this->createMock(Signature::class);
$signature->method('verifyCallback')->willReturn(true);
$payment = $this->createMock(Payment::class);
$payment->method('getMethod')->willReturn(Config::METHOD_CODE);
$payment->method('getAdditionalInformation')->willReturnCallback(
static fn(string $key): string => match ($key) {
'qianhai_payment_id' => 'payment-id',
default => '',
}
);
$payment->method('setIsTransactionClosed')->willReturnSelf();
$payment->expects(self::once())
->method('registerCaptureNotification')
->with(10.0, true)
->willReturnSelf();
$order = $this->createMock(Order::class);
$order->method('loadByIncrementId')->willReturnSelf();
$order->method('getEntityId')->willReturn(1);
$order->method('getPayment')->willReturn($payment);
$order->method('getStoreId')->willReturn(1);
$order->method('getOrderCurrencyCode')->willReturn('USD');
$order->method('getGrandTotal')->willReturn(10.0);
$order->method('getTotalDue')->willReturn(10.0);
$order->method('canInvoice')->willReturn(true);
$orderFactory = $this->createMock(OrderFactory::class);
$orderFactory->method('create')->willReturn($order);
$orderRepository = $this->createMock(OrderRepositoryInterface::class);
$orderRepository->expects(self::once())->method('save')->with($order);
$statusManager = $this->createMock(OrderStatusManager::class);
$statusManager->expects(self::once())
->method('apply')
->with($order, 'processing', Order::STATE_PROCESSING);
$processor = new Processor(
$config,
$signature,
$orderFactory,
$orderRepository,
$statusManager,
$this->createMock(LoggerInterface::class)
);
self::assertSame(Processor::SUCCESS, $processor->process([
'account' => 'account',
'terminal' => 'terminal',
'methods' => 'Credit Card',
'order_number' => 'ORDER-1',
'order_currency' => 'USD',
'order_amount' => '10.00',
'payment_id' => 'payment-id',
'payment_status' => '1',
'payment_details' => '80000:Transaction Approved',
], true));
}
}
@@ -0,0 +1,18 @@
<?php
declare(strict_types=1);
namespace Esun\Oceanpayment\Test\Unit\Model;
use Esun\Oceanpayment\Model\Config;
use PHPUnit\Framework\TestCase;
class ConfigTest extends TestCase
{
public function testCurrentAndLegacyPaymentMethodsAreSupported(): void
{
self::assertTrue(Config::isSupportedMethod(Config::METHOD_CODE));
self::assertTrue(Config::isSupportedMethod(Config::ONEPAGE_METHOD_CODE));
self::assertTrue(Config::isSupportedMethod(Config::LEGACY_METHOD_CODE));
self::assertFalse(Config::isSupportedMethod('other_payment_method'));
}
}
@@ -0,0 +1,41 @@
<?php
declare(strict_types=1);
namespace Esun\Oceanpayment\Test\Unit\Model\Gateway;
use Esun\Oceanpayment\Model\Gateway\ResponseParser;
use Magento\Framework\Exception\LocalizedException;
use PHPUnit\Framework\TestCase;
class ResponseParserTest extends TestCase
{
public function testParsesHostedCheckoutCreationResponse(): void
{
$xml = <<<'XML'
<root>
<account>995149</account>
<terminal>99514901</terminal>
<order_number>100000001</order_number>
<order_currency>USD</order_currency>
<order_amount>1.00</order_amount>
<payment_id>PAY-123</payment_id>
<pay_url>https://test-secure.oceanpayment.com/pay/123</pay_url>
<pay_results>1</pay_results>
<pay_details>Success</pay_details>
<signValue>ABCDEF</signValue>
</root>
XML;
$result = (new ResponseParser())->parse($xml);
self::assertSame('PAY-123', $result['payment_id']);
self::assertSame('1', $result['pay_results']);
self::assertSame('https://test-secure.oceanpayment.com/pay/123', $result['pay_url']);
}
public function testRejectsNonXmlResponse(): void
{
$this->expectException(LocalizedException::class);
(new ResponseParser())->parse('bad gateway');
}
}
@@ -0,0 +1,90 @@
<?php
declare(strict_types=1);
namespace Esun\Oceanpayment\Test\Unit\Model;
use Esun\Oceanpayment\Model\Signature;
use PHPUnit\Framework\TestCase;
class SignatureTest extends TestCase
{
private Signature $signature;
protected function setUp(): void
{
$this->signature = new Signature();
}
public function testCreatesHostedCheckoutRequestSignatureInDocumentedOrder(): void
{
$data = [
'account' => '995149',
'terminal' => '99514901',
'backUrl' => 'https://example.test/payment/back',
'order_number' => '100000001',
'order_currency' => 'USD',
'order_amount' => '1.00',
'billing_firstName' => 'Jane',
'billing_lastName' => 'Doe',
'billing_email' => 'jane@example.test',
];
self::assertSame(
'cb5715d1d66a44352b811b1d5c9aa74752244cb7c7304e9d2f0bc7fa18a820bf',
$this->signature->createRequest($data, 'test-secure-code')
);
}
public function testVerifiesCallbackAndRejectsTampering(): void
{
$data = [
'account' => '995149',
'terminal' => '99514901',
'order_number' => '100000001',
'order_currency' => 'USD',
'order_amount' => '1.00',
'order_notes' => '',
'card_number' => '411111***1111',
'payment_id' => 'PAY-123',
'payment_authType' => '0',
'payment_status' => '1',
'payment_details' => '80000:Transaction Approved',
'payment_risk' => '',
];
$data['signValue'] = hash(
'sha256',
implode('', array_values($data)) . 'test-secure-code'
);
self::assertSame($data['signValue'], $this->signature->createCallback($data, 'test-secure-code'));
self::assertTrue($this->signature->verifyCallback($data, 'test-secure-code'));
$data['order_amount'] = '100.00';
self::assertFalse($this->signature->verifyCallback($data, 'test-secure-code'));
}
public function testCreatesEmbeddedRequestSignatureWithoutBackUrl(): void
{
$data = [
'account' => '995149',
'terminal' => '99514901',
'backUrl' => 'https://example.test/payment/back',
'order_number' => '100000001',
'order_currency' => 'USD',
'order_amount' => '1.00',
'billing_firstName' => 'Jane',
'billing_lastName' => 'Doe',
'billing_email' => 'jane@example.test',
];
self::assertSame(
hash('sha256', '99514999514901100000001USD1.00JaneDoejane@example.testtest-secure-code'),
$this->signature->createEmbeddedRequest($data, 'test-secure-code')
);
}
public function testSanitizesCharactersThatBreakOceanpaymentSignatures(): void
{
self::assertSame('John Test ', $this->signature->sanitize(' John <Test>\'" '));
}
}
+21
View File
@@ -0,0 +1,21 @@
{
"name": "esun/module-oceanpayment",
"description": "Oceanpayment Hosted and OnePage checkout integration for Magento 2",
"type": "magento2-module",
"version": "1.1.1",
"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-csp": "^100.4",
"magento/module-payment": "^100.4",
"magento/module-sales": "^103.0"
},
"autoload": {
"files": ["registration.php"],
"psr-4": {
"Esun\\Oceanpayment\\": ""
}
}
}
@@ -0,0 +1,194 @@
<?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" translate="label" type="text" sortOrder="800"
showInDefault="1" showInWebsite="1" showInStore="1">
<label>钱海支付 - Hosted</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" type="text" sortOrder="20"
showInDefault="1" showInWebsite="1" showInStore="1">
<label>结账页标题</label>
</field>
<field id="sandbox" translate="label comment" type="select" sortOrder="30"
showInDefault="1" showInWebsite="1" showInStore="1">
<label>沙盒模式</label>
<comment>启用时使用 test-secure.oceanpayment.com;生产环境使用 secure.oceanpayment.com。</comment>
<source_model>Magento\Config\Model\Config\Source\Yesno</source_model>
</field>
<field id="account" translate="label" type="obscure" sortOrder="40"
showInDefault="1" showInWebsite="1" showInStore="0">
<label>Account</label>
<backend_model>Magento\Config\Model\Config\Backend\Encrypted</backend_model>
</field>
<field id="terminal" translate="label" type="obscure" sortOrder="50"
showInDefault="1" showInWebsite="1" showInStore="0">
<label>Terminal</label>
<backend_model>Magento\Config\Model\Config\Backend\Encrypted</backend_model>
</field>
<field id="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>
</field>
<field id="public_key" translate="label comment" type="obscure" sortOrder="70"
showInDefault="1" showInWebsite="1" showInStore="0">
<label>Key(可选)</label>
<comment>Oceanpayment 提供的 key;托管结账通常无需此字段,配置后将随请求提交。</comment>
<backend_model>Magento\Config\Model\Config\Backend\Encrypted</backend_model>
</field>
<field id="methods" translate="label comment" type="text" sortOrder="80"
showInDefault="1" showInWebsite="1" showInStore="1">
<label>支付方式代码</label>
<comment>例如 Credit Card、UnionPay;必须与钱海为该终端开通的官方方法名一致。</comment>
</field>
<field id="language" translate="label comment" type="text" sortOrder="90"
showInDefault="1" showInWebsite="1" showInStore="1">
<label>支付页语言(可选)</label>
<comment>例如 en_US、zh_CN;留空时由钱海按浏览器语言选择。</comment>
</field>
<field id="new_order_status" translate="label" type="select" sortOrder="100"
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="110"
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="120"
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" 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="allowspecific" translate="label" type="allowspecific" sortOrder="140"
showInDefault="1" showInWebsite="1" showInStore="1">
<label>适用国家</label>
<source_model>Magento\Payment\Model\Config\Source\Allspecificcountries</source_model>
</field>
<field id="specificcountry" translate="label" type="multiselect" sortOrder="150"
showInDefault="1" showInWebsite="1" showInStore="1">
<label>指定国家</label>
<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="160"
showInDefault="1" showInWebsite="1" showInStore="1">
<label>排序</label>
<validate>validate-number</validate>
</field>
<field id="debug" translate="label comment" type="select" sortOrder="170"
showInDefault="1" showInWebsite="1" showInStore="1">
<label>调试日志</label>
<comment>日志会脱敏,不记录 secureCode、key 或完整签名原文。</comment>
<source_model>Magento\Config\Model\Config\Source\Yesno</source_model>
</field>
</group>
<group id="esun_oceanpayment_onepage" translate="label" type="text" sortOrder="810"
showInDefault="1" showInWebsite="1" showInStore="1">
<label>钱海支付 - OnePage</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" type="text" sortOrder="20"
showInDefault="1" showInWebsite="1" showInStore="1">
<label>结账页标题</label>
</field>
<field id="sandbox" translate="label comment" type="select" sortOrder="30"
showInDefault="1" showInWebsite="1" showInStore="1">
<label>沙盒模式</label>
<comment>启用时由 SDK 使用 test-secure.oceanpayment.com。</comment>
<source_model>Magento\Config\Model\Config\Source\Yesno</source_model>
</field>
<field id="account" translate="label" type="obscure" sortOrder="40"
showInDefault="1" showInWebsite="1" showInStore="0">
<label>Account</label>
<backend_model>Magento\Config\Model\Config\Backend\Encrypted</backend_model>
</field>
<field id="terminal" translate="label" type="obscure" sortOrder="50"
showInDefault="1" showInWebsite="1" showInStore="0">
<label>Terminal</label>
<backend_model>Magento\Config\Model\Config\Backend\Encrypted</backend_model>
</field>
<field id="secure_code" translate="label comment" type="obscure" sortOrder="60"
showInDefault="1" showInWebsite="1" showInStore="0">
<label>Secure Code</label>
<comment>仅在服务器端参与 OnePage 专用签名。</comment>
<backend_model>Magento\Config\Model\Config\Backend\Encrypted</backend_model>
</field>
<field id="public_key" translate="label comment" type="obscure" sortOrder="70"
showInDefault="1" showInWebsite="1" showInStore="0">
<label>Key</label>
<comment>OnePage SDK 请求必填的钱海 key。</comment>
<backend_model>Magento\Config\Model\Config\Backend\Encrypted</backend_model>
</field>
<field id="methods" translate="label comment" type="text" sortOrder="80"
showInDefault="1" showInWebsite="1" showInStore="1">
<label>支付方式代码</label>
<comment>OnePage 当前使用 Credit Card。</comment>
</field>
<field id="language" translate="label comment" type="text" sortOrder="90"
showInDefault="1" showInWebsite="1" showInStore="1">
<label>支付页语言(可选)</label>
<comment>例如 en_US、zh_CN;留空时按浏览器语言选择。</comment>
</field>
<field id="new_order_status" translate="label" type="select" sortOrder="100"
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="110"
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="120"
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" 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="allowspecific" translate="label" type="allowspecific" sortOrder="140"
showInDefault="1" showInWebsite="1" showInStore="1">
<label>适用国家</label>
<source_model>Magento\Payment\Model\Config\Source\Allspecificcountries</source_model>
</field>
<field id="specificcountry" translate="label" type="multiselect" sortOrder="150"
showInDefault="1" showInWebsite="1" showInStore="1">
<label>指定国家</label>
<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="160"
showInDefault="1" showInWebsite="1" showInStore="1">
<label>排序</label>
<validate>validate-number</validate>
</field>
<field id="debug" translate="label comment" type="select" sortOrder="170"
showInDefault="1" showInWebsite="1" showInStore="1">
<label>调试日志</label>
<comment>日志会脱敏,不记录 secureCode、key 或完整签名原文。</comment>
<source_model>Magento\Config\Model\Config\Source\Yesno</source_model>
</field>
</group>
</section>
</system>
</config>
+38
View File
@@ -0,0 +1,38 @@
<?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>
<active>0</active>
<model>Esun\Oceanpayment\Model\PaymentMethod</model>
<title>Oceanpayment</title>
<sandbox>1</sandbox>
<methods>Credit Card</methods>
<language></language>
<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>0</allowspecific>
<sort_order>80</sort_order>
<debug>0</debug>
</esun_oceanpayment>
<esun_oceanpayment_onepage>
<active>0</active>
<model>Esun\Oceanpayment\Model\OnepagePaymentMethod</model>
<title>Oceanpayment OnePage</title>
<sandbox>1</sandbox>
<methods>Credit Card</methods>
<language></language>
<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>0</allowspecific>
<sort_order>81</sort_order>
<debug>0</debug>
</esun_oceanpayment_onepage>
</payment>
</default>
</config>
@@ -0,0 +1,29 @@
<?xml version="1.0"?>
<csp_whitelist xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Csp:etc/csp_whitelist.xsd">
<policies>
<policy id="script-src">
<values>
<value id="oceanpayment_secure_script" type="host">secure.oceanpayment.com</value>
</values>
</policy>
<policy id="frame-src">
<values>
<value id="oceanpayment_secure_frame" type="host">secure.oceanpayment.com</value>
<value id="oceanpayment_test_frame" type="host">test-secure.oceanpayment.com</value>
</values>
</policy>
<policy id="connect-src">
<values>
<value id="oceanpayment_secure_connect" type="host">secure.oceanpayment.com</value>
<value id="oceanpayment_test_connect" type="host">test-secure.oceanpayment.com</value>
</values>
</policy>
<policy id="form-action">
<values>
<value id="oceanpayment_secure_form" type="host">secure.oceanpayment.com</value>
<value id="oceanpayment_test_form" type="host">test-secure.oceanpayment.com</value>
</values>
</policy>
</policies>
</csp_whitelist>
+57
View File
@@ -0,0 +1,57 @@
<?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\Oceanpayment\Model\Gateway\Client">
<arguments>
<argument name="logger" xsi:type="object">Esun\Oceanpayment\Logger\Logger</argument>
</arguments>
</type>
<type name="Esun\Oceanpayment\Model\Callback\Processor">
<arguments>
<argument name="logger" xsi:type="object">Esun\Oceanpayment\Logger\Logger</argument>
</arguments>
</type>
<type name="Esun\Oceanpayment\Controller\Payment\Redirect">
<arguments>
<argument name="logger" xsi:type="object">Esun\Oceanpayment\Logger\Logger</argument>
</arguments>
</type>
<type name="Esun\Oceanpayment\Controller\Payment\Back">
<arguments>
<argument name="logger" xsi:type="object">Esun\Oceanpayment\Logger\Logger</argument>
</arguments>
</type>
<type name="Esun\Oceanpayment\Controller\Payment\Notify">
<arguments>
<argument name="logger" xsi:type="object">Esun\Oceanpayment\Logger\Logger</argument>
</arguments>
</type>
<type name="Esun\Oceanpayment\Controller\Payment\Onepage">
<arguments>
<argument name="logger" xsi:type="object">Esun\Oceanpayment\Logger\Logger</argument>
</arguments>
</type>
<type name="Esun\Oceanpayment\Controller\Payment\OnepageResult">
<arguments>
<argument name="logger" xsi:type="object">Esun\Oceanpayment\Logger\Logger</argument>
</arguments>
</type>
<type name="Magento\Config\Model\Config\TypePool">
<arguments>
<argument name="sensitive" xsi:type="array">
<item name="payment/esun_oceanpayment/account" xsi:type="string">1</item>
<item name="payment/esun_oceanpayment/terminal" xsi:type="string">1</item>
<item name="payment/esun_oceanpayment/secure_code" xsi:type="string">1</item>
<item name="payment/esun_oceanpayment/public_key" xsi:type="string">1</item>
<item name="payment/esun_oceanpayment_onepage/account" xsi:type="string">1</item>
<item name="payment/esun_oceanpayment_onepage/terminal" xsi:type="string">1</item>
<item name="payment/esun_oceanpayment_onepage/secure_code" xsi:type="string">1</item>
<item name="payment/esun_oceanpayment_onepage/public_key" xsi:type="string">1</item>
</argument>
<argument name="environment" xsi:type="array">
<item name="payment/esun_oceanpayment/sandbox" xsi:type="string">1</item>
<item name="payment/esun_oceanpayment_onepage/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" xsi:type="object">Esun\Oceanpayment\Model\ConfigProvider</item>
</argument>
</arguments>
</type>
</config>
@@ -0,0 +1,12 @@
<?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="oceanpayment" frontName="oceanpayment">
<module name="Esun_Oceanpayment"/>
</route>
<route id="paymentqianhai" frontName="paymentqianhai">
<module name="Esun_Oceanpayment"/>
</route>
</router>
</config>
+12
View File
@@ -0,0 +1,12 @@
<?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_Oceanpayment">
<sequence>
<module name="Magento_Checkout"/>
<module name="Magento_Csp"/>
<module name="Magento_Payment"/>
<module name="Magento_Sales"/>
</sequence>
</module>
</config>
@@ -0,0 +1,9 @@
"Oceanpayment","钱海支付"
"You will be redirected to Oceanpayment to complete your payment.","下单后将跳转至钱海安全支付页面完成付款。"
"Payment initialization failed. Please try again or choose another payment method.","支付初始化失败,请重试或选择其他支付方式。"
"The payment result could not be verified. Please contact customer service if you were charged.","无法验证支付结果。如已扣款,请联系客服。"
"Card details are securely collected by Oceanpayment.","银行卡信息由钱海安全组件直接采集。"
"Place Order and Pay","下单并支付"
"Pay Now","立即支付"
"Unable to load the secure Oceanpayment card form.","无法加载钱海安全卡支付表单。"
"The secure payment form is still loading. Please try again.","安全支付表单仍在加载,请稍后重试。"
1 Oceanpayment 钱海支付
2 You will be redirected to Oceanpayment to complete your payment. 下单后将跳转至钱海安全支付页面完成付款。
3 Payment initialization failed. Please try again or choose another payment method. 支付初始化失败,请重试或选择其他支付方式。
4 The payment result could not be verified. Please contact customer service if you were charged. 无法验证支付结果。如已扣款,请联系客服。
5 Card details are securely collected by Oceanpayment. 银行卡信息由钱海安全组件直接采集。
6 Place Order and Pay 下单并支付
7 Pay Now 立即支付
8 Unable to load the secure Oceanpayment card form. 无法加载钱海安全卡支付表单。
9 The secure payment form is still loading. Please try again. 安全支付表单仍在加载,请稍后重试。
@@ -0,0 +1,10 @@
<?php
declare(strict_types=1);
use Magento\Framework\Component\ComponentRegistrar;
ComponentRegistrar::register(
ComponentRegistrar::MODULE,
'Esun_Oceanpayment',
__DIR__
);
@@ -0,0 +1,45 @@
<?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" xsi:type="array">
<item name="component" xsi:type="string">Esun_Oceanpayment/js/view/payment/qianhai</item>
<item name="methods" xsi:type="array">
<item name="esun_oceanpayment" xsi:type="array">
<item name="isBillingAddressRequired" xsi:type="boolean">true</item>
</item>
<item name="esun_oceanpayment_onepage" 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,10 @@
var config = {
paths: {
oceanpaymentSdk: 'https://secure.oceanpayment.com/pages/js/oceanpayment'
},
shim: {
oceanpaymentSdk: {
exports: 'Oceanpayment'
}
}
};
@@ -0,0 +1,8 @@
#oceanpayment-element {
min-height: 180px;
iframe {
border: 0;
width: 100%;
}
}
@@ -0,0 +1,175 @@
define([
'jquery',
'ko',
'Magento_Checkout/js/view/payment/default',
'mage/translate',
'oceanpaymentSdk'
], function ($, ko, Component, $t, Oceanpayment) {
'use strict';
return Component.extend({
defaults: {
template: 'Esun_Oceanpayment/payment/onepage'
},
redirectAfterPlaceOrder: false,
orderPlaced: ko.observable(false),
processing: ko.observable(false),
sdkInitialized: false,
initialize: function () {
this._super();
window.oceanpaymentCallBack = this.handleOceanpaymentResult.bind(this);
return this;
},
initOceanpayment: function () {
var methodConfig = window.checkoutConfig.payment.esun_oceanpayment_onepage;
if (this.sdkInitialized) {
return;
}
try {
Oceanpayment.init(Boolean(methodConfig.sandbox), '', methodConfig.language || '');
this.sdkInitialized = true;
} catch (error) {
this.showError($t('Unable to load the secure Oceanpayment card form.'));
}
},
validate: function () {
if (!this.sdkInitialized) {
this.showError($t('The secure payment form is still loading. Please try again.'));
return false;
}
return true;
},
afterPlaceOrder: function () {
this.orderPlaced(true);
this.submitPayment();
},
retryPayment: function () {
this.submitPayment();
},
submitPayment: function () {
var self = this,
methodConfig = window.checkoutConfig.payment.esun_oceanpayment_onepage;
if (this.processing()) {
return;
}
this.processing(true);
$.ajax({
url: methodConfig.prepareUrl,
type: 'GET',
dataType: 'json',
cache: false
}).done(function (response) {
if (!response.success || !response.payload) {
self.processing(false);
self.showError(response.message || $t('Payment initialization failed.'));
return;
}
try {
Oceanpayment.checkout(response.payload);
} catch (error) {
self.processing(false);
self.showError($t('Payment initialization failed. Please try again.'));
}
}).fail(function (xhr) {
var response = xhr.responseJSON || {};
self.processing(false);
self.showError(response.message || $t('Payment initialization failed. Please try again.'));
});
},
handleOceanpaymentResult: function (data) {
var xml = typeof data === 'string' ? data : '',
documentNode,
parserError,
payUrl;
this.processing(false);
if (xml === '') {
this.showError((data && (data.message || data.error)) || $t('Oceanpayment returned an invalid response.'));
return;
}
documentNode = (new window.DOMParser()).parseFromString(xml, 'application/xml');
parserError = documentNode.getElementsByTagName('parsererror');
if (parserError.length) {
this.showError($t('Oceanpayment returned an invalid response.'));
return;
}
payUrl = this.getXmlValue(documentNode, 'pay_url');
if (payUrl !== '') {
if (!this.isAllowedPaymentUrl(payUrl)) {
this.showError($t('Oceanpayment returned an invalid redirect URL.'));
return;
}
window.location.assign(payUrl);
return;
}
this.verifyResult(xml);
},
verifyResult: function (xml) {
var self = this,
methodConfig = window.checkoutConfig.payment.esun_oceanpayment_onepage;
this.processing(true);
$.ajax({
url: methodConfig.resultUrl,
type: 'POST',
data: xml,
processData: false,
contentType: 'text/plain; charset=UTF-8',
dataType: 'json'
}).done(function (response) {
if (response.success) {
window.location.replace(methodConfig.successUrl);
return;
}
self.processing(false);
self.showError(response.message || $t('Payment was not completed. Please try again.'));
}).fail(function (xhr) {
var response = xhr.responseJSON || {};
self.processing(false);
self.showError(response.message || $t('The payment result could not be verified.'));
});
},
getXmlValue: function (documentNode, name) {
var nodes = documentNode.getElementsByTagName(name);
return nodes.length ? String(nodes[0].textContent || '').trim() : '';
},
isAllowedPaymentUrl: function (url) {
var anchor = document.createElement('a'),
hostname;
anchor.href = url;
hostname = String(anchor.hostname || '').toLowerCase();
return anchor.protocol === 'https:' && /(^|\.)oceanpayment\.com$/.test(hostname);
},
showError: function (message) {
this.messageContainer.addErrorMessage({message: String(message)});
}
});
});
@@ -0,0 +1,19 @@
define([
'Magento_Checkout/js/view/payment/default'
], function (Component) {
'use strict';
return Component.extend({
defaults: {
template: 'Esun_Oceanpayment/payment/qianhai'
},
redirectAfterPlaceOrder: false,
afterPlaceOrder: function () {
window.location.replace(
window.checkoutConfig.payment.esun_oceanpayment.redirectUrl
);
}
});
});
@@ -0,0 +1,17 @@
define([
'uiComponent',
'Magento_Checkout/js/model/payment/renderer-list'
], function (Component, rendererList) {
'use strict';
rendererList.push({
type: 'esun_oceanpayment',
component: 'Esun_Oceanpayment/js/view/payment/method-renderer/qianhai-method'
});
rendererList.push({
type: 'esun_oceanpayment_onepage',
component: 'Esun_Oceanpayment/js/view/payment/method-renderer/onepage-method'
});
return Component.extend({});
});
@@ -0,0 +1,41 @@
<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>
<div id="oceanpayment-element" data-bind="afterRender: initOceanpayment"></div>
<p data-bind="i18n: 'Card details are securely collected by Oceanpayment.'"></p>
<div class="actions-toolbar">
<div class="primary">
<!-- ko ifnot: orderPlaced -->
<button class="action primary checkout"
type="submit"
data-bind="click: placeOrder, attr: {title: $t('Place Order')}, enable: (getCode() === isChecked()) && !processing() && isPlaceOrderActionAllowed(), css: {disabled: processing() || !isPlaceOrderActionAllowed()}">
<span data-bind="i18n: 'Place Order and Pay'"></span>
</button>
<!-- /ko -->
<!-- ko if: orderPlaced -->
<button class="action primary checkout"
type="button"
data-bind="click: retryPayment, enable: !processing(), css: {disabled: processing()}">
<span data-bind="i18n: 'Pay Now'"></span>
</button>
<!-- /ko -->
</div>
</div>
</div>
</div>
@@ -0,0 +1,31 @@
<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 Oceanpayment to complete your payment.'"></p>
<div class="actions-toolbar">
<div class="primary">
<button class="action primary checkout"
type="submit"
data-bind="click: placeOrder, attr: {title: $t('Place Order')}, enable: (getCode() === isChecked()), css: {disabled: !isPlaceOrderActionAllowed()}">
<span data-bind="i18n: 'Place Order'"></span>
</button>
</div>
</div>
</div>
</div>