Documentation & API Reference

Comprehensive technical guide, cryptographic security architecture, and REST API specifications for BeraLabs WordPress modules, WooCommerce plugins, and cloud microservices.

⚡ BeraLabs Architecture & Quickstart

The BeraLabs ecosystem merges high-performance on-premise modules for WordPress / WooCommerce (built with strict architectural compliance, nonce validation and native HPOS support) with headless cloud microservices running on high-throughput protocols (WhatsApp Cloud API powered by our Baileys cluster, real-time Cart Recovery Engine, and POAS Analytics).

⚡
Base API URL

All production API calls are securely routed via HTTPS to:
https://beralabs.it/api

🔒
Secure Authentication

Native support for distinct API keys across environments (blk_live_... / blk_test_...).

🛡️
HMAC SHA-256 Signatures

Cryptographic signatures on all inbound and outbound webhooks to prevent replay attacks and tampering.

Payload Standards

All API mutation requests must be sent using POST with the header Content-Type: application/json; charset=utf-8. Responses are always formatted as JSON with native UTF-8 encoding.

Authentication with API Keys

Every request made to BeraLabs cloud endpoints (WhatsApp Gateway, Cart Recovery, Newsletter Engine) must authenticate using a valid API key in one of the following HTTP headers:

  • Recommended custom header: X-Bera-API-Key: blk_live_xxxxxxxxxxxxxxxxxxxxxxxx
  • Standard OAuth/Bearer header: Authorization: Bearer blk_live_xxxxxxxxxxxxxxxxxxxxxxxx
Key Prefix Environment Description Dispatches Real Messages
blk_live_... Production Sends real WhatsApp messages and processes active customer carts Yes (instant delivery)
blk_test_... Sandbox / Staging Simulates API responses, validates payloads, and logs events without delivery No (returns mock 200 OK)

Security & HMAC SHA-256 Webhook Signatures

When BeraLabs triggers a webhook towards your store (e.g., cart recovered or OTP verified), the request includes two critical security headers:

  • X-Bera-Timestamp: UNIX epoch timestamp (seconds) when the event occurred. Reject requests older than 300 seconds to prevent replay attacks.
  • X-Bera-Signature: Hexadecimal signature computed via HMAC-SHA256 over $timestamp . '.' . $raw_payload using your private Webhook Secret.
function verify_beralabs_webhook() {
    $secret    = get_option('beralabs_webhook_secret');
    $signature = $_SERVER['HTTP_X_BERA_SIGNATURE'] ?? '';
    $timestamp = $_SERVER['HTTP_X_BERA_TIMESTAMP'] ?? '';
    $raw_body  = file_get_contents('php://input');

    // 1. Anti-replay clock skew check (max 5 minutes)
    if (abs(time() - intval($timestamp)) > 300) {
        wp_send_json_error(['error' => 'Timestamp expired or clock skew detected'], 401);
    }

    // 2. Compute expected HMAC
    $expected_sig = 'sha256=' . hash_hmac('sha256', $timestamp . '.' . $raw_body, $secret);

    // 3. Constant-time comparison
    if (!hash_equals($expected_sig, $signature)) {
        wp_send_json_error(['error' => 'Invalid HMAC signature'], 403);
    }

    return json_decode($raw_body, true);
}
const crypto = require('crypto');

function verifyBeraWebhook(req, res, next) {
    const secret = process.env.BERALABS_WEBHOOK_SECRET;
    const signature = req.headers['x-bera-signature'];
    const timestamp = req.headers['x-bera-timestamp'];
    const rawBody = req.rawBody;

    if (!signature || !timestamp) {
        return res.status(401).json({ error: 'Missing security headers' });
    }

    if (Math.abs(Date.now() / 1000 - parseInt(timestamp, 10)) > 300) {
        return res.status(401).json({ error: 'Timestamp expired' });
    }

    const hmac = crypto.createHmac('sha256', secret);
    const expectedSig = 'sha256=' + hmac.update(`${timestamp}.${rawBody}`).digest('hex');

    if (!crypto.timingSafeEqual(Buffer.from(signature), Buffer.from(expectedSig))) {
        return res.status(403).json({ error: 'Invalid HMAC signature' });
    }

    next();
}
import hmac
import hashlib
import time

