Back to library

Stripe API

Skill for Stripe API — auto-generated from documentation

dev
by skynetv1.0.0
stripe-apidevauto-generated

0

Total Uses

0

Successes

0%

Success Rate

Compatible Agents

claude-codecodexgemini

Instruction

--- name: Stripe API Integration description: Use when building payment processing functionality, handling subscriptions, managing customers, processing refunds, or integrating any payment-related features into applications metadata: author: skynet version: 1.0.0 category: dev --- # Stripe API Integration ## Setup & Authentication ### Install Stripe CLI ```bash # macOS brew install stripe/stripe-cli/stripe # Linux wget -qO- https://github.com/stripe/stripe-cli/releases/latest/download/stripe_linux_x86_64.tar.gz | tar -xz # Login and configure stripe login stripe config --set account_id acct_xxxxxxxxxxxxx ``` ### Environment Setup ```bash # Set API keys in environment export STRIPE_PUBLISHABLE_KEY="pk_test_xxxxxxxxxxxxx" export STRIPE_SECRET_KEY="sk_test_xxxxxxxxxxxxx" export STRIPE_WEBHOOK_SECRET="whsec_xxxxxxxxxxxxx" ``` ## Core Operations ### Customer Management ```bash # Create customer stripe customers create \ --email="customer@example.com" \ --name="John Doe" \ --phone="+1234567890" # List customers stripe customers list --limit=10 # Retrieve customer stripe customers retrieve cus_xxxxxxxxxxxxx # Update customer stripe customers update cus_xxxxxxxxxxxxx \ --metadata[user_id]=12345 \ --description="Premium customer" ``` ### Payment Processing ```bash # Create payment intent stripe payment_intents create \ --amount=2000 \ --currency=usd \ --customer=cus_xxxxxxxxxxxxx \ --payment_method=pm_xxxxxxxxxxxxx \ --confirm=true # Create setup intent (for saving payment methods) stripe setup_intents create \ --customer=cus_xxxxxxxxxxxxx \ --payment_method_types[0]=card # Capture payment intent stripe payment_intents capture pi_xxxxxxxxxxxxx ``` ### Subscription Management ```bash # Create product stripe products create \ --name="Premium Plan" \ --description="Monthly premium subscription" # Create price stripe prices create \ --product=prod_xxxxxxxxxxxxx \ --unit_amount=2000 \ --currency=usd \ --recurring[interval]=month # Create subscription stripe subscriptions create \ --customer=cus_xxxxxxxxxxxxx \ --items[0][price]=price_xxxxxxxxxxxxx \ --payment_behavior=default_incomplete \ --expand[0]=latest_invoice.payment_intent # Cancel subscription stripe subscriptions cancel sub_xxxxxxxxxxxxx ``` ## Code Implementation Examples ### Node.js Payment Intent ```javascript const stripe = require('stripe')(process.env.STRIPE_SECRET_KEY); async function createPaymentIntent(amount, currency, customerId) { try { const paymentIntent = await stripe.paymentIntents.create({ amount: amount * 100, // Convert to cents currency: currency, customer: customerId, automatic_payment_methods: { enabled: true, }, }); return paymentIntent.client_secret; } catch (error) { console.error('Payment intent creation failed:', error); throw error; } } ``` ### Python Subscription Creation ```python import stripe stripe.api_key = os.getenv('STRIPE_SECRET_KEY') def create_subscription(customer_id, price_id): try: subscription = stripe.Subscription.create( customer=customer_id, items=[{'price': price_id}], payment_behavior='default_incomplete', payment_settings={'save_default_payment_method': 'on_subscription'}, expand=['latest_invoice.payment_intent'], ) return subscription except stripe.error.StripeError as e: print(f"Subscription creation failed: {e}") raise ``` ### Webhook Handler (Express.js) ```javascript app.post('/webhook', express.raw({type: 'application/json'}), (req, res) => { const sig = req.headers['stripe-signature']; let event; try { event = stripe.webhooks.constructEvent(req.body, sig, process.env.STRIPE_WEBHOOK_SECRET); } catch (err) { console.log(`Webhook signature verification failed.`, err.message); return res.status(400).send(`Webhook Error: ${err.message}`); } switch (event.type) { case 'payment_intent.succeeded': const paymentIntent = event.data.object; console.log('Payment succeeded:', paymentIntent.id); break; case 'invoice.payment_failed': const invoice = event.data.object; console.log('Payment failed:', invoice.id); break; default: console.log(`Unhandled event type ${event.type}`); } res.json({received: true}); }); ``` ## Decision Trees ### Payment Flow Selection ``` Need to process payment? ├── One-time payment │ ├── Immediate charge → Payment Intent + confirm=true │ └── Save card for later → Setup Intent → Payment Intent └── Recurring payment ├── Fixed schedule → Subscription ├── Usage-based → Subscription + usage records └── Marketplace → Connect accounts + transfers ``` ### Error Handling Strategy ``` Payment failed? ├── card_declined │ ├── insufficient_funds → Ask for different card │ ├── generic_decline → Retry with 3DS │ └── stolen_card → Block and report ├── authentication_required │ └── Initiate 3D Secure flow └── processing_error └── Retry with exponential backoff ``` ## Testing & Development ### Local Webhook Testing ```bash # Forward webhooks to local server stripe listen --forward-to localhost:3000/webhook # Trigger test events stripe trigger payment_intent.succeeded stripe trigger invoice.payment_failed stripe trigger customer.subscription.deleted # Test with specific data stripe payment_intents create \ --amount=2000 \ --currency=usd \ --payment_method=pm_card_visa ``` ### Test Card Numbers ```bash # Successful payments 4242424242424242 # Visa 4000056655665556 # Visa (debit) 5555555555554444 # Mastercard # Declined payments 4000000000000002 # Generic decline 4000000000009995 # Insufficient funds 4000000000009987 # Lost card # 3D Secure required 4000002760003184 # 3DS required 4000002500003155 # 3DS not supported ``` ## Troubleshooting ### Common Errors **Error: "No such customer: cus_xxxxxxxxxxxxx"** ```bash # Verify customer exists stripe customers retrieve cus_xxxxxxxxxxxxx # If not found, create new customer or check ID ``` **Error: "Your card was declined"** ```bash # Check decline code stripe charges retrieve ch_xxxxxxxxxxxxx --expand=outcome # Common fixes: # - Verify card details # - Check billing address # - Enable 3D Secure ``` **Error: "Invalid API key provided"** ```bash # Verify key format and environment echo $STRIPE_SECRET_KEY | cut -c1-7 # Should show "sk_test" or "sk_live" # Check key permissions in dashboard stripe config --list ``` **Error: "Webhook signature verification failed"** ```javascript // Ensure raw body is used app.use('/webhook', express.raw({type: 'application/json'})); // Verify webhook endpoint secret console.log('Webhook secret:', process.env.STRIPE_WEBHOOK_SECRET?.slice(0, 10)); ``` ### Monitoring Commands ```bash # Monitor real-time events stripe logs tail # View payment intent details stripe payment_intents retrieve pi_xxxxxxxxxxxxx --expand=charges.data.outcome # Check webhook deliveries stripe webhook_endpoints list stripe events list --type=payment_intent.succeeded # Balance and transfers stripe balance retrieve stripe transfers list --limit=10 ``` ### Production Checklist ```bash # Switch to live keys export STRIPE_SECRET_KEY="sk_live_xxxxxxxxxxxxx" export STRIPE_PUBLISHABLE_KEY="pk_live_xxxxxxxxxxxxx" # Verify webhook endpoints stripe webhook_endpoints list --live # Test payment flow end-to-end # Monitor error rates in dashboard # Set up automated alerts for failed payments ``` ## Advanced Features ### Connect for Marketplaces ```bash # Create connected account stripe accounts create \ --type=express \ --country=US \ --email="seller@example.com" # Create account link stripe account_links create \ --account=acct_xxxxxxxxxxxxx \ --refresh_url="https://example.com/reauth" \ --return_url="https://example.com/return" \ --type=account_onboarding ``` ### Usage-based Billing ```bash # Create usage record stripe subscription_items create_usage_record si_xxxxxxxxxxxxx \ --quantity=100 \ --timestamp=$(date +%s) # View usage summary stripe subscription_items list_usage_record_summaries si_xxxxxxxxxxxxx ```

Install

curl -s https://skills.skynet.ceo/api/skills/stripe-api/skill.md