Behind the Scan: How UPI Payments Really Work (with Live Demo) and future AI integration.

Behind the Scan: How UPI Payments Really Work (with Live Demo) and future AI integration.

🛒 Imagine this Scene:

You're at a tea shop. You drink tea and see a QR code sticker on the counter. You open Paytm, scan the QR code, and pay ₹20. Within seconds, the shopkeeper says, "Payment received!"


✅ Step-by-Step Explanation

🧩 Step 1: You Scan the QR Code

  • The QR code contains bank details of the shopkeeper – like his UPI ID (rahul@upi).
  • Think of this like scanning a phone number to send money.


💬 Step 2: App Reads the QR Code

  • Paytm reads the UPI ID hidden in the QR code.
  • It fills it in automatically – you don’t need to type anything.


💰 Step 3: You Enter Amount & Confirm

  • You type ₹20 and press “Pay”.
  • The app now needs to send money from your bank account to the shopkeeper's.


🔒 Step 4: App Asks UPI for Help

  • Paytm is just the helper app. It now talks to UPI (run by NPCI, a government body).
  • It sends your bank details, UPI PIN (securely), and amount to UPI.


🏦 Step 5: UPI Talks to Banks

  • UPI talks to your bank (like SBI, ICICI, etc.) and says:
  • Your bank checks:


💸 Step 6: Money is Sent

  • If all is good:
  • This happens almost instantly – in less than 2 seconds.


📢 Step 7: Both Get Notification

  • You get: ✅ "₹20 paid to rahul@upi"
  • Shopkeeper gets: 📢 "₹20 received"


🎯 Summary Like a Simple Story:


Article content

🛠️ Technical Step-by-Step Flow of UPI Payment via QR Code


Step 1: QR Code Scan and Decode

  • A UPI QR code typically follows the Bharat QR / UPI format and contains data like:

upi://pay?pa=rahul@upi&pn=Rahul Tea Stall&mc=1234&tid=TXN123456&tr=INV123&am=0&cu=INR

  • The app scans this QR and parses:

  • pa = Payee UPI ID (rahul@upi)
  • pn = Payee name
  • am = Optional amount
  • mc = Merchant code (used for GST/tracking)
  • tr = Transaction reference


Step 2: User Input and Intent Creation

  • The app displays the merchant name and amount (if not prefilled).
  • Once the user confirms and enters the amount:
  • App creates a payment intent in the required UPI format.
  • This includes:
  • Payer VPA (e.g., raj@paytm)
  • Payee VPA (e.g., rahul@upi)
  • Amount
  • Transaction ID
  • UPI app’s package ID
  • Timestamp
  • Device details (partially masked)


Step 3: UPI Collect Request or Push Transaction

There are two flows:

  • Push: User initiates payment (what you do while scanning QR)
  • Pull: Merchant sends a collect request (for payment later)

In our case, it's Push.

  • The app calls the UPI SDK or uses PSP (like Paytm, PhonePe, GPay) APIs.
  • It sends a POST request to the PSP backend server with payment payload.


Step 4: PSP to NPCI Communication

  • PSP (Paytm in this case) prepares a digitally signed payload using encryption (like RSA or HMAC).
  • It securely sends the transaction to NPCI UPI switch using APIs:

/upi/payment/push

  • NPCI validates:
  • Format
  • Transaction ID uniqueness
  • Signature
  • Time constraints


Step 5: NPCI Switch Routes to Banks

  • NPCI acts as a switch, like a router.
  • It forwards the transaction to:
  • Payer Bank (for debit)
  • Payee Bank (for credit)

Each bank is connected to NPCI through:

  • UPI APIs (/v1/debit, /v1/credit)
  • Secure VPNs / MPLS network


Step 6: Payer Bank Validates and Debits

Payer bank checks:

  • Is UPI ID valid?
  • Does user have balance?
  • Is the UPI PIN correct?

UPI PIN is verified using a secure PIN block, hashed and encrypted.

If valid: debited immediately.


Step 7: Payee Bank Credits

Once payer bank confirms success:

  • NPCI instructs the payee bank to credit the account.
  • Transaction reference (RRN) is generated.


Step 8: Acknowledgment

