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

# Testing & Configuration

> Interactive webhook configuration and testing guide

<Note>
  **Interactive API Playground**: Click the cards below to open the API playground where you can directly test and configure your webhooks with your API credentials.
</Note>

## Interactive Webhook Configuration

Configure and test your webhooks using the interactive API playground:

<CardGroup cols={2}>
  <Card title="Get Configuration" icon="download" href="/api-reference/admin/get-webhooks-configs">
    View your current webhook settings
  </Card>

  <Card title="Update Configuration" icon="upload" href="/api-reference/admin/put-webhooks-configs">
    Configure webhook events and URL
  </Card>
</CardGroup>

## Get Current Configuration

Retrieve your current webhook configuration to see what events you're subscribed to.

<Card title="Try It Now" icon="play" href="/api-reference/admin/get-webhooks-configs">
  Click here to get your current webhook configuration using the interactive API playground
</Card>

### Example Response

```json theme={null}
{
  "configs": [
    {
      "events": [
        "challenge-completion",
        "reward-distribution",
        "achievement-completion"
      ],
      "url": "https://your-webhook-endpoint.com/webhooks/nudj",
      "httpMethod": "POST",
      "isEnabled": true,
      "maxRetries": 3,
      "headers": {
        "X-API-Key": "your-secret-key"
      }
    }
  ]
}
```

## Configure Webhooks

Update your webhook configuration to subscribe to specific events and set your endpoint URL.

<Card title="Try It Now" icon="play" href="/api-reference/admin/put-webhooks-configs">
  Click here to configure your webhooks using the interactive API playground
</Card>

### Configuration Examples

<Tabs>
  <Tab title="Basic Setup">
    Start with essential events for most integrations:

    ```json theme={null}
    {
      "configs": [
        {
          "events": [
            "challenge-completion",
            "reward-distribution"
          ],
          "url": "https://your-app.com/webhooks/nudj",
          "httpMethod": "POST",
          "isEnabled": true,
          "maxRetries": 3,
          "headers": {
            "X-API-Key": "your-webhook-secret"
          }
        }
      ]
    }
    ```
  </Tab>

  <Tab title="Full Integration">
    Subscribe to all available webhook events:

    ```json theme={null}
    {
      "configs": [
        {
          "events": [
            "achievement-completion",
            "auth.email",
            "challenge-completion",
            "challenge-started",
            "organisation.invite-admin-user",
            "post-comment",
            "post-like",
            "reward-claim",
            "reward-distribution",
            "reward-redemption",
            "shop-purchase",
            "streak-extended"
          ],
          "url": "https://your-app.com/webhooks/nudj",
          "httpMethod": "POST",
          "isEnabled": true,
          "maxRetries": 5,
          "headers": {
            "X-API-Key": "your-webhook-secret",
            "X-Custom-Header": "custom-value"
          }
        }
      ]
    }
    ```
  </Tab>

  <Tab title="Development Setup">
    Configuration for local development and testing:

    ```json theme={null}
    {
      "configs": [
        {
          "events": [
            "challenge-completion",
            "reward-distribution"
          ],
          "url": "https://webhook.site/unique-url",
          "httpMethod": "POST",
          "isEnabled": true,
          "maxRetries": 1,
          "headers": {
            "X-API-Key": "test-key"
          }
        }
      ]
    }
    ```
  </Tab>
</Tabs>

## Testing Your Webhook

Follow these steps to test your webhook configuration:

### Step 1: Set Up a Test Endpoint

