{"id":576,"date":"2026-11-06T01:00:00","date_gmt":"2026-11-06T01:00:00","guid":{"rendered":"https:\/\/paymentsetu.com\/blog\/?p=576"},"modified":"2026-11-06T01:00:00","modified_gmt":"2026-11-06T01:00:00","slug":"upi-payment-integration-python-django","status":"publish","type":"post","link":"https:\/\/paymentsetu.com\/blog\/upi-payment-integration-python-django\/","title":{"rendered":"UPI Payment Integration in Python: Django &#038; Flask"},"content":{"rendered":"\n<p class=\"wp-block-paragraph\">UPI payment integration in Python becomes much easier when you separate order creation, the customer\u2019s UPI payment and server-side verification. This guide shows a requests-based flow for Django and Flask using PaymentSetu, with dynamic QR orders, HMAC-signed webhooks and a safe status-check fallback.<\/p>\n\n\n\n<aside class=\"ap-card\" aria-label=\"PaymentSetu Pro\">\n<span class=\"ap-card__badge\">Best for developers<\/span>\n<div class=\"ap-card__body\"><p class=\"ap-card__name\">PaymentSetu Pro<\/p><p class=\"ap-card__best\">Best for growing WooCommerce \/ WHMCS stores and service businesses with up to 1,000 UPI payments a month (most popular)<\/p><ul class=\"ap-card__features\"><li>1,000 credits (1 credit = 1 successful payment verified)<\/li><li>0% commission, direct-to-bank UPI settlement<\/li><li>Dynamic QR, webhooks and API access<\/li><li>WooCommerce and WHMCS plugins<\/li><li>Priority support<\/li><\/ul><\/div>\n<div class=\"ap-card__side\"><p class=\"ap-card__price\">\u20b9999 <small>Most popular \u00b7 \u20b9999 \/ 30 days \u00b7 1,000 verified payments<\/small><\/p><a class=\"ap-card__btn\" href=\"https:\/\/paymentsetu.com\/auth\/register\">Get Pro \u2192<\/a><\/div>\n<\/aside>\n\n\n\n<h2 class=\"wp-block-heading\">What you need<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">PaymentSetu is a payment verification service, not a payment gateway. The customer pays directly into your connected Paytm Business or PhonePe Business merchant account; PaymentSetu matches the amount and UTR to your order and notifies your application.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Prepare these items before writing the first view:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n\n<li>A Python application using Django or Flask, with a database record for each order.<\/li>\n\n\n<li>A public HTTPS URL for your webhook, such as <code>https:\/\/shop.example.com\/webhooks\/paymentsetu<\/code>.<\/li>\n\n\n<li>A PaymentSetu account with an API key, webhook secret and a connected merchant account.<\/li>\n\n\n<li>A stable order reference generated by your application. Send it as <code>client_txn_id<\/code> and save it before creating the QR.<\/li>\n\n\n<li>A server-side environment for secrets. Do not put the API key or webhook secret in browser JavaScript, templates or a mobile app.<\/li>\n\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">Install the HTTP client and the framework packages in your virtual environment:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>python -m venv .venv\nsource .venv\/bin\/activate\npython -m pip install requests django flask<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">The integration has five parts:<\/p>\n\n\n\n<ol class=\"wp-block-list\">\n\n<li>Your server creates an order with <code>POST \/api\/create_order<\/code>.<\/li>\n\n\n<li>Your checkout displays the QR or payment details returned by the API.<\/li>\n\n\n<li>The customer pays by UPI into your own merchant account.<\/li>\n\n\n<li>PaymentSetu matches the payment and sends an HMAC-signed webhook.<\/li>\n\n\n<li>Your application marks the order paid once, then uses <code>GET \/api\/order_status\/{client_txn_id}<\/code> when it needs to check again.<\/li>\n\n<\/ol>\n\n\n\n<p class=\"wp-block-paragraph\">For a WooCommerce store, the ready-made <a href=\"https:\/\/paymentsetu.com\/woocommerce-plugin\">PaymentSetu WooCommerce plugin<\/a> can handle the same payment-verification flow without custom API work. Use the Python route when your checkout or billing system is your own application.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Step 1: Model your order and secrets<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Why this matters: the webhook must map an external payment to one internal order, and your application must be able to ignore a repeated delivery safely.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Create an order row before calling the API. At minimum, keep your internal order ID, <code>client_txn_id<\/code>, expected amount, current status and the eventual UTR. Make <code>client_txn_id<\/code> unique in the database.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Set environment variables on the server, for example:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>export PAYMENTSETU_API_BASE=\"https:\/\/your-paymentsetu-api-host\"\nexport PAYMENTSETU_API_KEY=\"replace-with-your-api-key\"\nexport PAYMENTSETU_WEBHOOK_SECRET=\"replace-with-your-webhook-secret\"\nexport PAYMENTSETU_API_KEY_HEADER=\"X-API-Key\"\nexport PAYMENTSETU_SIGNATURE_HEADER=\"X-PaymentSetu-Signature\"\nexport PAYMENTSETU_SIGNATURE_DIGEST=\"sha256\"<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">The API is API-key authenticated and the webhook is HMAC-signed. The two header names and the digest encoding above are configuration examples: copy the exact names and algorithm from the API instructions shown in your PaymentSetu account. Keeping them in environment variables lets you follow that contract without changing application code.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Do not log <code>PAYMENTSETU_API_KEY<\/code>, <code>PAYMENTSETU_WEBHOOK_SECRET<\/code> or the complete webhook body if it contains personal data. Log a request ID, your <code>client_txn_id<\/code> and the result of processing instead.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Success looks like this: your database can find one pending order by <code>client_txn_id<\/code>, and the process running Django or Flask can read the five environment variables without exposing them to the browser.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Step 2: Create an order with <code>requests<\/code><\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Why this matters: the order reference is the link between your checkout, the dynamic QR and the verification callback.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Keep this call on your server. The browser should ask your application to create an order; it should never receive your API key.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import os\nfrom urllib.parse import quote\n\nimport requests\n\n\nAPI_BASE = os.environ[\"PAYMENTSETU_API_BASE\"].rstrip(\"\/\")\nAPI_KEY = os.environ[\"PAYMENTSETU_API_KEY\"]\nAPI_KEY_HEADER = os.getenv(\"PAYMENTSETU_API_KEY_HEADER\", \"X-API-Key\")\n\n\ndef api_headers():\n    return {\n        \"Accept\": \"application\/json\",\n        \"Content-Type\": \"application\/json\",\n        API_KEY_HEADER: API_KEY,\n    }\n\n\ndef create_payment_order(client_txn_id, amount_inr, webhook_url):\n    payload = {\n        \"client_txn_id\": client_txn_id,\n        \"amount\": str(amount_inr),\n        \"webhook_url\": webhook_url,\n    }\n\n    response = requests.post(\n        f\"{API_BASE}\/api\/create_order\",\n        headers=api_headers(),\n        json=payload,\n        timeout=15,\n    )\n    response.raise_for_status()\n    return response.json()\n\n\ndef get_payment_status(client_txn_id):\n    safe_id = quote(client_txn_id, safe=\"\")\n    response = requests.get(\n        f\"{API_BASE}\/api\/order_status\/{safe_id}\",\n        headers=api_headers(),\n        timeout=15,\n    )\n    response.raise_for_status()\n    return response.json()<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Call <code>create_payment_order<\/code> after inserting your pending order. A normal checkout service method might look like this:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>from uuid import uuid4\n\n\ndef start_checkout(cart_total):\n    client_txn_id = f\"ORDER-{uuid4().hex}\"\n    # Save this row before the network call in your real application.\n    save_pending_order(client_txn_id, amount=cart_total)\n\n    return create_payment_order(\n        client_txn_id=client_txn_id,\n        amount_inr=cart_total,\n        webhook_url=\"https:\/\/shop.example.com\/webhooks\/paymentsetu\",\n    )<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Read the returned JSON and pass only the QR\/payment fields your frontend needs to the checkout page. Do not mark the order paid from a browser redirect, a customer screenshot or an unverified field supplied by the browser. The paid transition belongs in the webhook handler after signature, reference and amount checks.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Success looks like this: a pending order has a unique <code>client_txn_id<\/code>, the API returns a successful JSON response, and the page can render the returned dynamic QR or payment instructions.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Step 3: Add the Django webhook view<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Why this matters: Django\u2019s CSRF middleware is designed for browser forms, while a server-to-server webhook normally cannot send your site\u2019s CSRF token. Exempt only this dedicated callback URL, then protect it with the webhook signature and your own idempotency checks. See Django\u2019s <a href=\"https:\/\/docs.djangoproject.com\/en\/stable\/howto\/csrf\/\" target=\"_blank\" rel=\"noopener\">CSRF guidance<\/a> before applying the exemption.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Verify the raw request bytes before parsing JSON. The sample uses SHA-256 and a hex signature as a configurable example; the values must match the PaymentSetu webhook contract for your account.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import hashlib\nimport hmac\nimport json\nimport os\n\nfrom django.db import transaction\nfrom django.http import HttpResponse, JsonResponse\nfrom django.views.decorators.csrf import csrf_exempt\n\nfrom .models import Order\n\n\nWEBHOOK_SECRET = os.environ[\"PAYMENTSETU_WEBHOOK_SECRET\"].encode(\"utf-8\")\nSIGNATURE_HEADER = os.getenv(\n    \"PAYMENTSETU_SIGNATURE_HEADER\", \"X-PaymentSetu-Signature\"\n)\nSUCCESS_VALUE = os.getenv(\"PAYMENTSETU_SUCCESS_VALUE\", \"success\").lower()\n\n\ndef valid_signature(raw_body, received_signature):\n    if not received_signature:\n        return False\n\n    expected = hmac.new(\n        WEBHOOK_SECRET,\n        raw_body,\n        hashlib.sha256,\n    ).hexdigest()\n    return hmac.compare_digest(expected, received_signature.strip())\n\n\n@csrf_exempt\ndef paymentsetu_webhook(request):\n    if request.method != \"POST\":\n        return HttpResponse(status=405)\n\n    raw_body = request.body\n    signature = request.headers.get(SIGNATURE_HEADER)\n    if not valid_signature(raw_body, signature):\n        return JsonResponse({\"ok\": False, \"error\": \"invalid signature\"}, status=401)\n\n    try:\n        event = json.loads(raw_body)\n    except json.JSONDecodeError:\n        return JsonResponse({\"ok\": False, \"error\": \"invalid JSON\"}, status=400)\n\n    client_txn_id = event.get(\"client_txn_id\")\n    status = str(event.get(\"status\", \"\")).lower()\n    if not client_txn_id:\n        return JsonResponse({\"ok\": False, \"error\": \"missing order reference\"}, status=400)\n\n    with transaction.atomic():\n        order = (\n            Order.objects.select_for_update()\n            .get(client_txn_id=client_txn_id)\n        )\n\n        # A retry for an already-paid order must not fulfil it twice.\n        if order.status == Order.Status.PAID:\n            return JsonResponse({\"ok\": True})\n\n        if status != SUCCESS_VALUE:\n            return JsonResponse({\"ok\": True})\n\n        received_amount = str(event.get(\"amount\", \"\"))\n        if received_amount != str(order.amount):\n            return JsonResponse({\"ok\": False, \"error\": \"amount mismatch\"}, status=400)\n\n        order.status = Order.Status.PAID\n        order.utr = event.get(\"utr\", \"\")\n        order.save(update_fields=[\"status\", \"utr\", \"updated_at\"])\n\n        enqueue_fulfilment(order.pk)\n\n    return JsonResponse({\"ok\": True})<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Replace <code>Order<\/code>, <code>enqueue_fulfilment<\/code> and the field names with your application\u2019s code. Also confirm the exact webhook payload keys and success value in your PaymentSetu API instructions. The important order is fixed: read raw bytes, validate HMAC, parse JSON, find the unique order, compare the amount, then perform one atomic paid transition.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Register the URL:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>from django.urls import path\n\nfrom .views import paymentsetu_webhook\n\n\nurlpatterns = [\n    path(\"webhooks\/paymentsetu\", paymentsetu_webhook, name=\"paymentsetu-webhook\"),\n]<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Python\u2019s <a href=\"https:\/\/docs.python.org\/3\/library\/hmac.html#hmac.compare_digest\" target=\"_blank\" rel=\"noopener\"><code>hmac.compare_digest<\/code><\/a> is intended for comparing secret-derived values without ordinary content-based short-circuiting. Do not replace it with a casual <code>expected == received<\/code> comparison in production code.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Success looks like this: a valid signed <code>POST<\/code> returns HTTP 200, an invalid signature returns HTTP 401, and sending the same valid event twice leaves one paid order and one fulfilment.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Step 4: Add the Flask webhook route<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Why this matters: Flask can expose the same verification flow with a small route. Keep the raw body for HMAC validation, then call <code>get_json()<\/code> only after the signature passes. Flask documents <code>request.get_json()<\/code> and JSON responses in its <a href=\"https:\/\/flask.palletsprojects.com\/en\/stable\/api\/\" target=\"_blank\" rel=\"noopener\">request API<\/a>.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import hashlib\nimport hmac\nimport os\n\nfrom flask import Flask, jsonify, request\n\napp = Flask(__name__)\n\nWEBHOOK_SECRET = os.environ[\"PAYMENTSETU_WEBHOOK_SECRET\"].encode(\"utf-8\")\nSIGNATURE_HEADER = os.getenv(\n    \"PAYMENTSETU_SIGNATURE_HEADER\", \"X-PaymentSetu-Signature\"\n)\nSUCCESS_VALUE = os.getenv(\"PAYMENTSETU_SUCCESS_VALUE\", \"success\").lower()\n\n\ndef valid_signature(raw_body, received_signature):\n    if not received_signature:\n        return False\n\n    expected = hmac.new(\n        WEBHOOK_SECRET,\n        raw_body,\n        hashlib.sha256,\n    ).hexdigest()\n    return hmac.compare_digest(expected, received_signature.strip())\n\n\n@app.post(\"\/webhooks\/paymentsetu\")\ndef paymentsetu_webhook():\n    raw_body = request.get_data(cache=True)\n    signature = request.headers.get(SIGNATURE_HEADER)\n\n    if not valid_signature(raw_body, signature):\n        return jsonify(ok=False, error=\"invalid signature\"), 401\n\n    event = request.get_json(silent=True)\n    if not isinstance(event, dict):\n        return jsonify(ok=False, error=\"invalid JSON\"), 400\n\n    client_txn_id = event.get(\"client_txn_id\")\n    if not client_txn_id:\n        return jsonify(ok=False, error=\"missing order reference\"), 400\n\n    with database.transaction():\n        order = database.lock_order(client_txn_id)\n\n        if order.status == \"paid\":\n            return jsonify(ok=True)\n\n        if str(event.get(\"status\", \"\")).lower() != SUCCESS_VALUE:\n            return jsonify(ok=True)\n\n        if str(event.get(\"amount\", \"\")) != str(order.amount):\n            return jsonify(ok=False, error=\"amount mismatch\"), 400\n\n        database.mark_paid(\n            order,\n            utr=event.get(\"utr\", \"\"),\n        )\n        database.enqueue_fulfilment(order.id)\n\n    return jsonify(ok=True)<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><code>database.lock_order<\/code>, <code>mark_paid<\/code> and <code>enqueue_fulfilment<\/code> are application-specific placeholders. Implement the lock or unique event constraint with your database library. A webhook handler should do the minimum durable work needed to record the payment, then queue email, stock, access or invoice actions so a slow downstream service does not hold the callback open.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Success looks like this: Flask accepts only <code>POST<\/code>, rejects malformed or unsigned requests, returns a 2xx response for a valid event, and keeps a replay of the event harmless.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Step 5: Show the QR and keep the browser out of verification<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Why this matters: the customer experience can be browser-based, but the decision that an order is paid must be server-side.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">After <code>create_payment_order<\/code> returns, store the response needed to redraw the checkout and show the QR. Keep the browser polling your own endpoint, such as <code>\/orders\/ORDER-123\/status<\/code>; do not expose the PaymentSetu API key or call the external API directly from JavaScript.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Your own status endpoint can read the database first:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>def checkout_status(client_txn_id):\n    order = load_order_for_current_customer(client_txn_id)\n    return {\n        \"client_txn_id\": order.client_txn_id,\n        \"status\": order.status,\n    }<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">The normal path is webhook-first. If the order remains pending, your server can call <code>GET \/api\/order_status\/{client_txn_id}<\/code> using the <code>get_payment_status<\/code> function from Step 2. Use a modest retry schedule or a staff \u201ccheck status\u201d action; do not make a tight loop that repeatedly calls the API.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Keep these records for reconciliation:<\/p>\n\n\n\n<figure class=\"wp-block-table ap-table\"><table><thead><tr><th>Record<\/th><th>Why you keep it<\/th><\/tr><\/thead><tbody><tr class=\"ap-win\"><td><code>client_txn_id<\/code><\/td><td>Maps PaymentSetu\u2019s event to your internal order<\/td><\/tr><tr><td>Expected amount<\/td><td>Detects a callback that does not match the order<\/td><\/tr><tr><td>Verified amount<\/td><td>Provides the received value for your receipt record<\/td><\/tr><tr><td>UTR<\/td><td>Gives your finance team a bank-reference field<\/td><\/tr><tr><td>Webhook event ID, if supplied<\/td><td>Makes replay protection explicit<\/td><\/tr><tr><td>Received timestamp<\/td><td>Helps reconcile the day\u2019s verified payments<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p class=\"wp-block-paragraph\">PaymentSetu sends money directly to your own connected merchant account and charges 0% commission on the payment. The Pro plan is \u20b9999 per 30 days for 1,000 credits, with one credit representing one successful payment verified; <a href=\"https:\/\/paymentsetu.com\/#pricing\">check the current plan details<\/a> when choosing capacity.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Success looks like this: the checkout displays a QR, the frontend sees a pending order until your backend records the signed event, and a status check can reconcile an order without trusting a screenshot.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Step 6: Test the integration before going live<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Why this matters: most payment-integration bugs are contract or state-transition bugs, not Python syntax errors. Test both the happy path and the security boundaries.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">First run a local syntax check and your application\u2019s tests:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>python -m compileall paymentsetu_client.py\npython manage.py check        # Django only\npytest                        # if your project uses pytest<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Then test these cases with a safe test order or the test procedure available in your PaymentSetu account:<\/p>\n\n\n\n<ol class=\"wp-block-list\">\n\n<li>Create one order and confirm that its <code>client_txn_id<\/code> and amount are saved before the QR is shown.<\/li>\n\n\n<li>Pay the exact amount and confirm that the webhook is accepted and the order becomes paid.<\/li>\n\n\n<li>Send the same signed body twice. Confirm that only one fulfilment job, email or access grant is created.<\/li>\n\n\n<li>Change one byte of the body without changing the signature. Confirm HTTP 401.<\/li>\n\n\n<li>Use a wrong signature with an otherwise valid body. Confirm HTTP 401.<\/li>\n\n\n<li>Change the amount in a signed body. Confirm the event is not applied to the order.<\/li>\n\n\n<li>Call the status endpoint for a pending and a paid order. Confirm your application maps both responses without exposing API credentials.<\/li>\n\n\n<li>Call <code>GET \/api\/check_credits<\/code> from the server when you need to display or monitor remaining credits.<\/li>\n\n<\/ol>\n\n\n\n<p class=\"wp-block-paragraph\">For a local signature unit test, calculate the expected digest from the exact raw bytes. Do not parse and re-serialise JSON before checking the signature, because whitespace and key order can change the bytes.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>def test_signature_round_trip():\n    body = b'{\"client_txn_id\":\"ORDER-123\",\"status\":\"success\"}'\n    secret = b\"local-test-secret\"\n    signature = hmac.new(secret, body, hashlib.sha256).hexdigest()\n    assert valid_signature(body, signature)\n    assert not valid_signature(body + b\" \", signature)<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Before production, configure the webhook URL as HTTPS, set the exact header and digest settings from your account, restrict the callback to <code>POST<\/code>, and make the order transition atomic. Never treat a customer-uploaded payment screenshot as confirmation.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Troubleshooting Python UPI integrations<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>The create-order call returns an authentication error.<\/strong> Confirm that the key is present only on the server, that the API-key header name matches the account instructions, and that the base URL does not contain a duplicated <code>\/api<\/code> path. Log the HTTP status and a request ID, not the key.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>The QR is displayed but the order stays pending.<\/strong> Check that the webhook URL is public HTTPS, the callback route accepts <code>POST<\/code>, and the saved <code>client_txn_id<\/code> is the same value sent during order creation. Use the server-side status endpoint to inspect the order rather than relying on a browser redirect.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Every webhook is rejected.<\/strong> Compare the signature header name, digest algorithm, encoding and secret. Compute the HMAC over the raw body bytes before <code>json.loads()<\/code> or <code>request.get_json()<\/code> and remove any accidental <code>Bearer <\/code> or <code>sha256=<\/code> prefix only if the PaymentSetu signature format requires it.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>The same order is fulfilled twice.<\/strong> Add a database lock or unique event record, and make the paid transition conditional. A repeated event should return success after the first durable transition without sending another email, granting access or shipping another item.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>A valid event gives an amount mismatch.<\/strong> Store amounts in a consistent representation, preferably integer paise or a fixed-precision decimal. Compare the verified value with the order\u2019s expected amount before marking the order paid, and do not silently round a mismatch.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">FAQ<\/h2>\n\n\n\n<h3 class=\"wp-block-heading\">Can I integrate UPI payments in Python without a gateway SDK?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Yes. A Python application can use HTTPS requests to create an order, render the returned QR\/payment details and receive the HMAC-signed verification webhook. This guide uses the framework-agnostic <code>requests<\/code> library, so the same client code can be shared by Django, Flask or another Python server.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Is PaymentSetu a payment gateway?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">No. PaymentSetu is a payment verification service. The customer pays directly to your connected Paytm Business or PhonePe Business merchant account, PaymentSetu matches the UTR and amount to your order and your application receives the webhook.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Should Django exempt the webhook from CSRF?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">A server-to-server webhook normally cannot supply the CSRF token used by your customer-facing forms, so a dedicated callback can use <code>csrf_exempt<\/code>. Compensate with HTTPS, HMAC verification, strict POST handling, idempotency and amount\/reference checks; never exempt an entire application or skip signature validation.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">What should a Python webhook do when the same event arrives again?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Return a successful response after confirming that the order is already paid, without repeating fulfilment. Store a unique transaction or event reference and use an atomic database transition so retries remain harmless.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Which PaymentSetu plan fits a growing Python checkout?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">PaymentSetu Pro is \u20b9999 per 30 days for 1,000 verified payments and includes API access, webhooks, dynamic QR and priority support. Choose the plan by expected successful payment count: Starter is \u20b9399 for 100 credits, while Business is \u20b91,499 for 100,000 credits.<\/p>\n\n\n\n<aside class=\"ap-cta\" aria-label=\"Automate UPI order verification\"><div class=\"ap-cta__content\"><p class=\"ap-cta__eyebrow\">Start with Python<\/p><p class=\"ap-cta__title\">Automate UPI order verification<\/p><p class=\"ap-cta__text\">Connect your own merchant account, generate order-linked QR payments and receive signed webhooks.<\/p><\/div><a class=\"ap-cta__btn\" href=\"https:\/\/paymentsetu.com\/auth\/register\">Create your account<\/a><\/aside>\n\n\n\n<p class=\"wp-block-paragraph\">DONE upi-payment-integration-python-django words=2016<\/p>\n\n\n\n<script type=\"application\/ld+json\">{\"@context\": \"https:\/\/schema.org\", \"@type\": \"FAQPage\", \"mainEntity\": [{\"@type\": \"Question\", \"name\": \"Can I integrate UPI payments in Python without a gateway SDK?\", \"acceptedAnswer\": {\"@type\": \"Answer\", \"text\": \"Yes. A Python application can use HTTPS requests to create an order, render the returned QR\/payment details and receive the HMAC-signed verification webhook. This guide uses the framework-agnostic requests library, so the same client code can be shared by Django, Flask or another Python server.\"}}, {\"@type\": \"Question\", \"name\": \"Is PaymentSetu a payment gateway?\", \"acceptedAnswer\": {\"@type\": \"Answer\", \"text\": \"No. PaymentSetu is a payment verification service. The customer pays directly to your connected Paytm Business or PhonePe Business merchant account, PaymentSetu matches the UTR and amount to your order and your application receives the webhook.\"}}, {\"@type\": \"Question\", \"name\": \"Should Django exempt the webhook from CSRF?\", \"acceptedAnswer\": {\"@type\": \"Answer\", \"text\": \"A server-to-server webhook normally cannot supply the CSRF token used by your customer-facing forms, so a dedicated callback can use csrf_exempt. Compensate with HTTPS, HMAC verification, strict POST handling, idempotency and amount\/reference checks; never exempt an entire application or skip signature validation.\"}}, {\"@type\": \"Question\", \"name\": \"What should a Python webhook do when the same event arrives again?\", \"acceptedAnswer\": {\"@type\": \"Answer\", \"text\": \"Return a successful response after confirming that the order is already paid, without repeating fulfilment. Store a unique transaction or event reference and use an atomic database transition so retries remain harmless.\"}}, {\"@type\": \"Question\", \"name\": \"Which PaymentSetu plan fits a growing Python checkout?\", \"acceptedAnswer\": {\"@type\": \"Answer\", \"text\": \"PaymentSetu Pro is \u20b9999 per 30 days for 1,000 verified payments and includes API access, webhooks, dynamic QR and priority support. Choose the plan by expected successful payment count: Starter is \u20b9399 for 100 credits, while Business is \u20b91,499 for 100,000 credits. DONE upi-payment-integration-python-django words=2016\"}}]}<\/script>\n\n","protected":false},"excerpt":{"rendered":"Learn upi payment integration in python with Django and Flask: create orders, show a QR, verify HMAC webhooks, prevent duplicates and test status.","protected":false},"author":1,"featured_media":575,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"csco_singular_sidebar":"","csco_page_header_type":"","csco_page_load_nextpost":"","footnotes":""},"categories":[29],"tags":[145,146,129,144,28],"class_list":["post-576","post","type-post","status-publish","format-standard","has-post-thumbnail","category-upi-payment-verification","tag-django","tag-flask","tag-python","tag-upi-payment-integration","tag-webhooks","cs-entry"],"_links":{"self":[{"href":"https:\/\/paymentsetu.com\/blog\/wp-json\/wp\/v2\/posts\/576","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/paymentsetu.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/paymentsetu.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/paymentsetu.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/paymentsetu.com\/blog\/wp-json\/wp\/v2\/comments?post=576"}],"version-history":[{"count":1,"href":"https:\/\/paymentsetu.com\/blog\/wp-json\/wp\/v2\/posts\/576\/revisions"}],"predecessor-version":[{"id":784,"href":"https:\/\/paymentsetu.com\/blog\/wp-json\/wp\/v2\/posts\/576\/revisions\/784"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/paymentsetu.com\/blog\/wp-json\/wp\/v2\/media\/575"}],"wp:attachment":[{"href":"https:\/\/paymentsetu.com\/blog\/wp-json\/wp\/v2\/media?parent=576"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/paymentsetu.com\/blog\/wp-json\/wp\/v2\/categories?post=576"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/paymentsetu.com\/blog\/wp-json\/wp\/v2\/tags?post=576"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}