### YooKassa SDK Initialization Examples Source: https://github.com/webzaytsev/yookassa-ts-sdk/blob/master/docs/api/type-aliases/ConnectorOpts.md Demonstrates how to configure the YooKassa SDK for different environments. The first example shows a high-load configuration for a single instance, while the second illustrates settings for a distributed system where each instance has a lower maxRPS to share the overall rate limit. ```typescript // High-load configuration for single instance const sdk = YooKassa({ shop_id: 'your_shop_id', secret_key: 'your_secret_key', maxRPS: 10, // Higher limit for single instance retries: 3, // Fewer retries for faster failure timeout: 10000, // Longer timeout for stability }); // Distributed system configuration (per instance) const sdk = YooKassa({ shop_id: 'your_shop_id', secret_key: 'your_secret_key', maxRPS: 2, // Low limit per instance (5 instances = 10 total RPS) retries: 5, // More retries for resilience }); ``` -------------------------------- ### Install YooKassa TypeScript SDK Source: https://github.com/webzaytsev/yookassa-ts-sdk/blob/master/docs/index.md Install the SDK using npm. This command fetches and installs the latest version of the SDK package. ```bash npm install @webzaytsev/yookassa-ts-sdk ``` -------------------------------- ### Clone Repository and Install Dependencies Source: https://github.com/webzaytsev/yookassa-ts-sdk/blob/master/CONTRIBUTING.md Clone the SDK repository and install project dependencies using pnpm. ```bash git clone https://github.com/WEBzaytsev/yookassa-ts-sdk.git cd yookassa-ts-sdk corepack enable pnpm install ``` -------------------------------- ### MaxRPS Configuration Examples Source: https://github.com/webzaytsev/yookassa-ts-sdk/blob/master/docs/api/type-aliases/ConnectorOpts.md Illustrates how to set the `maxRPS` option for rate limiting. The first example shows a higher limit for a single instance, while the second demonstrates setting a lower limit per instance in a distributed system to collectively manage the total requests per second. ```typescript // Single instance: use full rate limit maxRPS: 10 // 5 distributed instances sharing limit maxRPS: 2 // 2 * 5 = 10 total RPS ``` -------------------------------- ### Quick Start: Create a Payment Source: https://github.com/webzaytsev/yookassa-ts-sdk/blob/master/docs/index.md Initialize the SDK with your shop ID and secret key, then create a new payment. Ensure you replace 'your_shop_id' and 'your_secret_key' with your actual credentials. ```typescript import { YooKassa } from '@webzaytsev/yookassa-ts-sdk'; const sdk = YooKassa({ shop_id: 'your_shop_id', secret_key: 'your_secret_key', }); const payment = await sdk.payments.create({ amount: { value: '100.00', currency: 'RUB' }, confirmation: { type: 'redirect', return_url: 'https://example.com' }, }); ``` -------------------------------- ### Initialize YooKassa SDK and Create Payment Source: https://github.com/webzaytsev/yookassa-ts-sdk/blob/master/docs/api/classes/YooKassaSdk.md Demonstrates how to initialize the YooKassa SDK with shop and secret keys and create a payment. Includes examples for both auto-generated and custom idempotency keys. ```typescript import { YooKassa } from '@webzaytsev/yookassa-ts-sdk'; const sdk = YooKassa({ shop_id: 'your_shop_id', secret_key: 'your_secret_key', }); // Create payment with auto-generated idempotency key const payment = await sdk.payments.create({ amount: { value: '100.00', currency: 'RUB' }, confirmation: { type: 'redirect', return_url: 'https://example.com' }, }); // Create payment with custom idempotency key (recommended for retries) const payment = await sdk.payments.create(paymentData, `order-${orderId}`); ``` -------------------------------- ### Develop YooKassa SDK Repository Source: https://github.com/webzaytsev/yookassa-ts-sdk/blob/master/readme.md Commands to set up the development environment for this repository, including installing dependencies, checking types, and building the project. ```sh corepack enable pnpm install pnpm run check pnpm run build ``` -------------------------------- ### Create a Payment with YooKassa SDK Source: https://github.com/webzaytsev/yookassa-ts-sdk/blob/master/readme.md Example of creating a payment using the YooKassa TypeScript SDK. Requires shop ID and secret key. The payment confirmation URL is logged to the console. ```typescript import { YooKassa } from '@webzaytsev/yookassa-ts-sdk'; const sdk = YooKassa({ shop_id: 'your_shop_id', secret_key: 'your_secret_key', }); // Create a payment const payment = await sdk.payments.create({ amount: { value: '100.00', currency: 'RUB' }, confirmation: { type: 'redirect', return_url: 'https://example.com' }, description: 'Order #1', }); console.log(payment.confirmation.confirmation_url); ``` -------------------------------- ### GetRefundListFilter payment_id Example Source: https://github.com/webzaytsev/yookassa-ts-sdk/blob/master/docs/api/type-aliases/GetRefundListFilter.md Example of how to specify the payment_id filter for GetRefundListFilter. ```typescript `payment_id=1da5c87d-0984-50e8-a7f3-8de646dd9ec9` ``` -------------------------------- ### YooKassa() Instance Caching Example Source: https://github.com/webzaytsev/yookassa-ts-sdk/blob/master/docs/api/functions/YooKassa.md Demonstrates how YooKassa() caches SDK instances based on credentials. Identical credentials yield the same instance, while different credentials (like a new secret key or shop ID) produce new instances. ```typescript const sdk1 = YooKassa({ shop_id: '123', secret_key: 'key' }); const sdk2 = YooKassa({ shop_id: '123', secret_key: 'key' }); console.log(sdk1 === sdk2); // true const oldSdk = YooKassa({ shop_id: '123', secret_key: 'old' }); const newSdk = YooKassa({ shop_id: '123', secret_key: 'new' }); console.log(oldSdk === newSdk); // false const shopA = YooKassa({ shop_id: 'A', secret_key: 'keyA' }); const shopB = YooKassa({ shop_id: 'B', secret_key: 'keyB' }); ``` -------------------------------- ### Get Deal Source: https://github.com/webzaytsev/yookassa-ts-sdk/blob/master/docs/en/deals.md Retrieves a specific deal by its unique identifier. ```APIDOC ## GET /deals/{deal_id} ### Description Retrieves a specific deal by its unique identifier. ### Method GET ### Endpoint /deals/{deal_id} ### Parameters #### Path Parameters - **deal_id** (string) - Required - The unique identifier of the deal. ### Response #### Success Response (200) - **deal** (object) - The deal object. #### Response Example ```json { "deal": { "id": "deal_id", "type": "safe_deal", "fee_moment": "payment_succeeded", "description": "Order #42", "metadata": { "order_id": "42" }, "status": "opened", "created_at": "2024-01-01T10:00:00.000Z", "expires_at": "2024-01-08T10:00:00.000Z" } } ``` ``` -------------------------------- ### Error.captureStackTrace Example Source: https://github.com/webzaytsev/yookassa-ts-sdk/blob/master/docs/api/classes/WebhookValidationError.md Illustrates the usage of Error.captureStackTrace to create a .stack property on a target object. This is useful for capturing stack traces in specific scenarios, like hiding implementation details of error generation. ```javascript const myObject = {}; Error.captureStackTrace(myObject); myObject.stack; // Similar to `new Error().stack` ``` -------------------------------- ### Initialize SDK: Basic Configuration Source: https://github.com/webzaytsev/yookassa-ts-sdk/blob/master/docs/en/getting-started.md Instantiate the SDK with essential shop ID and secret key for basic operations. ```typescript // Basic const sdk = YooKassa({ shop_id: '123456', secret_key: 'test_secret_key', }); ``` -------------------------------- ### Initialize SDK: With Proxy Source: https://github.com/webzaytsev/yookassa-ts-sdk/blob/master/docs/en/getting-started.md Set up the SDK to use a proxy server for network requests, including authentication details. ```typescript // With proxy const sdk = YooKassa({ shop_id: '123456', secret_key: 'live_secret_key', proxy: 'http://user:password@proxy.example.com:8080', }); ``` -------------------------------- ### Get Payment Source: https://github.com/webzaytsev/yookassa-ts-sdk/blob/master/docs/en/payments.md Retrieves a specific payment by its unique identifier. ```APIDOC ## Get Payment ### Description Retrieves a specific payment transaction using its ID. ### Method `sdk.payments.load(paymentId) ` ### Parameters #### `paymentId` (string) - Required The unique identifier of the payment to retrieve. ### Response #### Success Response Returns a payment object with a `status` field (e.g., 'pending', 'succeeded', 'canceled'). ``` -------------------------------- ### Get Payout Source: https://github.com/webzaytsev/yookassa-ts-sdk/blob/master/docs/en/payouts.md Retrieves a specific payout by its unique identifier. ```APIDOC ## Get Payout ### Description Retrieves a specific payout by its unique identifier. ### Method Signature `load(id: string): Promise` ### Parameters #### Path Parameters - **id** (string) - Required - The unique identifier of the payout to retrieve. ### Response #### Success Response (200) - **IPayout** - An object representing the requested payout. ### Request Example ```ts const payout = await sdk.payouts.load('payout_id'); ``` ``` -------------------------------- ### Get Refund Source: https://github.com/webzaytsev/yookassa-ts-sdk/blob/master/docs/en/refunds.md Retrieves a specific refund by its unique identifier. ```APIDOC ## Get Refund ### Description Retrieves a specific refund by its unique identifier. ### Method `load(id)` ### Parameters #### Path Parameters - **id** (string) - Required - The ID of the refund to retrieve. ### Request Example ```ts const refund = await sdk.refunds.load('refund_id'); ``` ### Response #### Success Response (200) - **refund** (object) - Details of the requested refund. ``` -------------------------------- ### YooKassaSdk Initialization and Payment Creation Source: https://github.com/webzaytsev/yookassa-ts-sdk/blob/master/docs/api/classes/YooKassaSdk.md Demonstrates how to initialize the YooKassa SDK and create a payment using the SDK client. It shows both auto-generated and custom idempotency keys. ```APIDOC ## YooKassaSdk ### Description YooKassa SDK client for payment processing with features like automatic retries, built-in rate limiting, and idempotency. ### Usage ```typescript import { YooKassa } from '@webzaytsev/yookassa-ts-sdk'; const sdk = YooKassa({ shop_id: 'your_shop_id', secret_key: 'your_secret_key', }); // Create payment with auto-generated idempotency key const payment = await sdk.payments.create({ amount: { value: '100.00', currency: 'RUB' }, confirmation: { type: 'redirect', return_url: 'https://example.com' }, }); // Create payment with custom idempotency key (recommended for retries) const payment = await sdk.payments.create(paymentData, `order-${orderId}`); ``` ### Constructor #### Parameters ##### init - **init** (`ConnectorOpts`) - Options for initializing the connector. #### Returns - `YooKassaSdk` - An instance of the YooKassaSdk client. ``` -------------------------------- ### Get Receipt Source: https://github.com/webzaytsev/yookassa-ts-sdk/blob/master/docs/en/receipts.md Retrieves a specific receipt by its unique identifier. ```APIDOC ## Get Receipt ### Description Retrieves a specific receipt by its unique identifier. ### Method `load(id)` ### Parameters #### Path Parameters - **id** (string) - Required - The unique identifier of the receipt to retrieve. ### Request Example ```ts const receipt = await sdk.receipts.load('receipt_id'); ``` ``` -------------------------------- ### Get Refund by ID Source: https://github.com/webzaytsev/yookassa-ts-sdk/blob/master/docs/en/refunds.md Retrieves a specific refund using its unique identifier. ```typescript const refund = await sdk.refunds.load('refund_id'); ``` -------------------------------- ### Initialize SDK: With OAuth Token Source: https://github.com/webzaytsev/yookassa-ts-sdk/blob/master/docs/en/getting-started.md Initialize the SDK with an OAuth token for accessing partner API functionalities like webhooks and shop information. ```typescript // With OAuth token (for webhooks and shop info) const sdk = YooKassa({ shop_id: '123456', secret_key: 'live_secret_key', token: 'your_oauth_token', }); ``` -------------------------------- ### Get Payment by ID Source: https://github.com/webzaytsev/yookassa-ts-sdk/blob/master/docs/en/payments.md Retrieves a specific payment by its unique identifier. The payment status can then be accessed. ```typescript const payment = await sdk.payments.load('payment_id'); console.log(payment.status); // pending, waiting_for_capture, succeeded, canceled ``` -------------------------------- ### Run Project Scripts Source: https://github.com/webzaytsev/yookassa-ts-sdk/blob/master/CONTRIBUTING.md Available scripts for building, checking code quality, linting, and generating documentation. ```bash pnpm run build # Bundle CJS + ESM with tsup pnpm run check # Run knip + biome + tsc pnpm run lint # Check code style pnpm run lint:fix # Fix code style pnpm run docs:api # Generate API documentation ``` -------------------------------- ### Initialize SDK: Debug and Custom Settings Source: https://github.com/webzaytsev/yookassa-ts-sdk/blob/master/docs/en/getting-started.md Configure the SDK with debug mode enabled and custom network settings like timeout and retries. ```typescript // With debug and custom settings const sdk = YooKassa({ shop_id: '123456', secret_key: 'live_secret_key', debug: true, timeout: 10000, retries: 3, maxRPS: 10, }); ``` -------------------------------- ### GetDealListFilter Source: https://github.com/webzaytsev/yookassa-ts-sdk/blob/master/docs/api/interfaces/GetDealListFilter.md This interface defines the filter parameters for retrieving a list of deals via the GET /deals endpoint. ```APIDOC ## GET /deals ### Description Retrieves a list of deals with optional filtering. ### Endpoint /deals ### Query Parameters - **created_at** (DateFilter) - Optional - Filter deals by creation date. - **expires_at** (DateFilter) - Optional - Filter deals by expiration date. - **status** (DealStatus) - Optional - Filter deals by their status. - **full_text_search** (string) - Optional - Perform a full-text search on deal information. - **limit** (number) - Optional - The maximum number of deals to return. - **cursor** (string) - Optional - A cursor for paginating through the deal list. ``` -------------------------------- ### SDK Instance Caching: Force New Instance Source: https://github.com/webzaytsev/yookassa-ts-sdk/blob/master/docs/en/getting-started.md Demonstrates how to explicitly create a new SDK instance, bypassing the cache by providing a second argument. ```typescript // Force create a new instance (bypass cache) const newSdk = YooKassa({ shop_id: '123', secret_key: 'new_key' }, true); ``` -------------------------------- ### Correctly Saving and Using Payment Methods Source: https://github.com/webzaytsev/yookassa-ts-sdk/blob/master/docs/en/error-handling.md Demonstrates the correct sequence for saving a payment method on the first payment and using the saved method ID for subsequent recurring payments. ```typescript const firstPayment = await sdk.payments.create({ amount: { value: '100.00', currency: 'RUB' }, confirmation: { type: 'redirect', return_url: 'https://example.com' }, save_payment_method: true, // Save payment method }) const recurringPayment = await sdk.payments.create({ amount: { value: '100.00', currency: 'RUB' }, payment_method_id: firstPayment.payment_method?.id, // ID from first payment capture: true, }) ``` -------------------------------- ### Get a Receipt by ID Source: https://github.com/webzaytsev/yookassa-ts-sdk/blob/master/docs/en/receipts.md Retrieve a specific receipt using its unique ID. This is useful for checking the status or details of a previously created receipt. ```typescript const receipt = await sdk.receipts.load('receipt_id'); ``` -------------------------------- ### SDK Instance Caching: Different Shops Source: https://github.com/webzaytsev/yookassa-ts-sdk/blob/master/docs/en/getting-started.md Illustrates that different shop IDs and secret keys lead to distinct SDK instances. ```typescript // Different shops — different instances const shop1 = YooKassa({ shop_id: '111', secret_key: 'key1' }); const shop2 = YooKassa({ shop_id: '222', secret_key: 'key2' }); ``` -------------------------------- ### SDK Instance Caching: New Instance with Token Source: https://github.com/webzaytsev/yookassa-ts-sdk/blob/master/docs/en/getting-started.md Shows that adding a token to existing credentials creates a new SDK instance, bypassing the cache. ```typescript // Changing any credential (e.g. adding a token) creates a new instance const sdkWithOAuth = YooKassa({ shop_id: '123', secret_key: 'key1', token: 'oauth_token' }); ``` -------------------------------- ### SDK Instance Caching: Identical Credentials Source: https://github.com/webzaytsev/yookassa-ts-sdk/blob/master/docs/en/getting-started.md Demonstrates that identical credentials result in the same SDK instance due to internal caching. ```typescript // Both calls return the same instance (identical credentials) const sdk1 = YooKassa({ shop_id: '123', secret_key: 'key1' }); const sdk2 = YooKassa({ shop_id: '123', secret_key: 'key1' }); console.log(sdk1 === sdk2); // true ``` -------------------------------- ### Create a Payment Receipt Source: https://github.com/webzaytsev/yookassa-ts-sdk/blob/master/docs/en/receipts.md Use this snippet to create a new payment receipt. Ensure you provide the payment ID, customer details, item information with amounts and VAT codes, and set `send` to true if you want to send the receipt immediately. ```typescript const receipt = await sdk.receipts.create({ type: 'payment', payment_id: 'payment_id', customer: { email: 'customer@example.com' }, items: [ { description: 'Product', quantity: 1, amount: { value: '100.00', currency: 'RUB' }, vat_code: 1, }, ], send: true, }); ``` -------------------------------- ### List All Webhooks Source: https://github.com/webzaytsev/yookassa-ts-sdk/blob/master/docs/en/webhooks.md Retrieve a list of all configured webhooks for your account. This is useful for monitoring active subscriptions. ```typescript const webhooks = await sdk.webhooks.list(); ``` -------------------------------- ### Create Payment with QR Code Confirmation (SBP) Source: https://github.com/webzaytsev/yookassa-ts-sdk/blob/master/docs/en/payments.md Create a payment that uses a QR code for confirmation via the SBP (Faster Payments System). The confirmation data is used to generate the QR code. ```typescript const payment = await sdk.payments.create({ amount: { value: '100.00', currency: 'RUB' }, payment_method_data: { type: 'sbp' }, confirmation: { type: 'qr' }, }); // Generate QR code from this data console.log(payment.confirmation.confirmation_data); ``` -------------------------------- ### Connector Options Interface Source: https://github.com/webzaytsev/yookassa-ts-sdk/blob/master/docs/en/getting-started.md Defines the structure for configuration options when initializing the SDK. All fields are optional except shop ID and secret key. ```typescript interface ConnectorOpts { /** Shop ID (required) */ shop_id: string; /** Secret key (required) */ secret_key: string; /** OAuth token for partner API (webhooks, shop info) */ token?: string; /** Debug mode — logs requests and responses */ debug?: boolean; /** Request timeout in ms (default: 5000) */ timeout?: number; /** Number of retry attempts on errors (default: 5) */ retries?: number; /** Max requests per second (default: 5) */ maxRPS?: number; /** Proxy server URL */ proxy?: string; /** Custom API endpoint */ endpoint?: string; } ``` -------------------------------- ### Create a Webhook Source: https://github.com/webzaytsev/yookassa-ts-sdk/blob/master/docs/en/webhooks.md Use this snippet to create a new webhook subscription for a specific event. Ensure you have an OAuth token and are part of the partner program. ```typescript const webhook = await sdk.webhooks.create({ event: 'payment.succeeded', url: 'https://example.com/webhook', }); ``` -------------------------------- ### Create Payment for Bank Account Top-up Source: https://github.com/webzaytsev/yookassa-ts-sdk/blob/master/docs/en/payments.md Use this snippet to create a payment for topping up a bank account. Provide the account number and BIC for the receiver. ```typescript // Top up bank account const payment = await sdk.payments.create({ amount: { value: '1000.00', currency: 'RUB' }, confirmation: { type: 'redirect', return_url: 'https://example.com' }, receiver: { type: 'bank_account', account_number: '40817810000000000001', bic: '044525225', }, }); ``` -------------------------------- ### Create Webhook Source: https://github.com/webzaytsev/yookassa-ts-sdk/blob/master/docs/en/webhooks.md Creates a new webhook subscription for a specific event and URL. Requires partner API access and an OAuth token. ```APIDOC ## Create Webhook ### Description Creates a new webhook subscription for a specific event and URL. This method is part of the Partner API and requires an OAuth token. ### Method `create(data, idempotenceKey?)` ### Parameters #### Request Body - **event** (string) - Required - The event to subscribe to (e.g., 'payment.succeeded'). - **url** (string) - Required - The URL to receive webhook notifications. - **idempotenceKey** (string) - Optional - An idempotence key for safe retries. ### Request Example ```ts const webhook = await sdk.webhooks.create({ event: 'payment.succeeded', url: 'https://example.com/webhook', }); ``` ### Response #### Success Response Returns the created webhook object. #### Response Example (Response structure not provided in source) ``` -------------------------------- ### Create a Payout Source: https://github.com/webzaytsev/yookassa-ts-sdk/blob/master/docs/en/payouts.md Use this snippet to create a new payout. Ensure your account has payouts enabled and use the correct gateway shop ID and secret key. You can optionally provide an idempotence key for safe retries. ```typescript import { YooKassa } from '@webzaytsev/yookassa-ts-sdk'; const sdk = YooKassa({ shop_id: process.env.YOOKASSA_PAYOUT_SHOP_ID!, secret_key: process.env.YOOKASSA_PAYOUT_SECRET_KEY!, }); const payout = await sdk.payouts.create({ amount: { value: '100.00', currency: 'RUB' }, payout_destination_data: { type: 'yoo_money', account_number: '410011234567890', }, description: 'Payout contract 37', }); // With idempotence key const same = await sdk.payouts.create(payoutData, 'your-unique-key'); ``` -------------------------------- ### Create Payment for Digital Wallet Top-up Source: https://github.com/webzaytsev/yookassa-ts-sdk/blob/master/docs/en/payments.md Use this snippet to create a payment for topping up a digital wallet. Provide the account number for the receiver. ```typescript // Top up digital wallet const payment = await sdk.payments.create({ amount: { value: '500.00', currency: 'RUB' }, confirmation: { type: 'redirect', return_url: 'https://example.com' }, receiver: { type: 'digital_wallet', account_number: '4100175017397', }, }); ``` -------------------------------- ### Download YooKassa OpenAPI Specification Source: https://github.com/webzaytsev/yookassa-ts-sdk/blob/master/CONTRIBUTING.md Download the official OpenAPI 3.0.2 specification file using curl. ```bash curl -o openapi.yaml "https://yookassa.ru/developers/api/yookassa-openapi-specification.yaml" ``` -------------------------------- ### Create Payment with Redirect Confirmation Source: https://github.com/webzaytsev/yookassa-ts-sdk/blob/master/docs/en/payments.md Create a payment that redirects the user to a YooKassa or bank payment page for confirmation. The return URL is where the user is sent after payment. ```typescript const payment = await sdk.payments.create({ amount: { value: '100.00', currency: 'RUB' }, confirmation: { type: 'redirect', return_url: 'https://example.com/return', locale: 'ru_RU', // Optional: interface language }, }); // Redirect user to payment page console.log(payment.confirmation.confirmation_url); ``` -------------------------------- ### Specifying Correct Currency for Payments Source: https://github.com/webzaytsev/yookassa-ts-sdk/blob/master/docs/en/error-handling.md Illustrates the correct usage of the `currency` parameter, emphasizing that only 'RUB' is supported for saving payment methods. ```typescript const payment = await sdk.payments.create({ amount: { value: '100.00', currency: 'RUB' }, // Correct save_payment_method: true, }) ``` -------------------------------- ### Create Payment First, Then Receipt Source: https://github.com/webzaytsev/yookassa-ts-sdk/blob/master/docs/en/error-handling.md Demonstrates the scenario where a payment is created without receipt data, and a separate receipt is created afterward using the payment ID. This is useful when using third-party cash registers. ```typescript // 1. Create payment without receipt const payment = await sdk.payments.create({ amount: { value: '100.00', currency: 'RUB' }, confirmation: { type: 'redirect', return_url: 'https://example.com' }, // receipt not provided }) // 2. After successful payment, create receipt if (payment.status === 'succeeded') { const receipt = await sdk.receipts.create({ type: 'payment', payment_id: payment.id, customer: { email: 'customer@example.com' }, items: [ { description: 'Product', quantity: 1, amount: { value: '100.00', currency: 'RUB' }, vat_code: 1, }, ], send: true, settlements: [ { type: 'prepayment', amount: { value: '100.00', currency: 'RUB' }, }, ], }) } ``` -------------------------------- ### List Webhooks Source: https://github.com/webzaytsev/yookassa-ts-sdk/blob/master/docs/en/webhooks.md Retrieves a list of all configured webhooks for the partner account. Requires partner API access and an OAuth token. ```APIDOC ## List Webhooks ### Description Retrieves a list of all configured webhooks for the partner account. This method is part of the Partner API and requires an OAuth token. ### Method `list()` ### Parameters None ### Request Example ```ts const webhooks = await sdk.webhooks.list(); ``` ### Response #### Success Response Returns an array of webhook objects. #### Response Example (Response structure not provided in source) ``` -------------------------------- ### Create Payment for Mobile Balance Top-up Source: https://github.com/webzaytsev/yookassa-ts-sdk/blob/master/docs/en/payments.md Use this snippet to create a payment for topping up a phone balance. Provide the phone number for the receiver. ```typescript // Top up phone balance const payment = await sdk.payments.create({ amount: { value: '500.00', currency: 'RUB' }, confirmation: { type: 'redirect', return_url: 'https://example.com' }, receiver: { type: 'mobile_balance', phone: '79001234567', }, }); ``` -------------------------------- ### Include Receipt Data in Payment Creation Source: https://github.com/webzaytsev/yookassa-ts-sdk/blob/master/docs/en/error-handling.md Illustrates how to include necessary receipt data when creating a payment to satisfy fiscalization requirements. Ensure all required fields are present and correct. ```typescript const payment = await sdk.payments.create({ amount: { value: '100.00', currency: 'RUB' }, confirmation: { type: 'redirect', return_url: 'https://example.com' }, description: 'Order #123', receipt: { customer: { email: 'customer@example.com', // Required for YooKassa Receipts }, items: [ { description: 'Product', quantity: 1, amount: { value: '100.00', currency: 'RUB' }, vat_code: 1, // VAT code (required) }, ], }, }) ``` -------------------------------- ### Create Deal Source: https://github.com/webzaytsev/yookassa-ts-sdk/blob/master/docs/en/deals.md Creates a new safe deal. You can optionally provide an idempotence key to ensure the request is processed only once. ```APIDOC ## POST /deals ### Description Creates a new safe deal. ### Method POST ### Endpoint /deals ### Parameters #### Request Body - **type** (string) - Required - The type of deal, must be 'safe_deal'. - **fee_moment** (string) - Required - When the marketplace commission is charged. Possible values: 'payment_succeeded', 'deal_closed'. - **description** (string) - Optional - A description for the deal. - **metadata** (object) - Optional - Custom data for the deal. ### Request Example ```json { "type": "safe_deal", "fee_moment": "payment_succeeded", "description": "Order #42", "metadata": { "order_id": "42" } } ``` ### Response #### Success Response (200) - **deal** (object) - The created deal object. #### Response Example ```json { "deal": { "id": "deal_id", "type": "safe_deal", "fee_moment": "payment_succeeded", "description": "Order #42", "metadata": { "order_id": "42" }, "status": "opened", "created_at": "2024-01-01T10:00:00.000Z", "expires_at": "2024-01-08T10:00:00.000Z" } } ``` ``` -------------------------------- ### YooKassaErr Constructor Source: https://github.com/webzaytsev/yookassa-ts-sdk/blob/master/docs/api/classes/YooKassaErr.md Initializes a new instance of the YooKassaErr class. It takes an error response object as input and extends the base Error constructor. ```APIDOC ## Constructor ### new YooKassaErr(err: YooKassaErrResponse): YooKassaErr #### Parameters ##### err - **err** (`YooKassaErrResponse`) - The error response object from YooKassa. #### Returns - `YooKassaErr` - A new instance of the YooKassaErr class. #### Overrides `Error.constructor` ``` -------------------------------- ### Create Payment with Split Payments Source: https://github.com/webzaytsev/yookassa-ts-sdk/blob/master/docs/en/payments.md Use this to distribute a payment between multiple sellers on a marketplace. Ensure seller account IDs and amounts are correctly specified. ```typescript const payment = await sdk.payments.create({ amount: { value: '1000.00', currency: 'RUB' }, confirmation: { type: 'redirect', return_url: 'https://example.com' }, transfers: [ { account_id: 'seller_shop_id_1', amount: { value: '600.00', currency: 'RUB' }, platform_fee_amount: { value: '50.00', currency: 'RUB' }, // Your commission }, { account_id: 'seller_shop_id_2', amount: { value: '400.00', currency: 'RUB' }, platform_fee_amount: { value: '30.00', currency: 'RUB' }, }, ], }); ``` -------------------------------- ### Create Payment with Metadata Source: https://github.com/webzaytsev/yookassa-ts-sdk/blob/master/docs/en/payments.md Attach custom data to payments for later retrieval via API responses and webhooks. Supports up to 16 key-value pairs. ```typescript const payment = await sdk.payments.create({ amount: { value: '100.00', currency: 'RUB' }, confirmation: { type: 'redirect', return_url: 'https://example.com' }, metadata: { order_id: 'order-123', user_id: 'user-456', source: 'mobile_app', }, }); // Later, retrieve metadata const loaded = await sdk.payments.load(payment.id); console.log(loaded.metadata.order_id); // 'order-123' ``` -------------------------------- ### Create Payment with Token Source: https://github.com/webzaytsev/yookassa-ts-sdk/blob/master/docs/en/payments.md Use this snippet to create a payment when integrating with Checkout.js or the Mobile SDK. It requires a payment token obtained from the client-side integration. ```typescript const payment = await sdk.payments.create({ amount: { value: '100.00', currency: 'RUB' }, payment_token: 'token_from_checkout_js_or_mobile_sdk', description: 'Order #789', }); ``` -------------------------------- ### List Deals Source: https://github.com/webzaytsev/yookassa-ts-sdk/blob/master/docs/en/deals.md Retrieves a list of deals, with options for filtering and pagination. ```APIDOC ## GET /deals ### Description Retrieves a list of deals, with options for filtering and pagination. ### Method GET ### Endpoint /deals ### Parameters #### Query Parameters - **created_at** (object) - Optional - Filter by creation time. Supports `gte`, `gt`, `lte`, `lt`. - **expires_at** (object) - Optional - Filter by expiration time. Supports `gte`, `gt`, `lte`, `lt`. - **status** (string) - Optional - Filter by deal status. Possible values: `opened`, `closed`. - **full_text_search** (string) - Optional - Full-text search across deal fields. - **limit** (integer) - Optional - Page size (1-100, default 10). - **cursor** (string) - Optional - Pagination cursor. ### Response #### Success Response (200) - **deals** (array) - An array of deal objects. - **next_cursor** (string) - The cursor for the next page of results. #### Response Example ```json { "deals": [ { "id": "deal_id_1", "type": "safe_deal", "fee_moment": "payment_succeeded", "description": "Order #42", "status": "opened", "created_at": "2024-01-01T10:00:00.000Z", "expires_at": "2024-01-08T10:00:00.000Z" }, { "id": "deal_id_2", "type": "safe_deal", "fee_moment": "deal_closed", "description": "Order #43", "status": "closed", "created_at": "2024-01-02T11:00:00.000Z", "expires_at": "2024-01-09T11:00:00.000Z" } ], "next_cursor": "some_cursor_string" } ``` ``` -------------------------------- ### ConnectorOpts Configuration Source: https://github.com/webzaytsev/yookassa-ts-sdk/blob/master/docs/api/type-aliases/ConnectorOpts.md The ConnectorOpts type alias defines the configuration object used when initializing the YooKassa SDK. It includes mandatory shop and secret keys, along with several optional parameters to customize SDK behavior, such as rate limiting, request retries, timeouts, and debugging. ```APIDOC ## Type Alias: ConnectorOpts > **ConnectorOpts** = `object` Configuration options for YooKassa SDK. ### Properties * **shop_id** (`string`) - Required - Shop identifier from YooKassa dashboard * **secret_key** (`string`) - Required - Secret key from YooKassa dashboard * **token?** (`string`) - Optional - OAuth token for partner API (webhooks, shop info). Required for `sdk.webhooks.*` and `sdk.shop.*` methods. * **endpoint?** (`string`) - Optional - API endpoint URL (without trailing slash). Default: `"https://api.yookassa.ru/v3"` * **debug?** (`boolean`) - Optional - Debug mode — logs all requests and responses * **maxRPS?** (`number`) - Optional - Maximum requests per second (rate limiting). Default: `5` * **timeout?** (`number`) - Optional - Request timeout in milliseconds. Default: `5000` * **retries?** (`number`) - Optional - Number of retry attempts on retryable errors (5xx, 429, network errors). Default: `5` * **proxy?** (`ProxyConfig`) - Optional - Proxy server URL (e.g., "http://user:pass@proxy.example.com:8080") ``` -------------------------------- ### Create Receipt Source: https://github.com/webzaytsev/yookassa-ts-sdk/blob/master/docs/en/receipts.md Creates a new receipt for a payment. You can specify customer details, items, and whether to send the receipt immediately. ```APIDOC ## Create Receipt ### Description Creates a new receipt for a payment. You can specify customer details, items, and whether to send the receipt immediately. ### Method `create(data, idempotenceKey?)` ### Parameters #### Request Body - **type** (string) - Required - Type of the receipt (e.g., 'payment'). - **payment_id** (string) - Required - The ID of the associated payment. - **customer** (object) - Required - Customer information. - **email** (string) - Required - Customer's email address. - **items** (array) - Required - An array of items included in the receipt. - **description** (string) - Required - Description of the item. - **quantity** (number) - Required - Quantity of the item. - **amount** (object) - Required - Amount details for the item. - **value** (string) - Required - The monetary value. - **currency** (string) - Required - The currency code (e.g., 'RUB'). - **vat_code** (number) - Required - The VAT code for the item. - **send** (boolean) - Optional - Whether to send the receipt immediately. ### Request Example ```ts const receipt = await sdk.receipts.create({ type: 'payment', payment_id: 'payment_id', customer: { email: 'customer@example.com' }, items: [ { description: 'Product', quantity: 1, amount: { value: '100.00', currency: 'RUB' }, vat_code: 1, }, ], send: true, }); ``` ``` -------------------------------- ### Error.captureStackTrace with Constructor Option Source: https://github.com/webzaytsev/yookassa-ts-sdk/blob/master/docs/api/classes/WebhookValidationError.md Shows how to use the optional constructorOpt argument with Error.captureStackTrace to omit frames from the generated stack trace, effectively hiding internal function calls. ```javascript function a() { b(); } function b() { c(); } function c() { // Create an error without stack trace to avoid calculating the stack trace twice. const { stackTraceLimit } = Error; Error.stackTraceLimit = 0; const error = new Error(); Error.stackTraceLimit = stackTraceLimit; // Capture the stack trace above function b Error.captureStackTrace(error, b); // Neither function c, nor b is included in the stack trace throw error; } a(); ``` -------------------------------- ### CreateInvoiceRequest Interface Source: https://github.com/webzaytsev/yookassa-ts-sdk/blob/master/docs/api/interfaces/CreateInvoiceRequest.md Defines the structure for creating an invoice, including payment and cart details, expiration, and optional fields like description, locale, and metadata. ```APIDOC ## Interface: CreateInvoiceRequest ### Description Represents the data structure required to create a new invoice. It includes mandatory fields for payment and cart information, as well as an expiration timestamp. Optional fields allow for additional details such as a description, locale, delivery method, and custom metadata. ### Properties #### `payment_data` - **payment_data** (InvoicePaymentData) - Required - The payment details for the invoice. #### `cart` - **cart** (InvoiceCart) - Required - The items included in the invoice. #### `expires_at` - **expires_at** (string) - Required - The timestamp when the invoice expires. #### `delivery_method_data` - **delivery_method_data** (DeliveryMethodData) - Required - Information about the delivery method. #### `locale` - **locale** (ru_RU | en_US) - Optional - The locale for the invoice. Defaults to ru_RU or en_US. #### `description` - **description** (string) - Optional - A description for the invoice. #### `metadata` - **metadata** (Metadata) - Optional - Custom metadata associated with the invoice. ### Request Example ```json { "payment_data": { ... }, "cart": { ... }, "expires_at": "2023-12-31T23:59:59Z", "delivery_method_data": { ... }, "locale": "en_US", "description": "Example invoice for testing", "metadata": { "order_id": "12345" } } ``` ### Response (Note: Response structure for invoice creation is not detailed in the source. Typically, it would include invoice ID and status.) #### Success Response (200 OK) (Details not provided in source) #### Error Response (Details not provided in source) ``` -------------------------------- ### Retrieve a Deal by ID Source: https://github.com/webzaytsev/yookassa-ts-sdk/blob/master/docs/en/deals.md Fetches a specific deal using its unique identifier. ```typescript const deal = await sdk.deals.load('deal_id'); ``` -------------------------------- ### Create a Safe Deal Source: https://github.com/webzaytsev/yookassa-ts-sdk/blob/master/docs/en/deals.md Initiates a new safe deal. You can specify when the marketplace commission is charged and include optional metadata. An idempotence key can be used to prevent duplicate requests. ```typescript const deal = await sdk.deals.create({ type: 'safe_deal', fee_moment: 'payment_succeeded', // or 'deal_closed' description: 'Order #42', metadata: { order_id: '42' }, }); // With idempotence key const same = await sdk.deals.create(dealData, 'your-unique-key'); ``` -------------------------------- ### Catching YooKassaErr Source: https://github.com/webzaytsev/yookassa-ts-sdk/blob/master/docs/en/error-handling.md Demonstrates how to catch and inspect `YooKassaErr` instances to access error details like code, message, and request ID. ```typescript import { YooKassaErr } from '@webzaytsev/yookassa-ts-sdk'; try { const payment = await sdk.payments.create({ ... }); } catch (error) { if (error instanceof YooKassaErr) { console.error(error.name); // Error code (e.g., 'invalid_request') console.error(error.message); // Error description console.error(error.id); // Request ID } } ``` -------------------------------- ### Create Payment Source: https://github.com/webzaytsev/yookassa-ts-sdk/blob/master/docs/en/payments.md Creates a new payment with specified amount, confirmation method, and optional metadata. Supports custom idempotence keys for safe retries. ```typescript import { CurrencyEnum } from '@webzaytsev/yookassa-ts-sdk'; const payment = await sdk.payments.create({ amount: { value: '100.00', currency: CurrencyEnum.RUB, }, confirmation: { type: 'redirect', return_url: 'https://example.com/return', }, capture: true, description: 'Order #123', metadata: { order_id: '123', }, }); ``` ```typescript // With custom idempotence key const payment = await sdk.payments.create(paymentData, 'your-unique-key'); ``` -------------------------------- ### Shop API Source: https://github.com/webzaytsev/yookassa-ts-sdk/blob/master/readme.md Method to retrieve shop information, requires OAuth authentication. ```APIDOC ## Shop API ### Description Method to retrieve shop information, requires OAuth authentication. ### Methods - `sdk.shop.info()` - **Description**: Get shop information. ``` -------------------------------- ### PaymentCancellationDetails Interface Source: https://github.com/webzaytsev/yookassa-ts-sdk/blob/master/docs/api/YooKassa-SDK-API-Reference/namespaces/Payments/interfaces/PaymentCancellationDetails.md The PaymentCancellationDetails interface includes properties for the initiator and reason of a payment cancellation. ```APIDOC ## Interface: PaymentCancellationDetails Defined in: `src/types/payments/payment.type.ts:58` This interface provides details about a canceled payment, including who initiated the cancellation and the reason for it. ### Properties #### party > **party**: `"yoo_money"` | `"merchant"` | `"payment_network"` Defined in: `src/types/payments/payment.type.ts:64` Specifies the initiator of the cancellation. Possible values are `yoo_money`, `payment_network`, or `merchant`. #### reason > **reason**: `"3d_secure_failed"` | `"call_issuer"` | `"canceled_by_merchant"` | `"card_expired"` | `"country_forbidden"` | `"deal_expired"` | `"expired_on_capture"` | `"expired_on_confirmation"` | `"fraud_suspected"` | `"general_decline"` | `"identification_required"` | `"insufficient_funds"` | `"internal_timeout"` | `"invalid_card_number"` | `"invalid_csc"` | `"issuer_unavailable"` | `"loan_declined"` | `"payment_method_limit_exceeded"` | `"payment_method_restricted"` | `"permission_revoked"` | `"unsupported_mobile_operator"` Defined in: `src/types/payments/payment.type.ts:70` Describes the reason for the payment cancellation. A comprehensive list of possible reasons is provided. ``` -------------------------------- ### IConfirmationRedirect Interface Source: https://github.com/webzaytsev/yookassa-ts-sdk/blob/master/docs/api/interfaces/IConfirmationRedirect.md Details the properties of the IConfirmationRedirect interface for redirect payment confirmations. ```APIDOC ## Interface: IConfirmationRedirect **Сценарий Redirect** Пользователь действует на странице ЮKassa или партнёра (карта, 3-D Secure). Перенаправьте на `confirmation_url` из платежа. После оплаты ЮKassa вернёт на `return_url`. ### Properties #### confirmation_url * **confirmation_url** (string) - Optional URL для подтверждения оплаты #### enforce * **enforce** (boolean) - Optional Запрос 3-D Secure при приёме карт без подтверждения по умолчанию. Иначе 3-D Secure управляет ЮKassa #### locale * **locale** (LocaleEnum) - Optional Язык интерфейса, писем и SMS (ISO/IEC 15897): `ru_RU`, `en_US`. Регистр важен #### return_url * **return_url** (string) - Optional URL возврата после подтверждения или отмены. До 2048 символов. Можно не указывать при настроенном `default_return_url` в ConnectorOpts. #### type * **type** (string) - Required Код сценария подтверждения. Value: "redirect" ```