stripe-integration – skill Khác cho agent AI
Triển khai và kiểm tra Stripe checkout, subscription, webhook và hoàn tiền với phân quyền phía server rõ ràng và giới hạn retry.
Cài skill stripe-integration bằng một lệnh
Chọn công cụ bạn đang dùng, copy lệnh và dán vào terminal. Skill sẽ nằm trong thư mục skills của công cụ đó và sẵn sàng dùng ở phiên làm việc tiếp theo.
Claude Code
mkdir -p ~/.claude/skills && curl -fsSL https://skill.dn1nguoi.com/z/stripe-integration-ddc43.tgz | tar xz -C ~/.claude/skills
Gọi trong Claude Code: /stripe-integration – rồi mô tả công việc bạn muốn làm.
Codex
mkdir -p ~/.codex/skills && curl -fsSL https://skill.dn1nguoi.com/z/stripe-integration-ddc43.tgz | tar xz -C ~/.codex/skills
Gọi trong Codex: $stripe-integration – rồi mô tả công việc bạn muốn làm.
Hermes Agent
mkdir -p ~/.hermes/skills && curl -fsSL https://skill.dn1nguoi.com/z/stripe-integration-ddc43.tgz | tar xz -C ~/.hermes/skills
Gọi trong Hermes Agent: /stripe-integration – rồi mô tả công việc bạn muốn làm.
DeepSeek
mkdir -p ~/.deepcode/skills && curl -fsSL https://skill.dn1nguoi.com/z/stripe-integration-ddc43.tgz | tar xz -C ~/.deepcode/skills
Gọi trong DeepSeek: /stripe-integration – rồi mô tả công việc bạn muốn làm.
Nội dung SKILL.md
Nội dung SKILL.md gốc bằng tiếng Anh.
Stripe Integration
Implement and verify Stripe checkout, subscriptions, webhooks and refunds with explicit server-side authorization and retry boundaries.
Do not use this skill when
- The task is unrelated to stripe integration
- You need a different domain or tool outside this scope
Instructions
- Clarify goals, constraints, and required inputs.
- Apply relevant best practices and validate outcomes.
- Provide actionable steps and verification.
- Inspect the installed Stripe SDK and pinned API/webhook version. This single-file skill has no bundled playbook or production wrapper.
Use this skill when
- Implementing payment processing in web/mobile applications
- Setting up subscription billing systems
- Handling one-time payments and recurring charges
- Processing refunds and disputes
- Managing customer payment methods
- Implementing SCA (Strong Customer Authentication) for European payments
- Building marketplace payment flows with Stripe Connect
Core Concepts
1. Payment Flows
Checkout Session (Hosted)
- Stripe-hosted payment page
- Reduced direct card-data handling
- Fastest implementation
- Supports one-time and recurring payments
Payment Intents (Custom UI)
- Full control over payment UI
- Uses Stripe.js/Elements to avoid handling raw card data directly
- More complex implementation
- Better customization options
Setup Intents (Save Payment Methods)
- Collect payment method without charging
- Used for subscriptions and future payments
- Requires customer confirmation
2. Webhooks
Critical Events:
payment_intent.succeeded: Payment completedpayment_intent.payment_failed: Payment failedcustomer.subscription.updated: Subscription changedcustomer.subscription.deleted: Subscription canceledcharge.refunded: Refund processedinvoice.payment_succeeded: Subscription payment successful
3. Subscriptions
Components:
- Product: What you're selling
- Price: How much and how often
- Subscription: Customer's recurring payment
- Invoice: Generated for each billing cycle
4. Customer Management
- Create and manage customer records
- Store multiple payment methods
- Track customer metadata
- Manage billing details
Inputs and safety boundary
Use an explicitly authorized Stripe test account/sandbox, server-owned order and customer records, the installed SDK/API version and expected webhook types. Amounts, currencies, price/customer IDs and refund permissions must come from authenticated server policy, not arbitrary client parameters. Checkout/Elements can reduce card-data exposure; they do not establish PCI compliance by themselves.
The snippets are integration sketches. Test secret keys and webhook signing secrets are different; load them from the project secret mechanism and never print them. No live payment, refund, customer update or account configuration is authorized merely by reading this skill.
Quick Start
import os
import stripe
stripe.api_key = os.environ["STRIPE_SECRET_KEY"]
# Create a checkout session
session = stripe.checkout.Session.create(
payment_method_types=['card'],
line_items=[{
'price_data': {
'currency': 'usd',
'product_data': {
'name': 'Premium Subscription',
},
'unit_amount': 2000, # $20.00
'recurring': {
'interval': 'month',
},
},
'quantity': 1,
}],
mode='subscription',
success_url='https://yourdomain.com/success?session_id={CHECKOUT_SESSION_ID}',
cancel_url='https://yourdomain.com/cancel',
)
# Redirect user to session.url
print(session.url)Payment Implementation Patterns
Pattern 1: One-Time Payment (Hosted Checkout)
def create_checkout_session(amount, order_attempt_id, currency='usd'):
"""Create a one-time payment checkout session."""
try:
session = stripe.checkout.Session.create(
payment_method_types=['card'],
line_items=[{
'price_data': {
'currency': currency,
'product_data': {
'name': 'Purchase',
'images': ['https://example.com/product.jpg'],
},
'unit_amount': amount, # Amount in cents
},
'quantity': 1,
}],
mode='payment',
success_url='https://yourdomain.com/success?session_id={CHECKOUT_SESSION_ID}',
cancel_url='https://yourdomain.com/cancel',
metadata={
'order_id': 'order_123',
'user_id': 'user_456'
},
idempotency_key=order_attempt_id
)
return session
except stripe.error.StripeError as e:
# Handle error
print(f"Stripe error: {e.user_message}")
raisePattern 2: Custom Payment Intent Flow
def create_payment_intent(amount, order_attempt_id, currency='usd', customer_id=None):
"""Create a payment intent for custom checkout UI."""
intent = stripe.PaymentIntent.create(
amount=amount,
currency=currency,
customer=customer_id,
automatic_payment_methods={
'enabled': True,
},
metadata={
'integration_check': 'accept_a_payment'
},
idempotency_key=order_attempt_id
)
return intent.client_secret # Only to the authenticated client for this order; never log it
# Frontend (JavaScript)
"""
const stripe = Stripe('pk_test_...');
const elements = stripe.elements();
const cardElement = elements.create('card');
cardElement.mount('#card-element');
const {error, paymentIntent} = await stripe.confirmCardPayment(
clientSecret,
{
payment_method: {
card: cardElement,
billing_details: {
name: 'Customer Name'
}
}
}
);
if (error) {
// Handle error
} else if (paymentIntent.status === 'succeeded') {
// Update display only; server fulfillment still verifies payment state
}
"""Pattern 3: Subscription creation contract
Use the flow documented for the account’s pinned API version. Do not assume latest_invoice.payment_intent exists in every version or that every invoice has an immediately confirmable payment. Resolve an authorized customer and allowed price, create the incomplete subscription with an idempotency key, and handle the returned confirmation state through that version’s API. Grant access from verified subscription/invoice state; test trials, zero-amount invoices, delayed payments, cancellation and retries.
See [Stripe subscription integration](https://docs.stripe.com/billing/subscriptions/build-subscriptions). The customer portal below also requires ownership checks before accepting a customer ID.
Pattern 4: Customer Portal
def create_customer_portal_session(customer_id):
"""Create a portal session for customers to manage subscriptions."""
session = stripe.billing_portal.Session.create(
customer=customer_id,
return_url='https://yourdomain.com/account',
)
return session.url # Redirect customer hereWebhook Handling
Secure Webhook Endpoint
import os
from flask import Flask, request
import stripe
app = Flask(__name__)
endpoint_secret = os.environ["STRIPE_WEBHOOK_SECRET"]
@app.route('/webhook', methods=['POST'])
def webhook():
payload = request.get_data(cache=False) # Exact raw bytes; enforce an ingress body-size limit
sig_header = request.headers.get('Stripe-Signature')
if not sig_header:
return 'Missing signature', 400
try:
event = stripe.Webhook.construct_event(
payload, sig_header, endpoint_secret
)
except ValueError:
# Invalid payload
return 'Invalid payload', 400
except stripe.SignatureVerificationError:
# Invalid signature
return 'Invalid signature', 400
# Integration sketch: durable deduplication/queueing below must precede effects.
# Bind account, mode, order, amount/currency and expected current state first.
# Handle the event
if event['type'] == 'payment_intent.succeeded':
payment_intent = event['data']['object']
handle_successful_payment(payment_intent)
elif event['type'] == 'payment_intent.payment_failed':
payment_intent = event['data']['object']
handle_failed_payment(payment_intent)
elif event['type'] == 'customer.subscription.deleted':
subscription = event['data']['object']
handle_subscription_canceled(subscription)
return 'Success', 200
def handle_successful_payment(payment_intent):
"""Process successful payment."""
customer_id = payment_intent.get('customer')
amount = payment_intent['amount']
metadata = payment_intent.get('metadata', {})
# Update your database
# Send confi… (nội dung đầy đủ có trong gói tải về)
Skill liên quan
- suno-lyrics-to-song – Cài đặt và dùng gói Lyrics to Song chính thức, ghim theo digest, cho công việc trả phí…
- supabase – Dùng khi thực hiện BẤT KỲ tác vụ nào liên quan đến Supabase.
- systemd-services – Tạo và quản lý service và timer của systemd. Cấu hình phụ thuộc giữa các service và giới…
- talking-avatar-video – Cài đặt và sử dụng gói Talking Avatar Video chính thức, ghim theo digest, cho công việc…
- task-intelligence – Giao thức Trí tuệ Trước Tác vụ: lên kế hoạch cho tác vụ và chỉ truy vấn các agent khả…
- tcm-constitution-analyzer – Phân tích dữ liệu thể trạng theo Đông y, nhận diện loại thể trạng, đánh giá đặc điểm thể…
- tdd-workflows – Dùng khi làm việc với chu trình TDD (bí danh của tdd-workflows-tdd-cycle)
- tdd-workflows-tdd-cycle – Dùng khi làm việc với chu trình TDD.