Skip to content

YP-746-Marketplace-Requests Added MP2 getSeller(s) requests #22

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,10 @@ docker compose up --detach
4. [Печать анкеты](src/Examples/qstPrint.php)
5. [Список анкет](src/Examples/qstList.php)

##### 11. Маркетплейс
1. [Запрос продавца МП](src/Examples/Marketplace/getSeller.php)
2. [Запрос всех продавцов МП](src/Examples/Marketplace/getSellers.php)

## Ссылки
- [НКО «Твои Платежи»](https://YPMN.ru/)
- [Докуметация API](https://ypmn.ru/ru/documentation/)
Expand Down
2 changes: 2 additions & 0 deletions example.php
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,8 @@
case 'qstPrint':
case 'SOMGetPaymentLink':
case 'qstList':
case 'getSeller':
case 'getSellers':
require './src/Examples/start.php';
@include './src/Examples/'.$_GET['function'] . '__prepend.php';
require './src/Examples/'.$_GET['function'] . '.php';
Expand Down
12 changes: 12 additions & 0 deletions example_list.php
Original file line number Diff line number Diff line change
Expand Up @@ -166,4 +166,16 @@
'docLink' => 'https://ypmn.ru/ru/documentation/#tag/qst-api/paths/~1v4~1qst~1list/get',
'link' => '',
],
'getSeller' => [
'name' => 'Запрос продавца МП',
'about' => 'В этом примере показана реализация запроса продавца маркетплейса по его ID.',
'docLink' => 'https://ypmn.ru/ru/documentation/#tag/payment-api',
'link' => '',
],
'getSellers' => [
'name' => 'Запрос всех продавцов МП',
'about' => 'В этом примере показана реализация запроса всех продавцов маркетплейса.',
'docLink' => 'https://ypmn.ru/ru/documentation/#tag/payment-api',
'link' => '',
],
];
13 changes: 13 additions & 0 deletions src/ApiRequest.php
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ class ApiRequest implements ApiRequestInterface
const QST_STATUS_API = '/api/v4/qst/status';
const QST_PRINT_API = '/api/v4/qst/print';
const QST_LIST_API = '/api/v4/qst/list';
const MARKETPLACE_SELLER_API = '/api/v4/marketplace/sellers';
const HOST = 'https://secure.ypmn.ru';
const SANDBOX_HOST = 'https://sandbox.ypmn.ru';
const LOCAL_HOST = 'http://127.0.0.1';
Expand Down Expand Up @@ -681,4 +682,16 @@ private function addCurlOptHeaderFunction(array &$curlOptArr, array &$headers):
}
];
}

/** @inheritdoc */
public function sendMarketplaceGetSellerRequest(string $marketplaceSellerId): array
{
return $this->sendGetRequest(self::MARKETPLACE_SELLER_API . '/' . $marketplaceSellerId);
}

/** @inheritdoc */
public function sendMarketplaceGetSellersRequest(): array
{
return $this->sendGetRequest(self::MARKETPLACE_SELLER_API);
}
}
22 changes: 22 additions & 0 deletions src/Examples/Marketplace/getMasterAccountSettings.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
<?php

declare(strict_types=1);

use Ypmn\ApiRequest;

// Подключим файл, в котором заданы параметры мерчанта
include_once 'startMarketplace.php';

// Уникальный UUID селлера, информацио о котором хотим получить
$marketplaceSellerId = '30b0db49-5ba3-4358-8cae-9cd29de8b037';

// Отправим запрос
$apiRequest = new ApiRequest($merchant);
$apiRequest->setSandboxMode();
$apiRequest->setDebugMode();

try {
$session = $apiRequest->sendMarketplaceGetSellerRequest($marketplaceSellerId);

} catch (\Ypmn\PaymentException $e) {
}
22 changes: 22 additions & 0 deletions src/Examples/Marketplace/getSeller.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
<?php

declare(strict_types=1);

use Ypmn\ApiRequest;

// Подключим файл, в котором заданы параметры мерчанта
include_once 'startMarketplace.php';

// Уникальный UUID селлера, информацио о котором хотим получить
$marketplaceSellerId = '30b0db49-5ba3-4358-8cae-9cd29de8b037';

// Отправим запрос
$apiRequest = new ApiRequest($merchant);
$apiRequest->setSandboxMode();
$apiRequest->setDebugMode();

try {
$session = $apiRequest->sendMarketplaceGetSellerRequest($marketplaceSellerId);

} catch (\Ypmn\PaymentException $e) {
}
19 changes: 19 additions & 0 deletions src/Examples/Marketplace/getSellers.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
<?php

declare(strict_types=1);

