Back

Step by Step Guide to Building a Stripe API Integration in Python

Jul 19, 20246 minute read

Introduction

Hey there, fellow developer! Ready to dive into the world of online payments? Stripe's API is your ticket to hassle-free payment processing, and we're going to walk through integrating it with Python. Trust me, it's easier than you might think!

Prerequisites

Before we jump in, make sure you've got:

  • A Python environment set up (I know you've got this!)
  • A Stripe account with API keys handy

Installation

Let's start with the basics. Fire up your terminal and run:

pip install stripe

Easy peasy, right?

Authentication

Now, let's get you authenticated. Grab your API key from your Stripe dashboard and add this to your Python script:

import stripe stripe.api_key = "your_secret_key_here"

Remember, keep that API key secret!

Basic API Requests

Time for the fun part - let's make some API calls!

Creating a Customer

customer = stripe.Customer.create( email="[email protected]", name="John Doe" )

Creating a Payment Method

payment_method = stripe.PaymentMethod.create( type="card", card={ "number": "4242424242424242", "exp_month": 8, "exp_year": 2023, "cvc": "314", }, )

Creating a Charge

charge = stripe.Charge.create( amount=2000, # Amount in cents currency="usd", source="tok_visa", description="My First Test Charge (created for API docs)" )

Handling Webhooks

Webhooks are like Stripe's way of sliding into your DMs. Here's how to handle them:

@app.route('/webhook', methods=['POST']) def webhook(): payload = request.data sig_header = request.headers['Stripe-Signature'] try: event = stripe.Webhook.construct_event( payload, sig_header, webhook_secret ) except ValueError as e: return 'Invalid payload', 400 except stripe.error.SignatureVerificationError as e: return 'Invalid signature', 400 # Handle the event if event['type'] == 'payment_intent.succeeded': payment_intent = event['data']['object'] # Then define and call a method to handle the successful payment intent. # ... handle other event types else: print('Unhandled event type {}'.format(event['type'])) return '', 200

Error Handling

Stripe can throw some curveballs. Here's how to catch them:

try: # Stripe API call except stripe.error.CardError as e: # Since it's a decline, stripe.error.CardError will be caught print('Status is: %s' % e.http_status) print('Code is: %s' % e.code) print('Param is: %s' % e.param) print('Message is: %s' % e.user_message) except stripe.error.RateLimitError as e: # Too many requests made to the API too quickly pass except stripe.error.InvalidRequestError as e: # Invalid parameters were supplied to Stripe's API pass except stripe.error.AuthenticationError as e: # Authentication with Stripe's API failed # (maybe you changed API keys recently) pass except stripe.error.APIConnectionError as e: # Network communication with Stripe failed pass except stripe.error.StripeError as e: # Display a very generic error to the user, and maybe send # yourself an email pass except Exception as e: # Something else happened, completely unrelated to Stripe pass

Best Practices

  • Always specify the API version in your requests
  • Use idempotency keys for POST requests to prevent accidental duplicates
  • Be mindful of rate limits (don't go too crazy with those API calls!)

Testing

Stripe provides a test mode - use it! And don't forget to write unit tests for your integration. Your future self will thank you.

Conclusion

And there you have it! You're now equipped to handle payments like a pro. Remember, the Stripe docs are your friend for any advanced features you might need. Now go forth and process those payments!

Happy coding! 🚀💳