惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

GbyAI
GbyAI
爱范儿
爱范儿
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
月光博客
月光博客
腾讯CDC
Last Week in AI
Last Week in AI
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
博客园_首页
量子位
博客园 - 聂微东
Jina AI
Jina AI
小众软件
小众软件
The Cloudflare Blog
有赞技术团队
有赞技术团队
V
V2EX
博客园 - 司徒正美
Apple Machine Learning Research
Apple Machine Learning Research
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
大猫的无限游戏
大猫的无限游戏
博客园 - 三生石上(FineUI控件)
WordPress大学
WordPress大学
阮一峰的网络日志
阮一峰的网络日志
B
Blog
MongoDB | Blog
MongoDB | Blog
L
LangChain Blog
宝玉的分享
宝玉的分享
C
Check Point Blog
H
Hackread – Cybersecurity News, Data Breaches, AI and More
IT之家
IT之家
N
Netflix TechBlog - Medium
I
InfoQ
J
Java Code Geeks
S
SegmentFault 最新的问题
V
Visual Studio Blog
Microsoft Security Blog
Microsoft Security Blog
博客园 - 叶小钗
D
DataBreaches.Net
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
B
Blog RSS Feed
S
Schneier on Security
Webroot Blog
Webroot Blog
P
Proofpoint News Feed
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
T
Threatpost
Project Zero
Project Zero
Scott Helme
Scott Helme
C
CERT Recently Published Vulnerability Notes
P
Privacy International News Feed
T
The Exploit Database - CXSecurity.com
D
Darknet – Hacking Tools, Hacker News & Cyber Security

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
Tích hợp VNPay, Stripe trong Odoo 19
Dan Tran · 2026-05-25 · via DEV Community

1. Tính năng chính

2. Cấu trúc module

2.1. Flow

2.2. Endpoint API

3. PAYMENT TRANSACTION MODEL

3.1. Define model

Model payment.online.transaction là model chính của module, quản lý toàn bộ thông tin giao dịch thanh toán.

class PaymentTransaction(models.Model):
    _name = "payment.online.transaction"
    _description = "Online Payment Transaction"
    _inherit = ["mail.thread", "mail.activity.mixin"]
    _order = "create_date desc"

    name = fields.Char(string="Mã giao dịch", required=True, readonly=True, default=lambda self: _("New"), copy=False)

    partner_id = fields.Many2one("res.partner", string="Khách hàng", required=True, tracking=True)

    amount = fields.Monetary(string="Số tiền", required=True, tracking=True)

    currency_id = fields.Many2one("res.currency", string="Tiền tệ", default=lambda self: self.env.company.currency_id)

    provider = fields.Selection([("stripe", "Stripe"), ("vnpay", "VNPAY")], string="Nhà cung cấp", required=True, default="stripe", tracking=True)

    state = fields.Selection([("draft", "Nháp"), ("pending", "Chờ thanh toán"), ("done", "Thành công"), ("failed", "Thất bại"), ("cancelled", "Đã hủy")], string="Trạng thái", default="draft", tracking=True)

    transaction_id = fields.Char("Mã GD nhà cung cấp", readonly=True)

    request_id = fields.Char("Request ID", readonly=True)

    payment_url = fields.Char("Link thanh toán", readonly=True)

    response_code = fields.Char("Mã phản hồi", readonly=True)

    response_message = fields.Text("Thông báo phản hồi", readonly=True)

    payment_date = fields.Datetime("Thời gian thanh toán", readonly=True)

    note = fields.Text("Ghi chú")

    description = fields.Char("Mô tả thanh toán")

Enter fullscreen mode Exit fullscreen mode

3.2. State machine

3.3. Action methods

4. Tích hợp stripe

4.1. Giới thiệu

Stripe Checkout là giải pháp thanh toán hosted của Stripe, cung cấp giao diện thanh toán hoàn chỉnh, hỗ
trợ nhiều phương thức thanh toán và đa tiền tệ.
Ưu điểm:
Giao diện thanh toán đẹp, responsive
Hỗ trợ nhiều phương thức: Card, Apple Pay, Google Pay
PCI Compliance - không cần lưu thông tin thẻ
Hỗ trợ đa tiền tệ (135+ currencies)
Webhook đáng tin cậy

4.2 Cấu hình Stripe

class ResConfigSettings(models.TransientModel):
    _inherit = "res.config.settings"

    stripe_publishable_key = fields.Char(string="Stripe Publishable Key", config_parameter="online_paying.stripe_publishable_key")

    stripe_secret_key = fields.Char(string="Stripe Secret Key", config_parameter="online_paying.stripe_secret_key")

    stripe_webhook_secret = fields.Char(string="Stripe Webhook Secret", config_parameter="online_paying.stripe_webhook_secret")

    stripe_success_url = fields.Char(string="Stripe Success URL", config_parameter="online_paying.stripe_success_url")

    stripe_cancel_url = fields.Char(string="Stripe Cancel URL", config_parameter="online_paying.stripe_cancel_url")

