### Development Setup Commands Source: https://github.com/ashfromsky/acquiremock/blob/master/CONTRIBUTING.md Commands to clone the repository, create a virtual environment, install dependencies, and run tests. Use this to set up a local development environment for AcquireMock. ```bash # Clone your fork git clone https://github.com/illusiOxd/acquiremock.git cd acquiremock # Create virtual environment python -m venv venv source venv/bin/activate # Windows: venv\Scripts\activate # Install dependencies pip install -r requirements.txt # Run tests pytest tests/ ``` -------------------------------- ### Manual Setup Commands Source: https://github.com/ashfromsky/acquiremock/blob/master/README.md Set up AcquireMock manually by cloning the repository, creating a virtual environment, installing dependencies, copying the configuration file, and starting the application with uvicorn. ```bash git clone https://github.com/illusiOxd/acquiremock.git cd acquiremock # Create virtual environment python -m venv venv source venv/bin/activate # Linux/Mac # or venv\Scripts\activate # Windows # Install dependencies pip install -r requirements.txt # Copy configuration cp .env.example .env # Edit configuration nano .env # Start application uvicorn main:app --port 8000 --reload ``` -------------------------------- ### Install for Development Source: https://github.com/ashfromsky/acquiremock/blob/master/README.md Commands to clone the repository, install dependencies, run tests, format code with black and isort, and perform type checking with mypy. ```bash # Clone repository git clone https://github.com/illusiOxd/acquiremock.git cd acquiremock # Install dependencies pip install -r requirements.txt pip install -r requirements-dev.txt # Run tests pytest tests/ -v # Format code black . isort . # Type checking mypy . ``` -------------------------------- ### Create Invoice Example (curl) Source: https://github.com/ashfromsky/acquiremock/blob/master/docs/api-reference.md Example curl command to create an invoice with a sample payload. ```bash curl -X POST http://localhost:8000/api/create-invoice \ -H "Content-Type: application/json" \ -d '{ "amount": 25000, "reference": "ORDER-456", "webhookUrl": "https://api.mystore.com/webhook", "redirectUrl": "https://mystore.com/order/success" }' ``` -------------------------------- ### Docker Quick Start Source: https://github.com/ashfromsky/acquiremock/blob/master/README.md Clone the repository and start AcquireMock using Docker Compose. After running these commands, the service is available at http://localhost:8000. ```bash git clone https://github.com/illusiOxd/acquiremock.git cd acquiremock docker-compose up ``` -------------------------------- ### Start AcquireMock with Docker and check health Source: https://github.com/ashfromsky/acquiremock/blob/master/docs/getting-started.md Clones the repository, starts the service with docker-compose, and verifies it is running by curling the /health endpoint on localhost:8000. ```bash # Clone the repository git clone https://github.com/illusiOxd/acquiremock.git cd acquiremock # Start the service docker-compose up -d # Check if it's running curl http://localhost:8000/health ``` -------------------------------- ### Webhook Verify Example (curl) Source: https://github.com/ashfromsky/acquiremock/blob/master/docs/api-reference.md Example curl command to verify a webhook signature with a sample payload. ```bash curl -X POST http://localhost:8000/webhooks/verify \ -H "Content-Type: application/json" \ -H "X-Signature: a1b2c3d4..." \ -d '{"payment_id":"123","status":"paid","amount":10000}' ``` -------------------------------- ### Install ngrok on macOS and Linux Source: https://github.com/ashfromsky/acquiremock/blob/master/docs/webhook-guide.md Commands to install ngrok on macOS via Homebrew and on Linux via wget and tar extraction. ```bash # macOS brew install ngrok # Linux wget https://bin.equinox.io/c/bNyj1mQVY4c/ngrok-v3-stable-linux-amd64.tgz tar xvzf ngrok-*.tgz ``` -------------------------------- ### Docker Development Deployment Source: https://github.com/ashfromsky/acquiremock/blob/master/README.md Command to start the development environment using docker-compose. ```bash docker-compose up ``` -------------------------------- ### Start local server for ngrok testing Source: https://github.com/ashfromsky/acquiremock/blob/master/docs/webhook-guide.md Command to run a Python application on port 3000 for local webhook testing. ```bash python your_app.py # Running on port 3000 ``` -------------------------------- ### Basic Payment Flow with curl Source: https://github.com/ashfromsky/acquiremock/blob/master/README.md Create a payment invoice using the AcquireMock API. The example shows the required fields: amount, reference, and webhookUrl. After this, the user completes checkout, OTP verification is done via email, a webhook is sent, and the payment is confirmed. ```bash curl -X POST http://localhost:8000/api/create-invoice \ -H "Content-Type: application/json" \ -d '{ "amount": 25000, "reference": "ORDER-123", "webhookUrl": "https://your-site.com/webhook" }' ``` -------------------------------- ### Webhook Payload Example Source: https://github.com/ashfromsky/acquiremock/blob/master/README.md Shows the structure of a webhook payload with payment_id, reference, amount, status, and timestamp. ```json { "payment_id": "pay_abc123", "reference": "ORDER-123", "amount": 25000, "status": "paid", "timestamp": "2024-12-20T10:30:00Z" } ``` -------------------------------- ### Create ngrok tunnel to local port 3000 Source: https://github.com/ashfromsky/acquiremock/blob/master/docs/webhook-guide.md Starts an ngrok tunnel to expose the local server on port 3000 to the internet. ```bash ngrok http 3000 ``` -------------------------------- ### Health Check Example (curl) Source: https://github.com/ashfromsky/acquiremock/blob/master/docs/api-reference.md Simple curl command to check API health. ```bash curl http://localhost:8000/health ``` -------------------------------- ### Webhook Response JSON Source: https://github.com/ashfromsky/acquiremock/blob/master/docs/api-reference.md Example success response your endpoint should return. Any 2xx status code is accepted; failed webhooks are retried. ```json { "status": "ok" } ``` -------------------------------- ### Log webhook processing in Python Source: https://github.com/ashfromsky/acquiremock/blob/master/docs/webhook-guide.md Use this Python logging pattern to log webhook receipt and processing, and to log errors with the payment ID. The example uses a FastAPI-style endpoint and logs at info and error levels. ```python import logging logger = logging.getLogger(__name__) @app.post("/webhook/payment") async def payment_webhook(request: Request): payload = await request.json() payment_id = payload["payment_id"] logger.info(f"Webhook received: {payment_id}") try: # Process webhook await process_payment(payload) logger.info(f"Webhook processed: {payment_id}") except Exception as e: logger.error(f"Webhook failed: {payment_id}, error: {e}") raise ``` -------------------------------- ### Idempotency Key Usage Source: https://github.com/ashfromsky/acquiremock/blob/master/docs/api-reference.md Example curl command using the Idempotency-Key header to prevent duplicate payments. ```bash curl -X POST /pay/abc-123 \ -H "Idempotency-Key: unique-key-12345" \ -d "card_number=4444444444444444&..." ``` -------------------------------- ### GET /health Source: https://github.com/ashfromsky/acquiremock/blob/master/docs/api-reference.md Checks the API health status. ```APIDOC ## GET /health ### Description Checks the API health status. ### Method GET ### Endpoint /health ### Response #### Success Response (200) - **status** (string) - Health status, e.g., "ok" - **timestamp** (string) - Current server timestamp - **version** (string) - API version - **currency** (string) - Base currency #### Response Example { "status": "ok", "timestamp": "2025-01-15T10:30:00.000000", "version": "2.0.0", "currency": "USD" } ``` -------------------------------- ### Transaction history - GET /api/transactions Source: https://github.com/ashfromsky/acquiremock/blob/master/README.md Retrieves all transactions for a user by providing their email as a query parameter. ```bash GET /api/transactions?email=user@example.com ``` -------------------------------- ### Health Check Response Source: https://github.com/ashfromsky/acquiremock/blob/master/docs/api-reference.md Successful response from GET /health, including status, timestamp, version, and currency. ```json { "status": "ok", "timestamp": "2025-01-15T10:30:00.000000", "version": "2.0.0", "currency": "USD" } ``` -------------------------------- ### Webhook payload JSON structure Source: https://github.com/ashfromsky/acquiremock/blob/master/docs/webhook-guide.md Example JSON payload sent by AcquireMock webhook, containing payment details such as payment_id, reference, amount, status, timestamp, and card_mask. ```json { "payment_id": "550e8400-e29b-41d4-a716-446655440000", "reference": "ORDER-123", "amount": 10000, "status": "paid", "timestamp": "2025-01-15T10:30:00.000000", "card_mask": "**** 4444" } ``` -------------------------------- ### Verify webhook signature with HMAC-SHA256 in Python Source: https://github.com/ashfromsky/acquiremock/blob/master/docs/getting-started.md Use this function to verify that a webhook request came from AcquireMock. It computes an HMAC-SHA256 digest over the JSON payload with sorted keys and compares it to the provided signature using hmac.compare_digest. The example also shows a FastAPI handler that returns 403 when verification fails. ```python import hmac import hashlib import json def verify_webhook(payload: dict, signature: str, secret: str) -> bool: message = json.dumps(payload, sort_keys=True) expected = hmac.new( secret.encode(), message.encode(), hashlib.sha256 ).hexdigest() return hmac.compare_digest(expected, signature) # In your webhook handler @app.post("/webhook") async def payment_webhook(request: Request): signature = request.headers.get("X-Signature") payload = await request.json() if not verify_webhook(payload, signature, WEBHOOK_SECRET): return {"error": "Invalid signature"}, 403 # Process payment if payload["status"] == "paid": # Update order status in your database pass return {"status": "ok"} ``` -------------------------------- ### Project directory structure Source: https://github.com/ashfromsky/acquiremock/blob/master/README.md Shows the AcquireMock project layout, including FastAPI entry point, database models and operations, services for email/webhooks/background tasks, security modules, Jinja2 templates, and static assets. ```text acquiremock/ ├── main.py # FastAPI application entry point ├── database/ │ ├── models/ # SQLModel schemas │ │ ├── payment.py # Payment entity │ │ ├── saved_card.py # Saved cards │ │ └── webhook_log.py # Webhook delivery logs │ └── functional/ # Database operations │ ├── payment_crud.py # Payment CRUD │ ├── card_crud.py # Card operations │ └── webhook_crud.py # Webhook logging ├── services/ │ ├── smtp_service.py # Email delivery │ ├── webhook_service.py # Webhook HTTP calls │ └── background_tasks.py # Async job processing ├── security/ │ ├── crypto.py # Hashing & HMAC │ └── middleware.py # Security headers ├── templates/ # Jinja2 HTML templates │ ├── checkout.html # Payment page │ ├── otp.html # OTP verification │ └── test.html # Test interface └── static/ # CSS, JS, images ``` -------------------------------- ### Production Database Configuration (PostgreSQL) Source: https://github.com/ashfromsky/acquiremock/blob/master/README.md Database connection string for production using PostgreSQL with asyncpg driver. ```env DATABASE_URL=postgresql+asyncpg://user:password@localhost:5432/payment_db ``` -------------------------------- ### Running Tests Source: https://github.com/ashfromsky/acquiremock/blob/master/README.md Commands to run all tests, a specific test file, and generate a coverage report. ```bash # All tests pytest tests/ -v # Specific test file pytest tests/test_webhooks.py -v # Coverage report pytest --cov=. --cov-report=html ``` -------------------------------- ### Environment Variables Configuration (.env) Source: https://github.com/ashfromsky/acquiremock/blob/master/README.md Required and optional environment variables for the AcquireMock payment system. Includes database URL, webhook secret, base URL, and SMTP settings. Email is optional; if not configured, OTP codes are logged to console. ```env # Database (Required) DATABASE_URL=postgresql+asyncpg://user:password@localhost:5432/payment_db # For development: sqlite+aiosqlite:///./payment.db # Security (Required) WEBHOOK_SECRET=your-secret-key-min-32-chars BASE_URL=http://localhost:8000 # Email (Optional - logs to console if not configured) SMTP_HOST=smtp.gmail.com SMTP_PORT=587 SMTP_USER=your-email@gmail.com SMTP_PASS=your-app-password ``` -------------------------------- ### Download Postman Collection Source: https://github.com/ashfromsky/acquiremock/blob/master/docs/api-reference.md Use these commands to download the Postman collection and set up environment variables for testing. ```bash # Download collection curl -O https://raw.githubusercontent.com/illusiOxd/acquiremock/main/postman_collection.json # Import in Postman and set variables: # - base_url: http://localhost:8000 # - webhook_secret: your-secret-key ``` -------------------------------- ### API Documentation URLs Source: https://github.com/ashfromsky/acquiremock/blob/master/docs/api-reference.md These URLs provide interactive API documentation and the OpenAPI JSON specification. ```text http://localhost:8000/docs # Swagger UI http://localhost:8000/redoc # ReDoc http://localhost:8000/openapi.json # OpenAPI JSON ``` -------------------------------- ### curl command to create an invoice with webhook.site URL Source: https://github.com/ashfromsky/acquiremock/blob/master/docs/webhook-guide.md Sends a POST request to create an invoice with a webhook URL from webhook.site for testing. Includes amount, reference, and redirect URL. ```bash curl -X POST http://localhost:8000/api/create-invoice \ -H "Content-Type: application/json" \ -d '{ "amount": 10000, "reference": "TEST-123", "webhookUrl": "https://webhook.site/your-unique-id", "redirectUrl": "http://localhost:3000/success" }' ``` -------------------------------- ### Development Database Configuration (SQLite) Source: https://github.com/ashfromsky/acquiremock/blob/master/README.md Database connection string for development using SQLite with aiosqlite driver. ```env DATABASE_URL=sqlite+aiosqlite:///./payment.db ``` -------------------------------- ### Payment Flow Diagram Source: https://github.com/ashfromsky/acquiremock/blob/master/docs/getting-started.md ASCII diagram showing the payment flow from user through AcquireMock API, including invoice creation, OTP verification, webhook delivery, and redirect to success page. ```text User → Your Site → AcquireMock API ↓ Create Invoice ↓ Return pageUrl ↓ User → Payment Page → Enter Card ↓ Send OTP ↓ Verify OTP ↓ Update Status ↓ ┌─────────┴─────────┐ ↓ ↓ Send Webhook Redirect User ↓ ↓ Your Server Success Page ``` -------------------------------- ### Docker Production Deployment Source: https://github.com/ashfromsky/acquiremock/blob/master/README.md Docker Compose configuration for production deployment, including app and PostgreSQL services with environment variables and volume. ```yaml version: '3.8' services: app: build: . ports: - "8000:8000" environment: - DATABASE_URL=postgresql+asyncpg://user:password@db:5432/payment_db - WEBHOOK_SECRET=${WEBHOOK_SECRET} - BASE_URL=https://your-domain.com depends_on: - db db: image: postgres:15 environment: - POSTGRES_USER=user - POSTGRES_PASSWORD=password - POSTGRES_DB=payment_db volumes: - postgres_data:/var/lib/postgresql/data volumes: postgres_data: ``` -------------------------------- ### Payment with card storage - POST /api/create-invoice Source: https://github.com/ashfromsky/acquiremock/blob/master/README.md Creates a payment invoice with the option to save the card for future payments. The 'saveCard' field set to true triggers card storage. Saved cards are hashed using bcrypt and never stored in plain text. ```bash # Payment with card storage POST /api/create-invoice { "amount": 10000, "reference": "ORDER-456", "email": "user@example.com", "saveCard": true } ``` -------------------------------- ### Webhook Forwarding: Send to Multiple Services with httpx Source: https://github.com/ashfromsky/acquiremock/blob/master/docs/webhook-guide.md Forwards incoming webhooks to multiple target URLs concurrently using httpx.AsyncClient and asyncio.gather, returning a success status after dispatching. ```python WEBHOOK_TARGETS = [ "https://api.mystore.com/webhook", "https://analytics.mysite.com/webhook", "https://slack.com/api/incoming/webhook" ] @app.post("/webhook/payment") async def payment_webhook(request: Request): payload = await request.json() # Forward to all targets async with httpx.AsyncClient() as client: tasks = [ client.post(url, json=payload) for url in WEBHOOK_TARGETS ] await asyncio.gather(*tasks, return_exceptions=True) return {"status": "ok"} ``` -------------------------------- ### POST webhookUrl Source: https://github.com/ashfromsky/acquiremock/blob/master/docs/api-reference.md AcquireMock sends a POST request to your webhookUrl after payment completion. The webhook delivers payment status updates and includes a signature for verification. ```APIDOC ## [POST] [webhookUrl] ### Description AcquireMock sends a POST request to your webhookUrl after payment completion. The webhook delivers payment status updates and includes a signature for verification. ### Method POST ### Endpoint webhookUrl ### Headers - **Content-Type** (string) - Required - Set to application/json - **X-Signature** (string) - Required - HMAC-SHA256 signature of the payload - **X-Payment-ID** (string) - Required - The payment ID associated with the webhook ### Request Body - **payment_id** (string) - Required - Unique identifier for the payment - **reference** (string) - Required - Merchant reference for the payment - **amount** (integer) - Required - Payment amount in minor units - **status** (string) - Required - Payment status (pending, waiting_for_otp, paid, failed, expired, refunded) - **timestamp** (string) - Required - ISO 8601 timestamp of the event - **card_mask** (string) - Required - Masked card number ### Request Example { "payment_id": "550e8400-e29b-41d4-a716-446655440000", "reference": "ORDER-123", "amount": 10000, "status": "paid", "timestamp": "2025-01-15T10:30:00.000000", "card_mask": "**** 4444" } ### Response #### Success Response (200-299) - **status** (string) - Should be "ok" or any 2xx status code #### Response Example { "status": "ok" } ### Notes - Your endpoint should return a 2xx status code for success. - Respond within 10 seconds. - Handle duplicate webhooks idempotently. - Failed webhooks (4xx, 5xx, timeout) will be retried up to 5 times with delays: immediate, 2s, 4s, 8s, 16s. - Verify the X-Signature header using HMAC-SHA256 with your WEBHOOK_SECRET. The message is the JSON payload with sorted keys. ``` -------------------------------- ### curl command to create invoice with ngrok URL Source: https://github.com/ashfromsky/acquiremock/blob/master/docs/webhook-guide.md Sends a POST request to create an invoice with an ngrok webhook URL for testing. ```bash curl -X POST http://localhost:8000/api/create-invoice \ -d '{"webhookUrl": "https://abc123.ngrok.io/webhook/payment", ...}' ``` -------------------------------- ### Webhook Queue: Asynchronous Processing with asyncio and Queue Source: https://github.com/ashfromsky/acquiremock/blob/master/docs/webhook-guide.md Use this pattern for high-volume applications to process webhooks asynchronously. It verifies the signature, adds the payload to a queue, returns immediately, and processes the queue in a background worker. ```python import asyncio from queue import Queue webhook_queue = Queue() @app.post("/webhook/payment") async def payment_webhook(request: Request): payload = await request.json() # Verify signature if not verify_signature(payload, request.headers.get("X-Signature")): raise HTTPException(403, "Invalid signature") # Add to queue webhook_queue.put(payload) # Return immediately return {"status": "queued"} # Background worker async def process_webhook_queue(): while True: if not webhook_queue.empty(): payload = webhook_queue.get() await process_payment(payload) await asyncio.sleep(0.1) ``` -------------------------------- ### Handle Webhook with Python and FastAPI Source: https://github.com/ashfromsky/acquiremock/blob/master/README.md Verifies HMAC-SHA256 signature of incoming webhook, processes payment status, and updates order. Returns status ok. ```python import hmac import hashlib import json from fastapi import Request, HTTPException def verify_webhook(payload: dict, signature: str, secret: str) -> bool: """Verify HMAC-SHA256 signature""" message = json.dumps(payload, sort_keys=True) expected = hmac.new( secret.encode(), message.encode(), hashlib.sha256 ).hexdigest() return hmac.compare_digest(expected, signature) @app.post("/webhook") async def payment_webhook(request: Request): signature = request.headers.get("X-Signature") payload = await request.json() if not verify_webhook(payload, signature, WEBHOOK_SECRET): raise HTTPException(status_code=403, detail="Invalid signature") # Process payment if payload["status"] == "paid": order = await Order.get(payment_id=payload["payment_id"]) order.status = "paid" await order.save() return {"status": "ok"} ``` -------------------------------- ### Webhook Flow Diagram Source: https://github.com/ashfromsky/acquiremock/blob/master/docs/webhook-guide.md ASCII diagram showing the webhook flow from payment completion to your endpoint, with retry on failure and logging. ```text Payment Completed → AcquireMock → Your Webhook Endpoint ↓ Retry if Failed ↓ Log Result ``` -------------------------------- ### POST /webhooks/verify Source: https://github.com/ashfromsky/acquiremock/blob/master/docs/api-reference.md Utility endpoint to verify webhook signature calculation. ```APIDOC ## POST /webhooks/verify ### Description Utility endpoint to verify webhook signature calculation. ### Method POST ### Endpoint /webhooks/verify ### Headers - **X-Signature** (string) - Required - The calculated signature to verify ### Parameters #### Request Body - **payment_id** (string) - Required - Payment identifier - **status** (string) - Required - Payment status - **amount** (integer) - Required - Payment amount ### Request Example { "payment_id": "abc-123", "status": "paid", "amount": 10000 } ### Response #### Success Response (200) - **valid** (boolean) - Whether the signature is valid #### Response Example { "valid": true } ``` -------------------------------- ### Base URL Source: https://github.com/ashfromsky/acquiremock/blob/master/docs/api-reference.md The base URL for all API requests. Replace with your production domain. ```text http://localhost:8000 ``` -------------------------------- ### Gmail SMTP configuration in .env Source: https://github.com/ashfromsky/acquiremock/blob/master/docs/getting-started.md Add these environment variables to your .env file to configure Gmail SMTP. Requires 2-Factor Authentication and an App Password from your Google Account. ```env SMTP_HOST=smtp.gmail.com SMTP_PORT=587 SMTP_USER=your-email@gmail.com SMTP_PASS=your-16-char-app-password ``` -------------------------------- ### SQL query to monitor failed webhook retries Source: https://github.com/ashfromsky/acquiremock/blob/master/docs/webhook-guide.md Queries the webhook_logs table for failed webhook attempts, ordered by most recent first. Useful for monitoring retry status. ```sql SELECT * FROM webhook_logs WHERE success = false ORDER BY created_at DESC; ``` -------------------------------- ### Watch logs for OTP codes Source: https://github.com/ashfromsky/acquiremock/blob/master/docs/getting-started.md If SMTP is not configured, OTP codes print to the console. Use docker-compose logs to watch the app logs, or check terminal output when running manually. ```bash # Watch the logs docker-compose logs -f app # Or if running manually # Just look at your terminal output ``` -------------------------------- ### Create Payment Invoice with curl Source: https://github.com/ashfromsky/acquiremock/blob/master/README.md Sends a POST request to /api/create-invoice with amount, reference, webhookUrl, and redirectUrl. The response contains a pageUrl for the checkout page. ```bash curl -X POST http://localhost:8000/api/create-invoice \ -H "Content-Type: application/json" \ -d '{ "amount": 25000, "reference": "ORDER-123", "webhookUrl": "https://your-site.com/webhook", "redirectUrl": "https://your-site.com/success" }' ``` ```json { "pageUrl": "http://localhost:8000/checkout/{payment_id}" } ``` -------------------------------- ### Create Invoice Response Source: https://github.com/ashfromsky/acquiremock/blob/master/docs/api-reference.md Successful response from POST /api/create-invoice, returning a checkout page URL. ```json { "pageUrl": "http://localhost:8000/checkout/550e8400-e29b-41d4-a716-446655440000" } ``` -------------------------------- ### POST /api/create-invoice Source: https://github.com/ashfromsky/acquiremock/blob/master/docs/api-reference.md Creates a new payment invoice and returns a checkout URL. ```APIDOC ## POST /api/create-invoice ### Description Creates a new payment invoice and returns a checkout URL. ### Method POST ### Endpoint /api/create-invoice ### Parameters #### Request Body - **amount** (integer) - Required - Amount in smallest currency unit (e.g., cents) - **reference** (string) - Required - Your unique order reference - **webhookUrl** (string) - Required - URL to receive payment notifications - **redirectUrl** (string) - Required - URL to redirect user after payment ### Request Example { "amount": 10000, "reference": "ORDER-123", "webhookUrl": "https://yoursite.com/webhook", "redirectUrl": "https://yoursite.com/success" } ### Response #### Success Response (200) - **pageUrl** (string) - The checkout URL for the created invoice #### Response Example { "pageUrl": "http://localhost:8000/checkout/550e8400-e29b-41d4-a716-446655440000" } #### Error Responses - **400 Bad Request** - Invalid input data - **429 Too Many Requests** - Rate limit exceeded ``` -------------------------------- ### Create Invoice Request Body Source: https://github.com/ashfromsky/acquiremock/blob/master/docs/api-reference.md JSON payload for POST /api/create-invoice. Requires amount in smallest currency unit, reference, webhookUrl, and redirectUrl. ```json { "amount": 10000, "reference": "ORDER-123", "webhookUrl": "https://yoursite.com/webhook", "redirectUrl": "https://yoursite.com/success" } ``` -------------------------------- ### Signature Verification Source: https://github.com/ashfromsky/acquiremock/blob/master/docs/webhook-guide.md How to verify the webhook signature using HMAC-SHA256 to ensure the webhook is authentic and not tampered with. ```APIDOC ## Signature Verification ### Description AcquireMock signs each webhook with an HMAC-SHA256 signature using your `WEBHOOK_SECRET`. The signature is sent in the `X-Signature` header. You must verify it to prevent forgery and replay attacks. ### How It Works 1. AcquireMock creates HMAC-SHA256 signature using your `WEBHOOK_SECRET` 2. Signature is sent in `X-Signature` header 3. You calculate expected signature from payload 4. Compare signatures using constant-time comparison ### Implementation Examples **Python:** ```python import hmac import hashlib import json def verify_webhook_signature(payload: dict, signature: str, secret: str) -> bool: message = json.dumps(payload, sort_keys=True) expected = hmac.new(secret.encode(), message.encode(), hashlib.sha256).hexdigest() return hmac.compare_digest(expected, signature) ``` **Node.js:** ```javascript const crypto = require('crypto'); function verifyWebhookSignature(payload, signature, secret) { const message = JSON.stringify(payload, Object.keys(payload).sort()); const expected = crypto.createHmac('sha256', secret).update(message).digest('hex'); return crypto.timingSafeEqual(Buffer.from(signature), Buffer.from(expected)); } ``` **PHP:** ```php function verifyWebhookSignature($payload, $signature, $secret) { ksort($payload); $message = json_encode($payload); $expected = hash_hmac('sha256', $message, $secret); return hash_equals($expected, $signature); } ``` **Ruby:** ```ruby require 'openssl' require 'json' def verify_webhook_signature(payload, signature, secret) message = JSON.generate(payload.sort.to_h) expected = OpenSSL::HMAC.hexdigest('SHA256', secret, message) Rack::Utils.secure_compare(expected, signature) end ``` ### Important Notes - ❌ **Never** use `==` for signature comparison (timing attacks) - ✅ **Always** use constant-time comparison (`hmac.compare_digest`, `crypto.timingSafeEqual`, etc.) - ✅ **Always** sort JSON keys before hashing - ✅ Store `WEBHOOK_SECRET` securely (environment variables) ``` -------------------------------- ### Rate Limit Headers Source: https://github.com/ashfromsky/acquiremock/blob/master/docs/api-reference.md HTTP headers returned with each response indicating the current rate limit status. ```http X-RateLimit-Limit: 10 X-RateLimit-Remaining: 7 X-RateLimit-Reset: 1642252800 ``` -------------------------------- ### Python FastAPI webhook endpoint with idempotency check Source: https://github.com/ashfromsky/acquiremock/blob/master/docs/webhook-guide.md Handles a payment webhook by checking if it was already processed, then processes and marks it as processed. Returns a JSON response indicating success or already processed. ```python @app.post("/webhook/payment") async def payment_webhook(request: Request): payload = await request.json() payment_id = payload["payment_id"] # Check if already processed if await is_webhook_processed(payment_id): return {"status": "ok", "message": "Already processed"} # Process webhook await process_payment(payload) # Mark as processed await mark_webhook_processed(payment_id) return {"status": "ok"} ``` -------------------------------- ### Webhook Headers Source: https://github.com/ashfromsky/acquiremock/blob/master/docs/api-reference.md Required headers for webhook requests: Content-Type, X-Signature (HMAC-SHA256), and X-Payment-ID. ```text Content-Type: application/json X-Signature: hmac-sha256-signature-here X-Payment-ID: 550e8400-e29b-41d4-a716-446655440000 ``` -------------------------------- ### Webhook Verify Response Source: https://github.com/ashfromsky/acquiremock/blob/master/docs/api-reference.md Successful response from POST /webhooks/verify, indicating signature validity. ```json { "valid": true } ``` -------------------------------- ### Webhook Payload Structure Source: https://github.com/ashfromsky/acquiremock/blob/master/docs/webhook-guide.md The JSON structure of the webhook payload sent by AcquireMock. ```APIDOC ## Webhook Payload ### Description The webhook payload is sent to your endpoint when a payment event occurs. It contains payment details and status. ### Payload Example ```json { "payment_id": "550e8400-e29b-41d4-a716-446655440000", "reference": "ORDER-123", "amount": 10000, "status": "paid", "timestamp": "2025-01-15T10:30:00.000000", "card_mask": "**** 4444" } ``` ### Fields | Field | Type | Description | |-------|------|-------------| | `payment_id` | string | Unique payment identifier (UUID) | | `reference` | string | Your order reference from invoice creation | | `amount` | integer | Payment amount in smallest currency unit | | `status` | string | Payment status: `paid`, `failed`, `expired` | | `timestamp` | string | ISO 8601 timestamp of the event | | `card_mask` | string | Masked card number (e.g., `**** 4444`) | ### Status Values | Status | When Sent | Action Required | |--------|-----------|-----------------| | `paid` | Payment successfully completed | Update order, send confirmation | | `failed` | Payment failed (card declined) | Notify customer, retry payment | | `expired` | Payment session expired (15min) | Cancel order or request new payment | ``` -------------------------------- ### Webhook Signature Header Source: https://github.com/ashfromsky/acquiremock/blob/master/docs/api-reference.md Required header for POST /webhooks/verify, containing the calculated HMAC-SHA256 signature. ```text X-Signature: your-calculated-signature ``` -------------------------------- ### Webhook Verify Request Body Source: https://github.com/ashfromsky/acquiremock/blob/master/docs/api-reference.md JSON payload for POST /webhooks/verify, containing payment details to verify. ```json { "payment_id": "abc-123", "status": "paid", "amount": 10000 } ``` -------------------------------- ### Rate Limit Exceeded Response Source: https://github.com/ashfromsky/acquiremock/blob/master/docs/api-reference.md JSON response returned when the rate limit is exceeded, including the retry-after time. ```json { "error": "Rate limit exceeded", "retry_after": 60 } ``` -------------------------------- ### FastAPI Webhook Endpoint with HMAC-SHA256 Verification Source: https://github.com/ashfromsky/acquiremock/blob/master/docs/webhook-guide.md FastAPI endpoint that receives payment webhooks, verifies the X-Signature header using HMAC-SHA256, processes the payment status, and returns a success response. Requires a webhook secret and a publicly accessible URL. ```python from fastapi import FastAPI, Request, HTTPException import hmac import hashlib import json app = FastAPI() WEBHOOK_SECRET = "your_secret_here" @app.post("/webhook/payment") async def payment_webhook(request: Request): # 1. Get signature from headers signature = request.headers.get("X-Signature") if not signature: raise HTTPException(status_code=403, detail="Missing signature") # 2. Get payload payload = await request.json() # 3. Verify signature if not verify_signature(payload, signature): raise HTTPException(status_code=403, detail="Invalid signature") # 4. Process webhook payment_id = payload["payment_id"] status = payload["status"] reference = payload["reference"] if status == "paid": # Update your database order = await get_order(reference) order.status = "paid" await order.save() # Send confirmation email await send_confirmation_email(order) # 5. Return success response return {"status": "ok"} def verify_signature(payload: dict, signature: str) -> bool: """Verify HMAC-SHA256 signature.""" message = json.dumps(payload, sort_keys=True) expected = hmac.new( WEBHOOK_SECRET.encode(), message.encode(), hashlib.sha256 ).hexdigest() return hmac.compare_digest(expected, signature) ``` -------------------------------- ### Error Response Format Source: https://github.com/ashfromsky/acquiremock/blob/master/docs/api-reference.md JSON structure returned when an error occurs, including the error code, message, and payment ID. ```json { "error": "PAYMENT_EXPIRED", "message": "Payment session has expired", "payment_id": "550e8400-e29b-41d4-a716-446655440000" } ``` -------------------------------- ### ngrok dashboard URL Source: https://github.com/ashfromsky/acquiremock/blob/master/docs/webhook-guide.md URL to view incoming requests in the ngrok dashboard. ```text http://localhost:4040 ``` -------------------------------- ### Python webhook signature verification Source: https://github.com/ashfromsky/acquiremock/blob/master/docs/webhook-guide.md Python function to verify the webhook signature using HMAC-SHA256. It sorts JSON keys, computes the expected signature, and uses constant-time comparison to prevent timing attacks. ```python import hmac import hashlib import json def verify_webhook_signature(payload: dict, signature: str, secret: str) -> bool: message = json.dumps(payload, sort_keys=True) expected = hmac.new(secret.encode(), message.encode(), hashlib.sha256).hexdigest() return hmac.compare_digest(expected, signature) ``` -------------------------------- ### Test Card Details Source: https://github.com/ashfromsky/acquiremock/blob/master/README.md Use this test card for simulating payments: card number 4444 4444 4444 4444, any 3-digit CVV, and any future expiry date in MM/YY format. ```text Card: 4444 4444 4444 4444 CVV: any 3 digits Expiry: any future date (MM/YY) ``` -------------------------------- ### Ruby webhook signature verification Source: https://github.com/ashfromsky/acquiremock/blob/master/docs/webhook-guide.md Ruby function to verify the webhook signature using HMAC-SHA256. It sorts the payload, computes the expected signature, and uses secure_compare for constant-time comparison. ```ruby require 'openssl' require 'json' def verify_webhook_signature(payload, signature, secret) message = JSON.generate(payload.sort.to_h) expected = OpenSSL::HMAC.hexdigest('SHA256', secret, message) Rack::Utils.secure_compare(expected, signature) end ``` -------------------------------- ### Node.js webhook signature verification Source: https://github.com/ashfromsky/acquiremock/blob/master/docs/webhook-guide.md Node.js function to verify the webhook signature using HMAC-SHA256. It sorts JSON keys, computes the expected signature, and uses timing-safe comparison to prevent timing attacks. ```javascript const crypto = require('crypto'); function verifyWebhookSignature(payload, signature, secret) { const message = JSON.stringify(payload, Object.keys(payload).sort()); const expected = crypto.createHmac('sha256', secret).update(message).digest('hex'); return crypto.timingSafeEqual(Buffer.from(signature), Buffer.from(expected)); } ``` -------------------------------- ### PHP webhook signature verification Source: https://github.com/ashfromsky/acquiremock/blob/master/docs/webhook-guide.md PHP function to verify the webhook signature using HMAC-SHA256. It sorts the payload keys, computes the expected signature, and uses hash_equals for constant-time comparison. ```php function verifyWebhookSignature($payload, $signature, $secret) { ksort($payload); $message = json_encode($payload); $expected = hash_hmac('sha256', $message, $secret); return hash_equals($expected, $signature); } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.