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

Django电商站点如何将订单总金额传递至Flutterwave支付网关

问题修复方案

核心问题排查

金额传递失败是以下几个错误共同导致的:

  • 视图未将购物车数据传递到模板,模板变量渲染异常
  • 静态JS文件无法解析Django模板标签,你在JS中写的{{cart.get_total_price}}不会被替换为实际金额
  • HTML中按钮属性语法错误,金额取值逻辑完全错误
  • JS存在变量重复定义的笔误

分步修复代码

1. 修复视图逻辑

首先给模板传递需要的上下文变量:

@login_required
def CartView(request):
    cart = Cart(request)
    total = cart.get_total_price()
    # 把需要的变量通过context传递给模板
    return render(request, 'payment/payment_form.html', {'cart': cart, 'total': total})

2. 修复HTML模板

修改金额存储和按钮属性:

<!-- 删掉错误的p标签 <p id="{{cart.get_total_price}}"></p> -->
<!-- 替换为实际显示的金额(可选) -->
<p class="fw-bold">订单总金额:${{total}}</p>
<script src="https://checkout.flutterwave.com/v3.js"></script>
<!-- 修复双等号错误,把金额存在data-amount属性里 -->
<button type="button" data-amount="{{total}}" id="submit" class="btn btn-primary w-100 fw-bold" >Pay ${{total}}</button>

3. 修复JS逻辑

修正取值方式和笔误:

document.addEventListener("DOMContentLoaded", (event) => {
  document.getElementById("submit").addEventListener("click", (e) => {
    e.preventDefault();
    const PBFKey = "xxxxxxxxxxxxxxxxxxxxxxxxxx";
    const txRef = ''+Math.floor((Math.random() * 1000000000) + 1);
    const email = document.getElementById('email').value;
    const fullname= document.getElementById('fullName').value;
    const address1= document.getElementById('custAdd').value;
    const address2= document.getElementById('custAdd2').value;
    const country= document.getElementById('country').value;
    const state= document.getElementById('state').value;
    // 修复重复定义address1的笔误
    const postCode = document.getElementById('postCode').value;
    // 从按钮的data属性中读取金额,转换为数字类型
    const amount = parseFloat(document.getElementById('submit').dataset.amount);

    getpaidSetup({
      PBFPubKey: PBFKey,
      customer_email: email,
      // 确认支付网关要求的金额单位,此处如果需要转分确保amount是数字
      amount: amount * 100,
      currency: "USD",
      txref: txRef,
      onclose: function() {},
      callback: function(response) {
        flw_ref = response.tx.flwRef;
        console.log("This is the response returned after a charge", response);
        if(response.tx.chargeResponse =='00' || response.tx.chargeResponse == '0') {
          // 跳转到成功页
        } else {
          // 跳转到失败页
        }
      }
    });
  });
});

安全注意事项

不要信任前端传递的金额,用户可以通过浏览器控制台篡改data-amount的值,支付网关回调后必须在后端校验实际订单金额和网关返回的支付金额是否一致,避免资损。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.23 16:36:05