def verify_bera_signature(raw_body: bytes, signature_header: str, timestamp_header: str, secret: str) -> bool:
    try:
        ts = int(timestamp_header)
        if abs(time.time() - ts) > 300:
            return False
            
        expected = "sha256=" + hmac.new(
            secret.encode('utf-8'),
            f"{ts}.".encode('utf-8') + raw_body,
            hashlib.sha256
        ).hexdigest()
        
        return hmac.compare_digest(expected, signature_header)
    except Exception:
        return False

Rate Limiting & HTTP Headers

BeraLabs APIs use sliding-window token bucket algorithms. Every response returns quota status headers:

HTTP Header Description Example
X-RateLimit-Limit Maximum allowable requests within the current 60-second window 120
X-RateLimit-Remaining Available calls remaining before rate limiting kicks in 118
X-RateLimit-Reset UNIX timestamp when quota window resets 1731683400
Retry-After Present only on 429 responses: cooldown seconds to wait 45

🔒 Woo COD Anti-Fraud (WCCAF)

Woo COD Anti-Fraud is the gold standard WooCommerce extension designed to eliminate Cash on Delivery (COD) losses, refused packages, and fake checkouts. It blends an intelligent heuristic Risk Scoring Engine with friction-free WhatsApp OTP verification right at checkout.

⚡
System Requirements

WordPress 6.0+, WooCommerce 7.0+, PHP 7.4 - 8.3. 100% High-Performance Order Storage (HPOS) compatible.

🛡️
Zero Theme Overrides

Hooks seamlessly into standard WooCommerce checkout lifecycle (woocommerce_review_order_before_submit or modal flow).

📲
Free Baileys Gateway

Send OTP verification messages via zero-cost Baileys Cloud or official Meta Cloud API.

Heuristic Risk Scoring Algorithm

Whenever Cash on Delivery is selected, WCCAF computes an instant Risk Score (0 - 100) evaluating multiple signals:

Analysis Vector Score Impact Description & Calculation Rules
Phone Carrier & Format +15 to +35 Detects virtual VoIP numbers, burner SIMs, and country code mismatches.
Postal Code & Geo Mismatch +20 to +40 Checks consistency between ZIP code, City, and State/Province.
Checkout Velocity / Frequency +25 to +50 Flags multiple rapid checkout attempts from identical IP addresses or session cookies.
Persistent Blacklist +80 to +100 Matches phone, email, or subnet against local and global high-risk fraud registries.
Automated Action Thresholds

0 - 30 (Low Risk): Smooth instant order placement with zero friction.
31 - 70 (Medium Risk): WhatsApp OTP modal required before order confirmation.
71 - 100 (High Risk): COD payment option hidden, redirecting to prepaid cards, or hard blocked.

WhatsApp OTP Verification at Checkout

Upon clicking "Place Order" with COD selected, an elegant Dark SaaS modal intercepts the submission:

  • Immediate dispatch of a 6-digit one-time token: "Your verification code for order #10482 is: 849201. Valid for 5 minutes."
  • 60-second cooldown timer preventing spam requests.
  • Seamless SMS fallback if the recipient is not active on WhatsApp.
  • Invalidates session and locks COD after 3 failed verification attempts.

Postal Code Rules & Dynamic COD Surcharges

WCCAF allows merchants to add custom fees to offset courier cash collection costs:

  • Flat or Percentage Fees: e.g., $3.50 flat fee or 2.5% of the total cart.
  • Remote Regions & Islands: Specific postal code rules (e.g., remote islands) to enforce higher surcharges or outright disable COD due to high return-to-origin rates.

PHP Action & Filter Hooks for Developers

Extend WCCAF behavior via WordPress action and filter hooks in your child theme's functions.php:

/**
 * Dynamically adjust COD surcharge based on cart total or customer role
 */
add_filter('wccaf_cod_surcharge_amount', function ($fee_amount, $cart) {
    if (current_user_can('wholesale_customer')) {
        return 0.00; // Waive fee for wholesale accounts
    }
    if ($cart->get_subtotal() > 150.00) {
        return $fee_amount * 0.5; // 50% discount on high-ticket orders
    }
    return $fee_amount;
}, 10, 2);
/**
 * Customize risk engine thresholds for repeat customers
 */