use Ypmn\ApiRequest;

// Подключим файл, в котором заданы параметры мерчанта
include_once 'startMarketplace.php';

// Отправим запрос
$apiRequest = new ApiRequest($merchant);
$apiRequest->setSandboxMode();
$apiRequest->setDebugMode();

try {
$session = $apiRequest->sendMarketplaceGetSellersRequest();

} catch (\Ypmn\PaymentException $e) {
}
100 changes: 100 additions & 0 deletions src/Examples/Marketplace/simpleGetPaymentLink.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
<?php

declare(strict_types=1);

use Ypmn\Authorization;
use Ypmn\Payment;
use Ypmn\Client;
use Ypmn\Billing;
use Ypmn\ApiRequest;
use Ypmn\PaymentException;
use Ypmn\Product;
use Ypmn\Std;

// Подключим файл, в котором заданы параметры мерчанта
include_once 'start.php';

// Оплата по ссылке Ypmn
// Минимальный набор полей

// Представим, что мы не хотим передавать товары, только номер заказа и сумму
// Установим номер (ID) заказа (номер заказа в вашем магазине, должен быть уникален в вашей системе)
$merchantPaymentReference = "order_id_" . time();

$orderAsProduct = new Product([
'name' => 'Заказ №' . $merchantPaymentReference,
'sku' => $merchantPaymentReference,
'unitPrice' => 200.42,
'quantity' => 1,
]);

// Опишем Биллинговую (платёжную) информацию
$billing = new Billing;
// Установим Код страны
$billing->setCountryCode('RU');
// Установим Имя Плательщика
$billing->setFirstName('Иван');
// Установим Фамилия Плательщика
$billing->setLastName('Петров');
// Установим Email Плательщика
$billing->setEmail('[email protected]');
// Установим Телефон Плательщика
$billing->setPhone('+7-800-555-35-35');
// Установим Город
$billing->setCity('Москва');

// Создадим клиентское подключение
$client = new Client;
// Установим биллинг
$client->setBilling($billing);

// Создадим платёж
$payment = new Payment;
// Установим позиции
$payment->addProduct($orderAsProduct);
// Установим валюту
$payment->setCurrency('RUB');
// Создадим и установим авторизацию по типу платежа
$payment->setAuthorization(new Authorization('CCVISAMC',true));
// Установим номер заказа (должен быть уникальным в вашей системе)
$payment->setMerchantPaymentReference($merchantPaymentReference);
// Установим адрес перенаправления пользователя после оплаты
$payment->setReturnUrl('https://test.u2go.ru/php-api-client/?function=returnPage');
// Установим клиентское подключение
$payment->setClient($client);

// Создадим HTTP-запрос к API
$apiRequest = new ApiRequest($merchant);
// Включить режим отладки (закомментируйте или удалите в рабочей программе!)
$apiRequest->setDebugMode();
// Переключиться на тестовый сервер (закомментируйте или удалите в рабочей программе!)
$apiRequest->setSandboxMode();
// Отправим запрос
$responseData = $apiRequest->sendAuthRequest($payment, $merchant);
// Преобразуем ответ из JSON в массив
try {
$responseData = json_decode((string) $responseData["response"], true);

if ($responseData) {
// Выведем кнопку оплаты
echo Std::drawYpmnButton([
'url' => $responseData["paymentResult"]['url'],
'sum' => $payment->sumProductsAmount(),
]);

// .. или сделаем редирект на форму оплаты (опционально)
// Std::redirect($responseData["paymentResult"]['url']);
}
} catch (Exception $exception) {
//TODO: обработка исключения
echo Std::alert([
'text' => '
Извините, платёжный метод временно недоступен.<br>
Вы можете попробовать другой способ оплаты, либо свяжитесь с продавцом.<br>
<br>
<pre>' . $exception->getMessage() . '</pre>',
'type' => 'danger',
]);

throw new PaymentException('Платёжный метод временно недоступен');
}
16 changes: 16 additions & 0 deletions src/Examples/Marketplace/startMarketplace.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
<?php declare(strict_types=1);

use Ypmn\Merchant;

/**
* Создадим объект Мерчанта для работы с Маркетплейсом
* (получите Интеграционный Код Мерчанта и Секретный Ключ у вашего менеджера YPMN)
*
* Теперь включайте этот файл везде, где работаете с Маркетплейсом
*
* Запросы от вашего приложения будут отправляться на:
* https://secure.ypmn.ru/
* https://sandbox.ypmn.ru/
* Убедитесь, что эти адреса разрешены в Firewall вашего приложения
*/
$merchant = new Merchant('MARKTPLC', '_X6c^l8%o8]3&e)+n9D)');