> ## Documentation Index
> Fetch the complete documentation index at: https://docs.moduluslabs.io/llms.txt
> Use this file to discover all available pages before exploring further.

# Overview

> Receive real-time notifications when QR Ph transactions are completed

## Overview

Webhooks allow Modulus Labs to notify your application in real-time when QR Ph transactions are completed. Instead of repeatedly polling the API to check transaction status, webhooks push updates directly to your server the moment an event occurs.

<Warning>
  **Webhooks are REQUIRED for QR Ph integration.** Without webhooks, you cannot receive transaction status updates, which poses significant security risks. Your system would be unable to verify if a customer's payment succeeded or failed.
</Warning>

<CardGroup cols={2}>
  <Card title="Setup Guide" icon="gear" href="/docs/webhooks/setup">
    Configure webhook endpoints for your account
  </Card>

  <Card title="API Reference" icon="code" href="/api-reference/webhooks/create">
    Complete webhook management API documentation
  </Card>

  <Card title="Receiving Webhooks" icon="webhook" href="/docs/webhooks/receiving">
    Handle and process webhook notifications
  </Card>

  <Card title="Payload Structure" icon="brackets-curly" href="/docs/webhooks/payload">
    Understand webhook payload format and encryption
  </Card>
</CardGroup>

## API Endpoint

All Webhook API requests should be made to the sandbox environment:

```bash theme={null}
https://webhooks.sbx.moduluslabs.io
```

<Note>
  This is the sandbox environment URL. Production credentials and URL will be provided separately when you're ready to go live.
</Note>

## API Philosophy

The Webhooks API is designed for reliability and security:

<CardGroup cols={3}>
  <Card title="REST Architecture" icon="globe">
    Standard REST API with predictable URLs and HTTP methods
  </Card>

  <Card title="JSON Format" icon="brackets-curly">
    All requests and responses use JSON
  </Card>

  <Card title="HTTPS Only" icon="lock">
    All API requests must be made over HTTPS
  </Card>

  <Card title="HTTP Basic Auth" icon="shield">
    Simple authentication using your Secret Key
  </Card>

  <Card title="JWE Encryption" icon="shield-halved">
    All webhook payloads encrypted with JWE for security
  </Card>

  <Card title="Automatic Retries" icon="rotate">
    Up to 4 delivery attempts with 15-minute intervals
  </Card>

  <Card title="PCI DSS 4.1 Certified" icon="badge-check">
    Modulus Labs is PCI DSS 4.1 compliant, ensuring the highest standards of payment security and data protection
  </Card>
</CardGroup>

## How Webhooks Work

<Steps>
  <Step title="Configure Webhook Endpoint">
    Create a webhook endpoint on your server that accepts POST requests and register it with Modulus Labs using the Webhook API.
  </Step>

  <Step title="Customer Completes Payment">
    When a customer scans your Dynamic QR Ph code and completes payment in their banking app, the payment network processes the transaction.
  </Step>

  <Step title="Modulus Labs Sends Notification">
    Modulus Labs immediately sends a POST request to your webhook endpoint with the encrypted transaction details.
  </Step>

  <Step title="Your Server Processes Webhook">
    Your server receives the webhook, verifies its authenticity, decrypts the payload, and updates the order status in your system.
  </Step>

  <Step title="Automatic Retries">
    If your server doesn't respond successfully, Modulus Labs automatically retries up to 3 more times at 15-minute intervals.
  </Step>
</Steps>

## Why Webhooks Are Required

<AccordionGroup>
  <Accordion title="Can I skip webhooks and just poll the API?" icon="circle-xmark">
    **No.** Webhooks are mandatory for QR Ph integration. Polling is inefficient, introduces delays, and creates security gaps where fraudulent transactions could go undetected.

    **Without webhooks:**

    * You won't know when payments succeed or fail
    * Customers may complete payment but never receive their order
    * Your system cannot verify transaction authenticity
    * You risk order fulfillment errors and revenue loss
  </Accordion>

  <Accordion title="Real-Time Order Fulfillment" icon="bolt">
    Webhooks notify you instantly when payment completes, enabling immediate order fulfillment. Customers receive their digital goods, confirmations, or service access without delay.
  </Accordion>

  <Accordion title="Security and Fraud Prevention" icon="shield">
    Every webhook is encrypted with JWE (JSON Web Encryption). You can verify that notifications genuinely came from Modulus Labs and haven't been tampered with, preventing fraudulent payment claims.
  </Accordion>

  <Accordion title="Reliability with Automatic Retries" icon="rotate">
    If your server is temporarily unavailable, Modulus Labs automatically retries webhook delivery up to 4 times:

    * Immediately upon transaction completion
    * After 15 minutes (retry 1)
    * After 30 minutes (retry 2)
    * After 45 minutes (retry 3)

    This ensures you receive critical payment notifications even during brief outages.
  </Accordion>

  <Accordion title="Multi-Merchant Support" icon="building">
    If you manage multiple merchants, use the `activation-code` header to identify which merchant account the webhook belongs to, enabling centralized webhook handling.
  </Accordion>