add_filter('wccaf_fraud_score_thresholds', function ($thresholds, $order_data) {
    $customer_id = $order_data['customer_id'] ?? 0;
    if ($customer_id > 0 && wc_get_customer_order_count($customer_id) >= 3) {
        $thresholds['otp_required_min'] = 60; // Require OTP only above score 60
    }
    return $thresholds;
}, 10, 2);
/**
 * Triggered as soon as WhatsApp OTP is confirmed
 */
add_action('wccaf_otp_verified', function ($order_id, $phone, $timestamp) {
    $order = wc_get_order($order_id);
    if ($order) {
        $order->update_meta_data('_wccaf_whatsapp_verified_at', current_time('mysql'));
        $order->add_order_note(sprintf(
            __('WhatsApp OTP verification passed for phone %s at %s.', 'woo-cod-antifraud'),
            $phone,
            date('Y-m-d H:i:s', $timestamp)
        ));
        $order->save();
    }
}, 10, 3);

📊 Profit Warden — Real-Time POAS & Margin Engine

Profit Warden serves as your real-time digital CFO for WooCommerce. It replaces misleading ROAS (Return On Ad Spend) vanity metrics with true POAS (Profit On Ad Spend), calculating true net pocket profit across every SKU, marketing channel, and completed order.

The Mathematical POAS Formula

Net Profit = Gross Revenue - COGS - Actual Shipping Costs - Gateway Fees - Ad Spend (Meta/Google) - Taxes
POAS = Real Gross Profit / Total Advertising Spend

COGS & Gateway Fee Management

Map every operational cost eroding your e-commerce bottom line:

  • Product & Variation Level COGS: dedicated field (_profit_warden_cogs) to input unit cost per item or variation SKU. Full CSV batch import/export capability.
  • Live Carrier Costs: automatically subtract actual courier contracts (DHL, FedEx, UPS) from shipping fees collected at checkout.
  • Payment Gateway Fees: exact deduction of variable and fixed transaction rates (Stripe 1.5% + $0.25, PayPal 3.4% + $0.35, Klarna, Afterpay, Cash on Delivery).
  • HPOS Optimized: records all accounting figures directly into high-performance order tables without overhead on standard WordPress postmeta.

Profit Warden PHP Action & Filter Hooks

Integrate custom ERP syncs or specialized calculation logic:

/**
 * Pull live COGS from external ERP or Redis cache
 */
add_filter('profit_warden_custom_cogs', function ($cogs, $product_id, $variation_id) {
    $target_id = $variation_id ? $variation_id : $product_id;
    $sku = get_post_meta($target_id, '_sku', true);

    $erp_cost = get_transient('erp_cogs_' . $sku);
    if ($erp_cost !== false) {
        return floatval($erp_cost);
    }
    return $cogs;
}, 10, 3);
/**
 * Enforce negotiated enterprise Stripe interchange rates
 */
add_filter('profit_warden_gateway_fee', function ($calculated_fee, $payment_method, $order_total) {
    if ($payment_method === 'stripe') {
        return ($order_total * 0.012) + 0.20; // 1.2% + $0.20
    }
    return $calculated_fee;
}, 10, 3);
/**
 * Dispatch real-time alert on negative margin orders
 */
add_action('profit_warden_profit_computed', function ($order_id, $profit_breakdown) {
    if ($profit_breakdown['net_profit'] < 0) {
        do_action('send_slack_alert', sprintf("⚠️ Order #%d is underwater! Net Margin: $%.2f", $order_id, $profit_breakdown['net_profit']));
    }
}, 10, 2);

✨ GeoSchemaForge & BeraLab GEO Engine

GeoSchemaForge (also known as BeraLab GEO Engine) is an advanced Generative Engine Optimization (GEO) and Answer Engine Optimization (AEO) solution for WordPress and Joomla. It establishes your brand and products as authoritative citations in AI answer engines: ChatGPT Search, Perplexity AI, Claude 3.5, and Google AI Overviews.

🧠
Interconnected @graph

Injects nested Schema.org JSON-LD trees: WebSite, Organization, LocalBusiness, FAQPage, Speakable.

🤖
LLMs.txt Native Standard

