
# for Staging
# url = "https://securegw-stage.paytm.in/theia/api/v1/initiateTransaction?mid=YOUR_MID_HERE&orderId=ORDERID_98765"

# for Production
# url = "https://securegw.paytm.in/theia/api/v1/initiateTransaction?mid=YOUR_MID_HERE&orderId=ORDERID_98765"

import json
import requests
from datetime import datetime
from Crypto.Cipher import AES
from Crypto.Random import get_random_bytes
import base64
import hashlib

# Paytm configuration
PAYTM_MERCHANT_KEY = 'RdSOMK30068535532554'
PAYTM_MID = 'RdSOMK30068535532554'
PAYTM_WEBSITE = 'zirupay.in'
PAYTM_INITIATE_TRANSACTION_URL = 'https://securegw-stage.paytm.in/theia/api/v1/initiateTransaction?mid={}&orderId={}'
PAYTM_CALLBACK_URL = 'https://zirupay.in/'

# Function to generate checksum hash
def generate_checksum(params, merchant_key):
    params_string = '&'.join(['{}={}'.format(k, v) for k, v in sorted(params.items())])
    salt = ''.join([chr(ord('A') + c % 26) for c in get_random_bytes(4)])
    final_string = '{}|{}'.format(params_string, salt)

    hasher = hashlib.sha256(final_string.encode('utf-8')).digest()
    key = merchant_key.encode('utf-8').ljust(32, b'\0')[:32]  # Ensure key length is 32 bytes for AES-256
    cipher = AES.new(key, AES.MODE_ECB)
    checksum = base64.b64encode(cipher.encrypt(hasher)).decode('utf-8')

    return checksum


# Function to initiate transaction
def initiate_transaction(order_id, customer_id, txn_amount):
    headers = {
        'Content-Type': 'application/json'
    }

    body = {
        'mid': PAYTM_MID,
        'websiteName': PAYTM_WEBSITE,
        'orderId': order_id,
        'callbackUrl': PAYTM_CALLBACK_URL,
        'txnAmount': {
            'value': txn_amount,
            'currency': 'INR',
        },
        'userInfo': {
            'custId': customer_id,
        }
    }

    checksum = generate_checksum(body, PAYTM_MERCHANT_KEY)
    body['head'] = {
        'signature': checksum
    }

    url = PAYTM_INITIATE_TRANSACTION_URL.format(PAYTM_MID, order_id)
    response = requests.post(url, data=json.dumps(body), headers=headers)
    return response.json()

# Example usage
if __name__ == '__main__':
    order_id = 'ORDER_{}'.format(datetime.now().strftime('%Y%m%d%H%M%S'))
    customer_id = 'CUST_001'
    txn_amount = '100.00'  # Example transaction amount

    response = initiate_transaction(order_id, customer_id, txn_amount)
    print(response)