Enter fullscreen mode Exit fullscreen mode


4.3 Method: action_create_stripe_payment()

def action_create_stripe_payment(self):
    """Tạo yêu cầu thanh toán Stripe Checkout Session"""

    self.ensure_one()

    if self.provider != "stripe":
        raise UserError(_("Giao dịch này không phải thanh toán Stripe"))

    config = self._get_stripe_config()

    if not config["secret_key"]:
        raise UserError(
            _("Chưa cấu hình đầy đủ thông tin Stripe.\n"
              "Vào SetYings → Online Payment để cấu hình.")
        )

    # Stripe uses smallest currency unit
    currency_code = self.currency_id.name.lower() if self.currency_id else "usd"

    # Stripe requires amount in smallest currency unit
    if currency_code in ["vnd", "jpy", "krw"]:
        amount = int(self.amount)
    else:
        amount = int(self.amount * 100)

    order_info = self.description or f"Thanh toán đơn hàng {self.name}"

    payload = {
        "payment_method_types[]": "card",
        "line_items[0][price_data][currency]": currency_code,
        "line_items[0][price_data][product_data][name]": order_info,
        "line_items[0][price_data][unit_amount]": str(amount),
        "line_items[0][quantity]": "1",
        "mode": "payment",
        "success_url": f"{config['success_url']}?session_id={{CHECKOUT_SESSION_ID}}&transaction_id={self.id}",
        "cancel_url": f"{config['cancel_url']}?transaction_id={self.id}",
        "client_reference_id": str(self.id),
        "metadata[odoo_transaction_id]": str(self.id),
        "metadata[odoo_transaction_name]": self.name,
    }

    if self.partner_id.email:
        payload["customer_email"] = self.partner_id.email

    try:
        response = requests.post(
            "https://api.stripe.com/v1/checkout/sessions",
            data=payload,
            auth=(config["secret_key"], ""),
            timeout=30
        )

        result = response.json()

        if response.status_code == 200 and result.get("url"):
            payment_url = result.get("url")
            session_id = result.get("id")

            self.write({
                "state": "pending",
                "request_id": session_id,
                "transaction_id": session_id,
                "payment_url": payment_url,
            })

            return {
                "type": "ir.actions.act_url",
                "url": payment_url,
                "target": "new",
            }

        else:
            error_msg = result.get("error", {}).get("message", "Unknown error")
            raise UserError(_("Stripe Error: %s") % error_msg)

    except requests.exceptions.RequestException as e:
        raise UserError(_("Lỗi kết nối Stripe: %s") % str(e))

Enter fullscreen mode Exit fullscreen mode


4.4 Xử lý Currency

Stripe yêu cầu số tiền phải truyền ở đơn vị nhỏ nhất của tiền tệ.

Tiền tệ Xử lý Ví dụ
USD, EUR, GBP ×100 (cents) $10.50 → 1050
VND, JPY, KRW Giữ nguyên 150,000đ → 150000

Ví dụ xử lý:

if currency_code in ["vnd", "jpy", "krw"]:
    amount = int(self.amount)
else:
    amount = int(self.amount * 100)

Enter fullscreen mode Exit fullscreen mode

Ví dụ:

  • 10.50 USD1050
  • 150000 VND150000
  • 2000 JPY2000

Dưới đây là format Dev.to sạch, chỉ giữ phần có giá trị, code được format lại:

5: Tích hợp VNPAY

5.1 Tổng quan VNPAY

VNPAY là cổng thanh toán phổ biến tại Việt Nam, hỗ trợ:

  • 🏦 Internet Banking (40+ ngân hàng)
  • 💳 Thẻ nội địa (Napas)
  • 💳 Thẻ quốc tế (Visa, MasterCard, JCB, Amex)
  • 📱 Ví điện tử VNPAY

5.2 Cấu hình VNPAY

Thêm cấu hình vào res.config.settings

# VNPAY CONFIG

vnpay_tmn_code = fields.Char(
    string="VNPAY Terminal ID (vnp_TmnCode)",
    config_parameter="online_paying.vnpay_tmn_code",
    help="Mã website tại VNPAY"
)

vnpay_hash_secret = fields.Char(
    string="VNPAY Hash Secret (vnp_HashSecret)",
    config_parameter="online_paying.vnpay_hash_secret",
    help="Chuỗi bí mật tạo checksum"
)

