### Install and Configure NestJS YooKassa Module (TypeScript) Source: https://context7.com/teacoder-team/nestjs-yookassa/llms.txt Demonstrates how to install the nestjs-yookassa package and configure the module using both synchronous and asynchronous methods. It requires environment variables for shop ID and secret key, with an optional proxy URL. ```typescript // Установка пакета // npm install nestjs-yookassa // Переменные окружения (.env) // YOOKASSA_SHOP_ID=your_shop_id // YOOKASSA_SECRET_KEY=your_secret_key // YOOKASSA_PROXY_URL=http://127.0.0.1:8080 (опционально) // app.module.ts - Синхронная конфигурация import { Module } from '@nestjs/common'; import { YookassaModule } from 'nestjs-yookassa'; @Module({ imports: [ YookassaModule.forRoot({ shopId: process.env.YOOKASSA_SHOP_ID, apiKey: process.env.YOOKASSA_SECRET_KEY, proxyUrl: process.env.YOOKASSA_PROXY_URL // опционально }) ] }) export class AppModule {} ``` ```typescript // app.module.ts - Асинхронная конфигурация import { Module } from '@nestjs/common'; import { ConfigModule, ConfigService } from '@nestjs/config'; import { YookassaModule } from 'nestjs-yookassa'; @Module({ imports: [ ConfigModule.forRoot(), YookassaModule.forRootAsync({ imports: [ConfigModule], inject: [ConfigService], useFactory: async (configService: ConfigService) => ({ shopId: configService.get('YOOKASSA_SHOP_ID'), apiKey: configService.get('YOOKASSA_SECRET_KEY'), proxyUrl: configService.get('YOOKASSA_PROXY_URL') }) }) ] }) export class AppModule {} ``` -------------------------------- ### GET /refunds Source: https://github.com/teacoder-team/nestjs-yookassa/blob/main/apps/web/content/docs/refunds/list.mdx Retrieves a paginated list of all refunds, with optional filtering by date range. ```APIDOC ## GET /refunds ### Description Retrieves a list of all refunds. This endpoint supports pagination via a limit parameter and date-based filtering. ### Method GET ### Endpoint /refunds ### Parameters #### Query Parameters - **limit** (number) - Optional - Maximum number of refunds to return per page. - **from** (string) - Optional - Start date for filtering in YYYY-MM-DD format. - **to** (string) - Optional - End date for filtering in YYYY-MM-DD format. ### Request Example ```typescript const refunds = await yookassaService.refunds.getAll(2, '2025-01-01', '2025-01-31'); ``` ### Response #### Success Response (200) - **type** (string) - The type of the response (list). - **next_cursor** (string) - Cursor for the next page of results. - **items** (array) - List of refund objects. #### Response Example { "type": "list", "next_cursor": "2f1d20e1-0016-5000-8000-12fc2af7f19b", "items": [ { "id": "2f1d29e9-0015-5000-a000-1e7e28fedd75", "payment_id": "2f1d28e4-000f-5000-a000-15f2d944be24", "status": "succeeded", "created_at": "2025-01-18T02:47:05.077Z", "amount": { "value": "529.00", "currency": "RUB" }, "description": "Возврат на заказ с ID 2f1d28e4-000f-5000-a000-15f2d944be24" } ] } ``` -------------------------------- ### GET /payment-methods/:id Source: https://context7.com/teacoder-team/nestjs-yookassa/llms.txt Retrieves detailed information about a specific saved payment method by its ID. ```APIDOC ## GET /payment-methods/:id ### Description Fetches the current status and details of a previously created payment method. ### Method GET ### Endpoint `yookassaService.paymentMethods.getById(methodId)` ### Parameters #### Path Parameters - **methodId** (string) - Required - The unique ID of the payment method ### Response #### Success Response (200) - **id** (string) - Payment method ID - **status** (string) - Current status - **card** (object) - Card details including last4 digits #### Response Example { "id": "pm-12345678", "status": "succeeded", "card": { "last4": "4242" } } ``` -------------------------------- ### GET /payments/:id Source: https://context7.com/teacoder-team/nestjs-yookassa/llms.txt Retrieves detailed information about an existing payment using its unique ID. ```APIDOC ## GET /payments/:id ### Description Fetches the current state and details of a payment transaction by its ID. ### Method GET ### Endpoint yookassaService.payments.getById(paymentId) ### Parameters #### Path Parameters - **paymentId** (string) - Required - The unique UUID of the payment. ### Response #### Success Response (200) - **id** (string) - Payment ID. - **status** (string) - Current status (e.g., succeeded). - **paid** (boolean) - Indicates if the payment has been successfully processed. - **amount** (object) - The payment amount and currency. #### Response Example { "id": "32f3dce3-e775-424f-a265-4e1e86e3db08", "status": "succeeded", "paid": true, "amount": { "value": "1000.00", "currency": "RUB" } } ``` -------------------------------- ### Get Yookassa Payments List with Filters and Pagination Source: https://context7.com/teacoder-team/nestjs-yookassa/llms.txt Retrieve a list of Yookassa payments using the `YookassaService.payments.getAll()` method. Supports filtering by date range, payment status, payment method, and pagination using cursors. Requires the `nestjs-yookassa` package. ```typescript import { Injectable, YookassaService, PaymentStatusEnum, PaymentMethodsEnum, type GetPaymentsResponse } from 'nestjs-yookassa'; @Injectable() export class PaymentService { constructor(private readonly yookassaService: YookassaService) {} async listPayments(): Promise { // Получение первых 20 платежей const payments = await this.yookassaService.payments.getAll({ limit: 20 }); // Фильтрация по периоду создания const paymentsByDate = await this.yookassaService.payments.getAll({ 'created_at.gte': '2025-01-01T00:00:00.000Z', 'created_at.lte': '2025-01-31T23:59:59.000Z' }); // Фильтрация по статусу и методу оплаты const succeededPayments = await this.yookassaService.payments.getAll({ status: PaymentStatusEnum.SUCCEEDED, payment_method: PaymentMethodsEnum.BANK_CARD }); // Пагинация через курсор const firstPage = await this.yookassaService.payments.getAll({ limit: 10 }); if (firstPage.next_cursor) { const nextPage = await this.yookassaService.payments.getAll({ cursor: firstPage.next_cursor }); } return payments; } } ``` -------------------------------- ### Configure Yookassa Module Synchronously Source: https://github.com/teacoder-team/nestjs-yookassa/blob/main/apps/web/content/docs/getting-started/installation.mdx Demonstrates how to initialize the Yookassa module using the forRoot method with static environment variables. This approach is suitable for simple configurations where settings are available at application startup. ```typescript import { YookassaModule } from 'nestjs-yookassa' YookassaModule.forRoot({ shopId: process.env.YOOKASSA_SHOP_ID, apiKey: process.env.YOOKASSA_SECRET_KEY, proxyUrl: process.env.YOOKASSA_PROXY_URL // прокси активируется при наличии }) ``` -------------------------------- ### Отмена платежа через YookassaService в NestJS Source: https://github.com/teacoder-team/nestjs-yookassa/blob/main/apps/web/content/docs/payments/cancel.mdx Пример реализации метода в сервисе NestJS для отмены платежа по его идентификатору с использованием библиотеки nestjs-yookassa. ```typescript import { YookassaService } from 'nestjs-yookassa'; @Injectable() export class PaymentService { constructor(private readonly yookassaService: YookassaService) {} async cancelPayment() { const paymentId = '123456' const canceledPayment = await this.yookassaService.payments.cancel(paymentId); return canceledPayment } } ``` -------------------------------- ### Настройка доверия к прокси в NestJS Source: https://github.com/teacoder-team/nestjs-yookassa/blob/main/apps/web/content/docs/webhooks/security.mdx Необходимая конфигурация приложения для корректного определения IP-адреса клиента при работе за прокси-серверами (Nginx, Cloudflare и др.). Без этого Guard проверки IP-адресов будет работать некорректно. ```typescript async function bootstrap() { const app = await NestFactory.create(AppModule) // Обязательно для корректной работы IP-проверки webhook app.set('trust proxy', true) await app.listen(3000) } ``` -------------------------------- ### List and Filter Refunds with YookassaService Source: https://context7.com/teacoder-team/nestjs-yookassa/llms.txt Demonstrates how to fetch a list of refunds using various filters such as date ranges, payment IDs, and statuses, as well as how to implement cursor-based pagination. ```typescript import { Injectable } from '@nestjs/common'; import { YookassaService, RefundStatusEnum, type GetRefundsResponse } from 'nestjs-yookassa'; @Injectable() export class RefundService { constructor(private readonly yookassaService: YookassaService) {} async listRefunds(): Promise { const refunds = await this.yookassaService.refunds.getAll({ limit: 20 }); const refundsByDate = await this.yookassaService.refunds.getAll({ 'created_at.gte': '2025-01-01T00:00:00.000Z', 'created_at.lte': '2025-01-31T23:59:59.000Z' }); const refundsByPayment = await this.yookassaService.refunds.getAll({ payment_id: '2aa99c13-000f-5000-9000-19f66f41b6d1' }); const succeededRefunds = await this.yookassaService.refunds.getAll({ status: RefundStatusEnum.succeeded }); const firstPage = await this.yookassaService.refunds.getAll({ limit: 10 }); if (firstPage.next_cursor) { const nextPage = await this.yookassaService.refunds.getAll({ cursor: firstPage.next_cursor }); } return refunds; } } ``` -------------------------------- ### Handle YooKassa Payment Errors Source: https://github.com/teacoder-team/nestjs-yookassa/blob/main/apps/web/content/docs/payments/create.mdx Examples of JSON error responses returned by the API. These errors indicate issues with payment method availability or currency configuration settings. ```json { "statusCode": 400, "message": "Payment method is not available" } ``` ```json { "statusCode": 400, "message": "Incorrect currency of payment. The value of the amount.currency parameter doesn't correspond with the settings of your store. Specify another currency value in the request or contact the YooMoney manager to change the settings" } ``` -------------------------------- ### Get Invoice Details with NestJS Yookassa Source: https://github.com/teacoder-team/nestjs-yookassa/blob/main/apps/web/content/docs/invoices/info.mdx Retrieves detailed information for a given invoice ID using the `YookassaService`. This method requires the `nestjs-yookassa` package and an invoice identifier as input. It returns a detailed invoice object. ```typescript import { YookassaService } from 'nestjs-yookassa'; @Injectable() export class InvoiceService { constructor(private readonly yookassaService: YookassaService) {} async getInvoiceDetails() { const invoiceId = '123456'; // Уникальный идентификатор счёта const invoice = await this.yookassaService.invoices.getById(invoiceId); return invoice; } } ``` -------------------------------- ### POST /payment-methods Source: https://context7.com/teacoder-team/nestjs-yookassa/llms.txt Creates a new saved payment method for recurring payments or card binding. ```APIDOC ## POST /payment-methods ### Description Creates a saved payment method (e.g., bank card) to enable recurring payments or future transactions. ### Method POST ### Endpoint `yookassaService.paymentMethods.create()` ### Request Body - **type** (string) - Required - The payment method type (e.g., 'bank_card') - **confirmation** (object) - Required - Configuration for the confirmation process (e.g., redirect URL) ### Request Example { "type": "bank_card", "confirmation": { "type": "redirect", "return_url": "https://myshop.com/yookassa-return" } } ### Response #### Success Response (200) - **id** (string) - Unique identifier of the payment method - **status** (string) - Current status of the payment method - **confirmation** (object) - Contains the confirmation_url for user redirection #### Response Example { "id": "pm-12345678", "status": "waiting_for_capture", "confirmation": { "confirmation_url": "https://yookassa.ru/payments/external/123" } } ``` -------------------------------- ### Вызов API для создания платежа в NestJS (TypeScript) Source: https://github.com/teacoder-team/nestjs-yookassa/blob/main/apps/web/content/docs/payments/create.mdx Создает платеж, используя метод createPayment из YookassaService. Требует инъекции YookassaService в конструктор сервиса. Возвращает объект созданного платежа. Зависит от 'nestjs-yookassa'. ```typescript import { CurrencyEnum, type PaymentCreateRequest, PaymentMethodsEnum, YookassaService } from 'nestjs-yookassa'; @Injectable() export class PaymentService { constructor(private readonly yookassaService: YookassaService) {} async createPayment() { const paymentData: PaymentCreateRequest = { amount: { value: 100, currency: CurrencyEnum.RUB }, description: 'Test payment', payment_method_data: { type: PaymentMethodsEnum.yoo_money }, capture: false, confirmation: { type: 'redirect', return_url: 'https://example.com/thanks' }, metadata: { order_id: '12345678', }, } const newPayment = await this.yookassaService.payments.create(paymentData); return newPayment; } } ``` -------------------------------- ### Получение списка возвратов через YookassaService Source: https://github.com/teacoder-team/nestjs-yookassa/blob/main/apps/web/content/docs/refunds/list.mdx Демонстрация использования метода getAll для получения списка возвратов с применением лимита и фильтрации по датам. Метод возвращает массив объектов RefundDetails, интегрируемых в сервис NestJS. ```typescript import { YookassaService } from 'nestjs-yookassa'; @Injectable() export class RefundService { constructor(private readonly yookassaService: YookassaService) {} async getRefundsList() { const limit = 2; // Ограничение на количество возвратов const from = '2025-01-01'; // Начальная дата фильтра const to = '2025-01-31'; // Конечная дата фильтра const refunds = await this.yookassaService.refunds.getAll(limit, from, to); return refunds } } ``` -------------------------------- ### Get Payment Method Details with YookassaService Source: https://context7.com/teacoder-team/nestjs-yookassa/llms.txt Shows how to retrieve details of a saved payment method using `YookassaService.paymentMethods.getById`. This function takes a payment method ID as input and returns detailed information, including the card's last four digits and status. ```typescript import { Injectable } from '@nestjs/common'; import { YookassaService, type PaymentMethodDetails } from 'nestjs-yookassa'; @Injectable() export class PaymentMethodService { constructor(private readonly yookassaService: YookassaService) {} async getPaymentMethodDetails(methodId: string): Promise { const paymentMethod = await this.yookassaService.paymentMethods.getById(methodId); console.log(`Статус: ${paymentMethod.status}`); console.log(`Последние 4 цифры карты: ${paymentMethod.card?.last4}`); return paymentMethod; } } ``` -------------------------------- ### Secure Webhook Endpoints with @YookassaWebhook() Decorator Source: https://context7.com/teacoder-team/nestjs-yookassa/llms.txt Illustrates how to protect webhook endpoints from spoofed requests using the `@YookassaWebhook()` decorator. This decorator automatically verifies the IP address against YooKassa's whitelist. It also includes an example of handling different payment notification events. ```typescript import { Controller, Post, Body } from '@nestjs/common'; import { YookassaWebhook, NotificationEventEnum } from 'nestjs-yookassa'; interface WebhookPayload { type: string; event: NotificationEventEnum; object: { id: string; status: string; amount: { value: string; currency: string }; metadata?: Record; }; } @Controller('webhooks') export class WebhooksController { @Post('yookassa') @YookassaWebhook() // Автоматическая проверка IP-адреса async handleWebhook(@Body() payload: WebhookPayload) { const { event, object } = payload; switch (event) { case NotificationEventEnum.PAYMENT_SUCCEEDED: console.log(`Платеж ${object.id} успешно завершен`); // Обновить статус заказа в БД break; case NotificationEventEnum.PAYMENT_CANCELED: console.log(`Платеж ${object.id} отменен`); // Обработать отмену break; case NotificationEventEnum.PAYMENT_WAITING_FOR_CAPTURE: console.log(`Платеж ${object.id} ожидает захвата`); // Захватить средства или отменить break; case NotificationEventEnum.REFUND_SUCCEEDED: console.log(`Возврат ${object.id} успешно завершен`); // Обновить статус возврата break; } return { received: true }; } } // ВАЖНО: Настройка trust proxy для работы за прокси (Nginx, Docker, Cloudflare) // main.ts import { NestFactory } from '@nestjs/core'; import { AppModule } from './app.module'; async function bootstrap() { const app = await NestFactory.create(AppModule); // Обязательно для корректной работы IP-проверки webhook app.set('trust proxy', true); await app.listen(3000); } bootstrap(); ``` -------------------------------- ### Защита контроллера с помощью декоратора YookassaWebhook Source: https://github.com/teacoder-team/nestjs-yookassa/blob/main/apps/web/content/docs/webhooks/security.mdx Пример использования декоратора @YookassaWebhook для автоматической защиты эндпоинта. Декоратор подключает Guard, который проверяет IP-адрес отправителя по белому списку YooKassa и блокирует неавторизованные запросы. ```typescript import { Controller, Post, Body } from '@nestjs/common' import { YookassaWebhook } from 'nestjs-yookassa' @Controller('webhooks') export class WebhooksController { @Post('yookassa') @YookassaWebhook() handleWebhook(@Body() event: any) { // event.object.status // event.object.id } } ``` -------------------------------- ### Get Payment Details by ID using YookassaService.payments.getById() (TypeScript) Source: https://context7.com/teacoder-team/nestjs-yookassa/llms.txt This code snippet shows how to retrieve detailed information about a specific payment using its unique ID with the `YookassaService.payments.getById()` method. It returns a `Payment` object containing status, amount, payment method, and other relevant details. ```typescript import { Injectable } from '@nestjs/common'; import { YookassaService, type Payment } from 'nestjs-yookassa'; @Injectable() export class PaymentService { constructor(private readonly yookassaService: YookassaService) {} async getPaymentDetails(paymentId: string): Promise { const payment = await this.yookassaService.payments.getById(paymentId); // Ответ: // { // "id": "32f3dce3-e775-424f-a265-4e1e86e3db08", // "status": "succeeded", // "amount": { "value": "1000.00", "currency": "RUB" }, // "payment_method": { "type": "bank_card", "id": "...", "saved": false }, // "created_at": "2025-01-17T10:15:35.455Z", // "paid": true, // "refundable": true // } console.log(`Статус платежа: ${payment.status}`); console.log(`Оплачен: ${payment.paid}`); return payment; } } ``` -------------------------------- ### Захват платежа в NestJS Source: https://github.com/teacoder-team/nestjs-yookassa/blob/main/apps/web/content/docs/payments/confirm.mdx Пример реализации метода захвата платежа с использованием сервиса YookassaService. Метод принимает идентификатор платежа и возвращает обновленные данные о транзакции. ```typescript import { YookassaService } from 'nestjs-yookassa'; @Injectable() export class PaymentService { constructor(private readonly yookassaService: YookassaService) {} async capturePayment() { const paymentId = '123456' const capturedPayment = await this.yookassaService.payments.capture(paymentId); return capturedPayment } } ``` -------------------------------- ### Установка пакета nestjs-yookassa Source: https://github.com/teacoder-team/nestjs-yookassa/blob/main/apps/web/content/docs/getting-started/installation.mdx Установка пакета nestjs-yookassa с использованием npm или yarn. Пакет включает все необходимые зависимости для работы с ЮKassa. ```bash npm install nestjs-yookassa ``` -------------------------------- ### Example Yookassa Invoice API Response Source: https://github.com/teacoder-team/nestjs-yookassa/blob/main/apps/web/content/docs/invoices/info.mdx Illustrates the structure of the response received from the Yookassa API when fetching invoice details. This JSON object contains information such as invoice ID, status, cart items, creation date, expiration date, and payment details. ```json { "id": "3f2d2280-0015-5000-b000-1c02972ec0ef", "status": "pending", "cart": [ { "description": "Товар 1", "price": { "value": "1000.00", "currency": "RUB" }, "quantity": 1 } ], "delivery_method": { "type": "self", "url": "https://example.com/invoice/3f2d2280" }, "created_at": "2025-08-23T10:00:00.000Z", "expires_at": "2025-08-30T10:00:00.000Z", "description": "Счёт на оплату по заказу 123456", "metadata": { "order_id": "123456" }, "payment_details": { "id": "1a2b3c4d-0015-5000-b000-1c02972ec0ef", "status": "succeeded", "amount": { "value": "1000.00", "currency": "RUB" } } } ``` -------------------------------- ### Обработка ошибки при неверном статусе платежа Source: https://github.com/teacoder-team/nestjs-yookassa/blob/main/apps/web/content/docs/payments/cancel.mdx Пример структуры ошибки, возвращаемой API, если попытка отмены предпринята для платежа, который уже был завершен или не находится в статусе waiting_for_capture. ```json { "statusCode": 400, "message": "You can't cancel a payment with this status. You can only cancel payments with the waiting_for_capture status." } ``` -------------------------------- ### Create Payment using YookassaService.payments.create() (TypeScript) Source: https://context7.com/teacoder-team/nestjs-yookassa/llms.txt This snippet demonstrates how to create a new payment using the `YookassaService.payments.create()` method. It supports various payment methods, confirmation types, and metadata. The function returns a `CreatePaymentResponse` object. ```typescript import { Injectable } from '@nestjs/common'; import { YookassaService, CurrencyEnum, PaymentMethodsEnum, type CreatePaymentRequest, type CreatePaymentResponse } from 'nestjs-yookassa'; @Injectable() export class PaymentService { constructor(private readonly yookassaService: YookassaService) {} async createPayment(): Promise { const paymentData: CreatePaymentRequest = { amount: { value: 1000, currency: CurrencyEnum.RUB }, description: 'Оплата заказа #12345', payment_method_data: { type: PaymentMethodsEnum.BANK_CARD }, confirmation: { type: 'redirect', return_url: 'https://example.com/thanks' }, capture: true, // автоматический захват средств save_payment_method: false, metadata: { order_id: '12345', customer_id: 'user_001' } }; const payment = await this.yookassaService.payments.create(paymentData); // Ответ: // { // "id": "32f3dce3-e775-424f-a265-4e1e86e3db08", // "status": "pending", // "amount": { "value": "1000.00", "currency": "RUB" }, // "confirmation": { // "type": "redirect", // "confirmation_url": "https://yoomoney.ru/checkout/payments/v2/contract?orderId=..." // }, // "metadata": { "order_id": "12345", "customer_id": "user_001" } // } return payment; } } ``` -------------------------------- ### Create Saved Payment Method with YookassaService Source: https://context7.com/teacoder-team/nestjs-yookassa/llms.txt Demonstrates how to create a saved payment method (card binding) for recurring payments using `YookassaService.paymentMethods.create`. It requires the `nestjs-yookassa` package and configures a redirect confirmation URL. ```typescript import { Injectable } from '@nestjs/common'; import { YookassaService, PaymentMethodsEnum, type CreatePaymentMethodRequest, type CreatePaymentMethodResponse } from 'nestjs-yookassa'; @Injectable() export class PaymentMethodService { constructor(private readonly yookassaService: YookassaService) {} async createSavedPaymentMethod(): Promise { const paymentMethodData: CreatePaymentMethodRequest = { type: PaymentMethodsEnum.BANK_CARD, confirmation: { type: 'redirect', return_url: 'https://myshop.com/yookassa-return' } }; const method = await this.yookassaService.paymentMethods.create(paymentMethodData); console.log(`ID метода: ${method.id}`); console.log(`Статус: ${method.status}`); console.log(`URL подтверждения: ${method.confirmation?.confirmation_url}`); // Перенаправьте пользователя на confirmation_url для привязки карты return method; } } ``` -------------------------------- ### Implement Payment Lifecycle Service with NestJS Yookassa Source: https://context7.com/teacoder-team/nestjs-yookassa/llms.txt This service demonstrates how to handle the full payment lifecycle using the nestjs-yookassa package. It includes methods for creating payments, verifying status, capturing funds, cancelling pending payments, and processing refunds. ```typescript import { Injectable, BadRequestException } from '@nestjs/common'; import { YookassaService, CurrencyEnum, PaymentMethodsEnum, PaymentStatusEnum, type CreatePaymentRequest, type Payment } from 'nestjs-yookassa'; interface OrderPaymentResult { paymentId: string; confirmationUrl: string; } @Injectable() export class OrderPaymentService { constructor(private readonly yookassaService: YookassaService) {} async createOrderPayment( orderId: string, amount: number, returnUrl: string ): Promise { const paymentData: CreatePaymentRequest = { amount: { value: amount, currency: CurrencyEnum.RUB }, description: `Оплата заказа #${orderId}`, payment_method_data: { type: PaymentMethodsEnum.BANK_CARD }, confirmation: { type: 'redirect', return_url: returnUrl }, capture: true, metadata: { order_id: orderId } }; const payment = await this.yookassaService.payments.create(paymentData); return { paymentId: payment.id, confirmationUrl: payment.confirmation.confirmation_url }; } async checkPaymentStatus(paymentId: string): Promise { const payment = await this.yookassaService.payments.getById(paymentId); return payment; } async confirmPayment(paymentId: string): Promise { const payment = await this.yookassaService.payments.getById(paymentId); if (payment.status !== PaymentStatusEnum.WAITING_FOR_CAPTURE) { throw new BadRequestException( `Невозможно захватить платеж в статусе ${payment.status}` ); } return this.yookassaService.payments.capture(paymentId); } async cancelPayment(paymentId: string): Promise { const payment = await this.yookassaService.payments.getById(paymentId); if (![PaymentStatusEnum.PENDING, PaymentStatusEnum.WAITING_FOR_CAPTURE] .includes(payment.status as PaymentStatusEnum)) { throw new BadRequestException( `Невозможно отменить платеж в статусе ${payment.status}` ); } return this.yookassaService.payments.cancel(paymentId); } async refundPayment(paymentId: string, reason: string) { const payment = await this.yookassaService.payments.getById(paymentId); if (payment.status !== PaymentStatusEnum.SUCCEEDED) { throw new BadRequestException('Возврат возможен только для успешных платежей'); } return this.yookassaService.refunds.create({ payment_id: paymentId, description: reason }); } } ``` -------------------------------- ### Структура ответа API при отмене платежа Source: https://github.com/teacoder-team/nestjs-yookassa/blob/main/apps/web/content/docs/payments/cancel.mdx Пример JSON-ответа от API Yookassa, содержащего обновленный статус платежа и детали отмены. ```json { "id": "32f3dce3-e775-424f-a265-4e1e86e3db08", "status": "canceled", "amount": { "value": "100.00", "currency": "RUB" }, "cancellation_details": { "party": "merchant", "reason": "canceled_by_merchant" } } ``` -------------------------------- ### Получение списка платежей с пагинацией (TypeScript) Source: https://github.com/teacoder-team/nestjs-yookassa/blob/main/apps/web/content/docs/payments/list.mdx Метод `getAll` из `YookassaService` позволяет получать список платежей с возможностью фильтрации по дате и ограничением количества записей на странице. Требует импорта `YookassaService`. ```typescript import { YookassaService } from 'nestjs-yookassa'; @Injectable() export class PaymentService { constructor(private readonly yookassaService: YookassaService) {} async getPaymentsList() { const limit = 2; // Ограничение на количество платежей const from = '2025-01-01'; // Начальная дата фильтра const to = '2025-01-31'; // Конечная дата фильтра const payments = await this.yookassaService.payments.getAll(limit, from, to); return payments } } ``` -------------------------------- ### Configure Yookassa Module Asynchronously Source: https://github.com/teacoder-team/nestjs-yookassa/blob/main/apps/web/content/docs/getting-started/installation.mdx Shows how to configure the Yookassa module using an asynchronous factory pattern. This is typically used when configuration values must be retrieved from a service or external source like ConfigService. ```typescript useFactory: config => ({ shopId: config.get('YOOKASSA_SHOP_ID'), apiKey: config.get('YOOKASSA_SECRET_KEY'), proxyUrl: config.get('YOOKASSA_PROXY_URL') }) ``` -------------------------------- ### Обработка ошибок API Source: https://github.com/teacoder-team/nestjs-yookassa/blob/main/apps/web/content/docs/payments/confirm.mdx Пример структуры ошибки, возвращаемой API при попытке захвата несуществующего или невалидного платежа. ```json { "statusCode": 400, "message": "Incorrect payment_id. Payment doesn't exist or access denied. Specify the payment ID created in your store." } ``` -------------------------------- ### Вынесение конфигурации Yookassa в отдельный файл Source: https://github.com/teacoder-team/nestjs-yookassa/blob/main/apps/web/content/docs/getting-started/installation.mdx Организация конфигурации Yookassa в отдельном файле (yookassa.config.ts) для улучшения структуры приложения. Использует функцию getYookassaConfig для получения настроек через ConfigService. ```typescript // src/config/yookassa.config.ts import { ConfigService } from '@nestjs/config' import type { YookassaModuleOptions } from 'nestjs-yookassa' export function getYookassaConfig( configService: ConfigService ): YookassaModuleOptions { return { shopId: configService.get('YOOKASSA_SHOP_ID'), apiKey: configService.get('YOOKASSA_SECRET_KEY') } } ``` ```typescript import { Module } from '@nestjs/common' import { ConfigModule, ConfigService } from '@nestjs/config' import { YookassaModule } from 'nestjs-yookassa' import { getYookassaConfig } from './config/yookassa.config' @Module({ imports: [ ConfigModule.forRoot(), YookassaModule.forRootAsync({ imports: [ConfigModule], useFactory: getYookassaConfig, inject: [ConfigService] }) ] }) export class AppModule {} ``` -------------------------------- ### Create Payment Invoice with YookassaService Source: https://context7.com/teacoder-team/nestjs-yookassa/llms.txt Illustrates the creation of a new payment invoice, including defining cart items, setting expiration dates, and metadata. ```typescript import { Injectable } from '@nestjs/common'; import { YookassaService, type CreateInvoiceRequest, type CreateInvoiceResponse } from 'nestjs-yookassa'; @Injectable() export class InvoiceService { constructor(private readonly yookassaService: YookassaService) {} async createInvoice(): Promise { const invoiceData: CreateInvoiceRequest = { amount: { value: '2500.00', currency: 'RUB' }, gateway_id: 'subaccount-id', cart: [ { description: 'Товар 1', price: { value: '1500.00', currency: 'RUB' }, quantity: 1 }, { description: 'Товар 2', price: { value: '500.00', currency: 'RUB' }, quantity: 2 } ], expires_at: '2025-08-30T10:00:00.000Z', metadata: { order_id: '123456' } }; const invoice = await this.yookassaService.invoices.create(invoiceData); return invoice; } } ``` -------------------------------- ### Структура ответа API для списка возвратов Source: https://github.com/teacoder-team/nestjs-yookassa/blob/main/apps/web/content/docs/refunds/list.mdx Пример JSON-ответа от API, содержащего метаданные пагинации (next_cursor) и массив объектов с детальной информацией о каждом возврате. ```json { "type": "list", "next_cursor": "2f1d20e1-0016-5000-8000-12fc2af7f19b", "items": [ { "id": "2f1d29e9-0015-5000-a000-1e7e28fedd75", "payment_id": "2f1d28e4-000f-5000-a000-15f2d944be24", "status": "succeeded", "created_at": "2025-01-18T02:47:05.077Z", "amount": { "value": "529.00", "currency": "RUB" }, "description": "Возврат на заказ с ID 2f1d28e4-000f-5000-a000-15f2d944be24" }, { "id": "2f1d2280-0015-5000-b000-1c02972ec0ef", "payment_id": "2f1d224b-000f-5000-b000-12fc94fd0013", "status": "succeeded", "created_at": "2025-01-18T02:15:28.461Z", "amount": { "value": "529.00", "currency": "RUB" }, "description": "Возврат на заказ с ID 2f1d224b-000f-5000-b000-12fc94fd0013" } ] } ``` -------------------------------- ### Настройка прокси для запросов к API ЮKassa Source: https://github.com/teacoder-team/nestjs-yookassa/blob/main/apps/web/content/docs/getting-started/installation.mdx Настройка использования прокси-сервера для отправки запросов к API ЮKassa через переменную окружения YOOKASSA_PROXY_URL. Поддерживает HTTP и HTTPS прокси. ```bash YOOKASSA_PROXY_URL=http://127.0.0.1:8080 ``` -------------------------------- ### Вызов метода создания счета в NestJS (TypeScript) Source: https://github.com/teacoder-team/nestjs-yookassa/blob/main/apps/web/content/docs/invoices/create.mdx Демонстрирует использование сервиса Yookassa в NestJS для создания счета. Метод createInvoice подготавливает данные и вызывает метод create сервиса invoices. Требуется импорт YookassaService и InvoiceCreateRequest. ```typescript import { type InvoiceCreateRequest, YookassaService } from 'nestjs-yookassa' @Injectable() export class InvoiceService { constructor(private readonly yookassaService: YookassaService) {} async createInvoice() { const invoiceData: InvoiceCreateRequest = { amount: { value: '1000.00', currency: 'RUB' }, gateway_id: 'subaccount-id', cart: [ { description: 'Товар 1', price: { value: '1000.00', currency: 'RUB' }, quantity: 1 } ], expires_at: '2025-08-30T10:00:00.000Z' } const invoice = await this.yookassaService.invoices.create(invoiceData) return invoice } } ``` -------------------------------- ### Пример JSON-ответа для платежа в статусе 'pending' Source: https://github.com/teacoder-team/nestjs-yookassa/blob/main/apps/web/content/docs/payments/info.mdx Пример JSON-ответа от Yookassa API, когда платеж находится в статусе 'pending'. Этот статус указывает, что платеж ожидает обработки или подтверждения от клиента. Включает URL для подтверждения. ```json { "id": "2f1c91cd-000f-5000-8000-1e9f7e4ebff7", "status": "pending", "amount": { "value": "529.00", "currency": "RUB" }, "description": "Test payment", "recipient": { "account_id": "497037", "gateway_id": "2358944" }, "payment_method": { "type": "bank_card", "id": "2f1c91cd-000f-5000-8000-1e9f7e4ebff7", "saved": false, "status": "inactive" }, "created_at": "2025-01-17T15:58:05.278Z", "confirmation": { "type": "redirect", "return_url": "https://example.com/thanks", "confirmation_url": "https://yoomoney.ru/checkout/payments/v2/contract?orderId=2f1c91cd-000f-5000-8000-1e9f7e4ebff7" }, "test": true, "paid": false, "refundable": false, "metadata": { "order_id": "12345678" } } ``` -------------------------------- ### Структура ответа API Yookassa Source: https://github.com/teacoder-team/nestjs-yookassa/blob/main/apps/web/content/docs/payments/confirm.mdx Пример JSON-ответа от API Yookassa после успешного захвата платежа, содержащий детали транзакции, статус и метаданные. ```json { "id": "32f3dce3-e775-424f-a265-4e1e86e3db08", "status": "pending", "amount": { "value": "100.00", "currency": "RUB" }, "captured_at": "2025-01-17T11:45:09.367Z", "paid": true, "metadata": { "order_id": "12345678" } } ``` -------------------------------- ### Асинхронная конфигурация YookassaModule в NestJS Source: https://github.com/teacoder-team/nestjs-yookassa/blob/main/apps/web/content/docs/getting-started/installation.mdx Асинхронная конфигурация YookassaModule с использованием метода forRootAsync(). Позволяет динамически загружать параметры конфигурации, например, через ConfigService. ```typescript import { Module } from '@nestjs/common' import { ConfigModule, ConfigService } from '@nestjs/config' import { YookassaModule } from 'nestjs-yookassa' @Module({ imports: [ ConfigModule.forRoot(), YookassaModule.forRootAsync({ imports: [ConfigModule], inject: [ConfigService], useFactory: async (configService: ConfigService) => ({ shopId: configService.get('YOOKASSA_SHOP_ID'), apiKey: configService.get('YOOKASSA_SECRET_KEY') }) }) ] }) export class AppModule {} ``` -------------------------------- ### Синхронная конфигурация YookassaModule в NestJS Source: https://github.com/teacoder-team/nestjs-yookassa/blob/main/apps/web/content/docs/getting-started/installation.mdx Базовая синхронная конфигурация YookassaModule с использованием метода forRoot(). Требует передачи объекта с shopId и apiKey, полученными из переменных окружения. ```typescript import { Module } from '@nestjs/common'; import { YookassaModule } from 'nestjs-yookassa'; @Module({ imports: [ YookassaModule.forRoot({ shopId: process.env.YOOKASSA_SHOP_ID, apiKey: process.env.YOOKASSA_SECRET_KEY }) ] }) export class AppModule {} ```