stripe-payments

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Stripe Payment Integration

Stripe支付集成

Production-ready Stripe integration for payments, subscriptions, and webhooks.
可用于生产环境的Stripe集成方案,支持支付、订阅和webhook功能。

Payment Flows

支付流程

FlowUse CasePCI Burden
Checkout SessionHosted page, fastest setupMinimal
Payment IntentsCustom UI, full controlRequires Stripe.js
Setup IntentsSave card for laterMinimal
流程适用场景PCI合规负担
Checkout Session托管页面,设置最快极低
Payment Intents自定义UI,完全可控需要Stripe.js
Setup Intents保存卡片以便后续使用极低

Quick Start - Checkout Session

快速开始 - Checkout Session

python
import stripe
stripe.api_key = "sk_test_..."

session = stripe.checkout.Session.create(
    payment_method_types=['card'],
    line_items=[{
        'price_data': {
            'currency': 'usd',
            'product_data': {'name': 'Premium Plan'},
            'unit_amount': 2000,  # $20.00 in cents
            'recurring': {'interval': 'month'},
        },
        'quantity': 1,
    }],
    mode='subscription',
    success_url='https://example.com/success?session_id={CHECKOUT_SESSION_ID}',
    cancel_url='https://example.com/cancel',
)
python
import stripe
stripe.api_key = "sk_test_..."

session = stripe.checkout.Session.create(
    payment_method_types=['card'],
    line_items=[{
        'price_data': {
            'currency': 'usd',
            'product_data': {'name': 'Premium Plan'},
            'unit_amount': 2000,  # 20.00美元,单位为美分
            'recurring': {'interval': 'month'},
        },
        'quantity': 1,
    }],
    mode='subscription',
    success_url='https://example.com/success?session_id={CHECKOUT_SESSION_ID}',
    cancel_url='https://example.com/cancel',
)

Redirect to session.url

重定向至session.url

undefined
undefined

Custom Payment Intent Flow

自定义Payment Intent流程

python
undefined
python
undefined

Backend: Create payment intent

后端:创建支付意向

def create_payment_intent(amount, customer_id=None): intent = stripe.PaymentIntent.create( amount=amount, # In cents currency='usd', customer=customer_id, automatic_payment_methods={'enabled': True}, ) return intent.client_secret

```javascript
// Frontend: Confirm payment
const stripe = Stripe('pk_test_...');
const {error, paymentIntent} = await stripe.confirmCardPayment(
    clientSecret,
    {payment_method: {card: cardElement}}
);
def create_payment_intent(amount, customer_id=None): intent = stripe.PaymentIntent.create( amount=amount, # 单位为美分 currency='usd', customer=customer_id, automatic_payment_methods={'enabled': True}, ) return intent.client_secret

```javascript
// 前端:确认支付
const stripe = Stripe('pk_test_...');
const {error, paymentIntent} = await stripe.confirmCardPayment(
    clientSecret,
    {payment_method: {card: cardElement}}
);

Webhook Handling

Webhook处理

python
@app.route('/webhook', methods=['POST'])
def webhook():
    payload = request.data
    sig = request.headers.get('Stripe-Signature')

    try:
        event = stripe.Webhook.construct_event(
            payload, sig, 'whsec_...'
        )
    except stripe.error.SignatureVerificationError:
        return 'Invalid signature', 400

    if event['type'] == 'payment_intent.succeeded':
        handle_payment_success(event['data']['object'])
    elif event['type'] == 'customer.subscription.deleted':
        handle_subscription_canceled(event['data']['object'])

    return 'OK', 200
python
@app.route('/webhook', methods=['POST'])
def webhook():
    payload = request.data
    sig = request.headers.get('Stripe-Signature')

    try:
        event = stripe.Webhook.construct_event(
            payload, sig, 'whsec_...'
        )
    except stripe.error.SignatureVerificationError:
        return '无效签名', 400

    if event['type'] == 'payment_intent.succeeded':
        handle_payment_success(event['data']['object'])
    elif event['type'] == 'customer.subscription.deleted':
        handle_subscription_canceled(event['data']['object'])

    return 'OK', 200

Critical Webhook Events

关键Webhook事件

EventWhen to Handle
payment_intent.succeeded
Payment completed
payment_intent.payment_failed
Payment failed
customer.subscription.updated
Subscription changed
customer.subscription.deleted
Subscription canceled
invoice.payment_succeeded
Subscription payment OK
事件处理时机
payment_intent.succeeded
支付完成时
payment_intent.payment_failed
支付失败时
customer.subscription.updated
订阅变更时
customer.subscription.deleted
订阅取消时
invoice.payment_succeeded
订阅支付成功时

Subscription Management

订阅管理

python
undefined
python
undefined

Create subscription

创建订阅

subscription = stripe.Subscription.create( customer=customer_id, items=[{'price': 'price_xxx'}], payment_behavior='default_incomplete', expand=['latest_invoice.payment_intent'], )
subscription = stripe.Subscription.create( customer=customer_id, items=[{'price': 'price_xxx'}], payment_behavior='default_incomplete', expand=['latest_invoice.payment_intent'], )

Customer portal for self-service

客户自助管理门户

session = stripe.billing_portal.Session.create( customer=customer_id, return_url='https://example.com/account', )
session = stripe.billing_portal.Session.create( customer=customer_id, return_url='https://example.com/account', )

Redirect to session.url

重定向至session.url

undefined
undefined

Refunds

退款

python
undefined
python
undefined

Full refund

全额退款

stripe.Refund.create(payment_intent='pi_xxx')
stripe.Refund.create(payment_intent='pi_xxx')

Partial refund

部分退款

stripe.Refund.create( payment_intent='pi_xxx', amount=500, # $5.00 reason='requested_by_customer' )
undefined
stripe.Refund.create( payment_intent='pi_xxx', amount=500, # 5.00美元 reason='requested_by_customer' )
undefined

Test Cards

测试卡片

Card NumberResult
4242424242424242
Success
4000000000000002
Declined
4000002500003155
3D Secure required
4000000000009995
Insufficient funds
卡号测试结果
4242424242424242
支付成功
4000000000000002
支付被拒绝
4000002500003155
需要3D Secure验证
4000000000009995
余额不足

Best Practices

最佳实践

  1. Always use webhooks - Don't rely on client-side confirmation
  2. Idempotency - Handle webhook events exactly once
  3. Metadata - Link Stripe objects to your database
  4. Test mode - Test all flows before production
  5. PCI compliance - Never handle raw card data server-side
  6. SCA - Implement 3D Secure for European payments
  1. 始终使用webhook - 不要依赖客户端确认
  2. 幂等性 - 确保webhook事件仅被处理一次
  3. 元数据 - 将Stripe对象与你的数据库关联
  4. 测试模式 - 上线前测试所有流程
  5. PCI合规 - 切勿在服务器端处理原始卡片数据
  6. SCA - 针对欧洲支付实现3D Secure验证

Common Pitfalls

常见误区

  • Not verifying webhook signatures
  • Hardcoding amounts (use cents!)
  • Missing webhook event handlers
  • No retry logic for API calls
  • Skipping test card scenarios
  • 未验证webhook签名
  • 硬编码金额(务必使用美分!)
  • 遗漏webhook事件处理程序
  • API调用未添加重试逻辑
  • 跳过测试卡片场景