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!
Before we jump in, make sure you've got:
Let's start with the basics. Fire up your terminal and run:
pip install stripe
Easy peasy, right?
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!
Time for the fun part - let's make some API calls!
customer = stripe.Customer.create( email="[email protected]", name="John Doe" )
payment_method = stripe.PaymentMethod.create( type="card", card={ "number": "4242424242424242", "exp_month": 8, "exp_year": 2023, "cvc": "314", }, )
charge = stripe.Charge.create( amount=2000, # Amount in cents currency="usd", source="tok_visa", description="My First Test Charge (created for API docs)" )
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
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
Stripe provides a test mode - use it! And don't forget to write unit tests for your integration. Your future self will thank you.
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! 🚀💳