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

如何将Google Pay接入Django项目以实现课程付费功能?

Django 接入 Google Pay 支付系统实操指南

一、前置准备

  • 注册Google Pay商户账号,获取Merchant ID,并在控制台配置支持的支付方式(如Visa、Mastercard等)。
  • 确保你的Django站点在生产环境使用HTTPS(本地开发可通过ngrok生成HTTPS代理地址),Google Pay要求页面必须通过安全连接加载。

二、前端集成Google Pay按钮

在课程购买页面的Django模板中添加以下代码,实现Google Pay按钮的渲染与交互:

<!-- 加载Google Pay JS库 -->
<script src="https://pay.google.com/gp/p/js/pay.js"></script>

<div id="google-pay-button"></div>

<script>
  const baseRequest = {
    apiVersion: 2,
    apiVersionMinor: 0,
    allowedPaymentMethods: [
      {
        type: 'CARD',
        parameters: {
          allowedAuthMethods: ['PAN_ONLY', 'CRYPTOGRAM_3DS'],
          allowedCardNetworks: ['MASTERCARD', 'VISA']
        },
        tokenizationSpecification: {
          type: 'PAYMENT_GATEWAY',
          parameters: {
            // 替换为你的支付网关参数,比如用Stripe则填"gateway": "stripe", "stripe:publishableKey": "你的Stripe公钥"
            "gateway": "your-payment-gateway",
            "your-gateway-param": "your-value"
          }
        }
      }
    ]
  };

  const googlePayClient = new google.payments.api.PaymentsClient({environment: 'TEST'}); // 生产环境改为'PRODUCTION'

  googlePayClient.isReadyToPay(baseRequest)
    .then(response => {
      if (response.result) {
        const paymentDataRequest = Object.assign({}, baseRequest, {
          merchantInfo: {
            merchantId: '你的Merchant ID',
            merchantName: '你的课程平台名称'
          },
          transactionInfo: {
            totalPriceStatus: 'FINAL',
            totalPrice: '99.99', // 课程实际价格
            currencyCode: 'USD' // 根据业务调整货币代码
          }
        });

        googlePayClient.createButton({
          onClick: () => googlePayClient.loadPaymentData(paymentDataRequest)
            .then(paymentData => {
              // 将支付令牌发送到Django后端
              fetch('/process-google-pay/', {
                method: 'POST',
                headers: {
                  'Content-Type': 'application/json',
                  'X-CSRFToken': '{{ csrf_token }}' // Django CSRF令牌
                },
                body: JSON.stringify({payment_token: paymentData.paymentMethodData.tokenizationData.token})
              })
              .then(response => response.json())
              .then(result => {
                if (result.success) {
                  alert('支付成功,即将为你开通课程');
                  window.location.href = '/course-access/'; // 跳转到课程页面
                } else {
                  alert('支付失败,请重试');
                }
              })
            })
            .catch(error => console.error('支付请求失败:', error))
        }).render('#google-pay-button');
      }
    })
    .catch(error => console.error('Google Pay初始化失败:', error));
</script>

三、后端支付处理(Django视图)

在Django中创建视图处理支付令牌,调用支付网关完成扣款,并更新用户课程权限:

from django.http import JsonResponse
from django.views.decorators.http import require_POST
import json
# 导入你的支付网关SDK,示例以Stripe为例
import stripe

stripe.api_key = '你的Stripe私钥'

@require_POST
def process_google_pay(request):
    try:
        data = json.loads(request.body)
        payment_token = data.get('payment_token')
        
        # 调用支付网关完成扣款,金额单位为分(对应99.99美元)
        charge = stripe.Charge.create(
            amount=9999,
            currency='usd',
            source=payment_token,
            description='课程购买: Python进阶教程'
        )
        
        if charge.status == 'succeeded':
            # 为当前用户开通课程权限(示例逻辑,根据你的模型调整)
            user = request.user
            user.courses.add(your_course_instance) # 假设用户与课程为多对多关联
            user.save()
            
            return JsonResponse({'success': True})
        else:
            return JsonResponse({'success': False, 'error': '支付未完成'})
    except Exception as e:
        return JsonResponse({'success': False, 'error': str(e)})

四、关键注意事项

  • 测试环境:使用Google Pay官方测试卡号(如4111 1111 1111 1111,有效期填未来任意日期,CVV任意3位)进行测试,避免产生真实扣款。
  • 错误处理:前端需捕获用户取消支付、网络异常等场景,后端需记录支付日志以便排查问题。
  • 生产环境切换:将前端代码中的environment改为'PRODUCTION',并替换所有测试用的Merchant ID、支付网关参数为生产环境值。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 06:30:25