Integrating CCAvenue Payment Gateway’s API with Python in Simple Step
In today’s digital age, where e-commerce is flourishing, integrating a secure payment gateway into your web application is important to facilitate smooth and secure transactions. One such popular payment gateway in India is CCAvenue, which is known for its strength and reliability. In this guide, we’ll explore how to integrate the CCAvenue payment gateway API into your backend using Python, along with encryption and decryption techniques for increased security.
Understanding CCAvenue Encryption and Decryption
Before diving into the integration process, let’s grasp the encryption and decryption mechanism employed by CCAvenue. CCAvenue utilizes AES (Advanced Encryption Standard) with CBC (Cipher Block Chaining) mode for securing data transmission. This involves encrypting JSON-formatted request data using a working key and an initialization vector (IV) before sending it to CCAvenue’s servers. Upon receiving the encrypted data, CCAvenue decrypts it using the provided working key, ensuring the confidentiality and integrity of the transmitted information.
Prerequisites
To follow along with this guide, make sure you have the following prerequisites:
- Basic knowledge of Python programming.
- Python installed on your system (preferably Python 3.x).
- Necessary Python libraries installed:
- binascii
- Crypto
- hashlib
- json
- requests
Now, let’s delve into the integration process step by step.
Step 1: Setting Up Encryption and Decryption Class
We begin by defining a Python class `CCAvenueEncryptDecrypt` that encapsulates methods for encryption and decryption using AES with CBC mode. This class handles key management, padding, encryption, and decryption functionalities. Ensure that you have this class defined in your backend codebase.
from binascii import unhexlify
from Crypto.Cipher import AES
from binascii import hexlify
from hashlib import md5
import json
class CCAvenueEncryptDecrypt:
"""Class for encrypting and decrypting data using AES with CBC mode.
This class provides methods for encrypting and decrypting JSON data using AES with CBC mode.
It uses a provided working key for encryption and decryption.
Attributes:
__IV (str): The initialization vector used for AES encryption.
__KEY (str): The working key used for AES encryption and decryption.
Methods:
__init__(working_key): Initializes the CCAvenueEncryptDecrypt instance with the given working key.
getkey(): Returns the working key used for encryption and decryption.
enc_dec_cipher(): Returns an AES cipher object configured for encryption and decryption.
pad(data): Pads the input data to a multiple of the AES block size.
encrypt(request_data): Encrypts a JSON-formatted request data.
decrypt(cipherText): Decrypts the given ciphertext and returns the original JSON data.
"""
def __init__(self, working_key) -> None:
"""Initialize the CCAvenueEncryptDecrypt instance with the given working key.
Args:
working_key (str): The working key used for AES encryption and decryption.
"""
self.__IV = '\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f'
self.__KEY = working_key
def getkey(self):
"""Return the working key used for encryption and decryption."""
return self.__KEY
def pad(self, data):
"""Pad the input data to a multiple of the AES block size."""
length = 16 - (len(data) % 16)
data += chr(length)*length
return data
def encrypt(self, request_data : dict):
"""Encrypt the given JSON-formatted request data.
Args:
request_data (dict): The request data to be encrypted, formatted as a dictionary.
Returns:
str: The encrypted ciphertext in hexadecimal format.
"""
plainText = self.pad(json.dumps(request_data))
enc_cipher = self.enc_dec_ciper()
return hexlify(enc_cipher.encrypt(plainText.encode("utf-8"))).decode("utf-8")
def enc_dec_ciper(self):
"""Return an AES cipher object configured for encryption and decryption."""
bytearrayWorkingKey = bytearray()
bytearrayWorkingKey.extend(map(ord, self.__KEY))
return AES.new(
md5(bytearrayWorkingKey).digest(),
AES.MODE_CBC,
self.__IV.encode("utf-8"),
)
def decrypt(self, cipherText : str):
"""Decrypt the given ciphertext and return the original JSON data.
Args:
cipherText (str): The ciphertext to be decrypted, in hexadecimal format.
Returns:
dict: The original JSON-formatted data decrypted from the ciphertext.
"""
dec_cipher = self.enc_dec_ciper()
decryptedText = dec_cipher.decrypt(unhexlify(cipherText))
padding_length = decryptedText[-1]
decryptedText = decryptedText[:-padding_length]
return json.loads(decryptedText.decode("utf-8"))
Step 2: Configuring CCAvenue Parameters
Before making any API calls, you need to configure essential parameters such as `WORKING_KEY`, `ACCESS_CODE`, `MERCHANT_CODE`, `REDIRECT_URL`, and `CANCEL_URL`. These parameters are provided by CCAvenue upon registration. Replace the empty strings (“ ”) with your actual credentials.
WORKING_KEY = " "
ACCESS_CODE = " "
MERCHANT_CODE = " "
REDIRECT_URL = " "
CANCEL_URL = " "
Step 3: Encrypting Request Data
To initiate a transaction, you need to encrypt the request data using the `encrypt()` method provided by the `CCAvenueEncryptDecrypt` class. Construct your request data as a dictionary and pass it to the `encrypt()` method.
ccavenue = CCAvenueEncryptDecrypt(WORKING_KEY)
data = {
"reference_no": ""
}
encrypt_data = ccavenue.encrypt(data)
Step 4: Sending Encrypted Request to CCAvenue
Now, prepare the request payload by assembling the encrypted data along with other necessary parameters. Then, make a POST request to the CCAvenue API endpoint.
import requests
url = "https://apitest.ccavenue.com/apis/servlet/DoWebTrans"
payload = {
"request_type": "JSON",
"access_code": ACCESS_CODE,
"command": "orderStatusTracker",
"version": "1.2",
"response_type": "JSON",
"enc_request": encrypted_data
}
response = requests.post(url, data=payload, headers={})
Step 5: Handling Response
Upon receiving the response from CCAvenue, you need to parse it accordingly. If the request is successful and status = 1, extract the enc_response and enc_error_code to know the error’s message from the documentation. Otherwise, decrypt the enc_response data to retrieve the relevant details.
information = response.text.split('&')
data_size = len(information)
status1 = information[0].split('=')
status2 = information[1].split('=')
if status1[1] == '1':
record_data = status2[1]
else:
decrypted_response = ccavenue.decrypt(status2[1].strip())
# Further processing of decrypted response
print(decrypted_response)
Conclusion
Integrating CCAvenue Payment Gateway API into your backend empowers your web application with secure and reliable transaction capabilities. By leveraging AES encryption with CBC mode and following the steps outlined in this guide, you can seamlessly incorporate payment processing functionalities into your Python-based applications. Remember to adhere to best practices for handling sensitive data and ensure compliance with relevant security standards.
For more detailed information and API documentation, visit CCAvenue Developer Portal.
For Front-end Integration, Click here.
For Back-end Integration, Click here.
Happy coding!