vnpay_url = fields.Char(
    string="VNPAY Payment URL",
    config_parameter="online_paying.vnpay_url",
    default="https://sandbox.vnpayment.vn/paymentv2/vpcpay.html"
)

vnpay_return_url = fields.Char(
    string="VNPAY Return URL",
    config_parameter="online_paying.vnpay_return_url"
)

Enter fullscreen mode Exit fullscreen mode


5.3 Method: action_create_vnpay_payment()

def action_create_vnpay_payment(self):
    """Tạo yêu cầu thanh toán VNPAY"""

    self.ensure_one()

    import hashlib
    import hmac
    import urllib.parse
    from datetime import datetime, timedelta, timezone

    if self.provider != "vnpay":
        raise UserError(_("Giao dịch này không phải thanh toán VNPAY"))

    config = self._get_vnpay_config()

    if not config["tmn_code"] or not config["hash_secret"]:
        raise UserError(
            _("Chưa cấu hình đầy đủ thông tin VNPAY")
        )

    # VNPAY chỉ hỗ trợ VND
    if self.currency_id.name != "VND":
        raise UserError(_("VNPAY chỉ hỗ trợ thanh toán bằng VND"))

    vnp_txn_ref = f"{self.id}-{datetime.now().strftime('%Y%m%d%H%M%S')}"

    # VNPAY yêu cầu số tiền x100
    vnp_amount = int(self.amount * 100)

    order_info = self.description or f"Thanh toan don hang {self.name}"
    order_info = self._remove_diacritics(order_info)

    vn_tz = timezone(timedelta(hours=7))
    vn_now = datetime.now(vn_tz)

    vnp_create_date = vn_now.strftime("%Y%m%d%H%M%S")
    vnp_expire_date = (
        vn_now + timedelta(minutes=60)
    ).strftime("%Y%m%d%H%M%S")

    vnp_params = {
        "vnp_Version":"2.1.0",
        "vnp_Command":"pay",
        "vnp_TmnCode":config["tmn_code"],
        "vnp_Amount":str(vnp_amount),
        "vnp_CurrCode":"VND",
        "vnp_TxnRef":vnp_txn_ref,
        "vnp_OrderInfo":order_info,
        "vnp_OrderType":"other",
        "vnp_Locale":"vn",
        "vnp_ReturnUrl":config["return_url"],
        "vnp_IpAddr":"127.0.0.1",
        "vnp_CreateDate":vnp_create_date,
        "vnp_ExpireDate":vnp_expire_date
    }

Enter fullscreen mode Exit fullscreen mode

Tiếp theo tạo chữ ký:

sorted_params = sorted(vnp_params.items())

hash_data = "&".join([
    f"{urllib.parse.quote_plus(str(k))}={urllib.parse.quote_plus(str(v))}"
    for k, v in sorted_params
])

secure_hash = hmac.new(
    config["hash_secret"].encode("utf-8"),
    hash_data.encode("utf-8"),
    hashlib.sha512
).hexdigest()

Enter fullscreen mode Exit fullscreen mode

Build payment URL:

query_string = urllib.parse.urlencode(sorted_params)

payment_url = (
    f"{config['vnpay_url']}?"
    f"{query_string}"
    f"&vnp_SecureHash={secure_hash}"
)

self.write({
    "state":"pending",
    "request_id":vnp_txn_ref,
    "payment_url":payment_url
})

return {
    "type":"ir.actions.act_url",
    "url":payment_url,
    "target":"new"
}

Enter fullscreen mode Exit fullscreen mode


5.4 Thuật toán tạo chữ ký VNPAY

INPUT:
- vnp_params
- hash_secret

STEP 1:
Sort parameters alphabetically

STEP 2:
Build hash string

key1=value1&key2=value2...

(URL encode key + value)

STEP 3:
Generate SHA512 HMAC

secure_hash = HMAC_SHA512(
    hash_secret,
    hash_data
)

STEP 4:
Return secure_hash.hexdigest()

Enter fullscreen mode Exit fullscreen mode


5.5 Xử lý dấu tiếng Việt

VNPAY không hỗ trợ Unicode trong vnp_OrderInfo.

Ví dụ:

"Thanh toán đơn hàng"
↓
"Thanh toan don hang"

Enter fullscreen mode Exit fullscreen mode

Implementation:

def _remove_diacritics(self, text):
    """Remove Vietnamese diacritics"""

    import unicodedata
    import re

    text = unicodedata.normalize("NFD", text)

    text = re.sub(
        r'[\u0300-\u036f]',
        '',
        text
    )

    text = (
        text.replace('đ','d')
        .replace('Đ','D')
    )

    return text

Enter fullscreen mode Exit fullscreen mode


5.6 Mã lỗi VNPAY

