You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何获取适用于Python(含Django)的2checkout IPN响应验证示例代码?

2Checkout Django 框架 IPN 响应验证实现参考

2Checkout 官方提供了覆盖多种语言的 IPN 响应验证示例代码,但暂未推出 Python 语言版本。如果你需要 Django 框架下的对应实现,可以参考下方示例代码。

示例代码

import hashlib
import hmac
from django.conf import settings
from django.http import HttpResponse
from django.views.decorators.http import require_POST
from django.views.decorators.csrf import csrf_exempt

@csrf_exempt
@require_POST
def twocheckout_ipn(request):
    # 提取所有POST参数
    post_data = request.POST.copy()
    # 取出请求携带的哈希校验值
    received_hash = post_data.pop('HASH', [''])[0]

    # 按照2Checkout官方规则对参数按键名排序
    sorted_params = sorted(post_data.items(), key=lambda item: item[0].lower())
    hash_calc_str = ''
    for param_key, param_value in sorted_params:
        # 每个参数值前补两位长度标识,按照官方规则拼接字符串
        val_length = len(str(param_value))
        hash_calc_str += f"{val_length:02d}{str(param_value)}"

    # 使用IPN密钥计算校验哈希
    secret = settings.TWOCHECKOUT_IPN_SECRET.encode('utf-8')
    calculated_hash = hmac.new(
        secret,
        hash_calc_str.encode('utf-8'),
        hashlib.md5
    ).hexdigest().upper()

    if calculated_hash == received_hash:
        # 哈希验证通过,此处编写你的业务逻辑,如更新订单状态、发放权益等
        return HttpResponse('OK', status=200)
    # 哈希验证失败
    return HttpResponse('VALIDATION FAILED', status=403)

使用说明

  • 请先在Django项目配置文件中添加TWOCHECKOUT_IPN_SECRET配置,值为你在2Checkout后台获取的专属IPN密钥
  • 你需要自行将该视图配置到项目路由中,再将路由对应的完整URL填写到2Checkout后台的IPN回调地址配置项
  • 验证通过后的业务逻辑可根据实际需求自行扩展

内容的提问来源于stack exchange,提问作者zOthix

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.14 13:06:08