</AccordionGroup>

## Webhook Events

Modulus Labs sends webhooks for these QR Ph transaction events:

| Event           | Description                    | When It's Sent                                                          |
| --------------- | ------------------------------ | ----------------------------------------------------------------------- |
| `QRPH_SUCCESS`  | Payment completed successfully | Customer's bank confirms payment and transfers funds                    |
| `QRPH_DECLINED` | Payment failed or was declined | Bank rejects payment due to insufficient funds, limits, or other issues |

<Tip>
  Both success and declined webhooks are critical. Handle declined payments gracefully by notifying customers and offering alternative payment methods.
</Tip>

## Authentication

The Webhook API uses **HTTP Basic Authentication**, identical to the QR API.

<Steps>
  <Step title="Use Your Secret Key">
    Your secret key serves as the username. Leave the password empty.
  </Step>

  <Step title="Format the Authorization Header">
    ```
    Authorization: Basic {base64(secret_key:)}
    ```

    Note the colon (`:`) after your secret key before base64 encoding.
  </Step>

  <Step title="Send with Every Request">
    Include the Authorization header in all Webhook API requests (creating, updating, deleting webhooks).
  </Step>
</Steps>

<Card title="Authentication Guide" icon="key" href="/docs/qr/authentication">
  Detailed authentication instructions and code examples
</Card>

## Webhook Payload Security

All webhook payloads are encrypted using **JWE (JSON Web Encryption)** to protect sensitive transaction data.

### Encryption Details

* **Content Encryption Algorithm**: `A256CBC-HS512` (AES-256-CBC with HMAC SHA-512)
* **Key Encryption Algorithm**: `A256KW` (AES-256 Key Wrap)
* **Format**: JSON Web Encryption Compact Serialization

<CodeGroup>
  ```json Encrypted Payload (What You Receive) theme={null}
  {
    "data": "eyJhbGciOiJBMjU2S1ciLCJlbmMiOiJBMjU2Q0JDLUhTNTEyIn0.9x4mZBJaKc7QPZ-5u8NOBzjK-cQ2puX9eBaWOWgpGJ6SRvb8P8O2xA.Yp8AbjvIrVH46GKQtLV9PA.zlDcH_ES9xg7OdstFYn..."
  }
  ```

  ```json Decrypted Payload (After Processing) theme={null}
  {
    "payload": {
      "referenceNumber": "REF123456789",
      "amount": 1000,
      "currency": "PHP",
      "status": "SUCCESS",
      "transactionDate": "2024-01-15T10:30:00Z",
      "merchantId": "MERCH12345"
    }
  }
  ```
</CodeGroup>

<Card title="Payload Structure" icon="lock" href="/docs/webhooks/payload">
  Complete payload documentation with decryption examples
</Card>

## Webhook Management

The Webhook API provides full CRUD (Create, Read, Update, Delete) operations for managing webhook endpoints.

<CardGroup cols={2}>
  <Card title="Create Webhook" icon="plus" href="/api-reference/webhooks/create">
    Register a new webhook endpoint
  </Card>

  <Card title="List Webhooks" icon="list" href="/api-reference/webhooks/list">
    View all configured webhooks
  </Card>

  <Card title="Update Webhook" icon="pen" href="/api-reference/webhooks/update">
    Modify webhook URL or actions
  </Card>

  <Card title="Delete Webhook" icon="trash" href="/api-reference/webhooks/delete">
    Remove a webhook endpoint
  </Card>
</CardGroup>

### Webhook Status

Each webhook can have one of two statuses:

| Status     | Description                                                                   |
| ---------- | ----------------------------------------------------------------------------- |
| `ENABLED`  | Webhook is active and will receive notifications                              |
| `DISABLED` | Webhook is paused and will not receive notifications (useful for maintenance) |

<Tip>
  Disable webhooks temporarily during server maintenance instead of deleting them. This preserves your configuration and makes it easy to resume receiving notifications.
</Tip>

## Testing Webhooks

The Webhook API includes a **Simulate** endpoint for testing your webhook integration in the sandbox environment without generating real transactions.

