stripe-payments
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseStripe Payment Integration
Stripe支付集成
Production-ready Stripe integration for payments, subscriptions, and webhooks.
可用于生产环境的Stripe集成方案,支持支付、订阅和webhook功能。
Payment Flows
支付流程
| Flow | Use Case | PCI Burden |
|---|---|---|
| Checkout Session | Hosted page, fastest setup | Minimal |
| Payment Intents | Custom UI, full control | Requires Stripe.js |
| Setup Intents | Save card for later | Minimal |
| 流程 | 适用场景 | 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
undefinedundefinedCustom Payment Intent Flow
自定义Payment Intent流程
python
undefinedpython
undefinedBackend: 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', 200python
@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', 200Critical Webhook Events
关键Webhook事件
| Event | When to Handle |
|---|---|
| Payment completed |
| Payment failed |
| Subscription changed |
| Subscription canceled |
| Subscription payment OK |
| 事件 | 处理时机 |
|---|---|
| 支付完成时 |
| 支付失败时 |
| 订阅变更时 |
| 订阅取消时 |
| 订阅支付成功时 |
Subscription Management
订阅管理
python
undefinedpython
undefinedCreate 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
undefinedundefinedRefunds
退款
python
undefinedpython
undefinedFull 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'
)
undefinedstripe.Refund.create(
payment_intent='pi_xxx',
amount=500, # 5.00美元
reason='requested_by_customer'
)
undefinedTest Cards
测试卡片
| Card Number | Result |
|---|---|
| Success |
| Declined |
| 3D Secure required |
| Insufficient funds |
| 卡号 | 测试结果 |
|---|---|
| 支付成功 |
| 支付被拒绝 |
| 需要3D Secure验证 |
| 余额不足 |
Best Practices
最佳实践
- Always use webhooks - Don't rely on client-side confirmation
- Idempotency - Handle webhook events exactly once
- Metadata - Link Stripe objects to your database
- Test mode - Test all flows before production
- PCI compliance - Never handle raw card data server-side
- SCA - Implement 3D Secure for European payments
- 始终使用webhook - 不要依赖客户端确认
- 幂等性 - 确保webhook事件仅被处理一次
- 元数据 - 将Stripe对象与你的数据库关联
- 测试模式 - 上线前测试所有流程
- PCI合规 - 切勿在服务器端处理原始卡片数据
- 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调用未添加重试逻辑
- 跳过测试卡片场景