Python E-Commerce Automation: Process Orders, Update Inventory, and Email Customers
Running an online store manually means spending hours on order processing, inventory checks, and customer emails. Here's how to automate the entire backend with Python. These four scripts handle 80% of repetitive e-commerce work: Order processing pipeline Inventory level monitoring Automated customer emails Daily sales reporting Connect to your store's API (Shopify, WooCommerce, or direct DB): import httpx from datetime import datetime SHOPIFY_STORE = "your-store.myshopify.com" SHOPIFY_TOKEN = "your-access-token" def get_new_orders(since_hours=2): """Fetch orders from the last N hours.""" resp = httpx.get( f"https://{SHOPIFY_STORE}/admin/api/2024-01/orders.json", headers={"X-Shopify-Access-Token": SHOPIFY_TOKEN}, params={ "status": "open", "financial_status": "paid", "limit": 50 } ) return resp.json().get('orders', []) def process_order(order): """Extract key info and route to fulfillment.""" return { 'id': order['id'], 'email': order['email'], 'name': order['shipping_address']['name'], 'items': [ {'sku': item['sku'], 'qty': item['quantity'], 'title': item['title']} for item in order['line_items'] ], 'total': float(order['total_price']), 'address': order['shipping_address'] } Never run out of stock again: def check_inventory_levels(): """Check all SKUs against reorder thresholds.""" resp = httpx.get( f"https://{SHOPIFY_STORE}/admin/api/2024-01/inventory_levels.json", headers={"X-Shopify-Access-Token": SHOPIFY_TOKEN}, params={"limit": 250} ) inventory = resp.json().get('inventory_levels', []) low_stock = [] REORDER_THRESHOLD = 10 for item in inventory: available = item.get('available', 0) if available = 0: low_stock.append({ 'inventory_item_id': item.get('inventory_item_id'), 'available': available, 'threshold': REORDER_THRESHOLD }) return low_stock The sequence that increases repeat purchases: import smtplib from email.mime.text import MIMEText EMAIL_TEMPLATES = { 'order_confirmed': """Hi {name}, Your order #{order_id} has been confirmed! Items ordered: {items_list} Total: ${total:.2f} We'll send tracking info once your order ships (usually 1-2 business days). Thanks for your business!""", 'shipped': """Hi {name}, Great news - your order #{order_id} has shipped! Tracking number: {tracking_number} Carrier: {carrier} Expected delivery: {delivery_estimate}""", 'review_request': """Hi {name}, Hope you love your recent purchase! Could you take 30 seconds to leave a review? It helps other customers make decisions. Leave a review: {review_url} Thanks in advance!""" } def send_order_email(template_name, order_data, smtp_config): """Send a templated email for an order event.""" template = EMAIL_TEMPLATES[template_name] items_text = '\n'.join([ f" - {item['title']} x{item['qty']}" for item in order_data.get('items', []) ]) body = template.format( name=order_data['name'].split()[0], order_id=order_data['id'], items_list=items_text, total=order_data.get('total', 0), **order_data.get('extra', {}) ) msg = MIMEText(body) msg['Subject'] = f"Your order #{order_data['id']}" msg['From'] = smtp_config['from'] msg['To'] = order_data['email'] with smtplib.SMTP_SSL('smtp.gmail.com', 465) as server: server.login(smtp_config['from'], smtp_config['password']) server.send_message(msg) Get your business metrics every morning: from datetime import datetime, timedelta def generate_daily_report(): """Pull yesterday's data and build a summary.""" yesterday = (datetime.utcnow() - timedelta(days=1)).date().isoformat() resp = httpx.get( f"https://{SHOPIFY_STORE}/admin/api/2024-01/orders.json", headers={"X-Shopify-Access-Token": SHOPIFY_TOKEN}, params={ "created_at_min": f"{yesterday}T00:00:00Z", "created_at_max": f"{yesterday}T23:59:59Z", "financial_status": "paid", "limit": 250 } ) orders = resp.json().get('orders', []) total_revenue = sum(float(o['total_price']) for o in orders) total_orders = len(orders) avg_order = total_revenue / total_orders if total_orders > 0 else 0 report = f"""Daily Sales - {yesterday} Orders: {total_orders} Revenue: ${total_revenue:,.2f} Avg Order Value: ${avg_order:,.2f} """ print(report) return report def run_ecommerce_automation(): """Main loop - run every 30 minutes via cron.""" print(f"[{datetime.now().strftime('%H:%M')}] Running e-commerce automation...") # Process new orders new_orders = get_new_orders(since_hours=1) for order in new_orders: processed = process_order(order) send_order_email('order_confirmed', processed, smtp_config) print(f" Processed order #{processed['id']} for {processed['name']}") # Check inventory low_stock = check_inventory_levels() if low_stock: print(f" WARNING: {len(low_stock)} items low on stock") print(f" Done: {len(new_orders)} orders processed") if __name__ == '__main__': run_ecommerce_automation() # Run every 30 minutes */30 * * * * /usr/bin/python3 /path/to/ecommerce_automation.py # Daily report at 7am 0 7 * * * /usr/bin/python3 /path/to/daily_report.py This entire automation system — plus 20 more business scripts — is available as a ready-to-run toolkit: https://lukassbrad.gumroad.com/l/ugeka What's the biggest time drain in your e-commerce operations? Share in the comments.