Automated delivery of /llms.txt and /llms-full.txt endpoints for machine-readable AI agent scraping.

📍
Geospatial Precision

Accurate GPS lat/long coordinates, GeoShape boundaries, and ISO 8601 multiline opening hours.

Machine-Readable /llms.txt AI Endpoints

The plugin serves modern standardized endpoints directly at site root:

  • /llms.txt: condensed Markdown summary providing maximum contextual clarity with minimal token usage for AI agents.
  • /llms-full.txt: comprehensive documentation and knowledge base export designed for Retrieval-Augmented Generation (RAG) pipelines.
/**
 * Inject security certifications into Organization schema
 */
add_filter('geoschemaforge_jsonld_output', function ($graph_data, $post_id) {
    foreach ($graph_data['@graph'] as &$node) {
        if ($node['@type'] === 'Organization') {
            $node['hasCredential'] = [
                '@type' => 'EducationalOccupationalCredential',
                'name'  => 'ISO 27001 Certified Security'
            ];
        }
    }
    return $graph_data;
}, 10, 2);

[geoschema_business layout="card" show_map="yes" show_hours="yes"]


[geoschema_faq category="e-commerce" limit="5"]

🛒 WhatsApp Cart Recovery (OBJ-11)

WhatsApp Cart Recovery recovers up to 45% of abandoned checkout sessions in WooCommerce using high-engagement WhatsApp notifications (98% Open Rate, 45-60% CTR). It features Live Checkout Capture technology to capture phone and intent before customer drop-off.

POST https://beralabs.it/api/cart-recovery

This endpoint receives cart session payloads dispatched automatically when the user fills their phone number and blurs focus (JavaScript onblur event with 500ms debounce):

Parameter Type Required Description
phone String Yes Recipient phone number formatted in E.164 standard (e.g., +14155552671).
customer_name String Yes Customer first name or company used for personalized greeting.
cart_token String Yes Unique cart session identifier generated by WooCommerce (e.g., ct_9f8e7d6c5b4a).
cart_total Float Yes Total monetary value of items in the cart.
currency String No 3-letter ISO currency code (default: USD or EUR).
items Array Yes Product array containing product_id, name, quantity, price, image_url.
recovery_url String Yes URL with signed Magic Link for 1-click cart restoration.
delay_minutes Integer No Delay window before sending the recovery message (default: 20).
discount_code String No Optional incentive discount code (e.g., SAVE10) applied automatically.

Request Payload Example (JSON)

Request JSON Body
{
  "phone": "+14155552671",
  "customer_name": "Alex Morgan",
  "cart_token": "ct_9f8e7d6c5b4a",
  "currency": "USD",
  "cart_total": 89.90,
  "items": [
    {
      "product_id": 412,
      "name": "Nitro Pro Running Shoes",
      "quantity": 1,
      "price": 89.90,
      "image_url": "https://store.com/wp-content/uploads/nitro.jpg"
    }
  ],
  "recovery_url": "https://store.com/cart?restore=ct_9f8e7d6c5b4a&token=sec_abc123",
  "delay_minutes": 20,
  "discount_code": "SAVE10"
}

Success Response Example (HTTP 201 Created)

Response 201 Created
{
  "success": true,
  "recovery_id": "rec_7832a8901fbc",
  "status": "scheduled",
  "scheduled_at": "2026-03-30T10:45:00Z",
  "phone": "+14155552671",
  "message_preview": "Hi Alex! You left your Nitro Pro Running Shoes in your cart. Tap here to complete your order with 10% off: https://store.com/cart?restore=ct_9f8e7d6c5b4a"
}

Conversion Webhooks & Telemetry

When customers finalize payment through the magic link, a signed cart.recovered webhook is posted to your store:

Webhook Event: cart.recovered
{
  "event": "cart.recovered",
  "recovery_id": "rec_7832a8901fbc",
  "phone": "+14155552671",
  "order_id": "10499",
  "recovered_revenue": 89.90,
  "currency": "USD",
  "recovered_at": "2026-03-30T11:02:14Z",
  "time_to_convert_minutes": 17
}

⚡ WhatsApp OTP Gateway

The WhatsApp OTP Gateway powers two-factor authentication (2FA), Cash on Delivery phone verification, and passwordless logins across high-volume e-commerce stores.

