Dev.to · 8 min read

Self-Hosted WhatsApp E-Commerce & Automated Client Proposals in Pure Python + SQLite (Zero SaaS Fees)

Self-Hosted WhatsApp E-Commerce & Automated Client Proposals in Pure Python + SQLite (Zero SaaS Fees)

Running an online store or a freelance consulting business in 2026 often feels like a slow bleed of monthly SaaS subscriptions. You pay $29/month for a basic Shopify tier, another $15/month for a proposal signing app, $20/month for an invoice generator, and another $30/month for automated WhatsApp messaging plugins. Before making your first dollar in profit, your business is saddled with over $1,000 a year in fixed recurring overhead. Worse, your customer data, order history, and client contracts sit locked inside third-party walled gardens that can hike prices, change terms, or suspend your account at any moment. Over the past year at Antigravity Dev Studio, we set out to prove a different thesis: You can build a high-performance, self-hosted e-commerce checkout engine and client proposal portal using only the Python standard library and SQLite. No Django, no Celery, no Redis, and no monthly fees. In this deep-dive tutorial, we will walk through the exact architecture and runnable code for three mission-critical components: Generating pre-filled, structured WhatsApp checkout URLs with zero API gateway fees. Building an atomic, collision-free invoice numbering system on SQLite WAL mode. Securing client proposal digital acceptance links using cryptographic HMAC signatures. 1. Zero-Fee WhatsApp Checkout URL Builder In emerging e-commerce markets across Latin America, the Middle East, Africa, and Southeast Asia, WhatsApp is the dominant communication channel. Customers often abandon traditional multi-step checkout funnels that force account creation or require complex payment gateways. Instead of paying a third-party WhatsApp Business API provider hundreds of dollars in monthly platform fees, you can use the official https://wa.me/ direct URL protocol. When a customer clicks "Place Order via WhatsApp", your Python backend formats their entire shopping cart, customer notes, delivery address, and order code into an encoded message. When the customer taps the link on mobile or desktop, WhatsApp opens instantly with a perfectly structured, ready-to-send message: import urllib.parse from typing import Any, Dict, List def build_whatsapp_order_url( business_phone: str, order_code: str, customer_name: str, customer_phone: str, delivery_address: str, items: List[Dict[str, Any]], subtotal: float, discount_amount: float, delivery_fee: float, total: float, currency: str = "USD" ) -> str: """ Constructs an official, encoded WhatsApp Web/App direct checkout URL. Works natively on iOS, Android, macOS, and Windows. """ # Clean phone number (strip spaces, dashes, plus signs) clean_phone = "".join(ch for ch in business_phone if ch.isdigit()) # Build clean line items breakdown item_lines = [] for item in items: qty = item.get("qty", 1) name = item.get("name", "Product") price = item.get("price", 0.0) item_lines.append(f"• {qty}x {name} — {currency} {price * qty:,.2f}") items_block = "\n".join(item_lines) # Formatted customer message message = ( f"🛍️ *NEW ORDER: #{order_code}*\n" f"━━━━━━━━━━━━━━━━━━\n" f"👤 *Customer:* {customer_name.strip()}\n" f"📞 *Phone:* {customer_phone.strip()}\n" f"📍 *Delivery Address:* {delivery_address.strip()}\n\n" f"📦 *Ordered Items:*\n" f"{items_block}\n\n" f"━━━━━━━━━━━━━━━━━━\n" f"💰 *Subtotal:* {currency} {subtotal:,.2f}\n" ) if discount_amount > 0: message += f"🏷️ *Discount:* -{currency} {discount_amount:,.2f}\n" message += ( f"🚚 *Delivery Fee:* {currency} {delivery_fee:,.2f}\n" f"✅ *TOTAL AMOUNT:* {currency} {total:,.2f}\n" f"━━━━━━━━━━━━━━━━━━\n" f"Please confirm availability and dispatch details!" ) # Encode message safely for URL transmission encoded_text = urllib.parse.quote(message) return f"https://wa.me/{clean_phone}?text={encoded_text}" Testing the Output sample_items = [ {"name": "Mechanical Keyboard Pro", "qty": 1, "price": 89.00}, {"name": "USB-C Braided Cable", "qty": 2, "price": 12.50}, ] url = build_whatsapp_order_url( business_phone="+1 (555) 019-2834", order_code="ORD-78241", customer_name="Alex Mercer", customer_phone="+1 555 982 1102", delivery_address="742 Evergreen Terrace, Springfield", items=sample_items, subtotal=114.00, discount_amount=10.00, delivery_fee=5.00, total=109.00 ) print(url) The resulting link is clean, works without any third-party gateway dependencies, and provides customers with an immediate human connection to your store. 2. Atomic SQLite WAL Invoicing & Sequential Numbering When building an invoicing engine for clients, sequential and collision-free document numbering (such as INV-2026-001, INV-2026-002) is legally required in most jurisdictions. If two users or background tasks generate an invoice at the exact same millisecond, a standard SQL query without proper locking will generate duplicate invoice codes or trigger database locked errors. By leveraging SQLite Write-Ahead Logging (WAL) and an explicit write-transaction loop, you guarantee zero collisions and sub-millisecond execution: import contextlib import datetime as dt import pathlib import sqlite3 from typing import Generator class InvoiceDatabase: def __init__(self, db_path: pathlib.Path): self.db_path = pathlib.Path(db_path) self.db_path.parent.mkdir(parents=True, exist_ok=True) self._init_schema() def _connect(self) -> sqlite3.Connection: conn = sqlite3.connect(str(self.db_path), timeout=15.0) conn.row_factory = sqlite3.Row # WAL mode enables concurrent readers while writing conn.execute("PRAGMA journal_mode = WAL;") conn.execute("PRAGMA foreign_keys = ON;") conn.execute("PRAGMA synchronous = NORMAL;") return conn @contextlib.contextmanager def session(self) -> Generator[sqlite3.Connection, None, None]: conn = self._connect() try: with conn: # Enters transaction: BEGIN IMMEDIATE on writes yield conn finally: conn.close() def _init_schema(self) -> None: with self.session() as conn: conn.executescript(""" CREATE TABLE IF NOT EXISTS invoices ( id INTEGER PRIMARY KEY AUTOINCREMENT, invoice_code TEXT UNIQUE NOT NULL, client_name TEXT NOT NULL, amount REAL NOT NULL CHECK(amount >= 0), status TEXT NOT NULL DEFAULT 'UNPAID', created_at TEXT NOT NULL ); CREATE INDEX IF NOT EXISTS idx_invoices_code ON invoices(invoice_code); """) def generate_next_invoice(self, client_name: str, amount: float) -> str: """ Atomically queries the current year's highest invoice sequence and inserts the next consecutive record in an isolated transaction. """ year = dt.datetime.now(dt.timezone.utc).year now_iso = dt.datetime.now(dt.timezone.utc).replace(microsecond=0).isoformat() prefix = f"INV-{year}-" with self.session() as conn: # Find the highest existing sequence for the current year row = conn.execute( """ SELECT invoice_code FROM invoices WHERE invoice_code LIKE ? ORDER BY id DESC LIMIT 1 """, (f"{prefix}%",) ).fetchone() if row: last_code = row["invoice_code"] try: last_num = int(last_code.split("-")[-1]) next_num = last_num + 1 except ValueError: next_num = 1 else: next_num = 1 invoice_code = f"{prefix}{next_num:04d}" conn.execute( """ INSERT INTO invoices (invoice_code, client_name, amount, status, created_at) VALUES (?, ?, ?, 'UNPAID', ?) """, (invoice_code, client_name.strip(), round(amount, 2), now_iso) ) return invoice_code Because SQLite serializes writes at the file level inside with conn:, concurrent invoice generations will wait their turn cleanly rather than colliding. 3. Cryptographic Proposal Approvals via HMAC Tokens When sending proposals or fee quotes to clients, you do not want to force them to create a username and password just to approve a scope of work. At the same time, you cannot use easily guessable sequential URLs (like /proposals/42/accept), as anyone could guess the URL and fake an approval. Using standard library hmac and hashlib, you can generate tamper-proof signed authorization URLs. When the client clicks "Accept & Sign", your backend verifies that the token was signed with your server's secret key before marking the proposal as legally accepted: import hashlib import hmac import secrets import time SERVER_SECRET_KEY = secrets.token_bytes(32) # Store securely in env / config def generate_proposal_approval_token(proposal_id: str, client_email: str) -> str: """ Generates a cryptographically signed URL token valid for client signature. """ timestamp = str(int(time.time())) payload = f"{proposal_id}|{client_email.strip().lower()}|{timestamp}".encode("utf-8") # Generate HMAC-SHA256 signature sig = hmac.new(SERVER_SECRET_KEY, payload, hashlib.sha256).hexdigest() # Token structure: timestamp.signature return f"{timestamp}.{sig}" def verify_proposal_approval_token(proposal_id: str, client_email: str, token: str, max_age_days: int = 30) -> bool: """ Verifies that the proposal token was signed with the server key and has not expired. """ try: timestamp_str, candidate_sig = token.split(".", 1) created_time = int(timestamp_str) # Check expiration max_age_seconds = max_age_days * 86400 if time.time() - created_time > max_age_seconds: return False # Token expired expected_payload = f"{proposal_id}|{client_email.strip().lower()}|{timestamp_str}".encode("utf-8") expected_sig = hmac.new(SERVER_SECRET_KEY, expected_payload, hashlib.sha256).hexdigest() # Constant-time comparison prevents timing attacks return hmac.compare_digest(candidate_sig, expected_sig) except Exception: return False When verified, the system records the client's IP, acceptance timestamp, and digital signature string, instantly locking the proposal into a frozen state. Production Applications from Antigravity Dev Studio If you don't want to build these architectures from scratch, we have packaged our complete, battle-tested production systems into modular commercial toolkits: 🛍️ OrderFlow Pro ($29) The complete WhatsApp e-commerce storefront, interactive shopping cart, 1-click WhatsApp order generator, inventory manager, admin CRM with 7-day revenue analytics, and bilingual print-ready PDF invoices. Runtime: Pure Python 3.10+ standard library and SQLite WAL. License: Full unminified commercial source code. 📄 DocuPulse Pro ($19) The dedicated client proposal portal and automated invoicing studio. Features interactive proposal links with digital signatures, batch CSV-to-invoice processing (generate 100+ invoices from a single spreadsheet in seconds), and 1-click WhatsApp/Email overdue payment follow-ups. Runtime: Pure Python 3.10+ standard library and SQLite WAL. License: Full unminified commercial source code. 🎁 Python Automation Starter Kit (FREE / $0+) Want to inspect our coding patterns for free? Download five complete zero-dependency scripts: CSV cleaner & KPI report, folder organizer, website uptime monitor, SQLite live hot backup, and bilingual invoice renderer. 🚀 Full-Stack Pro Source Bundle ($45 — Save $17) Get all three commercial tools (OrderFlow Pro, DocuPulse Pro, and TabPilot & WebClipper Pro) plus the Python Starter Kit and the Agency White-Labeling Guide for a single discounted price of $45 (Regular $62). Special Launch Discount: Enter coupon code LAUNCH20 at checkout on Gumroad for an additional 20% off (Only $36)! Explore our complete software catalog at our official storefront: 🌐 Antigravity Dev Studio on Gumroad Have questions or need custom business software engineered for your team? Reach out directly at antig6464@gmail.com.

This is a summary aggregated from Dev.to. Read the complete article on the original site:

Read full article at Dev.to

More Programming & Dev News