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

如何在已集成PayPal结账的WordPress站点中添加折扣优惠券代码

PayPal结账页添加优惠券功能的修改方案

修改步骤

  • 第一步:新增优惠券输入、提示的前端UI
  • 第二步:定义优惠券规则、折扣计算逻辑
  • 第三步:修改PayPal订单创建逻辑,联动动态计算的最终金额,同时支持在PayPal账单中展示折扣明细
  • 第四步:补充后端校验逻辑(正式上线必须配置,避免前端篡改导致资损)

完整修改后代码

<meta name="viewport" content="width=device-width, initial-scale=1"> <!-- 适配移动端显示 -->
<meta http-equiv="X-UA-Compatible" content="IE=edge"> <!-- 适配IE浏览器 -->

<!-- 引入PayPal JavaScript SDK,把<test-id>替换为你自己的沙箱企业账户客户端ID -->
<script src="https://www.paypal.com/sdk/js?client-id=<test-id>;currency=USD"></script>

<!-- 新增优惠券输入区块 -->
<div style="margin: 20px 0;">
  <input type="text" id="coupon-code" placeholder="输入优惠券代码">
  <button id="apply-coupon">应用优惠券</button>
  <p id="coupon-message" style="margin: 10px 0;"></p>
  <p>原价:<span id="original-price">77.44</span> USD</p>
  <p>实付:<span id="final-price">77.44</span> USD</p>
</div>

<!-- PayPal按钮容器 -->
<div id="paypal-button-container"></div>

<script>
  // 配置优惠券规则(正式上线建议将规则存到后端,避免前端泄露所有可用券)
  const validCoupons = {
    "SAVE10": { type: "percent", value: 10 }, // 10%折扣
    "FIX20": { type: "fixed", value: 20 } // 固定减免20美元
  };
  const originalPrice = 77.44;
  let currentDiscount = 0;
  let finalPrice = originalPrice;

  // 优惠券应用逻辑
  document.getElementById('apply-coupon').addEventListener('click', function() {
    const inputCode = document.getElementById('coupon-code').value.trim();
    const messageEl = document.getElementById('coupon-message');
    const finalPriceEl = document.getElementById('final-price');

    if (validCoupons.hasOwnProperty(inputCode)) {
      const coupon = validCoupons[inputCode];
      // 计算折扣金额
      if (coupon.type === 'percent') {
        currentDiscount = originalPrice * (coupon.value / 100);
      } else if (coupon.type === 'fixed') {
        currentDiscount = coupon.value;
      }
      // 避免折扣后金额小于0.01(PayPal要求交易金额最低为0.01美元)
      finalPrice = Math.max((originalPrice - currentDiscount).toFixed(2), 0.01);
      messageEl.textContent = `优惠券应用成功,已减免${currentDiscount.toFixed(2)}美元`;
      messageEl.style.color = 'green';
      finalPriceEl.textContent = finalPrice;
    } else {
      currentDiscount = 0;
      finalPrice = originalPrice;
      messageEl.textContent = '无效的优惠券代码';
      messageEl.style.color = 'red';
      finalPriceEl.textContent = finalPrice;
    }
  });

  paypal.Buttons({
    // 点击支付按钮时创建交易
    createOrder: function(data, actions) {
      return actions.order.create({
        purchase_units: [{
          amount: {
            value: finalPrice,
            currency_code: 'USD',
            // 配置折扣明细,PayPal支付页会显示原价和折扣信息
            breakdown: {
              item_total: {
                currency_code: 'USD',
                value: originalPrice.toFixed(2)
              },
              discount: {
                currency_code: 'USD',
                value: currentDiscount.toFixed(2)
              }
            }
          }
        }]
      });
    },

    // 付款人授权后完成交易
    onApprove: function(data, actions) {
      return actions.order.capture().then(function(orderData) {
        // 测试阶段日志打印,上线后可删除
        console.log('Capture result', orderData, JSON.stringify(orderData, null, 2));
        var transaction = orderData.purchase_units[0].payments.captures[0];
        alert('交易'+ transaction.status + ': ' + transaction.id + '\n\n可查看控制台获取完整信息');

        // 正式上线建议在此处提交订单信息到后端,二次校验金额、优惠券有效性,再执行后续订单逻辑
        // var element = document.getElementById('paypal-button-container');
        // element.innerHTML = '';
        // element.innerHTML = '<h3>支付成功,感谢你的购买!</h3>';
        // 也可以跳转到感谢页:actions.redirect('thank_you.html');
      });
    }
  }).render('#paypal-button-container');
</script>

注意事项

  • 前端的优惠券校验仅做交互优化,正式上线必须加后端二次校验:用户提交支付前、交易回调后都要核对优惠券有效性、最终交易金额是否符合规则,避免前端被篡改导致资损。WordPress环境下可通过自定义REST API接口或者admin-ajax实现后端验券逻辑。
  • 测试阶段请使用PayPal沙箱环境验证不同优惠券对应的支付金额是否正确,确认无误后再上线。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 20:15:05