POST https://beralabs.it/api/send-otp
Parameter Type Required Description
phone String Yes Destination mobile number in international E.164 format (e.g., +14155552671).
shop_name String Yes Brand or store name displayed in the message header.
otp_length Integer No Token length: 4 or 6 digits (default: 6).
ttl_seconds Integer No Token validity duration in seconds (default: 300 = 5 minutes).
purpose String No Operation context: cod_verification, login_2fa, checkout_auth.
Response 200 OK
{
  "success": true,
  "session_id": "otp_sess_a819c9e830f",
  "status": "delivered",
  "channel": "whatsapp",
  "expires_at": 1731683100,
  "retry_after_seconds": 60
}

Verify OTP Token

Validate the token entered by the user against the active verification session:

POST https://beralabs.it/api/verify-otp
Parameter Type Required Description
session_id String Yes Session ID returned by /send-otp.
code String Yes The numeric code submitted by the user.
Response 200 OK (Verified)
{
  "success": true,
  "verified": true,
  "phone": "+14155552671",
  "verified_at": 1731682845
}

💬 WhatsApp Newsletter & Lead Gen

Collect verified phone leads with our lightweight floating widget and broadcast promotional campaigns with >95% open rates while staying 100% compliant with GDPR regulations.

POST https://beralabs.it/api/newsletter/subscribe
Parameter Type Required Description
phone String Yes Phone number in E.164 format (e.g., +14155552671).
name String No Subscriber name for personalized messaging.
email String No Email for CRM cross-channel sync.
consent_gdpr Boolean Yes Must be explicitly true.
tags Array No Segmentation tags (e.g., ["vip_drops", "sneakers"]).
WhatsApp Double Opt-in Process

Submitting the widget immediately sends an interactive WhatsApp message with two buttons: "Confirm Subscription" and "Decline". Subscribers are only enrolled after tapping "Confirm Subscription".

💻 Code & SDK Examples

Production-ready code snippets with error handling across major languages:

1. Send Cart Recovery Event

curl -X POST https://beralabs.it/api/cart-recovery \
  -H "Content-Type: application/json" \
  -H "X-Bera-API-Key: blk_live_xxxxxxxxxxxxxxxxxxxxxxxx" \
  -d '{
    "phone": "+14155552671",
    "customer_name": "Alex Morgan",
    "cart_token": "ct_9f8e7d6c5b4a",
    "cart_total": 89.90,
    "currency": "USD",
    "items": [
      {
        "product_id": 412,
        "name": "Nitro Pro Running Shoes",
        "quantity": 1,
        "price": 89.90
      }
    ],
    "recovery_url": "https://store.com/cart?restore=ct_9f8e7d6c5b4a",
    "delay_minutes": 20,
    "discount_code": "SAVE10"
  }'
$response = wp_remote_post('https://beralabs.it/api/cart-recovery', [
    'headers' => [
        'Content-Type'   => 'application/json; charset=utf-8',
        'X-Bera-API-Key' => get_option('beralabs_api_key'),
    ],
    'body'    => wp_json_encode([
        'phone'         => '+14155552671',
        'customer_name' => 'Alex Morgan',
        'cart_token'    => 'ct_9f8e7d6c5b4a',
        'cart_total'    => 89.90,
        'currency'      => 'USD',
        'items'         => [
            [
                'product_id' => 412,
                'name'       => 'Nitro Pro Running Shoes',
                'quantity'   => 1,
                'price'      => 89.90
            ]
        ],
        'recovery_url'  => 'https://store.com/cart?restore=ct_9f8e7d6c5b4a',
        'delay_minutes' => 20,
        'discount_code' => 'SAVE10'
    ]),
    'timeout' => 15,
]);

if (is_wp_error($response)) {
    error_log('BeraLabs Cart Recovery Error: ' . $response->get_error_message());
}
async function sendCartRecovery(cartData) {
  try {
    const response = await fetch('https://beralabs.it/api/cart-recovery', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'X-Bera-API-Key': process.env.BERALABS_API_KEY
      },
      body: JSON.stringify({
        phone: cartData.phone,
        customer_name: cartData.customerName,
        cart_token: cartData.token,
        cart_total: cartData.total,
        currency: 'USD',
        items: cartData.items,
        recovery_url: `https://store.com/cart?restore=${cartData.token}`,
        delay_minutes: 20,
        discount_code: 'SAVE10'
      })
    });
    const data = await response.json();
    return data;
  } catch (error) {
    console.error('BeraLabs Recovery Exception:', error);
  }
}
import requests

