### Install Robokassa Package Source: https://context7.com/dev-aces/robokassa/llms.txt Installs the Robokassa Node.js integration package using npm. This is the initial step before using any of its functionalities. ```bash npm install @dev-aces/robokassa ``` -------------------------------- ### Generate Recurring Payment URL - First Payment (TypeScript) Source: https://context7.com/dev-aces/robokassa/llms.txt Initiates a recurring payment setup by generating a URL for the first payment in a subscription. Requires the '@dev-aces/robokassa' library. Sets the 'recurring' flag to true to enable future automatic charges. Note that this feature requires prior agreement with Robokassa. ```typescript import { Robokassa } from '@dev-aces/robokassa'; const robokassa = new Robokassa({ merchantLogin: 'my_merchant_login', password1: 'my_password_1', password2: 'my_password_2' }); // First payment with recurring flag const initialPaymentUrl = robokassa.generatePaymentUrl({ outSum: 999, description: 'Monthly subscription - first payment', invId: 10001, recurring: true, // Saves card data for future charges userParameters: { shp_subscription_id: 'sub-12345', shp_user_id: '67890' }, receipt: { items: [ { name: 'Monthly subscription', sum: 999, quantity: 1, tax: 'none', payment_method: 'full_payment', payment_object: 'service' } ] } }); // After successful payment, use InvId 10001 for future recurring charges // Note: recurring requires prior agreement with Robokassa // Cannot be used with IncCurrLabel, ExpirationDate, or PreviousInvoiceID ``` -------------------------------- ### Generate Payment URL with Custom Parameters (TypeScript) Source: https://context7.com/dev-aces/robokassa/llms.txt Generates a payment URL that includes custom user parameters, which are returned to the server upon successful payment completion. Parameters must start with 'shp_'. ```typescript import { Robokassa } from '@dev-aces/robokassa'; const robokassa = new Robokassa({ merchantLogin: 'my_merchant_login', password1: 'my_password_1', password2: 'my_password_2' }); const paymentUrl = robokassa.generatePaymentUrl({ outSum: 500, description: 'Course enrollment', invId: 2042, // Custom parameters must start with "shp_", "Shp_" or "SHP_" // These will be returned unchanged after payment userParameters: { shp_user_id: '12345', shp_course_id: 'nodejs-advanced', shp_referral: 'promo2024' }, email: 'user@example.com', culture: 'en', // Interface language: 'ru' or 'en' incCurrLabel: 'BankCard' // Suggested payment method }); // Generated URL includes all parameters with proper encoding // After payment, Robokassa will return shp_user_id, shp_course_id, and shp_referral ``` -------------------------------- ### Validate Robokassa Webhook (TypeScript) Source: https://context7.com/dev-aces/robokassa/llms.txt Verifies and processes payment confirmation webhooks from Robokassa on your server using the @dev-aces/robokassa library. It checks the payment signature and extracts relevant details like invoice ID, amount, and custom parameters. This basic example focuses on signature validation and logging. ```typescript import { Robokassa, IRobokassaResponse } from '@dev-aces/robokassa'; import express, { Request, Response } from 'express'; const robokassa = new Robokassa({ merchantLogin: 'my_merchant_login', password1: 'my_password_1', password2: 'my_password_2' // Uses password2 for webhook validation }); const app = express(); app.use(express.urlencoded({ extended: true })); app.use(express.json()); // Configure this URL as Result URL in Robokassa settings (POST method recommended) app.post('/payment/result', function (req: Request, res: Response) { const robokassaResponse = req.body as IRobokassaResponse; // Validate signature using password2 if (robokassa.checkPayment(robokassaResponse)) { console.log('Payment verified successfully'); // Extract payment details const { InvId, // Invoice ID OutSum, // Payment amount Fee, // Robokassa commission EMail, // Customer email (note: EMail, not Email) PaymentMethod,// Payment method used (e.g., 'BankCard') IncCurrLabel, // Currency used shp_user_id, // Your custom parameters shp_course_id } = robokassaResponse; // Process successful payment // Update database, grant access, send confirmation email, etc. console.log(`Invoice ${InvId}: ${OutSum} RUB paid (fee: ${Fee})`); console.log(`User: ${shp_user_id}, Course: ${shp_course_id}`); // REQUIRED: Return success response to Robokassa res.send(`OK${InvId}`); } else { console.error('Invalid signature - possible fraud attempt'); // Return failure response res.send('Failure'); } }); app.listen(3000, () => { console.log('Payment webhook server running on port 3000'); }); // Expected POST body from Robokassa: // { // InvId: 1001, // OutSum: '150.00', // Fee: '5.25', // EMail: 'user@example.com', // SignatureValue: 'a1b2c3d4e5f6...', // PaymentMethod: 'BankCard', // IncCurrLabel: 'RUR', // shp_user_id: '12345', // shp_course_id: 'nodejs-advanced' // } ``` -------------------------------- ### Initialize Robokassa Client (TypeScript) Source: https://context7.com/dev-aces/robokassa/llms.txt Initializes the Robokassa client with merchant credentials and configuration options. Supports test and production environments, and allows specifying hash algorithms. ```typescript import { Robokassa } from '@dev-aces/robokassa'; const robokassa = new Robokassa({ merchantLogin: 'my_merchant_login', password1: 'my_password_1', password2: 'my_password_2', hashAlgorithm: 'md5', // optional, default: 'md5' isTest: false, // optional, default: false url: 'https://auth.robokassa.ru/Merchant/Index.aspx' // optional, default URL }); // For testing environment const testRobokassa = new Robokassa({ merchantLogin: 'test_merchant', password1: 'test_password_1', password2: 'test_password_2', isTest: true, hashAlgorithm: 'sha256' }); ``` -------------------------------- ### Generate Basic Payment URL (TypeScript) Source: https://context7.com/dev-aces/robokassa/llms.txt Creates a payment URL for redirecting users to the Robokassa payment page. Requires minimum parameters like amount, description, and invoice ID. ```typescript import { Robokassa } from '@dev-aces/robokassa'; const robokassa = new Robokassa({ merchantLogin: 'my_merchant_login', password1: 'my_password_1', password2: 'my_password_2' }); // Basic payment const paymentUrl = robokassa.generatePaymentUrl({ outSum: '150.00', // or outSum: 150 (number type) description: 'Premium subscription', invId: 1001 }); // Redirect user to: paymentUrl // Example output: // https://auth.robokassa.ru/Merchant/Index.aspx?MerchantLogin=my_merchant_login&Description=Premium%20subscription&InvId=1001&OutSum=150.00&SignatureValue=... ``` -------------------------------- ### Generate Payment URL with Advanced Options (TypeScript) Source: https://context7.com/dev-aces/robokassa/llms.txt Creates a payment URL with advanced options such as currency conversion, invoice expiration, IP tracking, and detailed receipt information. Requires the '@dev-aces/robokassa' library. Handles currency conversion automatically and supports custom user parameters. ```typescript import { Robokassa } from '@dev-aces/robokassa'; const robokassa = new Robokassa({ merchantLogin: 'my_merchant_login', password1: 'my_password_1', password2: 'my_password_2' }); const paymentUrl = robokassa.generatePaymentUrl({ outSum: '100.00', outSumCurrency: 'USD', // Robokassa will auto-convert to RUB description: 'International subscription', invId: 5001, culture: 'en', encoding: 'utf-8', email: 'customer@example.com', userIp: '192.168.1.100', // Enhances security and fraud prevention incCurrLabel: 'BankCard', // Suggested payment method expirationDate: '2026-12-31T23:59:59.0000000+03:00', // Invoice expiration receipt: { sno: 'usn_income', items: [ { name: 'Premium subscription', sum: 100, quantity: 1, tax: 'none', payment_method: 'full_payment', payment_object: 'service', cost: 100 // Price per unit (alternative to sum) } ] }, userParameters: { shp_subscription_type: 'premium', shp_duration_months: '12' } }); // All parameters are properly encoded and signed ``` -------------------------------- ### Generate Payment URL with Fiscalization (TypeScript) Source: https://context7.com/dev-aces/robokassa/llms.txt Creates a payment URL that includes fiscal receipt details, fulfilling Russian legal requirements for online services. Supports specifying tax systems and item details. ```typescript import { Robokassa } from '@dev-aces/robokassa'; const robokassa = new Robokassa({ merchantLogin: 'my_merchant_login', password1: 'my_password_1', password2: 'my_password_2' }); const paymentUrl = robokassa.generatePaymentUrl({ outSum: 1500, description: 'Software development services', invId: 3001, // Fiscal receipt for tax compliance receipt: { sno: 'usn_income', // Tax system: 'osn' | 'usn_income' | 'usn_income_outcome' | 'esn' | 'patent' items: [ { name: 'Web development', sum: 1000, quantity: 1, tax: 'none', // 'none' | 'vat0' | 'vat10' | 'vat20' | 'vat110' | 'vat120' payment_method: 'full_payment', // How the payment is made payment_object: 'service', // Type of item: 'commodity' | 'service' | 'job' | etc. }, { name: 'Design services', sum: 500, quantity: 1, tax: 'vat20', payment_method: 'full_payment', payment_object: 'service' } ] }, userParameters: { shp_project_id: 'proj-456' } }); // Receipt data is automatically JSON-encoded and included in the URL ``` -------------------------------- ### Robokassa Full Payment Flow with Express.js Source: https://context7.com/dev-aces/robokassa/llms.txt Implements a complete payment flow using Express.js. It handles payment initiation by generating a payment URL, redirects the user, and processes payment confirmations via webhooks. The webhook handling includes signature verification and extraction of custom user parameters. ```typescript import { Robokassa, IRobokassaResponse } from '@dev-aces/robokassa'; import express, { Request, Response } from 'express'; const robokassa = new Robokassa({ merchantLogin: 'my_merchant_login', password1: 'my_password_1', password2: 'my_password_2', isTest: false }); const app = express(); app.use(express.json()); app.use(express.urlencoded({ extended: true })); // Step 1: User initiates payment app.post('/api/purchase', (req: Request, res: Response) => { const { userId, productId, amount, productName } = req.body; // Create invoice in your database const invoiceId = Math.floor(Math.random() * 2147483647); // Generate payment URL const paymentUrl = robokassa.generatePaymentUrl({ outSum: amount, description: productName, invId: invoiceId, userParameters: { shp_user_id: userId.toString(), shp_product_id: productId.toString() }, receipt: { items: [ { name: productName, sum: amount, quantity: 1, tax: 'none', payment_method: 'full_payment', payment_object: 'service' } ] } }); // Return URL to frontend res.json({ success: true, paymentUrl: paymentUrl, invoiceId: invoiceId }); // Frontend redirects user: window.location.href = paymentUrl }); // Step 2: Robokassa calls this webhook after successful payment app.post('/webhooks/robokassa/result', (req: Request, res: Response) => { const payment = req.body as IRobokassaResponse; if (robokassa.checkPayment(payment)) { // Extract custom parameters const userId = payment.shp_user_id; const productId = payment.shp_product_id; // Update order status, grant access, etc. console.log(`Payment confirmed: User ${userId} purchased product ${productId}`); console.log(`Amount: ${payment.OutSum} RUB (Fee: ${payment.Fee})`); // Required response format res.send(`OK${payment.InvId}`); } else { console.error('Invalid payment signature'); res.send('Failure'); } }); // Step 3: Success URL - redirect user after payment app.get('/payment/success', (req: Request, res: Response) => { res.send('

