### Initiating Payment with Widget Source: https://github.com/onreza/cloudpayments-sdk-ts/blob/main/specs/raw.html This example shows how to configure and start the CloudKassir widget for processing a payment. It includes essential parameters like terminal ID, description, currency, amount, and the receipt object. Handle the promise to get the result or catch errors. ```javascript const intentParams = { publicTerminalId: "test_api_00000000000000000000002", // идентификатор терминала description: "Basket of oranges", // описание списания paymentSchema: 'Single', // схема currency: "RUB", // валюта amount: 1000, // сумма receipt: receipt } widget.start(intentParams).then(function(widgetResult) { console.log('result', widgetResult); }).catch(function(error) { console.log('error', error); }); ``` -------------------------------- ### Install @onreza/cloudpayments-sdk Source: https://github.com/onreza/cloudpayments-sdk-ts/blob/main/README.md Install the SDK using npm or bun. ```bash npm install @onreza/cloudpayments-sdk ``` ```bash # или bun add @onreza/cloudpayments-sdk ``` -------------------------------- ### Get Subscription Response Example Source: https://github.com/onreza/cloudpayments-sdk-ts/blob/main/specs/raw.html Example JSON response when retrieving subscription details. It includes the current status and other subscription parameters. ```json { "Model": { "Id": "sc_8cf8a9338fb8ebf7202b08d09c938", "AccountId": "user_x", "Description": null, "Email": "user@example.com", "Amount": 399, "CurrencyCode": 0, "Currency": "RUB", "RequireConfirmation": false, "StartDate": "/Date(1635886800000)/", "StartDateIso": "2021-11-02T21:00:00", "IntervalCode": 2, "Interval": "Day", "Period": 5, "MaxPeriods": null, "CultureName": "ru-RU", "StatusCode": 3, "Status": "Cancelled", "SuccessfulTransactionsNumber": 0, "FailedTransactionsNumber": 0, "LastTransactionDate": null, "LastTransactionDateIso": null, "NextTransactionDate": null, "NextTransactionDateIso": null, "Receipt": null, "FailoverSchemeId": null }, "Success": true, "Message": null } ``` -------------------------------- ### Start CloudPayments Widget with jQuery Source: https://github.com/onreza/cloudpayments-sdk-ts/blob/main/specs/raw.html Initiate the CloudPayments widget by calling the 'start' function on a click event. This example uses jQuery to bind the event. ```javascript public start(intentParams: CreateIntentCommand): Promise ``` ```javascript $('#checkout').click(start); ``` -------------------------------- ### Start CloudPayments Widget without jQuery Source: https://github.com/onreza/cloudpayments-sdk-ts/blob/main/specs/raw.html Initiate the CloudPayments widget by calling the 'start' function on a click event. This example uses plain JavaScript. ```javascript document.querySelector('#checkout').onclick = start ``` -------------------------------- ### Full PaymentBlocks Initialization Example Source: https://github.com/onreza/cloudpayments-sdk-ts/blob/main/specs/raw.html An example demonstrating the initialization of the PaymentBlocks constructor with all available parameters, including mandatory initialization and optional customization settings. ```javascript var blocksApp = new cp.PaymentBlocks( { "publicTerminalId":"test_api_00000000000000000000002", "paymentSchema":"Dual", "description":"Тестовая оплата", "amount":100.53, "currency":"RUB", "externalId":"123", "accountId":"123", "receiptEmail":"", "emailBehavior":"Optional", "language":"ru-RU" }, { "appearance":{ "colors":{ "primaryButtonColor":"#1dfa05", "primaryHoverButtonColor":"#da1ef7", "primaryButtonTextColor":"#da1ef7", "primaryButtonHoverTextColor":"#da1ef7", "activeInputColor":"#da1ef7", "inputBackground":"#da1ef7", "inputColor":"#1dfa05", "inputBorderColor":"#f20505", "titleColor":"#da1ef7", "textColor":"#1dfa05", "errorColor":"#ee05fa", "skeletonBackground":"#ee05fa" }, "borders":{ "radius":"80px" } } } ); ``` -------------------------------- ### Subscription Creation Response Example Source: https://github.com/onreza/cloudpayments-sdk-ts/blob/main/specs/raw.html Example JSON response for a successful subscription creation. It includes subscription details and status. ```json { "Model": { "Id": "sc_221da6421dc44dbd2cc3464f6f083", "AccountId": "user_x", "Description": "Ежемесячная подписка на сервис example.com", "Email": "user@example.com", "Amount": 399, "CurrencyCode": 0, "Currency": "RUB", "RequireConfirmation": false, "StartDate": "/Date(1635886800000)/", "StartDateIso": "2021-11-02T21:00:00", "IntervalCode": 2, "Interval": "Day", "Period": 5, "MaxPeriods": null, "CultureName": "ru-RU", "StatusCode": 0, "Status": "Active", "SuccessfulTransactionsNumber": 0, "FailedTransactionsNumber": 0, "LastTransactionDate": null, "LastTransactionDateIso": null, "NextTransactionDate": "/Date(1635886800000)/", "NextTransactionDateIso": "2021-11-02T21:00:00", "Receipt": null, "FailoverSchemeId": null }, "Success": true, "Message": null } ``` -------------------------------- ### Get Subscription Request Example Source: https://github.com/onreza/cloudpayments-sdk-ts/blob/main/specs/raw.html Example JSON payload for requesting information about a specific subscription using its ID. The 'Id' parameter is mandatory. ```json {"Id":"sc_8cf8a9338fb8ebf7202b08d09c938"} ``` -------------------------------- ### POST /payments/altpay/pay Request Example Source: https://github.com/onreza/cloudpayments-sdk-ts/blob/main/specs/raw.html This is an example of a request body for initiating an installment payment using the /payments/altpay/pay method. Ensure all required fields like PublicId, AltPayType, Amount, and Scheme are correctly populated. ```json { "PublicId": "pk_0fe1d5c9cb47e8cf8d96102201419", "AltPayType": "TcsBnplDolyame", "Amount": 1000, "Description": "Оплата в точке N", "AccountId": "email@email.com", "InvoiceId": "order_no4009", "CultureName": "ru-RU", "Scheme": "1", "SuccessRedirectUrl": "https://success-page.ru", "FailRedirectUrl": "https://fail-page.ru" } ``` -------------------------------- ### Find Subscriptions Response Example Source: https://github.com/onreza/cloudpayments-sdk-ts/blob/main/specs/raw.html Example JSON response when finding subscriptions for an account. It returns a list of subscription objects. ```json { "Model": [ { "Id": "sc_221da6421dc44dbd2cc3464f6f083", "AccountId": "user_x", "Description": null, "Email": "user@example.com", "Amount": 399, "CurrencyCode": 0, "Currency": "RUB", "RequireConfirmation": false, "StartDate": "/Date(1635886800000)/", "StartDateIso": "2021-11-02T21:00:00", "IntervalCode": 2, "Interval": "Day", "Period": 5, "MaxPeriods": null, "CultureName": "ru-RU", "StatusCode": 3, "Status": "Cancelled", "SuccessfulTransactionsNumber": 0, "FailedTransactionsNumber": 0, "LastTransactionDate": null, "LastTransactionDateIso": null, "NextTransactionDate": null, "NextTransactionDateIso": null, "Receipt": null, "FailoverSchemeId": null }, { "Id": "sc_3ffc96c001e152b341817341b075a", "AccountId": "user_x", "Description": null, "Email": "user@example.com", "Amount": 999, ``` -------------------------------- ### Create Subscription Request Example Source: https://github.com/onreza/cloudpayments-sdk-ts/blob/main/specs/raw.html Example JSON payload for creating a new subscription. Ensure all required fields like token, accountId, amount, currency, and interval are correctly populated. ```json { "token": "477BBA133C182267FE5F086924ABDC5DB71F77BFC27F01F2843F2CDC69D89F05", "accountId": "user_x", "description": "Ежемесячная подписка на сервис example.com", "email": "user@example.com", "amount": 399, "currency": "RUB", "requireConfirmation": false, "startDate": "2021-11-02T21:00:00", "interval": "Day", "period": 5 } ``` -------------------------------- ### Create Subscription Request Example Source: https://github.com/onreza/cloudpayments-sdk-ts/blob/main/specs/raw.html Example of a request to create a recurring payment subscription using a payment token. Ensure StartDate is in the future and in UTC. ```json { "Token": "tk_020a924486aa4df254331afa33f2a", "AccountId": "user_x", "Description": "Monthly subscription", "Email": "user@example.com", "Amount": 100.00, "Currency": "RUB", "RequireConfirmation": true, "StartDate": "2024-01-01T10:00:00Z", "Interval": "Month", "Period": 1, "MaxPeriods": 12 } ``` -------------------------------- ### Get Transaction Details Response Snippet Source: https://github.com/onreza/cloudpayments-sdk-ts/blob/main/specs/raw.html This is a partial example of a response when retrieving transaction details. It includes basic transaction information. ```json { "Model": { "ReasonCode": 0, "PublicId": "pk_*****************************************", "TerminalUrl": "http://test.test", "TransactionId": 897749645, "Amount": 159, "Currency": "RUB", "CurrencyCode": 0, "PaymentAmount": 159, "PaymentCurrency": "RUB", ``` -------------------------------- ### Initialize and Start CloudPayments Widget Source: https://github.com/onreza/cloudpayments-sdk-ts/blob/main/specs/raw.html This snippet demonstrates how to initialize the CloudPayments widget with payment intent parameters and start the payment process. It includes event listeners for completion and error handling. Ensure all required parameters are correctly populated before calling `widget.start()`. ```javascript const intentParams = { publicId: "", amount: 100.50, currency: "RUB", description: "Оплата товаров", email: "user@example.com", gatewayId: "", gatewayAuth: { login: "", password: "" }, paymentSchema: "Single", items: [ { "price": 100.50, "quantity": 1, "name": "Товар 1", "goodId": "123", "taxRate": "none" } ], credit: { credit: 0.00, // Сумма постоплатой(в кредит) (2 знака после точки) provision: 0.00 // Сумма оплаты встречным предоставлением (сертификаты, др. мат.ценности) (2 знака после точки) }, metadata: { referrerId: "some_referrer_123" }, successRedirectUrl: "", failRedirectUrl: "", escrow: { startAccumulation: true, accumulationId: null, escrowType: "OneToN" }, retryPayment: false, receiptEmail: "user@example.com", tokenize: true, emailBehavior: "Required", }; widget.oncomplete = (result) => { console.log(result); } widget.start(intentParams).then(function(widgetResult) { console.log('result', widgetResult); }).catch(function(error) { console.log('error', error); }); } btn.addEventListener('click', launchWidget) ``` -------------------------------- ### Chargebacks List Response Example Source: https://github.com/onreza/cloudpayments-sdk-ts/blob/main/specs/raw.html Example response structure for the chargebacks list endpoint, including chargeback details. ```json { "Model": [ { "ChargeBackId": "6811d4a17bab1c4b44c19371", "TerminalUrl": "https://cloudpayments.ru/", "TransactionId": 2200203594, "Amount": 100, "Currency": "RUB", "Type": "Chargeback", "Operation": "Presentment", "Card": "520500*******3055", "Gateway": "SberbankRu", "Date": "/Date(1745960400000)/" } ], "Success": true, "Message": null, "ErrorCode": null } ``` -------------------------------- ### Payment Tokens List Response Example Source: https://github.com/onreza/cloudpayments-sdk-ts/blob/main/specs/raw.html Example response for the payment tokens list endpoint, showing token details like AccountId and CardMask. ```json { "Model": [ { "Token": "tk_020a924486aa4df254331afa33f2a", "AccountId": "user_x", "CardMask": "4242 42****** 4242", "ExpirationDateMonth": 12, "ExpirationDateYear": 2020 }, { "Token": "tk_1a9f2f10253a30a7c5692a3fc4c17", "AccountId": "user_x", "CardMask": "5555 55****** 4444", "ExpirationDateMonth": 12, "ExpirationDateYear": 2021 }, { "Token": "tk_b91062f0f2875909233ab66d0fc7b", "AccountId": "user_x", "CardMask": "4012 88****** 1881", "ExpirationDateMonth": 12, "ExpirationDateYear": 2022 } ], "Success": true, "Message": null } ``` -------------------------------- ### Payment Response Example Source: https://github.com/onreza/cloudpayments-sdk-ts/blob/main/specs/raw.html This is an example of a successful payment response. It includes transaction details, status, and customer information. ```json { "Model": { "ReasonCode": 0, "PublicId": "test_api_00000000000000000000002", "TerminalUrl": "https://demo-preprod.cloudpayments.ru", "TransactionId": 2200976211, "Amount": 50, "Currency": "RUB", "CurrencyCode": 0, "PaymentAmount": 50, "PaymentCurrency": "RUB", "PaymentCurrencyCode": 0, "InvoiceId": null, "AccountId": "a.kadyrova@cloudpayments.ru", "Email": "a.kadyrova@cloudpayments.cloudpayments.ru", "Description": null, "JsonData": null, "CreatedDate": "/Date(1717514966896)/", "PayoutDate": null, "PayoutDateIso": null, "PayoutAmount": null, "CreatedDateIso": "2024-06-04T15:29:26", "AuthDate": "/Date(1717514967037)/", "AuthDateIso": "2024-06-04T15:29:27", "ConfirmDate": "/Date(1717514967037)/", "ConfirmDateIso": "2024-06-04T15:29:27", "AuthCode": "A1B2C3", "TestMode": true, "Rrn": null, "OriginalTransactionId": null, "FallBackScenarioDeclinedTransactionId": null, "IpAddress": "172.18.200.35", "IpCountry": "", "IpCity": null, "IpRegion": null, "IpDistrict": null, "IpLatitude": null, "IpLongitude": null, "CardFirstSix": "424242", "CardLastFour": "4242", "CardExpDate": "01/77", "CardType": "Visa", "CardProduct": "", "CardCategory": "Не определен ()", "EscrowAccumulationId": null, "IssuerBankCountry": "RU", "Issuer": "TINKOFF", "CardTypeCode": 0, "Status": "Completed", "StatusCode": 3, "CultureName": "ru", "Reason": "Approved", "CardHolderMessage": "Оплата успешно проведена", "Type": 2, "Refunded": false, "Name": "SERGEY", "Token": null, "SubscriptionId": null, "GatewayName": "Test", "AndroidPay": false, "WalletType": "", "TotalFee": 0, "IsLocalOrder": false, "Gateway": 0, "MasterPass": false, "InfoShopData": null, "Receiver":{ "FirstName":"Тест", "LastName":"Тестов", "MiddleName":"Тестович", "Address":"тестовый проезд дом тест", "Birth":"1955-02-24", "City":"MO", "Street":"Ленина", "Country":"RU", "Phone":"+71234567890", "Postcode":"345" } }, "Success": true, "Message": null, "ErrorCode": null } ``` -------------------------------- ### Find Subscriptions Request Example Source: https://github.com/onreza/cloudpayments-sdk-ts/blob/main/specs/raw.html Example JSON payload for finding subscriptions associated with a specific account. The 'accountId' parameter is mandatory. ```json {"accountId":"user@example.com"} ``` -------------------------------- ### Install Payment Constructor Script Source: https://github.com/onreza/cloudpayments-sdk-ts/blob/main/specs/raw.html Include this script in the head section of your HTML to enable the Payment Constructor functionality. ```html ``` -------------------------------- ### POST /payments/altpay/pay Response Example Source: https://github.com/onreza/cloudpayments-sdk-ts/blob/main/specs/raw.html This is an example of a successful response from the /payments/altpay/pay endpoint. The 'Model.ExtensionData.Link' field contains the URL for the payment form. Note that the 'Success' field indicates the success of the API request, not the transaction status. ```json { "Model": { "TransactionId": 183930901, "Amount": 1000, "IsTest": true }, "ExtensionData": { "Link": "https://dolyame.ru/form/demoPayment-52030933-b65e-4e5a-acdc/example/example" }, "Success": true, "Message": null, "ErrorCode": null } ``` -------------------------------- ### JavaScript: Initialize and Start Payment Form (Provider Bill) Source: https://github.com/onreza/cloudpayments-sdk-ts/blob/main/specs/raw.html Initializes the CloudPayments widget and starts a payment process for recurring bills, suitable for internet providers. Requires jQuery and specific HTML element values for amount, account ID, and recurrent options. The `userInfo` object is mandatory for creating subscriptions. ```javascript this.paySample3 = function () { var widget = new cp.CloudPayments(); var userInfo = {}; var auto = $('#recurrent-sample-3').is(':checked'); //проверка if (auto) { //включаем подписку var accountId = $('#account-sample-3').val(); var date = new Date(); //текущая дата date.setMonth(date.getMonth() + 1); //следующий месяц date.setDate(date.getDate() - 1); //минус один день var recurrent = { interval: 'Month', period: 1, startDate: date }; //один раз в месяц начиная со следующего месяца за минусом одного дня userInfo.accountId = "accountId" //идентификатор плательщика (обязательно для создания подписки) } var amount = parseFloat($('#amount-sample-3').val()); widget.start({ publicTerminalId: 'test_api_00000000000000000000002', //id из личного кабинета description: 'Пополнение счета абонента ' + accountId, //назначение paymentSchema: "Single" // Одностадийная оплата amount: amount, //сумма currency: 'RUB', //валюта recurrent: recurrent, userInfo: userInfo }, function (options) { // success //действие при успешной оплате }, function (reason, options) { // fail //действие при неуспешной оплате }); }; $('#checkout-sample-3').click(paySample3); ``` -------------------------------- ### Initiating Payment with Widget and Item List Source: https://github.com/onreza/cloudpayments-sdk-ts/blob/main/specs/raw.html This example demonstrates initiating a payment using the CloudKassir widget, providing both the receipt object and a separate list of items. This is useful when item details are managed externally and referenced by ID. ```javascript var items = [ { id: "some_id_1", count: 1, name: "Пластырь", price: 500, }, { id: "some_id_2", count: 1, name: "Доставка", price: 500, }, ], const intentParams = { publicTerminalId: "test_api_00000000000000000000002", // идентификатор терминала description: "Basket of oranges", // описание списания paymentSchema: 'Single', // схема currency: "RUB", // валюта amount: 1000, // сумма receipt: receipt, items: items } widget.start(intentParams).then(function(widgetResult) { console.log('result', widgetResult); }).catch(function(error) { console.log('error', error); }); ``` -------------------------------- ### Initialize Payment Constructor with Customization Source: https://github.com/onreza/cloudpayments-sdk-ts/blob/main/specs/raw.html Example of initializing the payment constructor with both required initialization parameters and optional customization parameters for appearance and components. ```json { "components":{ "paymentButton":{ "text":"Свое название кнопки", "fontSize":"40px" }, "paymentForm":{ "labelFontSize":"5px", "activeLabelFontSize":"50px", "fontSize":"90px" } }, "appearance":{ "colors":{ "primaryButtonColor":"#1dfa05", "primaryHoverButtonColor":"#da1ef7", "primaryButtonTextColor":"#da1ef7", "primaryButtonHoverTextColor":"#da1ef7", "activeInputColor":"#da1ef7", "inputBackground":"#da1ef7", "inputColor":"#1dfa05", "inputBorderColor":"#f20505", "titleColor":"#da1ef7", "textColor":"#1dfa05", "errorColor":"#ee05fa", "skeletonBackground":"#ee05fa" }, "borders":{ "radius":"80px" } } } ``` -------------------------------- ### Initialize and Launch CloudPayments Widget Source: https://github.com/onreza/cloudpayments-sdk-ts/blob/main/specs/raw.html This example demonstrates how to initialize the CloudPayments widget and configure various payment parameters, including user information, recurrent payments, and item details. Ensure all required fields are populated correctly. ```javascript const btn = document.getElementById("payButton") const widget = new cp.CloudPayments(); const launchWidget = () => { const intentParams = { publicTerminalId: "test_api_00000000000000000000002", // идентификатор терминала description: "Basket of oranges", // описание списания paymentSchema: 'Dual', // схема currency: "RUB", // валюта culture: "ru-RU", amount: 1001, // сумма skin: "modern", //дизайн виджета (необязательно) autoClose: 3, //время в секундах до авто-закрытия виджета (необязательный) cryptogramMode: false, // признак режима работы виджета. Если указано true - вместо проведения оплаты будет сформирована криптограмма карточных данных externalId: "your_system_payment_identifier", // идентификатор платежа в вашей системе restrictedPaymentMethods: [ 'Sbp' ], userInfo: { accountId: "your_system_user_id", firstName: "Test", lastName: "Test", middleName: "Test", fullName: "Test Test Test", birth: "2000-30-03", address: "д. 7", street: "ул. Тестовая", city: "г. Москва", country: "Россия", phone: "+71234567890", postCode: "119518", email: "user@email.com", customField: { name: "your_field_name", value: "your_field_value" } }, payerServiceFee: 50, // комиссия, оплачиваемая пользователем recurrent: { period: 1, // частота списания interval: 'Day', // интервал списания amount: 500, // сумма startDate: "2030-04-15T00:00:00.0000000Z", // дата начала maxPeriods: 50, // количество списаний после которых рекуррент будет остановлен receipt: { items: [ { label: 'Наименование товара 3', price: 300.00, quantity: 3.00, amount: 900.00, vat: 20, method: 0, object: 0, } ], taxationSystem: 0, email: 'user@example.com', phone: '', isBso: false, amounts: { electronic: 900.00, advancePayment: 0.00, credit: 0.00, provision: 0.00 } } }, items: [ { id: "your_system_item_unique_identifier_1", name: "Basket", count: 1, price: 100, } ] }; widget.start(intentParams); } ``` -------------------------------- ### Get Pay Notification Settings Response Source: https://github.com/onreza/cloudpayments-sdk-ts/blob/main/specs/raw.html This is an example response for retrieving notification settings for the 'Pay' event. It shows if notifications are enabled and their configuration. ```json { "Model": { "IsEnabled": true, "Address": "http://example.com", "HttpMethod": "POST", "Encoding": "UTF8", "Format": "CloudPayments" }, "Success": true, "Message": null } ``` -------------------------------- ### Get Escrow Info Response Example Source: https://github.com/onreza/cloudpayments-sdk-ts/blob/main/specs/raw.html The response contains arrays of paidout, not-paidout, and refunded transactions, along with payout transactions and the final balance. The Status field indicates the overall status of the escrow accumulation. ```json { "Model": [ { "Status": "Closed", "PaidoutTransactions": [ { "Id": 608632, "Status": "Completed", "Amount": 1500.0 }, { "Id": 608631, "Status": "Completed", "Amount": 901.0 } ], "NotPaidoutTransactions": [ { "Id": 608632, "Status": "Completed", "Amount": 1500.0 }, { "Id": 608634, "Status": "Completed", "Amount": 901.0 } ], "PayoutTransactions": [ { "Id": 608635, "Status": "Completed", "Amount": 1500.0, "IsFinalPayout": true }, { "Id": 608636, "Status": "Completed", "Amount": 901.0, "IsFinalPayout": false } ], "RefundedTransactions": null, "EscrowAccumulationId": "2533b003-da5d-463f-af85-fe6621354cd6", "Balance": 0.0 } ], "Success": true, "Message": null } ``` -------------------------------- ### Get Escrow Info Request Example Source: https://github.com/onreza/cloudpayments-sdk-ts/blob/main/specs/raw.html Send a POST request to this endpoint with an array of EscrowAccumulationIds to retrieve escrow transaction details. Requires Basic Auth with public key as username and API secret as password. ```json { "EscrowAccumulationIds" : ["7de3281f-4339-4e2e-9df9-06dcfbcdceac"] } ``` -------------------------------- ### Payment Request Parameters Example Source: https://github.com/onreza/cloudpayments-sdk-ts/blob/main/specs/raw.html This JSON object demonstrates the required and optional parameters for initiating a payment request. Ensure all mandatory fields like PublicId, Amount, Currency, and Scheme are correctly populated. ```json { "PublicId": "test_api_00000000000000000000002", "Amount": 1000, "Currency": "RUB", "Description": "Оплата по СБП", "AccountId": "email@email.com", "Email": "email@email.com", "InvoiceId": "order_no4009", "Scheme": "charge", "SuccessRedirectUrl": "https://cp.ru", "SaveCard": false } ``` -------------------------------- ### GET /payments/get - Get Transaction Details Source: https://context7.com/onreza/cloudpayments-sdk-ts/llms.txt Retrieves detailed information about a specific transaction using its ID, including declined transactions. ```APIDOC ## GET /payments/get ### Description Retrieves detailed information about a specific transaction using its ID, including declined transactions. ### Method GET ### Endpoint /payments/get ### Parameters #### Query Parameters - **TransactionId** (number) - Required - The ID of the transaction to retrieve. ### Request Example ```json { "TransactionId": 123456789 } ``` ### Response #### Success Response (200) - **TransactionId** (number) - The ID of the transaction. - **Status** (string) - The status of the transaction. - **Amount** (number) - The transaction amount. - **Currency** (string) - The transaction currency. - **CreatedDateIso** (string) - The ISO 8601 formatted creation date. - **CardFirstSix** (string) - The first six digits of the card number. - **CardLastFour** (string) - The last four digits of the card number. - **Issuer** (string) - The card issuer. - **Refunded** (number) - The amount refunded. - **Token** (string) - The card token, if saved. #### Response Example ```json { "TransactionId": 123456789, "Status": "Completed", "Amount": 100.00, "Currency": "RUB", "CreatedDateIso": "2024-01-15T10:30:00Z", "CardFirstSix": "411111", "CardLastFour": "1111", "Issuer": "Sberbank", "Refunded": 0, "Token": "tk_abc123xyz789" } ``` ``` -------------------------------- ### Payment Request Example Source: https://github.com/onreza/cloudpayments-sdk-ts/blob/main/specs/raw.html Use this structure to initiate a payment. Ensure 'Amount' is a number with a decimal point and 'Currency' is set to 'RUB'. 'Receiver.Phone' is mandatory for SBP payouts. ```json { "Amount":1, "AccountId":"user@example.com", "MemberId":"12456", "Currency":"RUB", "InvoiceId":"1234567", "Receiver": { "Phone":"+71234567890" } } ``` -------------------------------- ### Construct SBP Bank Transition URL Source: https://github.com/onreza/cloudpayments-sdk-ts/blob/main/specs/raw.html Demonstrates how to construct a direct bank transition URL for SBP payments by combining a payment link and a bank template URL. Ensure the bank template URL's path is correctly truncated before concatenation. ```text 1. Payment link: https://qr.nspk.ru/AD1000XXXXX1000?type=02&bank=100000000004&sum=1299900&cur=RUB&crc=8DA8 2. Template URL: https://online.vtb.ru/i/paymentSbp/{QRC_ID}{QUERY_STRING} 3. Result: https://online.vtb.ru/i/paymentSbp/AD1000XXXXX1000?type=02&bank=100000000004&sum=1299900&cur=RUB&crc=8DA8 ``` -------------------------------- ### Example CloudPayments Response Source: https://github.com/onreza/cloudpayments-sdk-ts/blob/main/specs/raw.html This is an example of a successful response from CloudPayments, including transaction details and payment status. The 'QrImage' field will contain an SVG in base64 format. ```json { "Model": { "QrUrl": null, "QrImage": "{string}", // будет содержать svg в base64 "TransactionId": 11122233344, // id транзакции CloudPayments "Amount": 10 }, "Success": true, "Message": null } ``` -------------------------------- ### CloudPayments QR Code Payment Response Example Source: https://github.com/onreza/cloudpayments-sdk-ts/blob/main/specs/raw.html This is an example of a successful response when requesting a QR code for payment. It includes transaction details and a URL for redirection. ```json { "Model": { "QrUrl": "{URL-адрес}", // будет содержать url-адрес для редиректа "QrImage": null, "TransactionId": 11122233344, // id транзакции CloudPayments "MerchantOrderId": "12345", // переданный InvoiceId "ProviderQrId": "", "Amount": 10, "Message": "Created", "IsTest": false }, "Success": true, "Message": null } ``` -------------------------------- ### Payment Widget Integration Source: https://github.com/onreza/cloudpayments-sdk-ts/blob/main/specs/raw.html Example of launching the CloudPayments payment widget with specified parameters and handling completion events. ```APIDOC ## POST /payment/widget ### Description Launches the CloudPayments payment widget to process a payment. It accepts various parameters to configure the payment details, user experience, and post-payment actions. ### Method POST ### Endpoint /payment/widget ### Parameters #### Request Body - **publicTerminalId** (string) - Required - Public terminal ID. - **amount** (float) - Required - Payment amount. Must be greater than 0. Example: 2, 2.5, 2.57. - **currency** (string) - Required - Payment currency (see [currency list](#spisok-valyut)). - **culture** (string) - Optional - Widget language (default is `ru-RU`) (see [cultures](#cultures)). - **description** (string) - Optional - A free-form description of the payment purpose. - **externalId** (string) - Optional - Order identifier in your system. Received in [notifications](#uvedomleniya) (formerly `invoiceId`). - **paymentSchema** (string enum) - Required - Transaction processing schema (`Single` for one-stage, `Dual` for two-stage payments). - **receiptEmail** (string) - Optional - Email address for sending receipts and invoices. - **restrictedPaymentMethods** (string[]) - Optional - List of payment methods disabled for this payment. Available values: `Card`, `TcsInstallment`, `Sbp`, `TinkoffPay`, `MirPay`, `Dolyame`, `ForeignCard`, `SberPay`. - **tokenize** (bool) - Optional - Save card for future use. Received in [notifications](#uvedomleniya) and allows payment by [token](#oplata-po-tokenu-rekarring). - **recurrent** (object) - Optional - Settings for recurring payments (see [recurrent widget](#recurrent-widget)). - **escrow** (object) - Optional - Settings for secure transactions (see [escrow widget](#escrow-widget)). - **items** (object[]) - Optional - List of goods (see [list of goods](#spisok-tovarov)). - **receipt** (object) - Optional - Receipt object. Used when CloudKassir is connected. For more details, see [data format for online check](#format-peredachi-dannyh-dlya-onlayn-cheka). - **userInfo** (object) - Optional - Payer information (see [payer data](#dannye-o-platelshchike)). - **metadata** (object) - Optional - Additional JSON metadata associated with the transaction (formerly `data`). Received in [notifications](#uvedomleniya). - **successRedirectUrl** (string) - Optional - URL for redirect upon successful payment. - **failRedirectUrl** (string) - Optional - URL for redirect upon failed payment. - **emailBehavior** (string) - Optional - User email behavior: `Required`, `Hidden`, `Optional`. - **retryPayment** (bool) - Optional - Show "Retry Payment" button on failure (default is `true`). If `false`, the user is immediately prompted to return to the site. - **autoClose** (int) - Optional - Automatically close the widget after successful payment in seconds (between 3 and 10 inclusive). - **skin** (string[]) - Optional - Widget appearance. Available values: `classic` (light theme, default), `modern` (dark theme). ### Request Example ```javascript const intentParams = { publicTerminalId: "1234567890", amount: 100.50, currency: "RUB", description: "Test payment", successRedirectUrl: "https://example.com/success", failRedirectUrl: "https://example.com/fail", receiptEmail: "user@example.com", tokenize: true, emailBehavior: "Required", items: [ { "name": "Product 1", "price": 50.25, "quantity": 1, "amount": 50.25, "vat": 20 }, { "name": "Product 2", "price": 50.25, "quantity": 1, "amount": 50.25, "vat": 20 } ], escrow: { startAccumulation: true, accumulationId: null, escrowType: "OneToN" }, metadata: { referrerId: "some_referrer_123" }, retryPayment: false }; widget.start(intentParams).then(function(widgetResult) { console.log('result', widgetResult); }).catch(function(error) { console.log('error', error); }); ``` ### Response #### Success Response (200) - **widgetResult** (object) - Result object from the widget. #### Response Example ```json { "status": "success", "transactionId": "txn_12345abcde" } ``` ``` -------------------------------- ### Accessing Escrow Type Constants Source: https://github.com/onreza/cloudpayments-sdk-ts/blob/main/specs/raw.html Examples showing how to access the predefined constants for escrow transaction types within the cp.constant.escrow object. ```javascript cp.constant.escrow.NToOne // переменная для типа сделки = 0 ``` ```javascript cp.constant.escrow.OneToN // переменная для типа сделки = 1 ``` -------------------------------- ### Transaction List Export Response Example Source: https://github.com/onreza/cloudpayments-sdk-ts/blob/main/specs/raw.html This is an example of a successful response when exporting a transaction list. It includes details for each transaction, such as transaction ID, amount, currency, and status. ```json { "Model":[ { "PublicId":"test_api_00000000000000000000001", "TerminalUrl":"https://cloudpayments.ru", "TransactionId":54, "Amount":12.34, "Currency":"RUB", "CurrencyCode":0, "PaymentAmount":12.34, "PaymentCurrency":"RUB", "PaymentCurrencyCode":0, "InvoiceId":"1234567", "AccountId":"User@Example.com", "Email":null, "Description":"Оплата товаров в example.com", "JsonData":"{\"some\": \"value\"}", "CreatedDate":"\/Date(1615288374632)\/", "PayoutDate":null, "PayoutDateIso":null, "PayoutAmount":null, "CreatedDateIso":"2021-03-09T11:12:54", "AuthDate":null, "AuthDateIso":null, "ConfirmDate":null, "ConfirmDateIso":null, "AuthCode":null, "TestMode":true, "Rrn":null, "OriginalTransactionId":null, "FallBackScenarioDeclinedTransactionId":null, "IpAddress":"127.0.0.1", "IpCountry":"", "IpCity":null, "IpRegion":null, "IpDistrict":null, "IpLatitude":null, "IpLongitude":null, "CardFirstSix":"424242", "CardLastFour":"4242", "CardExpDate":"05/22", "CardType":"Visa", "CardProduct":null, "CardCategory":null, "IssuerBankCountry":"FF", "Issuer":null, "CardTypeCode":0, "Status":"Declined", "StatusCode":5, "CultureName":"ru", "Reason":"SystemError", "CardHolderMessage":"Повторите попытку позже", "Type":0, "Refunded":false, "Name":"CARD HOLDER", "Token":null, "SubscriptionId":null, "IsLocalOrder":false, "HideInvoiceId":false, "Gateway":0, "GatewayName":"Test", "AndroidPay":false, "MasterPass":false, "TotalFee":0, "EscrowAccumulationId":null, "ReasonCode":5096 } ], "Success":true, "Message":null } ``` -------------------------------- ### Initialize Bun.WebView for Headless Chrome Source: https://github.com/onreza/cloudpayments-sdk-ts/blob/main/CLAUDE.md Configure Bun.WebView to use Chrome in headless mode for testing. This prevents Chrome from opening a visible window and avoids prompts for remote debugging. ```typescript new Bun.WebView({ backend: { type: "chrome", argv: ["--headless=new", "--disable-gpu", "--no-sandbox"] } }) ``` -------------------------------- ### CloudPayments QR Code Image Response Example Source: https://github.com/onreza/cloudpayments-sdk-ts/blob/main/specs/raw.html This response example shows the structure when a QR code image (in SVG format, base64 encoded) is returned. It contains transaction and payment details. ```json { "Model": { "QrUrl": null, "QrImage": {string}, // будет содержать svg в base64 "TransactionId": 11122233344, // id транзакции CloudPayments "MerchantOrderId": "12345", // переданный InvoiceId "ProviderQrId": "", "Amount": 10, "Message": "Created", "IsTest": false }, "Success": true, "Message": null } ```