<Steps>
  <Step title="Register Your Webhook">
    Use the Create Webhook API to register your test endpoint
  </Step>

  <Step title="Call the Simulate API">
    Trigger a test webhook with SUCCESS or DECLINED status
  </Step>

  <Step title="Verify Your Handler">
    Confirm your server correctly receives, decrypts, and processes the webhook
  </Step>

  <Step title="Test Error Scenarios">
    Simulate declined payments to ensure proper error handling
  </Step>
</Steps>

<Card title="Simulate Webhook" icon="flask" href="/api-reference/webhooks/simulate">
  Test your webhook integration without real transactions
</Card>

## Integration Checklist

Use this checklist to ensure your webhook integration is complete:

<Steps>
  <Step title="Implement Webhook Endpoint">
    * [ ] Create POST endpoint that accepts webhook notifications
    * [ ] Implement JWE decryption for webhook payloads
    * [ ] Return `200 OK` status code within 10 seconds
    * [ ] Handle webhook retries idempotently (same webhook may arrive multiple times)
  </Step>

  <Step title="Register Webhook with Modulus Labs">
    * [ ] Call Create Webhook API with your endpoint URL
    * [ ] Specify which actions to receive (`QRPH_SUCCESS`, `QRPH_DECLINED`, or both)
    * [ ] Verify webhook status is `ENABLED`
  </Step>

  <Step title="Test in Sandbox">
    * [ ] Use Simulate API to send test webhooks
    * [ ] Verify SUCCESS webhook handling
    * [ ] Verify DECLINED webhook handling
    * [ ] Test retry mechanism by returning 5xx errors
  </Step>

  <Step title="Security Validation">
    * [ ] Verify JWE signature to confirm webhook authenticity
    * [ ] Decrypt payload using your secret key
    * [ ] Validate referenceNumber matches your QR creation request
    * [ ] Implement request signature verification (if required)
  </Step>

  <Step title="Error Handling">
    * [ ] Log all webhook receipts for debugging
    * [ ] Implement retry logic for transient errors
    * [ ] Alert monitoring systems for webhook failures
    * [ ] Handle duplicate webhook deliveries gracefully
  </Step>
</Steps>

## Use Cases

<AccordionGroup>
  <Accordion title="E-commerce Order Fulfillment">
    Customer completes QR Ph payment at checkout. Webhook notifies your system instantly, triggering order processing, inventory updates, and shipping label generation.
  </Accordion>

  <Accordion title="Point of Sale (POS)">
    In-store customer scans QR code and pays. Webhook notifies POS system to print receipt and complete transaction without manual verification.
  </Accordion>

  <Accordion title="Digital Content Delivery">
    Customer purchases downloadable content. Webhook triggers instant delivery of download link or license key upon payment confirmation.
  </Accordion>
</AccordionGroup>

## Best Practices

<CardGroup cols={2}>
  <Card title="Idempotency" icon="repeat">
    Design webhook handlers to be idempotent. You may receive the same webhook multiple times due to retries, so use `referenceNumber` to prevent duplicate processing.
  </Card>

  <Card title="Fast Response" icon="gauge-high">
    Return `200 OK` quickly (within 10 seconds). Process webhooks asynchronously using background jobs to avoid timeouts.
  </Card>

  <Card title="Security First" icon="shield-halved">
    Always decrypt and verify webhook payloads. Never trust webhook data without cryptographic verification.
  </Card>

  <Card title="Logging" icon="file-lines">
    Log every webhook receipt with timestamp, referenceNumber, and processing result for debugging and audit trails.
  </Card>

  <Card title="Error Monitoring" icon="bell">
    Set up alerts for webhook processing failures. Missing webhook notifications means missed payments.
  </Card>

  <Card title="Graceful Degradation" icon="circle-exclamation">
    If webhook processing fails, have a fallback mechanism to detect and recover from missed notifications.
  </Card>
</CardGroup>

## Next Steps

<CardGroup cols={2}>
  <Card title="Setup Guide" icon="rocket" href="/docs/webhooks/setup">
    Configure your first webhook endpoint
  </Card>

  <Card title="Receiving Webhooks" icon="code" href="/docs/webhooks/receiving">
    Implement webhook handling in your application
  </Card>

  <Card title="Payload Documentation" icon="brackets-curly" href="/docs/webhooks/payload">
    Understand webhook payload structure and decryption
  </Card>

  <Card title="Create Webhook API" icon="plus" href="/api-reference/webhooks/create">
    Register a webhook endpoint via API
  </Card>
</CardGroup>

<Note>
  **Ready to integrate webhooks?** Start with the [Setup Guide](/docs/webhooks/setup) to register your first webhook endpoint.
</Note>
