### Install Robokassa Library Source: https://github.com/bybenpuls/robokassa/blob/master/README.md Installs the Robokassa Python library using pip. This is the first step to using the library for payment integration. ```bash pip install robokassa ``` -------------------------------- ### Initialize Robokassa Client in Python Source: https://context7.com/bybenpuls/robokassa/llms.txt Instantiate the Robokassa client by providing merchant credentials (login and passwords) and configuring the hash algorithm. Supports test and production environments. ```python from robokassa import Robokassa, HashAlgorithm # Initialize client with merchant credentials robokassa = Robokassa( merchant_login="my_shop_login", password1="test_password_1", password2="test_password_2", algorithm=HashAlgorithm.sha256, is_test=True # Use test mode for development ) # Production configuration robokassa_prod = Robokassa( merchant_login="production_login", password1="prod_pass1", password2="prod_pass2", algorithm=HashAlgorithm.sha512, is_test=False ) ``` -------------------------------- ### Configure Robokassa Hash Algorithms in Python Source: https://context7.com/bybenpuls/robokassa/llms.txt Configure different cryptographic hash algorithms for signature generation when initializing the Robokassa client. Supports MD5, SHA-1, SHA-384, SHA-256, SHA-512, and RIPEMD-160. The choice of algorithm affects security and performance. ```python from robokassa import Robokassa, HashAlgorithm # MD5 (default, less secure but faster) robokassa_md5 = Robokassa( merchant_login="shop", password1="pass1", password2="pass2", algorithm=HashAlgorithm.md5, is_test=True ) # SHA-256 (recommended for production) robokassa_sha256 = Robokassa( merchant_login="shop", password1="pass1", password2="pass2", algorithm=HashAlgorithm.sha256, is_test=False ) # SHA-512 (maximum security) robokassa_sha512 = Robokassa( merchant_login="shop", password1="pass1", password2="pass2", algorithm=HashAlgorithm.sha512, is_test=False ) # Other supported algorithms robokassa_sha1 = Robokassa( merchant_login="shop", password1="pass1", password2="pass2", algorithm=HashAlgorithm.sha1, is_test=False ) robokassa_sha384 = Robokassa( merchant_login="shop", password1="pass1", password2="pass2", algorithm=HashAlgorithm.sha384, is_test=False ) robokassa_ripemd160 = Robokassa( merchant_login="shop", password1="pass1", password2="pass2", algorithm=HashAlgorithm.ripemd160, is_test=False ) print(f"Algorithm: {robokassa_sha256.algorithm.value}") print(f"Test mode: {robokassa_sha256.is_test}") ``` -------------------------------- ### Generate Open Payment Link in Python Source: https://context7.com/bybenpuls/robokassa/llms.txt Creates a standard Robokassa payment URL where all parameters are visible. Supports basic and advanced configurations including custom URLs, payment methods, and additional parameters. ```python from robokassa import Robokassa, HashAlgorithm from robokassa.types import HTTPMethod, Culture, PaymentMethod robokassa = Robokassa( merchant_login="demo", password1="password1", password2="password2", algorithm=HashAlgorithm.md5, is_test=True ) # Basic payment link response = robokassa.generate_open_payment_link( out_sum=1500.50, inv_id=12345, description="Order #12345 - Premium Subscription", email="customer@example.com" ) print(response.url) # Output: https://auth.robokassa.ru/Merchant/Index.aspx?MerchantLogin=demo&OutSum=1500.5&InvId=12345&Description=Order... # Advanced payment link with custom parameters and URLs response = robokassa.generate_open_payment_link( out_sum=2500, inv_id=67890, description="Product Purchase", email="user@test.com", culture=Culture.EN, success_url="https://myshop.com/payment/success", success_url_method=HTTPMethod.POST, fail_url="https://myshop.com/payment/fail", fail_url_method=HTTPMethod.GET, result_url="https://myshop.com/api/robokassa/callback", payment_methods=[PaymentMethod.BANK_CARD, PaymentMethod.SBP], user_ip="192.168.1.100", # Custom parameters with shp_ prefix product_id=456, user_id=789, subscription_type="premium" ) print(f"Payment URL: {response.url}") print(f"Invoice ID: {response.params.inv_id}") ``` -------------------------------- ### Generate Open Payment Link with Robokassa Source: https://github.com/bybenpuls/robokassa/blob/master/README.md Demonstrates how to generate an open payment link using the Robokassa Python library. This involves initializing the Robokassa client with merchant credentials and payment details, then calling the generate_open_payment_link method. ```python from robokassa import HashAlgorithm, Robokassa robokassa = Robokassa( merchant_login="my_login", password1="password", password2="password", is_test=False, algorithm=HashAlgorithm.md5, ) payment_link = robokassa.generate_open_payment_link(out_sum=1000, inv_id=0) print(payment_link) ``` -------------------------------- ### Generate Recurring Payment Link with Robokassa Source: https://context7.com/bybenpuls/robokassa/llms.txt Creates a subscription payment link based on a previous recurring payment. This function requires the merchant login, passwords, and hash algorithm configuration. It takes an invoice ID, previous invoice ID, payment amount, and receipt details as input to generate the subscription URL. ```python from robokassa import Robokassa, HashAlgorithm robokassa = Robokassa( merchant_login="subscription_shop", password1="pass1", password2="pass2", algorithm=HashAlgorithm.sha256, is_test=True ) # Generate recurring payment for existing subscription response = robokassa.generate_subscription_link( inv_id=54321, previous_inv_id=12345, # Reference to initial payment out_sum=999.99, receipt={ "sno": "osn", "items": [ { "name": "Monthly Subscription Fee", "quantity": 1, "sum": 999.99, "payment_method": "full_payment", "payment_object": "service", "tax": "vat20" } ] } ) print(f"Subscription payment URL: {response.url}") ``` -------------------------------- ### Generate Protected Payment Link Asynchronously Source: https://github.com/bybenpuls/robokassa/blob/master/README.md Shows how to generate a protected payment link asynchronously using the Robokassa Python library. This method supports different invoice types, such as reusable ones, and requires the Robokassa client to be initialized. ```python from robokassa.types import InvoiceType # Assuming 'robokassa' is an initialized Robokassa instance my_link = await robokassa.generate_protected_payment_link( invoice_type=InvoiceType.REUSABLE, inv_id=233, out_sum=1000 ) ``` -------------------------------- ### Generate Protected Payment Link (JWT) in Python Source: https://context7.com/bybenpuls/robokassa/llms.txt Generates a secure, JWT-based payment link where transaction details are hidden from the user. Requires an asynchronous context and is primarily for production use. ```python import asyncio from robokassa import Robokassa, HashAlgorithm from robokassa.types import InvoiceType, HTTPMethod async def create_protected_link(): robokassa = Robokassa( merchant_login="shop_login", password1="password1", password2="password2", algorithm=HashAlgorithm.sha256, is_test=False # Protected links only work in production ) # Generate JWT-based payment link response = await robokassa.generate_protected_payment_link( invoice_type=InvoiceType.ONE_TIME, out_sum=5000.00, inv_id=99999, merchant_comments="Internal order reference #ABC-123", description="Annual Subscription Payment", email="premium.user@example.com", success_url="https://myshop.com/payment/success", success_url_method=HTTPMethod.POST, fail_url="https://myshop.com/payment/fail", fail_url_method=HTTPMethod.GET, # Fiscal receipt data for Russian tax compliance receipt={ "sno": "osn", "items": [ { "name": "Annual Subscription", "quantity": 1, "sum": 5000.00, "payment_method": "full_payment", "payment_object": "service", "tax": "vat20" } ] }, # Custom user fields customer_id=12345, order_type="subscription" ) print(f"Protected payment URL: {response.url}") print(f"Invoice ID: {response.params.id}") return response ``` -------------------------------- ### Check Robokassa Payment Status Source: https://context7.com/bybenpuls/robokassa/llms.txt Queries the current status of a payment operation by invoice ID. This asynchronous function initializes the Robokassa client with appropriate credentials and hash algorithm. It then calls `get_payment_details` with the invoice ID and prints various details about the payment state, amounts, dates, and custom fields. ```python import asyncio from robokassa import Robokassa, HashAlgorithm from robokassa.types import PaymentState async def check_payment(): robokassa = Robokassa( merchant_login="merchant", password1="pass1", password2="pass2", algorithm=HashAlgorithm.sha512, is_test=False ) try: # Get payment details by invoice ID details = await robokassa.get_payment_details(inv_id=12345) print(f"Payment State: {details.state.name}") print(f"Amount: {details.out_sum} {details.out_curr_label}") print(f"Received: {details.inc_sum} {details.inc_curr_label}") print(f"Request Date: {details.request_date}") print(f"State Date: {details.state_date}") print(f"Operation Key: {details.op_key}") print(f"Custom Fields: {details.user_fields}") # Check payment state if details.state == PaymentState.COMPLETED: print("Payment successfully completed!") elif details.state == PaymentState.PENDING: print("Payment is still pending...") elif details.state == PaymentState.FAILED: print("Payment failed") elif details.state == PaymentState.CANCELLED: print("Payment was cancelled") except Exception as e: print(f"Error checking payment: {e}") asyncio.run(check_payment()) ``` -------------------------------- ### Validate Robokassa Payment Callback Signature Source: https://context7.com/bybenpuls/robokassa/llms.txt Verifies the authenticity of success or fail redirect callbacks from Robokassa. This function requires Robokassa configuration and the signature data received from the callback. It uses password1 for validation and returns a boolean indicating whether the signature is valid. ```python from robokassa import Robokassa, HashAlgorithm robokassa = Robokassa( merchant_login="my_shop", password1="password1", password2="password2", algorithm=HashAlgorithm.md5, is_test=True ) # Simulate callback data from success redirect callback_data = { "OutSum": "1500.50", "InvId": "12345", "SignatureValue": "a1b2c3d4e5f6g7h8i9j0", "shp_product_id": "789", "shp_user_id": "456" } # Validate signature (use password1 for success/fail URLs) is_valid = robokassa.is_redirect_valid( signature=callback_data["SignatureValue"], out_sum=callback_data["OutSum"], inv_id=callback_data["InvId"], shp_product_id=callback_data["shp_product_id"], shp_user_id=callback_data["shp_user_id"] ) if is_valid: print("Payment verified successfully!") # Process successful payment else: print("Invalid signature - possible fraud attempt") # Reject payment ``` -------------------------------- ### Validate Robokassa Result URL Notification Source: https://context7.com/bybenpuls/robokassa/llms.txt Verifies server-to-server payment notification callbacks using password2. This asynchronous function handles POST requests, extracts data, and validates the signature using Robokassa's `is_result_notification_valid` method. It returns an 'OK' response upon successful validation or an error response otherwise. ```python from robokassa import Robokassa, HashAlgorithm from aiohttp import web robokassa = Robokassa( merchant_login="webshop", password1="password1", password2="password2", algorithm=HashAlgorithm.sha256, is_test=True ) async def handle_result_notification(request): """Handle Robokassa server-to-server callback""" post_data = await request.post() # Validate result notification signature (uses password2) is_valid = robokassa.is_result_notification_valid( signature=post_data["SignatureValue"].lower(), out_sum=post_data["OutSum"], inv_id=post_data["InvId"], shp_order_id=post_data.get("shp_order_id"), shp_customer_id=post_data.get("shp_customer_id") ) if is_valid: # Process payment confirmation order_id = post_data.get("shp_order_id") print(f"Payment confirmed for order {order_id}") # Update database, send confirmation email, etc. # Must return "OK{InvId}" for successful processing return web.Response(text=f"OK{post_data['InvId']}") else: print("Invalid notification signature") return web.Response(text="bad sign", status=400) # Add route to aiohttp application app = web.Application() app.router.add_post("/payment/robokassa/result", handle_result_notification) ``` -------------------------------- ### Deactivate Protected Invoice with Robokassa Python Source: https://context7.com/bybenpuls/robokassa/llms.txt Cancel an active protected payment invoice before it expires or is paid. Supports deactivation by invoice ID, encoded ID from a URL, or internal API ID. Requires the `robokassa` library and an asyncio event loop. ```python import asyncio from robokassa import Robokassa, HashAlgorithm async def deactivate_invoice(): robokassa = Robokassa( merchant_login="shop_login", password1="password1", password2="password2", algorithm=HashAlgorithm.sha256, is_test=False ) # Deactivate by invoice ID try: await robokassa.deactivate_invoice(inv_id=12345) print("Invoice deactivated successfully") except Exception as e: print(f"Failed to deactivate: {e}") # Alternative: deactivate by encoded ID from URL # URL: https://auth.robokassa.ru/merchant/Invoice/6hucaX7-BkKNi4lyi-Iu2g try: await robokassa.deactivate_invoice( encoded_id="6hucaX7-BkKNi4lyi-Iu2g" ) print("Invoice deactivated by encoded ID") except Exception as e: print(f"Failed to deactivate: {e}") # Alternative: deactivate by internal ID returned from API try: await robokassa.deactivate_invoice( id="f47ac10b-58cc-4372-a567-0e02b2c3d479" ) print("Invoice deactivated by internal ID") except Exception as e: print(f"Failed to deactivate: {e}") asyncio.run(deactivate_invoice()) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.