NPCI sends the response back to:

  • PSP (Paytm)
  • Merchant’s bank

Response includes:

  • Status: SUCCESS / FAILURE
  • Timestamp
  • RRN (reference number)


Step 9: UI Notification to Both Parties

  • Paytm receives the success/failure from NPCI and updates UI.
  • Merchant gets an audio/visual notification (via Push Notification or WebSocket).
  • SMS/Email may also be triggered by the bank.


🧱 Tech Stack & Protocols Involved:


Article content

⚙️ Summary Flow (Simplified Diagram):

You (Paytm App)
     |
Scan QR → Read UPI ID
     |
Create Transaction Payload
     |
↓ Secure API (to Paytm Server)
     |
↓ Secure API (to NPCI)
     |
NPCI → Payer Bank: Debit ₹
     |
NPCI → Payee Bank: Credit ₹
     |
NPCI → Paytm: Transaction Success
     |
Paytm → You + Merchant: ✅ Notification        

Simple UPI Demo in Python

rajeevdave/upi-streamlit-demo: This is simple UPI demo app for beginners

Where Can You Implement AI in Your UPI Simulation?


🔍 1. Intelligent Fraud Detection

Add a simple ML model to flag suspicious transactions.

✅ Use cases:

  • Unusual payment amounts
  • Frequent transactions to same merchant
  • Multiple failed PIN attempts

✅ How:

  • Use a small logistic regression or decision tree model trained on simulated transaction data:

features = [amount, time_of_day, frequency, success_rate]        

🧠 2. AI Assistant (GenAI) for User Queries

A ChatGPT-like assistant inside the app.

✅ Example prompts:

  • “How does UPI work?”
  • “Why did my payment fail?”
  • “Who did I pay the most last week?”

✅ How:

  • Use OpenAI API locally or via LangChain-style retrieval from transaction logs.
  • Add st.chat_input() with custom LLM prompt handling.


📊 3. AI-Powered Spending Insights

Summarize the user’s transaction behavior using natural language.

✅ Example:

“You've spent ₹180 on tea last week across 6 transactions. Your biggest transaction was ₹50.”

✅ How:

  • Use simple rule-based logic or pandas + GenAI (gpt-3.5) to convert structured data into human summaries.


📸 4. QR Code Scanning Using AI Vision (Advanced)

Use a vision model (YOLO / OCR) to locate and extract UPI QR from a cluttered image.

✅ Useful for:

  • Scanning printed receipts
  • Reading QR codes from posters in real time


🎙️ 5. Voice-Powered Payments (Conversational AI)

"Pay ₹20 to Rahul" → fills form automatically.

✅ How:

  • Use speech_recognition to convert voice to text
  • Parse text with NLP (e.g., spaCy or GenAI)
  • Pre-fill form fields


🤖 6. Autonomous Payment Agent

A smart agent that can:

  • Suggest when to pay (e.g., monthly bill reminders)
  • Group transactions by merchant type
  • Automate low-risk payments

✅ How:

  • Use a rule-based agent (LangChain or simple FSM)
  • Add NLP-powered natural triggers


🧪 Suggested AI Add-on (Minimal Setup)

🧩 Add-on Idea: "Ask UPI Assistant" Panel

import openai

def ask_upi_assistant(user_question, history):
    prompt = f"""
    You are a UPI expert assistant. Answer clearly and helpfully.
    {history}
    Q: {user_question}
    A:"""
    response = openai.ChatCompletion.create(
        model="gpt-3.5-turbo",
        messages=[{"role": "user", "content": prompt}]
    )
    return response['choices'][0]['message']['content']        


query = st.text_input("Ask UPI Assistant")
if query:
    reply = ask_upi_assistant(query, "Transaction data: ...")
    st.markdown(f"💬 **Assistant:** {reply}")        



🛠️ Tools You Can Use


Article content

This project simulates how UPI apps like Paytm work when scanning a QR code, from generating the QR to confirming the payment. It includes a hands-on Python + Streamlit demo that mimics a basic UPI transaction experience. An integrated AI assistant explains UPI concepts and answers user queries in real time, making it interactive and educational.

To view or add a comment, sign in

Others also viewed

Explore topics