### Basic DescriptionRequest send example Source: https://github.com/dicrtarasov/yii2-payparts/blob/master/_autodocs/api-reference/request/DescriptionRequest.md Basic usage: get the module, create DescriptionRequest, send it, and print the response state. ```php /** @var PayPartsModule $module */ $module = Yii::$app->getModule('payparts'); $response = (new DescriptionRequest($module, [ 'orderId' => $orderId, 'description' => 'Оплата заказа №' . $orderId, ]))->send(); echo 'State: ' . $response->state . "\n"; ``` -------------------------------- ### Basic decline request example Source: https://github.com/dicrtarasov/yii2-payparts/blob/master/_autodocs/api-reference/request/DeclineRequest.md Basic usage: get the module, create a decline request with orderId and amount, send it, and print the response state. Expects PayParts::STATE_SUCCESS on success. ```php /** @var PayPartsModule $module */ $module = Yii::$app->getModule('payparts'); $response = $module->declineRequest([ 'orderId' => $orderId, 'amount' => 246.26, // сумма возврата ])->send(); echo 'State: ' . $response->state . "\n"; // PayParts::STATE_SUCCESS ``` -------------------------------- ### Manual Product Creation Source: https://github.com/dicrtarasov/yii2-payparts/blob/master/_autodocs/api-reference/Product.md Example of manually instantiating a Product object and accessing its sum. ```php use dicr\payparts\Product; $product = new Product([ 'name' => 'Рулон бумаги', 'price' => 0.01, 'count' => 2, ]); echo $product->sum; // 0.02 ``` -------------------------------- ### stateRequest() usage example Source: https://github.com/dicrtarasov/yii2-payparts/blob/master/_autodocs/api-reference/PayPartsModule.md Shows how to send a state request and output the payment state. ```php $response = $module->stateRequest(['orderId' => $orderId])->send(); echo 'PaymentState: ' . $response->paymentState . "\n"; ``` -------------------------------- ### Product Validation Source: https://github.com/dicrtarasov/yii2-payparts/blob/master/_autodocs/api-reference/Product.md Example of validating a Product instance and handling validation errors. ```php $product = new Product(['name' => '', 'price' => 0.001, 'count' => 0]); if (! $product->validate()) { // ошибки по атрибутам: name — required, price — min 0.01, count — min 1 foreach ($product->errors as $attr => $messages) { echo $attr . ': ' . implode(', ', $messages) . "\n"; } } ``` -------------------------------- ### Module configuration with PayParts constants Source: https://github.com/dicrtarasov/yii2-payparts/blob/master/_autodocs/api-reference/PayParts.md Example of configuring the PayParts module using test store ID and password constants. ```php 'modules' => [ 'payparts' => [ 'class' => dicr\payparts\PayPartsModule::class, 'storeId' => dicr\payparts\PayParts::TEST_STORE_ID, 'password' => dicr\payparts\PayParts::TEST_PASSWORD, ], ], ``` -------------------------------- ### getPaymentUrl() usage example Source: https://github.com/dicrtarasov/yii2-payparts/blob/master/_autodocs/api-reference/PayPartsResponse.md Example of echoing the payment URL from a response object. The output shows the expected format with the token parameter. ```php echo 'Redirect URL: ' . $response->paymentUrl . "\n"; // https://payparts2.privatbank.ua/ipp/v2/payment?token=... ``` -------------------------------- ### Basic state request example Source: https://github.com/dicrtarasov/yii2-payparts/blob/master/_autodocs/api-reference/request/StateRequest.md Sends a state request with only orderId and prints the paymentState from the response. ```php /** @var PayPartsModule $module */ $module = Yii::$app->getModule('payparts'); $response = $module->stateRequest([ 'orderId' => $orderId, // номер заказа ])->send(); echo 'PaymentState: ' . $response->paymentState . "\n"; // например 'CLIENT_WAIT', 'SUCCESS', 'CANCELED' — см. PayParts::STATES ``` -------------------------------- ### DeclineRequest usage example Source: https://github.com/dicrtarasov/yii2-payparts/blob/master/_autodocs/api-reference/request/DeclineRequest.md Demonstrates sending a decline request and handling the response. ```APIDOC ## DeclineRequest usage example ### Description Shows how to send a decline request and process the response, including error handling. ### Example ```php /** @var PayPartsModule $module */ $module = Yii::$app->getModule('payparts'); $response = $module->declineRequest([ 'orderId' => $orderId, 'amount' => 246.26, // сумма возврата ])->send(); echo 'State: ' . $response->state . "\n"; // PayParts::STATE_SUCCESS ``` ### Error Handling Example ```php use dicr\validate\ValidateException; use yii\base\Exception; try { $module->declineRequest([ 'orderId' => $orderId, 'amount' => $sum, 'recipientId' => $recipientId, // опционально ])->send(); // возврат выполнен } catch (ValidateException $ex) { // не задан orderId/amount или amount < 0.01 Yii::warning('Невалидный запрос возврата: ' . json_encode($ex->errors)); } catch (Exception $ex) { // HTTP-ошибка, некорректный ответ, state != SUCCESS Yii::error('Не удалось выполнить возврат: ' . $ex->getMessage()); } ``` ``` -------------------------------- ### paymentRequest() usage example Source: https://github.com/dicrtarasov/yii2-payparts/blob/master/_autodocs/api-reference/PayPartsModule.md Shows how to create and send a payment request using the module's paymentRequest() method with order details and product list. ```php $request = $module->paymentRequest([ 'orderId' => (string)time(), 'partsCount' => 4, 'merchantType' => PayParts::MERCHANT_TYPE_PP, 'products' => [ ['name' => 'Кофе', 'price' => 199.90, 'count' => 1], ], ]); $response = $request->send(); ``` -------------------------------- ### Error Response Example Source: https://github.com/dicrtarasov/yii2-payparts/blob/master/doc/api-oc.pdf Shows an example of an error response with state FAIL and a message. The response is a JSON object with state and message fields. ```json { "state": "FAIL", "message": "bad value: not found." } ``` -------------------------------- ### Calculate for Legal Entity (1 month) Source: https://github.com/dicrtarasov/yii2-payparts/blob/master/doc/api-oc.pdf Example of using PP_CALCULATOR.calculateJur to calculate installment plan for a legal entity with 1 month term. The result includes payCount, stPpValue, ipValue, and ipaValue. ```javascript var resCalc = PP_CALCULATOR.calculateJur(1, 500); resCalc = {payCount: 2, stPpValue: "482.50", ipValue: "490.00", ipaValue: "482.50"} ``` -------------------------------- ### Calculate for Legal Entity (6 months) Source: https://github.com/dicrtarasov/yii2-payparts/blob/master/doc/api-oc.pdf Example of using PP_CALCULATOR.calculateJur to calculate installment plan for a legal entity with 6 months term. The result includes payCount, stPpValue, ipValue, and ipaValue. ```javascript var resCalc = PP_CALCULATOR.calculateJur(6, 500); resCalc = {payCount: 7, stPpValue: "432.50", ipValue: "490.00", ipaValue: "449.00"} ``` -------------------------------- ### Basic cancel request example Source: https://github.com/dicrtarasov/yii2-payparts/blob/master/_autodocs/api-reference/request/CancelRequest.md Basic usage: obtains the module, creates a cancel request with the orderId, sends it, and prints the response state. ```php /** @var PayPartsModule $module */ $module = Yii::$app->getModule('payparts'); $response = $module->cancelRequest([ 'orderId' => $orderId, // номер hold-платежа, который нужно отменить ])->send(); echo 'State: ' . $response->state . "\n"; ``` -------------------------------- ### Passing Products in PaymentRequest Source: https://github.com/dicrtarasov/yii2-payparts/blob/master/_autodocs/api-reference/Product.md Example of passing an array of product data to the paymentRequest method. ```php $response = $module->paymentRequest([ 'orderId' => $orderId, 'products' => [ ['name' => 'Рулон бумаги', 'price' => 0.01, 'count' => 2], ['name' => 'Автомобиль', 'price' => 123, 'count' => 1], ['name' => 'Талоны на Интернет', 'price' => 123.123, 'count' => 3], ], ])->send(); ``` -------------------------------- ### Full configuration example for PayPartsModule Source: https://github.com/dicrtarasov/yii2-payparts/blob/master/_autodocs/configuration.md Use this configuration to set up the PayParts module in a Yii2 application. It registers the module with storeId and password, an optional callbackHandler for payment state changes, and default paymentRequestConfig values. The urlManager hostInfo must be set to the shop's domain. ```php return [ 'components' => [ 'urlManager' => [ 'hostInfo' => 'https://shop.example.com', // ... ], ], 'modules' => [ 'payparts' => [ 'class' => dicr\payparts\PayPartsModule::class, 'storeId' => '* мой storeId *', 'password' => '* мой password *', // обработчик состояний платежей (опционально) 'callbackHandler' => static function(dicr\payparts\PayPartsResponse $response) { Order::setPayed($response->orderId); }, // значения по умолчанию для paymentRequest() 'paymentRequestConfig' => [ 'merchantType' => dicr\payparts\PayParts::MERCHANT_TYPE_PP, 'partsCount' => 4, ], ], ], ]; ``` -------------------------------- ### QrRequest with error handling Source: https://github.com/dicrtarasov/yii2-payparts/blob/master/_autodocs/api-reference/request/QrRequest.md Example with error handling. Catches ValidateException for missing token/amount or amount below 0.01, and Exception for HTTP errors, non-success state, or empty QR code. ```php use dicr\validate\ValidateException; use yii\base\Exception; try { $qr = $module->qrRequest([ 'token' => $token, 'amount' => 0.01, // меньше лимита банка или неверный токен ])->send(); } catch (ValidateException $ex) { // не задан token/amount или amount < 0.01 Yii::warning('Невалидный запрос QR: ' . json_encode($ex->errors)); } catch (Exception $ex) { // HTTP-ошибка, state != SUCCESS или пустой qr Yii::error('Ошибка генерации QR: ' . $ex->getMessage()); } ``` -------------------------------- ### Usage of PayParts constants Source: https://github.com/dicrtarasov/yii2-payparts/blob/master/_autodocs/api-reference/PayParts.md Shows how to access API URLs, validate merchant types, and get human-readable status names. ```php use dicr\payparts\PayParts; // URL для самостоятельного формирования запросов $apiUrl = PayParts::API_URL; $qrUrl = PayParts::QR_URL; // проверка допустимого типа рассрочки if (in_array('PP', array_keys(PayParts::MERCHANT_TYPES), true)) { // ... } // человекочитаемое название статуса платежа echo PayParts::STATES[PayParts::STATE_CLIENT_WAIT]; // 'ожидание оплаты клиентом' ``` -------------------------------- ### GET /ipp/qr/generate Source: https://github.com/dicrtarasov/yii2-payparts/blob/master/doc/api-oc.pdf Генерирует QR-код для подтверждения платежа. Требуется токен, полученный при создании платежа, и размер изображения. ```APIDOC ## [GET] /ipp/qr/generate ### Description Генерирует QR-код для подтверждения платежа. Требуется токен, полученный при создании платежа, и размер изображения. ### Method GET ### Endpoint https://payparts2.privatbank.ua/ipp/qr/generate ### Parameters #### Query Parameters - **token** (string) - Required - Токен, полученный при создании платежа - **size** (integer) - Optional - Размер картинки - **type** (string) - Optional - Тип платежа: II, PP, PB, IA ### Request Example GET https://payparts2.privatbank.ua/ipp/qr/generate?token=C7C09327B608A1AA4C13ACFB&size=512&type=PP ### Response #### Success Response (200) - **qr** (string) - Картинка в Base64 - **state** (string) - SUCCESS #### Response Example { "qr": "iVBORw0KGg.....oAAAANSUhEUgA", "state": "SUCCESS" } #### Error Response - **state** (string) - FAIL - **errorMessage** (string) - Сообщение об ошибке #### Response Example { "state": "FAIL", "errorMessage": "INCORRECT TOKEN OR PAYMENT DOES NOT EXIST" } ``` -------------------------------- ### State request with additional data Source: https://github.com/dicrtarasov/yii2-payparts/blob/master/_autodocs/api-reference/request/StateRequest.md Sends a state request with showAmount and showRefund flags to get amount and refund details. ```php $response = $module->stateRequest([ 'orderId' => $orderId, 'showAmount' => true, // вернуть сумму сделки 'showRefund' => true, // вернуть детали возвратов ])->send(); echo 'State: ' . $response->state . "\n"; ``` -------------------------------- ### Calculate for Physical Entity Source: https://github.com/dicrtarasov/yii2-payparts/blob/master/doc/api-oc.pdf Example of using PP_CALCULATOR.calculatePhys to calculate installment plan for a physical entity. The result includes payCount, ipValue, ppValue, and ipaValue. ```javascript var resCalc = PP_CALCULATOR.calculatePhys(1, 500); resCalc = {payCount: 2, ipValue: "264.50", ppValue: "250.00", ipaValue: "254.95"} ``` -------------------------------- ### init() Source: https://github.com/dicrtarasov/yii2-payparts/blob/master/_autodocs/api-reference/PayPartsModule.md Validates the module configuration and registers a JSON parser for web applications. Throws an InvalidConfigException if required properties are missing or invalid. ```APIDOC ## init() ### Description Validates the module configuration and registers a JSON parser for web applications. ### Method init ### Signature public function init() : void ### Parameters None ### Throws - **yii\base\InvalidConfigException** - If any configuration check fails. ### Validation Checks 1. `url` - must not be empty. 2. `storeId` - after trim() must not be empty and length must be <= 20. 3. `password` - after trim() must not be empty. 4. `callbackHandler` - if set, must be callable. 5. If web application, registers `yii\web\JsonParser` for `application/json`. ``` -------------------------------- ### init() method signature Source: https://github.com/dicrtarasov/yii2-payparts/blob/master/_autodocs/api-reference/PayPartsModule.md Declares the init() method that validates module configuration and registers a JSON parser for web applications. Throws InvalidConfigException on invalid configuration. ```php /** * @inheritDoc * @throws InvalidConfigException */ public function init() : void ``` -------------------------------- ### Create DescriptionRequest instance Source: https://github.com/dicrtarasov/yii2-payparts/blob/master/_autodocs/api-reference/request/DescriptionRequest.md Creating a DescriptionRequest instance directly, passing the module and configuration with orderId and description. No factory method exists in PayPartsModule. ```php use dicr\payparts\request\DescriptionRequest; $request = new DescriptionRequest($module, [ 'orderId' => $orderId, 'description' => 'Оплата заказа №' . $orderId, ]); ``` -------------------------------- ### GET /ipp/v2/payment Source: https://github.com/dicrtarasov/yii2-payparts/blob/master/doc/api-oc.pdf Redirects the user to the payment page. The token is obtained from the payment creation response. ```APIDOC ## GET /ipp/v2/payment ### Description Redirects the user to the payment page. The token is obtained from the payment creation response. ### Method GET ### Endpoint https://payparts2.privatbank.ua/ipp/v2/payment ### Parameters #### Query Parameters - **token** (String) - Required - Token received in the response when creating a payment. ### Request Example https://payparts2.privatbank.ua/ipp/v2/payment?token=C7C09327B608A1AA4C13ACFB||| ### Response #### Success Response (302) Redirects to the payment page. #### Response Example Redirect to the payment page. ``` -------------------------------- ### DeclineRequest creation via PayPartsModule::declineRequest() Source: https://github.com/dicrtarasov/yii2-payparts/blob/master/_autodocs/api-reference/request/DeclineRequest.md Shows how to create a DeclineRequest instance using the module factory method. ```APIDOC ## DeclineRequest creation via PayPartsModule::declineRequest() ### Description Creates a DeclineRequest instance using the module factory method. The request is configured with the provided attributes (e.g., orderId, amount, recipientId). ### Method `PayPartsModule::declineRequest(array $config = []) : DeclineRequest` ### Parameters - **$config** (array) - Optional. Configuration array for the request, e.g., ['orderId' => $orderId, 'amount' => 246.26]. ### Return Value - **DeclineRequest** - The created request instance. ### Example ```php $request = $module->declineRequest(['orderId' => $orderId, 'amount' => 246.26]); ``` ``` -------------------------------- ### POST {url}/payment/state Source: https://github.com/dicrtarasov/yii2-payparts/blob/master/_autodocs/endpoints.md Gets payment status. Request is a StateRequest with storeId, signature, orderId, and optional showRefund/showAmount flags. ```APIDOC ## POST {url}/payment/state ### Description Gets payment status. Request is a StateRequest. ### Method POST ### Endpoint {url}/payment/state ### Parameters #### Request Body - **storeId** (string) - Required - Store identifier - **signature** (string) - Required - Signature: base64(sha1(password . storeId . orderId . password, raw)) - **orderId** (string) - Required - Payment order number - **showRefund** (string) - Optional - 'true'/'false' - refund details - **showAmount** (string) - Optional - 'true'/'false' - transaction amount ### Response - **paymentState** (string) - Status from PayParts::STATES - **storeId** (string) - Store identifier - **orderId** (string) - Order number - **signature** (string) - Signature - Additional fields if showRefund/showAmount (not modeled in library) ``` -------------------------------- ### Create and send a payment request with PayPartsModule Source: https://github.com/dicrtarasov/yii2-payparts/blob/master/_autodocs/api-reference/PayPartsModule.md Retrieves the PayPartsModule instance, creates a payment request with order ID, merchant type, parts count, and products, then sends it and redirects the customer to the payment URL. The response token and payment URL are echoed before redirecting. ```php /** @var PayPartsModule $module получаем модуль оплат */ $module = Yii::$app->getModule('payparts'); // 1. создание платежа $request = $module->paymentRequest([ 'orderId' => $orderId, 'merchantType' => PayParts::MERCHANT_TYPE_PP, 'partsCount' => 2, 'products' => [ ['name' => 'Рулон бумаги', 'price' => 0.01, 'count' => 2], ], ]); // 2. отправка и редирект покупателя на оплату $response = $request->send(); echo 'Token: ' . $response->token . "\n"; echo 'Redirect URL: ' . $response->paymentUrl . "\n"; $response->redirectCheckout(); ``` -------------------------------- ### getHttpClient() method signature Source: https://github.com/dicrtarasov/yii2-payparts/blob/master/_autodocs/api-reference/PayPartsModule.md Declares the getHttpClient() method that returns an HTTP client instance, creating it on first access. ```php /** * Возвращает HTTP-клиент. * * @return Client */ public function getHttpClient() : Client ``` -------------------------------- ### GET https://payparts2.privatbank.ua/ipp/qr/generate Source: https://github.com/dicrtarasov/yii2-payparts/blob/master/_autodocs/endpoints.md Generates a QR code for a payment. Request is a QrRequest with query parameters token, size, amount, and type. ```APIDOC ## GET https://payparts2.privatbank.ua/ipp/qr/generate ### Description Generates a QR code for a payment. Request is a QrRequest. ### Method GET ### Endpoint https://payparts2.privatbank.ua/ipp/qr/generate ### Parameters #### Query Parameters - **token** (string) - Required - Payment token - **size** (mixed) - Optional - Image size - **amount** (float) - Required - Final amount, ≥ 0.01 - **type** (string) - Optional - Installment type from MERCHANT_TYPES ### Response #### Success Response (200) - **state** (string) - SUCCESS - **qr** (string) - QR code data #### Error Response - **state** (string) - Error state - **message** (string) - Error message ### Notes Library returns the qr string from QrRequest::send(). ``` -------------------------------- ### Create DeclineRequest via module factory Source: https://github.com/dicrtarasov/yii2-payparts/blob/master/_autodocs/api-reference/request/DeclineRequest.md Recommended instantiation via PayPartsModule::declineRequest() factory (src/PayPartsModule.php:163). ```php $request = $module->declineRequest(['orderId' => $orderId, 'amount' => 246.26]); ``` -------------------------------- ### Handle PayPartsModule configuration errors Source: https://github.com/dicrtarasov/yii2-payparts/blob/master/_autodocs/api-reference/PayPartsModule.md Creates a PayPartsModule with empty storeId and password, then calls init() to trigger validation. Catches InvalidConfigException and logs the error message, which will mention 'storeId' or 'password'. ```php use dicr\payparts\PayPartsModule; use yii\base\InvalidConfigException; try { $module = new PayPartsModule([ 'storeId' => '', 'password' => '', ]); $module->init(); } catch (InvalidConfigException $ex) { // сообщение исключения: 'storeId' или 'password' Yii::error('Ошибка конфигурации модуля оплат: ' . $ex->getMessage()); } ``` -------------------------------- ### QrRequest Source: https://github.com/dicrtarasov/yii2-payparts/blob/master/_autodocs/types.md Request class for generating a QR code. Users can set token, size, amount, and type, then call send() to get the QR code. ```APIDOC ## QrRequest ### Description Request class for generating a QR code. Users can set token, size, amount, and type, then call send() to get the QR code. ### Properties - **token** (string) - Required - Token for the QR code. - **size** (?mixed) - Optional - Size of the image. - **amount** (float) - Required - Amount, min 0.01. - **type** (?string) - Optional - Merchant type, must be in `MERCHANT_TYPES`. ### Methods - **send()** (string) - Returns the QR code as a string. ### Example ```php $request = new QrRequest([ 'token' => 'abc123', 'size' => 200, 'amount' => 100.00, 'type' => 'PP', ]); $qrCode = $request->send(); ``` ``` -------------------------------- ### POST /ipp/v2/payment/confirm Source: https://github.com/dicrtarasov/yii2-payparts/blob/master/doc/api-oc.pdf Confirms an installment payment transaction. The request includes store and order identifiers and a signature. The response indicates success or failure of the confirmation. ```APIDOC ## POST /ipp/v2/payment/confirm ### Description Confirms an installment payment transaction. ### Method POST ### Endpoint /ipp/v2/payment/confirm ### Headers - **Accept**: application/json; charset=UTF-8 - **Accept-Encoding**: UTF-8 - **Content-Type**: application/json; charset=UTF-8 ### Parameters #### Request Body - **storeId** (string) - Required - Merchant store identifier. - **orderId** (string) - Required - Unique payment order number. - **signature** (string) - Required - Unique transaction signature. ### Signature Calculation SIGNATURE = encodeBase64(SHA1(password + storeId + orderId + password)) Where: - **encodeBase64()** - Encodes a string in BASE64 format. - **SHA1()** - Standard SHA-1 hash function, returns binary data. - **"+"** - Concatenation of text strings. ### Request Example ```json { "storeId": "merchant", "orderId": "9DA37124F46test8", "signature": "Gnk2CncQ62I5eVOb0/bRM=" } ``` ### Response #### Success Response (200) ```json { "state": "SUCCESS", "storeId": "merchant", "orderId": "9DA37124Fest8", "signature": "Gnk2CncQ62I5RM" } ``` #### Error Response ```json { "state": "FAIL", "storeId": "merchant", "orderId": "order_id", "message": "error message", "signature": "37d9c97324fb4b0fa" } ``` ### Response Fields - **state** (string) - Result of the confirmation (SUCCESS or FAIL). - **storeId** (string) - Merchant store identifier. - **orderId** (string) - Unique payment order number. - **message** (string) - Error message (only on failure). - **signature** (string) - Response signature. ``` -------------------------------- ### DescriptionRequest Source: https://github.com/dicrtarasov/yii2-payparts/blob/master/_autodocs/types.md Request class for setting a description. Users must provide a description string. ```APIDOC ## DescriptionRequest ### Description Request class for setting a description. Users must provide a description string. ### Properties - **description** (string) - Required - Description text. ### Example ```php $request = new DescriptionRequest([ 'description' => 'Payment for order #123', ]); $response = $request->send(); ``` ``` -------------------------------- ### paymentRequest() Source: https://github.com/dicrtarasov/yii2-payparts/blob/master/_autodocs/api-reference/PayPartsModule.md Creates a request to initiate a payment. Accepts an optional configuration array that is merged with base values and module-level paymentRequestConfig. ```APIDOC ## paymentRequest() ### Description Creates a request to initiate a payment. ### Method paymentRequest ### Signature public function paymentRequest(array $config = []) : PaymentRequest ### Parameters #### Request Body - **$config** (array) - Optional - Configuration for the PaymentRequest (public property values). Default: `[]`. ### Configuration Merge Order 1. Base values 2. `paymentRequestConfig` 3. `$config` Base values: - `responseUrl` = absolute URL to the module's callback endpoint (`Url::to('/' . $this->uniqueId . '/callback', true)`) - `redirectUrl` = root URL of the application (`Url::to('/', true)`) ### Returns - **dicr\payparts\request\PaymentRequest** - The payment request object. ### Example ```php $request = $module->paymentRequest([ 'orderId' => (string)time(), 'partsCount' => 4, 'merchantType' => PayParts::MERCHANT_TYPE_PP, 'products' => [ ['name' => 'Кофе', 'price' => 199.90, 'count' => 1], ], ]); $response = $request->send(); ``` ``` -------------------------------- ### redirectCheckout() usage with error handling Source: https://github.com/dicrtarasov/yii2-payparts/blob/master/_autodocs/api-reference/PayPartsResponse.md Example of calling redirectCheckout() inside a try-catch block. Catches yii\base\Exception when payment creation fails or token is missing, and sets a flash message. ```php try { $response = $module->paymentRequest([...])->send(); $response->redirectCheckout(); // редирект покупателя на страницу оплаты } catch (yii\base\Exception $ex) { // платёж не создан, токен не получен или не задан Yii::$app->session->setFlash('error', 'Не удалось начать оплату: ' . $ex->getMessage()); } ``` -------------------------------- ### POST /ipp/v2/payment/create Source: https://github.com/dicrtarasov/yii2-payparts/blob/master/doc/api-oc.pdf Creates a payment using the PayParts Installment in Internet API. This endpoint initiates a payment transaction and returns a token for redirecting the customer to the bank's payment page. ```APIDOC ## [POST] /ipp/v2/payment/create ### Description Creates a payment request in the PayParts system for the ``` -------------------------------- ### Confirm request with error handling Source: https://github.com/dicrtarasov/yii2-payparts/blob/master/_autodocs/api-reference/request/ConfirmRequest.md Example with error handling: catches ValidateException for missing orderId and generic Exception for HTTP errors, rejected responses, or non-SUCCESS state. On success, marks the order as paid. ```php use dicr\validate\ValidateException; use yii\base\Exception; try { $module->confirmRequest(['orderId' => $orderId])->send(); // деньги списаны — отгружаем заказ Order::setPayed($orderId); } catch (ValidateException $ex) { // не задан orderId Yii::warning('Не задан orderId: ' . json_encode($ex->errors)); } catch (Exception $ex) { // HTTP-ошибка, ответ отклонён (подпись/storeId/orderId), state != SUCCESS Yii::error('Не удалось подтвердить платёж: ' . $ex->getMessage()); } ``` -------------------------------- ### POST /ipp/v2/payment/create Source: https://github.com/dicrtarasov/yii2-payparts/blob/master/doc/api-oc.pdf Creates a new installment payment transaction. The request includes store and order details, amount, number of parts, and product information. The response provides a token and signature for subsequent operations. ```APIDOC ## POST /ipp/v2/payment/create ### Description Creates a new installment payment transaction. ### Method POST ### Endpoint /ipp/v2/payment/create ### Parameters #### Request Body - **storeId** (string) - Required - Merchant store identifier. - **orderId** (string) - Required - Unique payment order number. - **amount** (number) - Required - Final purchase amount without floating point (e.g., 301.00 becomes 30100). - **partsCount** (integer) - Required - Number of parts to split the transaction amount (must be > 1). - **merchantType** (string) - Required - Type of credit. - **responseUrl** (string) - Required - URL where the bank will send the transaction result. - **redirectUrl** (string) - Required - URL where the bank will redirect the client. - **products** (array) - Required - List of products, each with name, count, and price. - **signature** (string) - Required - Signature calculated as described below. ### Signature Calculation SIGNATURE = encodeBase64(SHA1(password + storeId + orderId + withoutFloatingPoint(amount) + partsCount + password + redirectUrl + products_string + merchantType + responseUrl + password)) Where: - **encodeBase64()** - Encodes a string in BASE64 format. - **SHA1()** - Standard SHA-1 hash function, returns binary data. - **withoutFloatingPoint()** - Returns the number without a floating point. - **"+"** - Concatenation of text strings. - **products_string** = product.name(A) + product.count(A) + withoutFloatingPoint(product.price(A)) + product.name(B) + product.count(B) + withoutFloatingPoint(product.price(B)) + ... ### Request Example ```json { "storeId": "merchant", "orderId": "order_id", "amount": 30100, "partsCount": 3, "merchantType": "PP", "responseUrl": "https://example.com/response", "redirectUrl": "https://example.com/redirect", "products": [ {"name": "Product A", "count": 1, "price": 10000}, {"name": "Product B", "count": 2, "price": 10050} ], "signature": "b47f80a7fbb34db084bb35527f84ed4a" } ``` ### Response #### Success Response (200) ```json { "state": "SUCCESS", "storeId": "merchant", "orderId": "order_id", "token": "E8E354374D404C1E9279DCCF1C7B5541", "signature": "b47f80a7fbb34db084bb35527f84ed4a" } ``` #### Error Response ```json { "state": "FAIL", "storeId": "merchant", "orderId": "order_id", "message": "error message", "signature": "37d9c9732fe843929deb01424fb4b0fa" } ``` ### Response Fields - **state** (string) - Result of the request (SUCCESS or FAIL). - **storeId** (string) - Merchant store identifier. - **orderId** (string) - Unique payment order number. - **token** (string) - Payment token (only on success). - **message** (string) - Error message (only on failure). - **signature** (string) - Response signature. ### Response Signature Calculation For success: SIGNATURE = encodeBase64(SHA1(password + state + storeId + orderId + token + password)) For error: SIGNATURE = encodeBase64(SHA1(password + state + storeId + orderId + message + password)) ``` -------------------------------- ### QrRequest constructor Source: https://github.com/dicrtarasov/yii2-payparts/blob/master/_autodocs/api-reference/request/QrRequest.md Constructor for QrRequest. Requires a PayPartsModule instance and accepts an optional config array for public property values. ```php /** * QrRequest constructor. * * @param PayPartsModule $module * @param array $config */ public function __construct(PayPartsModule $module, $config = []) ```