<Tabs>
  <Tab title="Webhook.site">
    1. Visit [webhook.site](https://webhook.site)
    2. Copy your unique URL
    3. Use it as your webhook URL in the configuration
    4. Monitor incoming requests in real-time
  </Tab>

  <Tab title="ngrok">
    1. Install ngrok: `brew install ngrok`
    2. Start your local server: `node server.js`
    3. Create tunnel: `ngrok http 3000`
    4. Use the HTTPS URL as your webhook endpoint
  </Tab>

  <Tab title="RequestBin">
    1. Visit [requestbin.com](https://requestbin.com)
    2. Create a new bin
    3. Copy the bin URL
    4. Use it as your webhook URL
  </Tab>
</Tabs>

### Step 2: Configure Your Webhook

Use the [PUT endpoint](/api-reference/admin/put-webhooks-configs) to set your test webhook URL:

```bash theme={null}
curl -X PUT https://{subdomain}.nudj.cx/api/v2/admin/webhooks/configs \
  -H "x-api-token: YOUR_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "configs": [{
      "events": ["challenge-completion"],
      "url": "https://webhook.site/YOUR-UNIQUE-URL",
      "httpMethod": "POST",
      "isEnabled": true,
      "maxRetries": 1,
      "headers": {
        "X-API-Key": "test-secret"
      }
    }]
  }'
```

### Step 3: Trigger Test Events

Perform actions in your Nudj community to trigger webhook events:

| Action               | Triggered Event          | Expected Payload             |
| -------------------- | ------------------------ | ---------------------------- |
| Complete a challenge | `challenge-completion`   | Contains challengeId, userId |
| Earn rewards         | `reward-distribution`    | Contains points, XP, rewards |
| Unlock achievement   | `achievement-completion` | Contains achievement details |
| Purchase from shop   | `shop-purchase`          | Contains purchase details    |
| Like a post          | `post-like`              | Contains postId              |

### Step 4: Verify Delivery

Check your test endpoint to confirm webhook delivery:

<Info>
  **What to Look For:**

  * HTTP method matches configuration (POST/PUT/GET)
  * Custom headers are present
  * Event payload structure is correct
  * Response status is 2xx
</Info>

## Testing Checklist

Use this checklist to ensure your webhook integration is working correctly:

<Steps>
  <Step title="Configure Test Endpoint">
    Set up webhook.site, ngrok, or RequestBin endpoint
  </Step>

  <Step title="Update Configuration">
    Use [PUT endpoint](/api-reference/admin/put-webhooks-configs) to set your webhook URL and events
  </Step>

  <Step title="Verify Configuration">
    Use [GET endpoint](/api-reference/admin/get-webhooks-configs) to confirm settings are saved
  </Step>

  <Step title="Trigger Test Event">
    Complete a challenge or perform another action
  </Step>

  <Step title="Check Delivery">
    Verify webhook received at test endpoint
  </Step>

  <Step title="Validate Payload">
    Confirm event structure matches documentation
  </Step>

  <Step title="Test Error Handling">
    Return non-2xx status to test retry logic
  </Step>

  <Step title="Switch to Production">
    Update URL to production endpoint
  </Step>
</Steps>

## Common Test Scenarios

### Testing Retry Logic

To test the retry mechanism:

1. Configure webhook with `maxRetries: 3`
2. Have your endpoint return `500` status
3. Observe 3 delivery attempts with 5-second delays
4. After 3 failures, webhook marked as failed

### Testing Authentication

Verify your authentication headers:

```javascript theme={null}
app.post('/webhooks/test', (req, res) => {
  const apiKey = req.headers['x-api-key'];
  
  if (apiKey !== 'expected-secret') {
    console.log('Auth failed:', apiKey);
    return res.status(401).json({ error: 'Unauthorized' });
  }
  
  console.log('Auth successful');
  res.status(200).json({ success: true });
});
```

### Testing Idempotency

Ensure duplicate events are handled:

```javascript theme={null}
const processedEvents = new Set();

app.post('/webhooks/test', (req, res) => {
  const eventId = req.body.id;
  
  if (processedEvents.has(eventId)) {
    console.log('Duplicate event:', eventId);
    return res.status(200).json({ duplicate: true });
  }
  
  processedEvents.add(eventId);
  console.log('New event:', eventId);
  res.status(200).json({ success: true });
});
```

## Monitoring Webhook Health

### Key Metrics to Track

* **Delivery Success Rate**: Should be > 99%
* **Average Response Time**: Should be \< 1 second
* **Retry Rate**: Should be \< 1%
* **Failed Deliveries**: Should be investigated immediately

### Health Check Endpoint

Implement a health check for your webhook:

```javascript theme={null}
app.get('/webhooks/health', (req, res) => {
  res.status(200).json({
    status: 'healthy',
    uptime: process.uptime(),
    memory: process.memoryUsage(),
    lastWebhook: lastWebhookTime,
    totalProcessed: webhookCount
  });
});
```

## Troubleshooting Test Issues

<AccordionGroup>
  <Accordion title="Webhook not receiving events">
    * Verify webhook is enabled (`isEnabled: true`)
    * Check URL is publicly accessible (not localhost)
    * Confirm events are in the subscription list
    * Ensure organization has active events
  </Accordion>

  <Accordion title="Authentication errors">
    * Verify custom headers match exactly
    * Check for case sensitivity in header names
    * Ensure HTTPS is used (not HTTP)
  </Accordion>

  <Accordion title="Payload validation failures">
    * Compare received payload with documentation
    * Check JSON parsing for large payloads
    * Verify character encoding (UTF-8)
  </Accordion>

  <Accordion title="Intermittent failures">
    * Check for timeout issues (> 5 seconds)
    * Monitor server resource usage
    * Review network connectivity
    * Check for rate limiting
  </Accordion>
</AccordionGroup>