Code Ý nghĩa
00 Giao dịch thành công
07 Giao dịch nghi ngờ
09 Chưa đăng ký Internet Banking
10 Xác thực sai quá 3 lần
11 Hết hạn thanh toán
12 Tài khoản bị khóa
13 Sai OTP
24 Khách hàng hủy giao dịch
51 Không đủ số dư
65 Vượt hạn mức giao dịch
75 Ngân hàng bảo trì
79 Sai mật khẩu thanh toán
99 Lỗi khác

6.Controllers & Webhooks

6.1 Tổng quan

Controller File Chức năng
OnlinePaymentController main.py Trang trạng thái
StripeWebhookController stripe.py Xử lý webhook Stripe
VNPayController vnpay.py Callback VNPAY

6.2 Main Controller

class OnlinePaymentController(http.Controller):

    @http.route(
        "/payment/status",
        type="http",
        auth="public",
        methods=["GET"],
        csrf=False,
        website=True
    )
    def payment_status(self, **kwargs):

        transaction_id = kwargs.get(
            "transaction_id"
        )

        status = kwargs.get(
            "status",
            "unknown"
        )

        values = {
            "transaction_id":transaction_id,
            "status":status,
            "message":self._get_status_message(status)
        }

        return request.render(
            "online_paying.payment_status_page",
            values
        )

Enter fullscreen mode Exit fullscreen mode


6.3 Stripe Webhook Controller

class StripeWebhookController(http.Controller):

    @http.route(
        "/payment/stripe/webhook",
        type="json",
        auth="public",
        methods=["POST"],
        csrf=False
    )
    def stripe_webhook(self, **kwargs):

        payload = request.get_json_data()
        event_type = payload.get("type","")

        if event_type=="checkout.session.completed":
            return self._handle_checkout_completed(payload)

        elif event_type=="checkout.session.expired":
            return self._handle_checkout_expired(payload)

        return {"status":"ignored"}

Enter fullscreen mode Exit fullscreen mode


6.4 VNPAY Controller

class VNPayController(http.Controller):

    @http.route(
        "/payment/vnpay/return",
        type="http",
        auth="public",
        methods=["GET"],
        csrf=False,
        website=True
    )
    def vnpay_return(self, **kwargs):

        vnp_response_code=kwargs.get(
            "vnp_ResponseCode"
        )

        vnp_txn_ref=kwargs.get(
            "vnp_TxnRef"
        )

        if not self._verify_vnpay_signature(kwargs):
            return request.redirect(
                "/payment/status?status=failed"
            )

        transaction_id=vnp_txn_ref.split("-")[0]

        transaction=request.env[
            "payment.online.transaction"
        ].sudo().browse(
            int(transaction_id)
        )

        if vnp_response_code=="00":
            transaction.write({
                "state":"done"
            })

        return request.redirect(
            f"/payment/status?transaction_id={transaction.id}&status=success"
        )
else:
    error_message = self._get_vnpay_error_message(
        vnp_response_code
    )

    transaction.write({
        "state":"failed",
        "response_code":vnp_response_code,
        "response_message":error_message
    })

    return request.redirect(
        f"/payment/status?transaction_id={transaction_id}&status=failed"
    )

except Exception:
    return request.redirect(
        "/payment/status?status=failed"
    )

Enter fullscreen mode Exit fullscreen mode

6.5 Xác thực chữ ký VNPAY

def _verify_vnpay_signature(self, params):
    """Xác thực chữ ký VNPAY"""

    try:
        import hashlib
        import hmac
        import urllib.parse

        ir_config = request.env[
            "ir.config_parameter"
        ].sudo()

        hash_secret = ir_config.get_param(
            "online_paying.vnpay_hash_secret",
            ""
        )

        if not hash_secret:
            return False

        # Lấy hash từ VNPAY response
        vnp_secure_hash = params.get(
            "vnp_SecureHash",
            ""
        )

        # Loại bỏ các field không dùng để hash
        input_data = {
            k:v for k,v in params.items()
            if k not in [
                "vnp_SecureHash",
                "vnp_SecureHashType"
            ] and v
        }

        # Sort theo alphabet
        sorted_data = sorted(
            input_data.items()
        )

        # Build hash string
        hash_data = "&".join([
            f"{urllib.parse.quote_plus(str(k))}={urllib.parse.quote_plus(str(v))}"
            for k,v in sorted_data
        ])

        # Tính lại checksum
        calculated_hash = hmac.new(
            hash_secret.encode("utf-8"),
            hash_data.encode("utf-8"),
            hashlib.sha512
        ).hexdigest().upper()

        return (
            vnp_secure_hash.upper()
            == calculated_hash
        )

    except Exception:
        return False

Enter fullscreen mode Exit fullscreen mode