### 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('