Hey there, fellow developer! Ready to dive into the world of GoCardless API integration? You're in the right place. We'll be using the gocardless_pro
package to make our lives easier. Let's get cracking!
Before we jump in, make sure you've got:
First things first, let's get that gocardless_pro
package installed:
pip install gocardless_pro
Easy peasy, right?
Now, let's import the package and set up our client:
import gocardless_pro client = gocardless_pro.Client( access_token='your_access_token_here', environment='live' # Use 'sandbox' for testing )
Let's create a customer:
customer = client.customers.create( params={ "email": "[email protected]", "given_name": "Jane", "family_name": "Doe", "address_line1": "123 Main St", "city": "London", "postal_code": "SW1A 1AA", "country_code": "GB" } )
Now, let's set up a mandate for our customer:
mandate = client.mandates.create( params={ "scheme": "bacs", "links": { "customer_bank_account": "BA123456" } } )
Time to create a payment:
payment = client.payments.create( params={ "amount": 1000, # Amount in pence "currency": "GBP", "links": { "mandate": mandate.id }, "metadata": { "order_id": "ORDER-123" } } )
Webhooks are crucial for staying updated. Here's a quick example using Flask:
from flask import Flask, request import gocardless_pro app = Flask(__name__) @app.route('/webhooks', methods=['POST']) def handle_webhook(): webhook_secret = 'your_webhook_secret' signature = request.headers.get('Webhook-Signature') try: events = client.events.parse(request.data, signature, webhook_secret) for event in events: # Process the event print(f"Received event: {event.action}") return "", 200 except gocardless_pro.errors.InvalidSignatureError: return "Invalid signature", 498
Always wrap your API calls in try-except blocks:
try: payment = client.payments.create(...) except gocardless_pro.errors.ValidationFailedError as e: print(f"Validation failed: {e.error}") except gocardless_pro.errors.GoCardlessProError as e: print(f"API error: {e}")
Remember to respect rate limits and implement proper logging!
Want to set up recurring payments? It's a breeze:
subscription = client.subscriptions.create( params={ "amount": 1500, "currency": "GBP", "interval_unit": "monthly", "day_of_month": "1", "links": { "mandate": mandate.id } } )
Always use the sandbox environment for testing:
client = gocardless_pro.Client( access_token='your_sandbox_access_token', environment='sandbox' )
And don't forget to write those unit tests!
And there you have it! You're now equipped to integrate GoCardless into your Python projects like a pro. Remember, practice makes perfect, so keep coding and exploring. If you need more info, check out the GoCardless API docs. Happy coding!