moneta-sdk-php v2.0.0

This commit is contained in:
nikita.ivanaev committed 2025-02-24 22:31:15 +03:00
commit 7a455450ce
16 files changed
+1443

No files matched your search

+432
View File
@@ -0,0 +1,432 @@
<?php
namespace Moneta;
use Moneta\MonetaSdkService;
use Moneta\MonetaSdkSettings;
use Moneta\MonetaSdkReceipt;
class MonetaSdk {
/**
* Assistant endpoints
*/
const PROD_ENDPOINT = 'https://www.payanyway.ru/assistant.htm?';
const DEMO_ENDPOINT = 'https://demo.moneta.ru/assistant.htm?';
/**
* Exception messages text
*/
const EXCEPTION_MERCHANT_API_NO_TRANSACTION_ID = 'There is no operation number in the response.';
const EXCEPTION_VAR_AMOUNT_EMPTY = 'The amount argument is not passed.';
private
$configPath,
$transactionId,
$amount,
$description;
public function __construct($transactionId, ?float $amount = null, ?string $description = null, ?string $configPath = null) {
$this->configPath = $configPath;
$this->transactionId = $transactionId;
$this->amount = $amount;
$this->description = $description;
}
/**
* @return string
* @throws MonetaSdkException
*/
public function getAssistantPaymentLink() {
if (!isset($this->amount)) {
throw new MonetaSdkException(self::EXCEPTION_VAR_AMOUNT_EMPTY);
}
$httpParams = [
'MNT_ID' => MonetaSdkSettings::getSettings('id', $this->configPath),
'MNT_AMOUNT' => number_format($this->amount, 2, '.', ''),
'MNT_TRANSACTION_ID' => $this->transactionId,
'MNT_CURRENCY_CODE' => 'RUB',
'MNT_DESCRIPTION' => $this->description,
'MNT_SIGNATURE' => MonetaSdkService::createSignature('generateLink', $this->transactionId, $this->configPath, $this->amount),
'MNT_SUCCESS_URL' => MonetaSdkSettings::getSettings('success', $this->configPath),
'MNT_INPROGRESS_URL' => MonetaSdkSettings::getSettings('inprogress', $this->configPath),
'MNT_FAIL_URL' => MonetaSdkSettings::getSettings('fail', $this->configPath),
'MNT_RETURN_URL' => MonetaSdkSettings::getSettings('return', $this->configPath),
'moneta.locale' => MonetaSdkSettings::getSettings('locale', $this->configPath),
'paymentSystem.unitId' => MonetaSdkSettings::getSettings('unit_id', $this->configPath),
'paymentSystem.limitIds' => MonetaSdkSettings::getSettings('limit_ids', $this->configPath),
];
$httpParams = array_diff($httpParams, ['']);
$endpoint = MonetaSdkSettings::getSettings('demo_mode', $this->configPath) ? self::DEMO_ENDPOINT : self::PROD_ENDPOINT;
$paymentLink = $endpoint . http_build_query($httpParams);
return $paymentLink;
}
/**
* @param MonetaSdkReceipt $mSdkR
* @param string $transactionId
* @return string
* @throws MonetaSdkException
*/
public function responseToCheckRequest(MonetaSdkReceipt $mSdkR) {
if (!isset($this->amount)) {
throw new MonetaSdkException(self::EXCEPTION_VAR_AMOUNT_EMPTY);
}
$response = [
'id' => MonetaSdkSettings::getSettings('id', $this->configPath),
'transactionId' => $this->transactionId,
'amount' => number_format($this->amount, 2, '.', ''),
'signature' => MonetaSdkService::createSignature('checkRequest', $this->transactionId, $this->configPath),
'resultCode' => '402',
'receipt' => $mSdkR->getJsonReceipt()
];
header('Content-Type: application/json; charset=utf-8');
echo json_encode($response, JSON_UNESCAPED_UNICODE);
die;
}
/**
* @param MonetaSdkReceipt $mSdkR
* @param string $transactionId
* @return string
* @throws MonetaSdkException
*/
public function responseToPaymentNotification(?MonetaSdkReceipt $mSdkR = null) {
if (isset($mSdkR)) {
$xmlResponse = '<?xml version="1.0" encoding="UTF-8"?>';
$xmlResponse .= '<MNT_RESPONSE>';
$xmlResponse .= ' <MNT_ID>' . MonetaSdkSettings::getSettings('id', $this->configPath) . '</MNT_ID>';
$xmlResponse .= ' <MNT_TRANSACTION_ID>' . $this->transactionId . '</MNT_TRANSACTION_ID>';
$xmlResponse .= ' <MNT_RESULT_CODE>200</MNT_RESULT_CODE>';
$xmlResponse .= ' <MNT_SIGNATURE>' . MonetaSdkService::createSignature('paymentNotification', $this->transactionId, $this->configPath) . '</MNT_SIGNATURE>';
$xmlResponse .= ' <MNT_ATTRIBUTES>';
$xmlResponse .= ' <MNT_ATTRIBUTE>';
$xmlResponse .= ' <KEY>INVENTORY</KEY>';
$xmlResponse .= ' <VALUE>' . $mSdkR->getXmlItems() . '</VALUE>';
$xmlResponse .= ' </MNT_ATTRIBUTE>';
if (isset($mSdkR->customer['email'])) {
$xmlResponse .= ' <MNT_ATTRIBUTE>';
$xmlResponse .= ' <KEY>CUSTOMER</KEY>';
$xmlResponse .= ' <VALUE>' . $mSdkR->customer['email'] . '</VALUE>';
$xmlResponse .= ' </MNT_ATTRIBUTE>';
}
if (isset($mSdkR->customer['phone'])) {
$xmlResponse .= ' <MNT_ATTRIBUTE>';
$xmlResponse .= ' <KEY>PHONE</KEY>';
$xmlResponse .= ' <VALUE>' . $mSdkR->customer['phone'] . '</VALUE>';
$xmlResponse .= ' </MNT_ATTRIBUTE>';
}
if (isset($mSdkR->delivery)) {
$xmlResponse .= ' <MNT_ATTRIBUTE>';
$xmlResponse .= ' <KEY>DELIVERY</KEY>';
$xmlResponse .= ' <VALUE>' . number_format($mSdkR->delivery, 2, '.', '') . '</VALUE>';
$xmlResponse .= ' </MNT_ATTRIBUTE>';
}
$xmlResponse .= ' </MNT_ATTRIBUTES>';
$xmlResponse .= '</MNT_RESPONSE>';
header("Content-type: application/xml");
echo $xmlResponse;
die;
}
echo 'SUCCESS';
die;
}
/**
* @param string $operationId
* @return string
*/
public function getPaymentLink($operationId) {
$endpoint = MonetaSdkSettings::getSettings('demo_mode', $this->configPath) ? self::DEMO_ENDPOINT : self::PROD_ENDPOINT;
$httpParams = [
'operationId' => $operationId,
'moneta.locale' => MonetaSdkSettings::getSettings('locale', $this->configPath),
'paymentSystem.unitId' => MonetaSdkSettings::getSettings('unit_id', $this->configPath),
'paymentSystem.limitIds' => MonetaSdkSettings::getSettings('limit_ids', $this->configPath),
'MNT_SUCCESS_URL' => MonetaSdkSettings::getSettings('success', $this->configPath),
'MNT_INPROGRESS_URL' => MonetaSdkSettings::getSettings('inprogress', $this->configPath),
'MNT_FAIL_URL' => MonetaSdkSettings::getSettings('fail', $this->configPath),
'MNT_RETURN_URL' => MonetaSdkSettings::getSettings('return', $this->configPath),
'MNT_SIGNATURE' => MonetaSdkService::createSignature('generateLink', $this->transactionId, $this->configPath, number_format($this->amount, 2, '.', ''),),
];
$httpParams = array_diff($httpParams, ['']);
$paymentLink = $endpoint . http_build_query($httpParams);
return $paymentLink;
}
/**
* @return int
* @throws MonetaSdkException
*/
public function createInvoice($isTwoPhase = false) {
if (!isset($this->amount)) {
throw new MonetaSdkException(self::EXCEPTION_VAR_AMOUNT_EMPTY);
}
$params = [
'Envelope' => [
'Header' => [
'Security' => [
'UsernameToken' => [
'Username' => MonetaSdkSettings::getSettings('username', $this->configPath),
'Password' => MonetaSdkSettings::getSettings('password', $this->configPath)
]
]
],
'Body' => [
'InvoiceRequest' => [
'payer' => 'card',
'payee' => MonetaSdkSettings::getSettings('id', $this->configPath),
'amount' => number_format($this->amount, 2, '.', ''),
'clientTransaction' => (string) $this->transactionId,
]
]
]
];
if ($isTwoPhase) {
$params['Envelope']['Body']['InvoiceRequest']['operationInfo']['attribute'] = [
[
'key' => 'AUTHORIZEONLY',
'value' => '1'
]
];
}
$response = MonetaSdkService::sendCurl($params, $this->configPath);
if (!isset($response['Envelope']['Body']['InvoiceResponse']['transaction'])) {
throw new MonetaSdkException(self::EXCEPTION_MERCHANT_API_NO_TRANSACTION_ID . " Request result: " . json_encode($response, JSON_UNESCAPED_UNICODE));
}
return $response['Envelope']['Body']['InvoiceResponse']['transaction'];
}
/**
* @param string $operationId
* @return array
*/
public function confirmInvoice($operationId) {
$params = [
'Envelope' => [
'Header' => [
'Security' => [
'UsernameToken' => [
'Username' => MonetaSdkSettings::getSettings('username', $this->configPath),
'Password' => MonetaSdkSettings::getSettings('password', $this->configPath)
]
]
],
'Body' => [
'ConfirmTransactionRequest' => [
'transactionId' => $operationId,
'paymentPassword' => MonetaSdkSettings::getSettings('payment_password', $this->configPath),
]
]
]
];
$response = MonetaSdkService::sendCurl($params, $this->configPath);
return $response['Envelope']['Body'];
}
/**
* @param string $operationId
* @return array
*/
public function cancelInvoice($operationId) {
$params = [
'Envelope' => [
'Header' => [
'Security' => [
'UsernameToken' => [
'Username' => MonetaSdkSettings::getSettings('username', $this->configPath),
'Password' => MonetaSdkSettings::getSettings('password', $this->configPath)
]
]
],
'Body' => [
'CancelTransactionRequest' => [
'transactionId' => $operationId
]
]
]
];
$response = MonetaSdkService::sendCurl($params, $this->configPath);
return $response['Envelope']['Body'];
}
/**
* @return int
* @throws MonetaSdkException
*/
public function createRecurrentInvoice() {
if (!isset($this->amount)) {
throw new MonetaSdkException(self::EXCEPTION_VAR_AMOUNT_EMPTY);
}
$params = [
'Envelope' => [
'Header' => [
'Security' => [
'UsernameToken' => [
'Username' => MonetaSdkSettings::getSettings('username', $this->configPath),
'Password' => MonetaSdkSettings::getSettings('password', $this->configPath)
]
]
],
'Body' => [
'InvoiceRequest' => [
'payer' => 'card',
'payee' => MonetaSdkSettings::getSettings('id', $this->configPath),
'amount' => number_format($this->amount, 2, '.', ''),
'clientTransaction' => (string) $this->transactionId,
'description' => $this->description ?? 'Рекуррентный платеж по заказу №' . $this->transactionId,
'operationInfo' => [
'attribute' => [
[
'key' => 'PAYMENTTOKEN',
'value' => 'request'
]
]
]
]
]
]
];
$response = MonetaSdkService::sendCurl($params, $this->configPath);
if (!isset($response['Envelope']['Body']['InvoiceResponse']['transaction'])) {
throw new MonetaSdkException(self::EXCEPTION_MERCHANT_API_NO_TRANSACTION_ID . " Request result: " . json_encode($response, JSON_UNESCAPED_UNICODE));
}
return $response['Envelope']['Body']['InvoiceResponse']['transaction'];
}
/**
* @param string $token
* @return array
*/
public function recurringPayment($token) {
if (!isset($this->amount)) {
throw new MonetaSdkException(self::EXCEPTION_VAR_AMOUNT_EMPTY);
}
$params = [
'Envelope' => [
'Header' => [
'Security' => [
'UsernameToken' => [
'Username' => MonetaSdkSettings::getSettings('username', $this->configPath),
'Password' => MonetaSdkSettings::getSettings('password', $this->configPath)
]
]
],
'Body' => [
'PaymentRequest' => [
'payer' => 'card',
'payee' => MonetaSdkSettings::getSettings('id', $this->configPath),
'amount' => number_format($this->amount, 2, '.', ''),
'clientTransaction' => (string) $this->transactionId . '_MONETA' . time(),
'description' => $this->description ?? 'Рекуррентный платеж по заказу ' . $this->transactionId,
'operationInfo' => [
'attribute' => [
[
'key' => 'PAYMENTTOKEN',
'value' => $token
]
]
]
]
]
]
];
$response = MonetaSdkService::sendCurl($params, $this->configPath);
return $response['Envelope']['Body'];
}
/**
* @param int $operationId
* @return array
*/
public function refund($operationId) {
if (!isset($this->amount)) {
throw new MonetaSdkException(self::EXCEPTION_VAR_AMOUNT_EMPTY);
}
$params = [
'Envelope' => [
'Header' => [
'Security' => [
'UsernameToken' => [
'Username' => MonetaSdkSettings::getSettings('username', $this->configPath),
'Password' => MonetaSdkSettings::getSettings('password', $this->configPath)
]
]
],
'Body' => [
'RefundRequest' => [
'amount' => number_format($this->amount, 2, '.', ''),
'paymentPassword' => MonetaSdkSettings::getSettings('payment_password', $this->configPath),
'transactionId' => $operationId,
'description' => $this->description ?? 'Возврат по операции ' . $this->transactionId,
'clientTransaction' => (string) $this->transactionId,
]
]
]
];
$response = MonetaSdkService::sendCurl($params, $this->configPath);
return $response['Envelope']['Body'];
}
/**
* @param string $operationId
* @return array
*/
public function getOperationDetailsById($operationId) {
$params = [
'Envelope' => [
'Header' => [
'Security' => [
'UsernameToken' => [
'Username' => MonetaSdkSettings::getSettings('username', $this->configPath),
'Password' => MonetaSdkSettings::getSettings('password', $this->configPath)
]
]
],
'Body' => [
'GetOperationDetailsByIdRequest' => $operationId
]
]
];
$response = MonetaSdkService::sendCurl($params, $this->configPath);
return $response['Envelope']['Body'];
}
}
+13
View File
@@ -0,0 +1,13 @@
<?php
namespace Moneta;
class MonetaSdkException extends \Exception {
public function __construct($message, $code = 0, ?Exception $previous = null) {
parent::__construct($message, $code, $previous);
}
public function __toString() {
return __CLASS__ . ": [{$this->code}]: {$this->message}\n";
}
}
+167
View File
@@ -0,0 +1,167 @@
<?php
namespace Moneta;
class MonetaSdkReceipt {
/**
* Exception messages text
*/
const EXCEPTION_REQUIRED_ITEM_PARAM = "This item param is required: ";
const EXCEPTION_REQUIRED_CUSTOMER_PARAM = "This customer param is required: ";
const EXCEPTION_ARRAY_ITEMS_IS_REQUIRED = "The items array is required";
public array $items, $customer, $additionalUserProps;
public string $additionalCheckProp;
public float $delivery;
/**
* @return array
*/
public function getJsonReceipt() {
$receipt = [
'client' => $this->getJsonCustomer(),
'items' => $this->getJsonItems(),
];
if (isset($this->additionalCheckProp)) {
$receipt['additionalCheckProp'] = $this->additionalCheckProp;
}
if (isset($this->additionalUserProps)) {
$receipt['additionalUserProps'] = $this->additionalUserProps;
}
return $receipt;
}
/**
* @return array
* @throws MonetaSdkException
*/
private function getJsonItems() {
$this->checkReceiptParams();
foreach ($this->items as $iteration => $item) {
$receiptItems[] = array_diff([
'name' => $item['name'],
'price' => $item['price'],
'quantity' => $item['quantity'],
'measure' => $item['measure'] ?? '',
'paymentMethod' => $item['paymentMethod'] ?? '',
'paymentObject' => $item['paymentObject'] ?? '',
'vat' => $item['vat'] ?? 'none',
], ['']);
if (isset($item['agentInfo']['payingAgent'])) {
$receiptItems[$iteration]['agentInfo']['payingAgent'] = [
'operation' => $item['agentInfo']['payingAgent']['operation'],
'phones' => $item['agentInfo']['payingAgent']['phones']
];
}
if (isset($item['agentInfo']['supplierInfo'])) {
$receiptItems[$iteration]['agentInfo']['supplierInfo'] = [
'phones' => $item['agentInfo']['supplierInfo']['phones'],
'name' => $item['agentInfo']['supplierInfo']['name'],
'inn' => $item['agentInfo']['supplierInfo']['inn'],
];
}
}
if (isset($this->delivery)) {
$receiptItems[] = [
'name' => 'Доставка',
'price' => $this->delivery,
'quantity' => 1,
'vat' => 'none',
'paymentObject' => 'service'
];
}
return $receiptItems;
}
/**
* @return array
* @throws MonetaSdkException
*/
private function getJsonCustomer() {
$this->checkReceiptParams(false);
$customer = [
'name' => $this->customer['name'] ?? '',
'inn' => $this->customer['inn'] ?? '',
'email' => $this->customer['email'],
'phone' => $this->customer['phone'] ?? '',
];
$customer = array_diff($customer, ['']);
return $customer;
}
/**
* @return array
* @throws MonetaSdkException
*/
public function getXmlItems() {
$this->checkReceiptParams();
foreach ($this->items as $iteration => $item) {
$receiptItems[] = array_diff([
'name' => $item['name'],
'price' => $item['price'],
'quantity' => $item['quantity'],
'vatTag' => MonetaSdkService::getXmlVat($item['vat'] ?? 'none'),
'pm' => $item['paymentMethod'] ?? 'full_payment',
'po' => $item['paymentObject'] ?? 'commodity',
]);
if (isset($item['agentInfo']['type'])) {
$receiptItems[$iteration]['agentInfo']['type'] = $item['agentInfo']['type'];
}
if (isset($item['supplierInfo'])) {
$receiptItems[$iteration]['supplierInfo'] = [
'name' => $item['supplierInfo']['name'],
'inn' => $item['supplierInfo']['inn'],
'phones' => $item['supplierInfo']['phones'],
];
}
}
return json_encode($receiptItems, JSON_UNESCAPED_UNICODE);
}
/**
* @param bool $isItems
* @throws MonetaSdkException
*/
private function checkReceiptParams($isItems = true) {
switch ($isItems) {
case true:
if (!isset($this->items)) {
throw new MonetaSdkException(self::EXCEPTION_ARRAY_ITEMS_IS_REQUIRED);
}
foreach ($this->items as $i) {
if (!isset($i['name'])) {
throw new MonetaSdkException(self::EXCEPTION_REQUIRED_ITEM_PARAM . '"name"');
} else if (!isset($i['price'])) {
throw new MonetaSdkException(self::EXCEPTION_REQUIRED_ITEM_PARAM . '"price"');
} else if (!isset($i['quantity'])) {
throw new MonetaSdkException(self::EXCEPTION_REQUIRED_ITEM_PARAM . '"quantity"');
}
}
break;
case false:
if (!isset($this->customer['email'])) {
throw new MonetaSdkException(self::EXCEPTION_REQUIRED_CUSTOMER_PARAM . '"email"');
}
break;
default:
break;
}
}
}
+111
View File
@@ -0,0 +1,111 @@
<?php
namespace Moneta;
class MonetaSdkService {
/**
* Exception messages text
*/
const EXCEPTION_ERROR_ACTION_NAME = "Wrong action name: ";
/**
* @param string $action
* @param string $transactionId
* @param float|int $amount
* @param string $subscriber
* @return string
* @throws MonetaSdkException
*/
public static function createSignature($action, $transactionId, $configPath, ?float $amount = null,) {
switch ($action) {
case 'generateLink':
return md5(
MonetaSdkSettings::getSettings('id', $configPath) .
$transactionId .
number_format($amount, 2, '.', '') .
MonetaSdkSettings::getSettings('currency', $configPath) .
'' .
0 .
MonetaSdkSettings::getSettings('secret', $configPath)
);
break;
case 'checkRequest':
return md5(
402 .
MonetaSdkSettings::getSettings('id', $configPath) .
$transactionId .
MonetaSdkSettings::getSettings('secret', $configPath)
);
break;
case 'paymentNotification':
return md5(
200 .
MonetaSdkSettings::getSettings('id', $configPath) .
$transactionId .
MonetaSdkSettings::getSettings('secret', $configPath)
);
break;
default:
throw new MonetaSdkException(self::EXCEPTION_ERROR_ACTION_NAME . $action);
break;
}
}
/**
* @param string $jsonVat
* @return string
*/
public static function getXmlVat($jsonVat) {
$xmlVatList = [
'none' => '1105',
'vat0' => '1104',
'vat10' => '1103',
'vat110' => '1107',
'vat20' => '7000',
'vat120' => '7001',
'vat5' => '1108',
'vat7' => '1109',
'vat15' => '1110',
'vat17' => '1111'
];
return isset($xmlVatList[$jsonVat]) ? $xmlVatList[$jsonVat] : '1105';
}
/**
* MerchantAPI query builder
*/
/**
* @return string
*/
private static function getApiUrl($configPath) {
$url = MonetaSdkSettings::getSettings('demo_mode', $configPath) ? MonetaSdkSettings::getSettings('payment_url', $configPath)['demo'] : MonetaSdkSettings::getSettings('payment_url', $configPath)['production'];
$urn = MonetaSdkSettings::getSettings('urn');
return $url . $urn;
}
/**
* @param array $params
* @return string
*/
public static function sendCurl($params, $configPath) {
$ch = curl_init(self::getApiUrl($configPath));
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type:application/json'));
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($params, JSON_UNESCAPED_UNICODE));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_HEADER, false);
$result = curl_exec($ch);
curl_close($ch);
return json_decode($result, true);
}
}
+57
View File
@@ -0,0 +1,57 @@
<?php
namespace Moneta;
class MonetaSdkSettings {
/**
* Config file names
*/
const SETTINGS_ACCOUNT = '/account.php';
const SETTINGS_API = '/api.php';
const SETTINGS_STORAGE = '/storage.php';
const SETTINGS_URL = '/url.php';
/**
* Exception messages text
*/
const EXCEPTION_ERROR_PARAM_NAME = 'There is no such parameter: ';
const EXCEPTION_NO_PARAM_FILE = "Config file not found: ";
/**
* @param null $configPath
* @param @nameParam
* @return array
* @throws MonetaSdkException
*/
public static function getSettings($nameParam, ?string $configPath = null) {
$configPath = $configPath ? $configPath : dirname(__DIR__) . '/config';
$arrayAccountSettings = self::getSettingsFromConfigFiles($configPath . self::SETTINGS_ACCOUNT);
$arrayApiSettings = require dirname(__DIR__) . '/config/api.php';
$arrayUrlSettings = self::getSettingsFromConfigFiles($configPath . self::SETTINGS_URL);
$allSettings = array_merge(
$arrayAccountSettings,
$arrayApiSettings,
$arrayUrlSettings
);
if (!isset($allSettings[$nameParam])) {
throw new MonetaSdkException(self::EXCEPTION_ERROR_PARAM_NAME . $nameParam);
}
return $allSettings[$nameParam];
}
/**
* @param $fileName
* @return array
* @throws MonetaSdkException
*/
private static function getSettingsFromConfigFiles($fileName) {
if (!file_exists($fileName)) {
throw new MonetaSdkException(self::EXCEPTION_NO_PARAM_FILE . $fileName);
}
return require($fileName);
}
}