C
CoderspaE
/Documentation

Webhooks API

Configure webhooks to receive real-time notifications about battles, user activities, and system events in your applications.

Overview

Webhooks allow CoderspaE to send HTTP POST requests to your server when specific events occur. This enables you to build integrations that react to platform activities in real-time.

Key Features

  • • Real-time event notifications
  • • Automatic retry mechanism with exponential backoff
  • • HMAC signature verification for security
  • • Delivery status tracking and logs
  • • Custom headers and payload filtering

Setup

Creating a Webhook

Create webhooks via the API or dashboard:

POST /api/v1/webhooks

{
  "url": "https://your-app.com/webhooks/coderspae",
  "events": ["battle.completed", "user.registered"],
  "secret": "your-webhook-secret",
  "active": true,
  "description": "Battle completion notifications"
}

Webhook Configuration

FieldTypeDescription
urlstringHTTPS endpoint to receive webhooks
eventsarrayList of events to subscribe to
secretstringSecret for HMAC signature verification
activebooleanEnable/disable webhook delivery

Available Events

Battle Events

battle.createdNew battle room created
battle.startedBattle started with matched players
battle.completedBattle finished with results
battle.submissionCode submitted during battle

User Events

user.registeredNew user account created
user.profile_updatedUser profile information changed
user.achievement_earnedUser earned a new achievement
user.rating_changedUser rating updated after battle

Team Events

team.createdNew team formed
team.member_joinedUser joined a team
team.battle_completedTeam battle finished

System Events

system.maintenance_scheduledMaintenance window announced
system.tournament_startedTournament competition began
system.leaderboard_updatedWeekly leaderboard refresh

Payload Structure

Standard Format

{
  "id": "evt_1234567890",
  "event": "battle.completed",
  "created": "2024-01-15T10:30:00Z",
  "data": {
    "object": "battle",
    "id": "battle_abc123",
    // Event-specific data
  },
  "request": {
    "id": "req_987654321",
    "idempotency_key": "unique-key-123"
  }
}

Battle Completed Example

{
  "id": "evt_battle_completed_123",
  "event": "battle.completed",
  "created": "2024-01-15T10:30:00Z",
  "data": {
    "object": "battle",
    "id": "battle_abc123",
    "mode": "quick-battle",
    "difficulty": "medium",
    "problem": {
      "id": "prob_456",
      "title": "Two Sum",
      "difficulty": "medium"
    },
    "participants": [
      {
        "user_id": "user_123",
        "username": "alice_codes",
        "score": 100,
        "submission_time": 847,
        "rank": 1
      },
      {
        "user_id": "user_456",
        "username": "bob_dev",
        "score": 85,
        "submission_time": 1203,
        "rank": 2
      }
    ],
    "winner": "user_123",
    "duration": 1800,
    "started_at": "2024-01-15T10:00:00Z",
    "completed_at": "2024-01-15T10:30:00Z"
  }
}

User Achievement Example

{
  "id": "evt_achievement_789",
  "event": "user.achievement_earned",
  "created": "2024-01-15T10:30:00Z",
  "data": {
    "object": "achievement",
    "user": {
      "id": "user_123",
      "username": "alice_codes",
      "email": "alice@example.com"
    },
    "achievement": {
      "id": "achievement_speedster",
      "name": "Speed Demon",
      "description": "Win 10 battles in under 5 minutes",
      "tier": "silver",
      "points": 50
    },
    "progress": {
      "current": 10,
      "required": 10,
      "completed_at": "2024-01-15T10:30:00Z"
    }
  }
}

Security

HMAC Signature Verification

All webhook requests include an HMAC signature in the X-CoderspaE-Signature header:

// Node.js example
const crypto = require('crypto');

function verifyWebhook(payload, signature, secret) {
  const expectedSignature = crypto
    .createHmac('sha256', secret)
    .update(payload, 'utf8')
    .digest('hex');
    
  const receivedSignature = signature.replace('sha256=', '');
  
  return crypto.timingSafeEqual(
    Buffer.from(expectedSignature, 'hex'),
    Buffer.from(receivedSignature, 'hex')
  );
}

IP Whitelist

CoderspaE webhooks are sent from these IP ranges:

185.199.108.0/22
192.30.252.0/22
140.82.112.0/20
143.55.64.0/20

Delivery & Retries

Delivery Requirements

  • • Endpoint must respond with 2xx status code
  • • Response must be received within 10 seconds
  • • HTTPS required for production webhooks
  • • Valid SSL certificate required

Retry Policy

Failed deliveries are retried with exponential backoff:

AttemptDelayTotal Time
1Immediate0s
230 seconds30s
32 minutes2m 30s
48 minutes10m 30s
530 minutes40m 30s

Testing Webhooks

Local Development

Use ngrok or similar tools to expose local endpoints:

# Install ngrok
npm install -g ngrok

# Expose local server
ngrok http 3000

# Use the https URL for webhook endpoint
# https://abc123.ngrok.io/webhooks/coderspae

Test Endpoint

// Express.js webhook handler
app.post('/webhooks/coderspae', (req, res) => {
  const signature = req.headers['x-coderspae-signature'];
  const payload = JSON.stringify(req.body);
  
  if (!verifyWebhook(payload, signature, process.env.WEBHOOK_SECRET)) {
    return res.status(401).send('Unauthorized');
  }
  
  const event = req.body;
  console.log('Received event:', event.event);
  
  switch (event.event) {
    case 'battle.completed':
      handleBattleCompleted(event.data);
      break;
    case 'user.achievement_earned':
      handleAchievementEarned(event.data);
      break;
    default:
      console.log('Unhandled event:', event.event);
  }
  
  res.status(200).send('OK');
});

Manual Testing

Trigger test webhooks via API:

POST /api/v1/webhooks/test

{
  "webhook_id": "webhook_123",
  "event": "battle.completed",
  "test_data": {
    "battle_id": "test_battle_456"
  }
}

Monitoring & Logs

Delivery Status

GET /api/v1/webhooks/webhook_123/deliveries

{
  "deliveries": [
    {
      "id": "delivery_789",
      "event_id": "evt_123",
      "status": "delivered",
      "attempts": 1,
      "response_code": 200,
      "response_time": 245,
      "created_at": "2024-01-15T10:30:00Z",
      "delivered_at": "2024-01-15T10:30:00Z"
    }
  ]
}

Failed Deliveries

GET /api/v1/webhooks/webhook_123/failed_deliveries

{
  "failed_deliveries": [
    {
      "id": "delivery_456",
      "event_id": "evt_789",
      "status": "failed",
      "attempts": 5,
      "last_response_code": 500,
      "error_message": "Internal Server Error",
      "next_retry": null,
      "created_at": "2024-01-15T09:00:00Z",
      "failed_at": "2024-01-15T09:40:30Z"
    }
  ]
}

Best Practices

Security

  • • Always verify HMAC signatures
  • • Use HTTPS endpoints only
  • • Implement IP whitelisting
  • • Store webhook secrets securely

Reliability

  • • Respond with 2xx status codes for success
  • • Process webhooks idempotently
  • • Handle duplicate events gracefully
  • • Implement proper error logging

Performance

  • • Respond quickly (under 10 seconds)
  • • Process heavy work asynchronously
  • • Use queues for batch processing
  • • Monitor endpoint performance