Python Examples
Ready-to-use Python code for common Pixlpay API operations.
Setup
Using requests
python
import requests
import os
class PixlpayClient:
def __init__(self, subdomain: str, api_token: str):
self.base_url = f"https://{subdomain}.pixlpay.net/api/external/v1"
self.headers = {
'Authorization': f'Bearer {api_token}',
'Accept': 'application/json',
'Content-Type': 'application/json',
}
def get(self, endpoint: str, params: dict = None):
response = requests.get(
f"{self.base_url}{endpoint}",
headers=self.headers,
params=params
)
return response
def post(self, endpoint: str, data: dict = None):
response = requests.post(
f"{self.base_url}{endpoint}",
headers=self.headers,
json=data
)
return responseFetching Products
python
client = PixlpayClient('yourstore', os.environ['PIXLPAY_TOKEN'])
# Get all products
response = client.get('/products')
if response.status_code == 200:
products = response.json()['data']
for product in products:
print(f"{product['name']} - ${product['price']}")
# Get single product
response = client.get('/products/1')
product = response.json()['data']Fetching Orders
python
client = PixlpayClient('yourstore', os.environ['PIXLPAY_TOKEN'])
# Get pending orders
response = client.get('/orders', {'status': 'pending'})
orders = response.json()['data']
for order in orders:
print(f"Order #{order['order_number']} - {order['customer']['email']}")
# Get orders by date
response = client.get('/orders', {'from': '2025-01-01', 'to': '2025-01-31'})Fulfilling Orders
python
client = PixlpayClient('yourstore', os.environ['PIXLPAY_TOKEN'])
order_id = 1
response = client.post(f'/orders/{order_id}/fulfill', {
'note': 'Delivered via API'
})
if response.status_code == 200:
print('Order fulfilled successfully!')Flask Webhook Handler
python
from flask import Flask, request, abort
import hmac
import hashlib
import os
app = Flask(__name__)
def verify_signature(payload: bytes, signature: str, secret: str) -> bool:
computed = hmac.new(
secret.encode(),
payload,
hashlib.sha256
).hexdigest()
return hmac.compare_digest(computed, signature)
@app.route('/webhooks/pixlpay', methods=['POST'])
def handle_webhook():
signature = request.headers.get('X-Pixlpay-Signature', '')
secret = os.environ['PIXLPAY_WEBHOOK_SECRET']
if not verify_signature(request.data, signature, secret):
abort(401, 'Invalid signature')
event = request.json
event_type = event['event']
data = event['data']
handlers = {
'order.paid': handle_order_paid,
'order.completed': handle_order_completed,
'subscription.cancelled': handle_subscription_cancelled,
}
handler = handlers.get(event_type)
if handler:
handler(data)
return '', 200
def handle_order_paid(order: dict):
print(f"Order paid: {order['order_number']}")
# Your delivery logic here
def handle_order_completed(order: dict):
print(f"Order completed: {order['order_number']}")
def handle_subscription_cancelled(subscription: dict):
print(f"Subscription cancelled: {subscription['id']}")
if __name__ == '__main__':
app.run(port=3000)Creating Webhooks
python
client = PixlpayClient('yourstore', os.environ['PIXLPAY_TOKEN'])
response = client.post('/webhooks', {
'url': 'https://yoursite.com/webhooks/pixlpay',
'events': ['order.paid', 'order.completed']
})
if response.status_code == 201:
webhook = response.json()['data']
print(f"Webhook created! Secret: {webhook['secret']}")Analytics
python
client = PixlpayClient('yourstore', os.environ['PIXLPAY_TOKEN'])
response = client.get('/analytics/revenue', {
'from': '2025-01-01',
'to': '2025-01-31'
})
if response.status_code == 200:
data = response.json()['data']
print(f"Revenue: ${data['total_revenue']}")
print(f"Orders: {data['total_orders']}")
print(f"AOV: ${data['average_order_value']}")Error Handling
python
client = PixlpayClient('yourstore', os.environ['PIXLPAY_TOKEN'])
response = client.get('/products/99999')
if response.status_code != 200:
error = response.json()
print(f"Error: {error.get('message', 'Unknown error')}")
error_handlers = {
401: lambda: print('Check your API token'),
404: lambda: print('Resource not found'),
429: lambda: print('Rate limited - slow down!'),
}
handler = error_handlers.get(response.status_code)
if handler:
handler()Async with aiohttp
python
import aiohttp
import asyncio
class AsyncPixlpayClient:
def __init__(self, subdomain: str, api_token: str):
self.base_url = f"https://{subdomain}.pixlpay.net/api/external/v1"
self.headers = {
'Authorization': f'Bearer {api_token}',
'Accept': 'application/json',
}
async def get(self, endpoint: str):
async with aiohttp.ClientSession() as session:
async with session.get(
f"{self.base_url}{endpoint}",
headers=self.headers
) as response:
return await response.json()
# Usage
async def main():
client = AsyncPixlpayClient('yourstore', os.environ['PIXLPAY_TOKEN'])
products = await client.get('/products')
print(products)
asyncio.run(main())