def send_cart_recovery(api_key: str, cart: dict):
    url = "https://beralabs.it/api/cart-recovery"
    headers = {
        "Content-Type": "application/json",
        "X-Bera-API-Key": api_key
    }
    payload = {
        "phone": cart["phone"],
        "customer_name": cart["customer_name"],
        "cart_token": cart["token"],
        "cart_total": cart["total"],
        "currency": "USD",
        "items": cart["items"],
        "recovery_url": f"https://store.com/cart?restore={cart['token']}",
        "delay_minutes": 20,
        "discount_code": "SAVE10"
    }
    res = requests.post(url, json=payload, headers=headers, timeout=10)
    res.raise_for_status()
    return res.json()

2. Full OTP Lifecycle SDK

Example implementation in Node.js / Express:

Node.js / Express Implementation
// 1. Send OTP Request
async function requestOtp(phoneNumber, brandName) {
  const res = await fetch('https://beralabs.it/api/send-otp', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'X-Bera-API-Key': process.env.BERALABS_API_KEY
    },
    body: JSON.stringify({
      phone: phoneNumber,
      shop_name: brandName,
      otp_length: 6,
      ttl_seconds: 300,
      purpose: 'cod_verification'
    })
  });
  return await res.json();
}

// 2. Verify OTP
async function verifyOtp(sessionId, userCode) {
  const res = await fetch('https://beralabs.it/api/verify-otp', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'X-Bera-API-Key': process.env.BERALABS_API_KEY
    },
    body: JSON.stringify({
      session_id: sessionId,
      code: userCode
    })
  });
  return await res.json();
}

3. HMAC Webhook Signature Verification

Always verify the HMAC SHA-256 signature on inbound webhooks (detailed snippet in Security & HMAC Signatures).

🛡️ Error Handling & HTTP Status Codes

BeraLabs APIs follow conventional HTTP status code conventions. All 4xx and 5xx errors return standardized JSON responses:

Standard Error JSON Payload
{
  "success": false,
  "error_code": "INVALID_PHONE_FORMAT",
  "message": "The provided phone number is not formatted as valid E.164 (e.g. +14155552671).",
  "field": "phone",
  "docs_url": "https://beralabs.it/en/docs#http-status-codes"
}
HTTP Status Error Code Meaning Recommended Action
200 OK - Request succeeded. Process response data.
201 Created - Resource created successfully. Store returned session/cart ID.
400 Bad Request MISSING_REQUIRED_FIELD Missing mandatory parameters in JSON payload. Check payload and Content-Type header.
401 Unauthorized INVALID_API_KEY API Key is missing or invalid. Verify X-Bera-API-Key header.
403 Forbidden INSUFFICIENT_PERMISSIONS Endpoint disabled or invalid HMAC signature. Verify plan limits or Webhook Secret.
404 Not Found SESSION_EXPIRED_OR_NOT_FOUND OTP session or cart token expired. Prompt user to request a fresh OTP token.
422 Unprocessable PHONE_NOT_ON_WHATSAPP Phone number has no active WhatsApp account. Trigger automatic SMS fallback.
429 Too Many Req RATE_LIMIT_EXCEEDED Rate limit quota exceeded. Wait for seconds specified in Retry-After.
500 Server Error INTERNAL_GATEWAY_ERROR Internal server error. Retry with exponential backoff or contact support.

Troubleshooting Guide

Common Issues & Fixes

1. OTP WhatsApp message not arriving: Verify the recipient number includes international country code (e.g. +1, +44, +39) with no hyphens or spaces.
2. "Invalid HMAC Signature" error: Validate the raw request body buffer before any JSON parsing.
3. CORS error at checkout: Whitelist your e-commerce domain under BeraLabs dashboard settings if posting from browser fetch.
4. 429 Rate Limit error: Implement exponential retry backoff with 1 to 3 seconds jitter.