Payment successful! Thank you for your purchase.

'); }); // Step 4: Failure URL - redirect if payment failed app.get('/payment/failure', (req: Request, res: Response) => { res.send('

Payment failed. Please try again.

'); }); app.listen(3000, () => { console.log('Server running on http://localhost:3000'); }); // Configure in Robokassa dashboard: // Result URL (POST): https://yourdomain.com/webhooks/robokassa/result // Success URL: https://yourdomain.com/payment/success // Failure URL: https://yourdomain.com/payment/failure ``` -------------------------------- ### Generate Recurring Payment URL - Subsequent Payments (TypeScript) Source: https://context7.com/dev-aces/robokassa/llms.txt Generates a URL for subsequent automatic subscription charges using the original payment's invoice ID. Requires the '@dev-aces/robokassa' library and a specific 'Recurring' endpoint. Both 'invId' (new unique ID) and 'previousInvoiceId' are mandatory for this operation. ```typescript import { Robokassa } from '@dev-aces/robokassa'; const robokassa = new Robokassa({ merchantLogin: 'my_merchant_login', password1: 'my_password_1', password2: 'my_password_2', url: 'https://auth.robokassa.ru/Merchant/Recurring' // Different URL for recurring }); // Subsequent automatic charge const recurringPaymentUrl = robokassa.generatePaymentUrl({ outSum: 999, description: 'Monthly subscription - renewal', invId: 10002, // New unique invoice ID previousInvoiceId: 10001, // Reference to the original payment with recurring: true userParameters: { shp_subscription_id: 'sub-12345', shp_billing_period: 'february-2026' }, receipt: { items: [ { name: 'Monthly subscription renewal', sum: 999, quantity: 1, tax: 'none', payment_method: 'full_payment', payment_object: 'service' } ] } }); // This will charge the saved card without user interaction // Both invId and previousInvoiceId are required // invId must be unique and non-zero // previousInvoiceId is NOT included in signature calculation ``` -------------------------------- ### Robokassa TypeScript Type Definitions Source: https://context7.com/dev-aces/robokassa/llms.txt Defines TypeScript interfaces for various Robokassa integration points. This includes configuration options, order details, receipt items, and the structure of the webhook response, enabling type-safe development. ```typescript import { Robokassa, IRobokassaInitOptions, IRobokassaOrder, IRobokassaResponse, IRobokassaReceipt, IRobokassaReceiptItem } from '@dev-aces/robokassa'; // Configuration options const options: IRobokassaInitOptions = { merchantLogin: 'my_merchant', password1: 'pass1', password2: 'pass2', hashAlgorithm: 'sha256', // optional: 'md5' | 'sha1' | 'sha256' | 'sha384' | 'sha512' | 'ripemd160' isTest: false, // optional url: 'https://auth.robokassa.ru/Merchant/Index.aspx' // optional }; // Payment order structure const order: IRobokassaOrder = { description: 'Product name', outSum: 1000, invId: 123, outSumCurrency: 'USD', // optional: 'USD' | 'EUR' | 'KZT' culture: 'en', // optional: 'ru' | 'en' email: 'user@example.com', userParameters: { shp_custom_field: 'value' }, receipt: { sno: 'usn_income', items: [] } }; // Receipt item structure const receiptItem: IRobokassaReceiptItem = { name: 'Service name', sum: 1000, quantity: 1, tax: 'none', // 'none' | 'vat0' | 'vat10' | 'vat20' | 'vat110' | 'vat120' payment_method: 'full_payment', payment_object: 'service', cost: 1000, // optional, alternative to sum nomenclature_code: '1234567890' // optional, required for marked goods }; // Webhook response structure const handleWebhook = (response: IRobokassaResponse) => { const invId: number = response.InvId; const outSum: string = response.OutSum; const fee: string = response.Fee; const email: string | undefined = response.EMail; // Note: EMail, not Email const signature: string = response.SignatureValue; const paymentMethod: string = response.PaymentMethod; const currency: string = response.IncCurrLabel; // Custom parameters are automatically typed const customParam: string = response.shp_custom_field; }; ``` -------------------------------- ### Robust Robokassa Webhook Validation with Error Handling (TypeScript) Source: https://context7.com/dev-aces/robokassa/llms.txt Implements comprehensive Robokassa webhook validation with proper error handling and logging using the @dev-aces/robokassa library and Express.js. This snippet includes checks for payment idempotency and integrates with a mock database and access granting function. ```typescript import { Robokassa, IRobokassaResponse } from '@dev-aces/robokassa'; import express, { Request, Response } from 'express'; const robokassa = new Robokassa({ merchantLogin: 'my_merchant_login', password1: 'my_password_1', password2: 'my_password_2' }); const app = express(); app.use(express.json()); app.use(express.urlencoded({ extended: true })); app.post('/payment/result', async (req: Request, res: Response) => { try { const payment = req.body as IRobokassaResponse; // Log incoming webhook console.log('Received payment webhook:', { invId: payment.InvId, outSum: payment.OutSum, timestamp: new Date().toISOString() }); // Validate signature if (!robokassa.checkPayment(payment)) { console.error('Signature validation failed:', { invId: payment.InvId, receivedSignature: payment.SignatureValue }); return res.status(400).send('Failure'); } // Check if payment already processed (idempotency) const existingPayment = await database.getPaymentByInvoiceId(payment.InvId); if (existingPayment) { console.log('Payment already processed:', payment.InvId); return res.send(`OK${payment.InvId}`); } // Process payment await database.savePayment({ invoiceId: payment.InvId, amount: parseFloat(payment.OutSum), fee: parseFloat(payment.Fee), email: payment.EMail, paymentMethod: payment.PaymentMethod, userId: payment.shp_user_id, status: 'completed', processedAt: new Date() }); // Grant access or perform business logic await grantUserAccess(payment.shp_user_id, payment.shp_course_id); console.log('Payment processed successfully:', payment.InvId); // Must return OK[InvId] format res.send(`OK${payment.InvId}`); } catch (error) { console.error('Payment processing error:', error); res.status(500).send('Failure'); } }); // Mock functions for example const database = { getPaymentByInvoiceId: async (id: number) => null, savePayment: async (data: any) => {} }; const grantUserAccess = async (userId: string, courseId: string) => { console.log(`Granting access: User ${userId} -> Course ${courseId}`); }; app.listen(3000); ``` -------------------------------- ### POST /payment/result - Advanced Webhook Validation with Error Handling Source: https://context7.com/dev-aces/robokassa/llms.txt This endpoint provides a more robust implementation for handling Robokassa webhooks. It includes comprehensive error handling, logging, checks for payment idempotency, and simulates database operations and user access grants. ```APIDOC ## POST /payment/result (Advanced) ### Description Handles Robokassa payment webhooks with advanced error handling, logging, and idempotency checks. It simulates database operations and grants user access upon successful payment verification. ### Method POST ### Endpoint /payment/result ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **InvId** (number) - Required - Invoice ID. - **OutSum** (string) - Required - Payment amount. - **Fee** (string) - Required - Robokassa commission. - **EMail** (string) - Required - Customer email. - **SignatureValue** (string) - Required - The signature to validate. - **PaymentMethod** (string) - Optional - Payment method used. - **IncCurrLabel** (string) - Optional - Currency used. - **shp_user_id** (string) - Optional - Your custom parameter for user ID. - **shp_course_id** (string) - Optional - Your custom parameter for course ID. ### Request Example ```json { "InvId": 1001, "OutSum": "150.00", "Fee": "5.25", "EMail": "user@example.com", "SignatureValue": "a1b2c3d4e5f6...", "PaymentMethod": "BankCard", "IncCurrLabel": "RUR", "shp_user_id": "12345", "shp_course_id": "nodejs-advanced" } ``` ### Response #### Success Response (200) - **OK[InvId]** (string) - Confirmation message format required by Robokassa, e.g., `OK1001`. #### Response Example ``` OK1001 ``` #### Failure Response (400 or 500) - **Failure** (string) - Indicates that the signature validation failed or an internal error occurred. ``` -------------------------------- ### POST /payment/result - Basic Webhook Validation Source: https://context7.com/dev-aces/robokassa/llms.txt This endpoint validates incoming payment confirmation webhooks from Robokassa using the provided signature. It logs the payment details upon successful verification and sends a required success response to Robokassa. ```APIDOC ## POST /payment/result ### Description Verifies and processes payment confirmation webhooks from Robokassa on your server. It checks the signature and logs basic payment details. ### Method POST ### Endpoint /payment/result ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **InvId** (number) - Required - Invoice ID. - **OutSum** (string) - Required - Payment amount. - **Fee** (string) - Required - Robokassa commission. - **EMail** (string) - Required - Customer email. - **SignatureValue** (string) - Required - The signature to validate. - **PaymentMethod** (string) - Optional - Payment method used. - **IncCurrLabel** (string) - Optional - Currency used. - **shp_user_id** (string) - Optional - Your custom parameter for user ID. - **shp_course_id** (string) - Optional - Your custom parameter for course ID. ### Request Example ```json { "InvId": 1001, "OutSum": "150.00", "Fee": "5.25", "EMail": "user@example.com", "SignatureValue": "a1b2c3d4e5f6...", "PaymentMethod": "BankCard", "IncCurrLabel": "RUR", "shp_user_id": "12345", "shp_course_id": "nodejs-advanced" } ``` ### Response #### Success Response (200) - **OK[InvId]** (string) - Confirmation message format required by Robokassa, e.g., `OK1001`. #### Response Example ``` OK1001 ``` #### Failure Response (400 or 500) - **Failure** (string) - Indicates that the signature validation failed or an internal error occurred. ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.