# Belohnungen für Stimmen {#vote-rewards}

Belohnungen für Stimmen nutzen die Webhook-Ereignisse `server.vote` und `project.vote`: Der Handler empfängt das Ereignis, ruft Stimmdaten über die API ab und gibt die Belohnung nur einmal aus.

Richten Sie zuerst den [Projekt-Webhook](https://gamemonitoring.de/developers/docs/webhook#connect) und die Prüfung von [signature](https://gamemonitoring.de/developers/docs/webhook#signature) ein. Stimmdaten werden über [GET /votes/:vote_id](https://gamemonitoring.de/developers/docs/api/votes/:vote_id/__GET) abgefragt.

## So funktioniert der Ablauf {#flow}

1. Nehmen Sie das Webhook-Ereignis an und prüfen Sie [signature](https://gamemonitoring.de/developers/docs/webhook#signature). Wenn [is_test](https://gamemonitoring.de/developers/docs/webhook#tests-resend) `true` ist, geben Sie `204` zurück, ohne die Stimme abzurufen und ohne eine Belohnung auszugeben.
2. Stellen Sie sicher, dass `event_type` `server.vote` oder `project.vote` ist.
3. Verwenden Sie `event_id` als ID der Stimme.
4. Rufen Sie Stimmdaten über [GET /votes/:vote_id](https://gamemonitoring.de/developers/docs/api/votes/:vote_id/__GET) ab und finden Sie den Spieler in Ihrem System.
5. Wenden Sie in einer Transaktion den [Schutz vor erneuter Verarbeitung](https://gamemonitoring.de/developers/docs/webhook#deduplication) über `event_type` + `event_id` an und geben Sie die Belohnung nur für ein neues Ereignis aus.
6. Wenn die Belohnung nicht sicher ausgegeben werden kann, geben Sie eine Fehlerantwort zurück. Nach Behebung der Ursache [wiederholen Sie die Zustellung](https://gamemonitoring.de/developers/docs/webhook#tests-resend) aus der Oberfläche.

## Belohnungsbeispiel {#reward-example}

Angenommen, Spieler `PlayerName` hat für den Server mit ID `1` gestimmt, und Ihr System soll ihm `100` Münzen gutschreiben.

1. GAMEMONITORING sendet einen Webhook mit `event_type: server.vote` und `event_id: 9824cabb-2203-437e-9b6c-aba43dde3e4b`.
2. Der Handler prüft [signature](https://gamemonitoring.de/developers/docs/webhook#signature). Bei falscher Signatur gibt er `401` zurück und stoppt.
3. Der Handler ruft `GET /votes/9824cabb-2203-437e-9b6c-aba43dde3e4b` auf, erhält Nickname, Server und Benutzer und findet das lokale Konto.
4. In einer Transaktion speichert der Handler `event_type` + `event_id` für den [Schutz vor erneuter Verarbeitung](https://gamemonitoring.de/developers/docs/webhook#deduplication).
5. Für ein neues Ereignis schreibt der Handler `100` Münzen in derselben Transaktion gut.
6. Bei erneuter Zustellung findet der Handler das bereits gespeicherte Ereignis, gibt die Belohnung nicht erneut aus und gibt `204` zurück.

Der gleiche Ablauf eignet sich auch für Gegenstände, Rollen, VIP-Zeit, Promo-Codes oder Aufgaben in einer internen Queue.

## Stimmenereignis {#vote-event}

Für eine Serverstimme sendet GAMEMONITORING `server.vote`, für eine Projektstimme `project.vote`. Der Ereignis-Body enthält nur Zustelldaten: `event_type`, `event_id`, `is_test` und `signature`. Vollständige Stimmdaten müssen separat abgefragt werden.

**Ereignisbeispiel**

```json
{
  "event_id": "9824cabb-2203-437e-9b6c-aba43dde3e4b",
  "event_type": "server.vote",
  "is_test": false,
  "signature": "ae83b8aba88a3a9ab3b97b1f6d65664da5628a9cb64d56d5132807bca5472e4f"
}
```

In diesem Ereignis ist `event_id` die ID der Stimme. Verwenden Sie den Webhook-Body nicht als Quelle für Nickname, Server oder Benutzer: Diese Daten kommen aus der API.

## Stimmdaten abrufen {#fetch-vote}

Verwenden Sie `event_id` als `vote_id` und rufen Sie die Stimmdaten über [GET /votes/:vote_id](https://gamemonitoring.de/developers/docs/api/votes/:vote_id/__GET) ab:

**Anfrage der Stimmdaten**

```bash
curl -sS "https://api.gamemonitoring.de/votes/9824cabb-2203-437e-9b6c-aba43dde3e4b"
```

Für die Belohnung benötigen Sie normalerweise `response.nickname`, `response.server` und öffentliche Daten aus `response.user`. Wenn die Belohnung von einem bestimmten Server abhängt, prüfen Sie immer `response.server.id`.

So verwenden Sie die Felder: `response.nickname` hilft, das Spielerkonto in Ihrer Datenbank zu finden, `response.server.id` wählt die Belohnungsregel für den Server aus, und `response.user.id` kann im Belohnungsprotokoll als GAMEMONITORING-Benutzer-ID gespeichert werden.

Wenn die API vorübergehend nicht verfügbar ist oder eine unerwartete Antwort liefert, geben Sie keine Belohnung ohne Prüfung aus. Geben Sie einen Fehlercode zurück, beheben Sie die Ursache und [wiederholen Sie die Zustellung](https://gamemonitoring.de/developers/docs/webhook#tests-resend) aus der Oberfläche.

## Schritt 3. Handler für Stimm-Belohnungen {#complete-example}

Das Beispiel setzt den Basis-Handler fort: Es prüft die Signatur, ruft Stimmdaten ab, schützt das Ereignis vor erneuter Verarbeitung und schreibt die Belohnung in einer Transaktion gut. Ersetzen Sie den Namen der Benutzertabelle, das Kontostandfeld und die Regel zur Spielersuche durch die Struktur Ihres Systems.

Vor dem Start des Beispiels richten Sie den [Projekt-Webhook](https://gamemonitoring.de/developers/docs/webhook#connect) ein, prüfen [GET /votes/:vote_id](https://gamemonitoring.de/developers/docs/api/votes/:vote_id/__GET) und ersetzen die SQL-Updates für Benutzer durch Ihr Kontomodell.

### PHP

```php
<?php
// Replace this token with the signing token from your GAMEMONITORING webhook settings.
$secret = 'paste-webhook-token-here';

// Add the GAMEMONITORING API URL and reward settings for vote events.
$apiUrl = 'https://api.gamemonitoring.de';
$rewardAmount = '1.00';

// Read and decode the JSON body sent by GAMEMONITORING.
$event = json_decode(file_get_contents('php://input'), true) ?: [];

// Test deliveries are signed too. Normalize the boolean value to the lowercase
// string used by GAMEMONITORING when the signature is calculated.
$isTest = ($event['is_test'] ?? false) === true;
$signingData = array_replace($event, ['is_test' => $isTest ? 'true' : 'false']);

// Build the exact signing string: all body fields except signature,
// sorted by key and joined as key=value pairs with &.
$fields = array_values(array_filter(array_keys($event), fn($field) => $field !== 'signature'));
sort($fields, SORT_STRING);

// Calculate HMAC-SHA256 with the webhook token from your settings.
$signing = implode('&', array_map(fn($field) => $field . '=' . (string) ($signingData[$field] ?? ''), $fields));
$expected = hash_hmac('sha256', $signing, $secret);
$actual = (string) ($event['signature'] ?? '');

// Reject the request before doing any work when the signature is invalid.
if (!hash_equals($expected, $actual)) {
    http_response_code(401);
    exit;
}

// Test deliveries must not change balance, inventory, roles, or production data.
if ($isTest) {
    http_response_code(204);
    exit;
}

// Real deliveries must include an event type and a stable event id.
$eventType = (string) ($event['event_type'] ?? '');
$eventId = (string) ($event['event_id'] ?? '');

if ($eventType === '' || $eventId === '') {
    http_response_code(400);
    exit;
}

// This reward handler processes server and project vote events.
if (!in_array($eventType, ['server.vote', 'project.vote'], true)) {
    http_response_code(204);
    exit;
}

// At this point the webhook is trusted. Load vote data before opening a database transaction.
$pdo = null;

try {
    // Load full vote data by event_id. Nickname, entity, and user data are not
    // in the webhook body. Return 500 if the API cannot confirm the vote.
    $voteUrl = $apiUrl . '/votes/' . rawurlencode($eventId);
    $voteContext = stream_context_create(['http' => ['timeout' => 5]]);
    $voteBody = @file_get_contents($voteUrl, false, $voteContext);

    if ($voteBody === false) {
        throw new RuntimeException('Vote API request failed');
    }

    $voteResponse = json_decode($voteBody, true) ?: [];
    $vote = $voteResponse['response'] ?? null;

    // Do not issue a reward when the vote response is missing a concrete nickname.
    if (!is_array($vote) || !isset($vote['nickname']) || !is_string($vote['nickname'])) {
        throw new RuntimeException('Vote API response does not include nickname');
    }

    // Verify that the API entity matches the event before changing the account.
    $expectedEntityType = $eventType === 'project.vote' ? 'project' : 'server';
    if (($vote['entity_type'] ?? '') !== $expectedEntityType) {
        throw new RuntimeException('Vote entity type does not match event type');
    }

    // Use vote nickname to update the local account. The entity id is available in
    // vote.entity_id and in either vote.server.id or vote.project.id.
    $nickname = trim($vote['nickname']);

    if ($nickname === '') {
        throw new RuntimeException('Vote nickname is empty');
    }

    // Add your local database connection for deduplication and event-specific work.
    $pdo = new PDO('mysql:host=127.0.0.1;dbname=game;charset=utf8mb4', 'game', 'password', [
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
    ]);

    // Keep deduplication and the real state change in one transaction.
    // If any step fails, return 500 so the delivery can be retried.
    $pdo->beginTransaction();

    // Store the event once. This requires the table to have a unique key on
    // (event_type, event_id). Duplicate deliveries affect zero rows.
    $deduplicate = $pdo->prepare('INSERT IGNORE INTO gamemonitoring_webhooks (event_type, event_id) VALUES (?, ?)');
    $deduplicate->execute([$eventType, $eventId]);

    // The event was already processed earlier. Return success without changing
    // state again, because duplicate delivery is expected.
    if ($deduplicate->rowCount() === 0) {
        $pdo->commit();
        http_response_code(204);
        exit;
    }

    // Add event-specific database changes here. Keep them after the
    // deduplication insert and inside this same transaction.
    $balance = $pdo->prepare('UPDATE users SET balance = balance + ? WHERE nickname = ?');
    $balance->execute([$rewardAmount, $nickname]);

    // Commit only after deduplication and event-specific work both succeed.
    $pdo->commit();

    // Log only newly processed real events after the transaction succeeds.
    syslog(LOG_INFO, 'Accepted webhook event ' . $eventType . ' #' . $eventId);

    http_response_code(204);
} catch (Throwable $error) {
    // Roll back partial database work so the event can be retried safely.
    if ($pdo instanceof PDO && $pdo->inTransaction()) {
        $pdo->rollBack();
    }

    // 500 keeps the delivery failed instead of marking unfinished work as done.
    http_response_code(500);
}
```

### JavaScript

```javascript
const crypto = require('node:crypto')
const express = require('express')
const mysql = require('mysql2/promise')

const app = express()
// Replace this token with the signing token from your GAMEMONITORING webhook settings.
const secret = 'paste-webhook-token-here'

// Add the GAMEMONITORING API URL and reward settings for vote events.
const apiUrl = 'https://api.gamemonitoring.de'
const rewardAmount = '1.00'

// Add your local database connection for deduplication and event-specific work.
const db = mysql.createPool({
  database: 'game',
  host: '127.0.0.1',
  password: 'password',
  user: 'game',
})

// GAMEMONITORING sends JSON with Content-Type: application/json.
app.use(express.json())

function isValidSignature(event) {
  // Build the exact signing string: all body fields except signature,
  // sorted by key and joined as key=value pairs with &.
  const fields = Object.keys(event).filter((field) => field !== 'signature').sort()
  const signing = fields.map((field) => field + '=' + String(event[field] ?? '')).join('&')

  // Calculate HMAC-SHA256 with the webhook token from your settings.
  const expected = crypto.createHmac('sha256', secret).update(signing).digest('hex')
  const actual = String(event.signature || '')

  // timingSafeEqual requires buffers with the same length.
  const expectedBuffer = Buffer.from(expected)
  const actualBuffer = Buffer.from(actual)

  return expectedBuffer.length === actualBuffer.length && crypto.timingSafeEqual(expectedBuffer, actualBuffer)
}

app.post('/gamemonitoring-webhook', async (req, res) => {
  // Read the webhook payload parsed by express.json().
  const event = req.body || {}

  // Reject the request before doing any work when the signature is invalid.
  if (!isValidSignature(event)) {
    return res.sendStatus(401)
  }

  // Test deliveries must not change balance, inventory, roles, or production data.
  if (event.is_test === true) {
    return res.sendStatus(204)
  }

  // Real deliveries must include an event type and a stable event id.
  const eventType = String(event.event_type || '')
  const eventId = String(event.event_id || '')

  if (!eventType || !eventId) {
    return res.sendStatus(400)
  }

  // This reward handler processes server and project vote events.
  if (!['server.vote', 'project.vote'].includes(eventType)) {
    return res.sendStatus(204)
  }

  // At this point the webhook is trusted. Load vote data before opening a database transaction.
  let connection

  try {
    // Load full vote data by event_id. Nickname, entity, and user data are not
    // in the webhook body. Return 500 if the API cannot confirm the vote.
    const voteUrl = apiUrl + '/votes/' + encodeURIComponent(eventId)
    const voteResponse = await fetch(voteUrl, { signal: AbortSignal.timeout(5000) })

    if (!voteResponse.ok) {
      throw new Error('Vote API request failed')
    }

    const voteBody = await voteResponse.json()
    const vote = voteBody.response

    // Do not issue a reward when the vote response is missing a concrete nickname.
    if (!vote || typeof vote.nickname !== 'string') {
      throw new Error('Vote API response does not include nickname')
    }

    // Verify that the API entity matches the event before changing the account.
    const expectedEntityType = eventType === 'project.vote' ? 'project' : 'server'
    if (vote.entity_type !== expectedEntityType) {
      throw new Error('Vote entity type does not match event type')
    }

    // Use vote nickname to update the local account. The entity id is available in
    // vote.entity_id and in either vote.server.id or vote.project.id.
    const nickname = vote.nickname.trim()

    if (!nickname) {
      throw new Error('Vote nickname is empty')
    }

    connection = await db.getConnection()

    // Keep deduplication and the real state change in one transaction.
    // If any step fails, return 500 so the delivery can be retried.
    await connection.beginTransaction()

    // Store the event once. This requires the table to have a unique key on
    // (event_type, event_id). Duplicate deliveries affect zero rows.
    const [deduplicate] = await connection.execute(
      'INSERT IGNORE INTO gamemonitoring_webhooks (event_type, event_id) VALUES (?, ?)',
      [eventType, eventId],
    )

    // The event was already processed earlier. Return success without changing
    // state again, because duplicate delivery is expected.
    if (deduplicate.affectedRows === 0) {
      await connection.commit()
      return res.sendStatus(204)
    }

    // Add event-specific database changes here. Keep them after the
    // deduplication insert and inside this same transaction.
    await connection.execute('UPDATE users SET balance = balance + ? WHERE nickname = ?', [rewardAmount, nickname])

    // Commit only after deduplication and event-specific work both succeed.
    await connection.commit()

    // Log only newly processed real events after the transaction succeeds.
    console.log('Accepted webhook event ' + eventType + ' #' + eventId)

    return res.sendStatus(204)
  } catch (error) {
    // Roll back partial database work so the event can be retried safely.
    if (connection) {
      await connection.rollback()
    }

    // 500 keeps the delivery failed instead of marking unfinished work as done.
    return res.sendStatus(500)
  } finally {
    // Return the connection to the pool.
    if (connection) {
      connection.release()
    }
  }
})

app.listen(3000)
```

### Python

```python
import hashlib
import hmac

import pymysql
import requests
from flask import Flask, abort, request

app = Flask(__name__)
# Replace this token with the signing token from your GAMEMONITORING webhook settings.
secret = b'paste-webhook-token-here'

# Add the GAMEMONITORING API URL and reward settings for vote events.
api_url = 'https://api.gamemonitoring.de'
reward_amount = '1.00'

# Add your local database connection for deduplication and event-specific work.
db_config = {
    'database': 'game',
    'host': '127.0.0.1',
    'password': 'password',
    'user': 'game',
}

def stringify(value):
    # GAMEMONITORING signs booleans as lowercase true/false strings.
    if isinstance(value, bool):
        return 'true' if value else 'false'

    return '' if value is None else str(value)

def is_valid_signature(event):
    # Build the exact signing string: all body fields except signature,
    # sorted by key and joined as key=value pairs with &.
    fields = sorted(field for field in event.keys() if field != 'signature')
    signing = '&'.join(f'{field}={stringify(event.get(field))}' for field in fields)

    # Calculate HMAC-SHA256 with the webhook token from your settings.
    expected = hmac.new(secret, signing.encode(), hashlib.sha256).hexdigest()
    actual = str(event.get('signature') or '')

    return hmac.compare_digest(expected, actual)

@app.post('/gamemonitoring-webhook')
def gamemonitoring_webhook():
    # Read and decode the JSON body sent by GAMEMONITORING.
    event = request.get_json(silent=True) or {}

    # Reject the request before doing any work when the signature is invalid.
    if not is_valid_signature(event):
        abort(401)

    # Test deliveries must not change balance, inventory, roles, or production data.
    if event.get('is_test') is True:
        return '', 204

    # Real deliveries must include an event type and a stable event id.
    event_type = str(event.get('event_type') or '')
    event_id = str(event.get('event_id') or '')

    if not event_type or not event_id:
        abort(400)

    # This reward handler processes server and project vote events.
    if event_type not in ('server.vote', 'project.vote'):
        return '', 204

    # At this point the webhook is trusted. Load vote data before opening a database transaction.
    connection = None

    try:
        # Load full vote data by event_id. Nickname, entity, and user data
        # are not in the webhook body. Return 500 if the API cannot confirm the vote.
        vote_url = f"{api_url}/votes/{event_id}"
        response = requests.get(vote_url, timeout=5)

        if not response.ok:
            raise RuntimeError('Vote API request failed')

        vote = response.json().get('response')

        # Do not issue a reward when the vote response is missing a concrete nickname.
        if not isinstance(vote, dict) or not isinstance(vote.get('nickname'), str):
            raise RuntimeError('Vote API response does not include nickname')

        # Verify that the API entity matches the event before changing the account.
        expected_entity_type = 'project' if event_type == 'project.vote' else 'server'
        if vote.get('entity_type') != expected_entity_type:
            raise RuntimeError('Vote entity type does not match event type')

        # Use vote nickname to update the local account. The entity id is available in
        # vote.entity_id and in either vote.server.id or vote.project.id.
        nickname = vote['nickname'].strip()

        if not nickname:
            raise RuntimeError('Vote nickname is empty')

        connection = pymysql.connect(**db_config)
        connection.begin()

        # Keep deduplication and the real state change in one transaction.
        # If any step fails, return 500 so the delivery can be retried.
        with connection.cursor() as cursor:
            # Store the event once. This requires the table to have a unique key
            # on (event_type, event_id). Duplicate deliveries affect zero rows.
            cursor.execute(
                'INSERT IGNORE INTO gamemonitoring_webhooks (event_type, event_id) VALUES (%s, %s)',
                (event_type, event_id),
            )

            # The event was already processed earlier. Return success without
            # changing state again, because duplicate delivery is expected.
            if cursor.rowcount == 0:
                connection.commit()
                return '', 204

            # Add event-specific database changes here. Keep them after the
            # deduplication insert and inside this same transaction.
            cursor.execute('UPDATE users SET balance = balance + %s WHERE nickname = %s', (reward_amount, nickname))

        # Commit only after deduplication and event-specific work both succeed.
        connection.commit()

        # Log only newly processed real events after the transaction succeeds.
        app.logger.info('Accepted webhook event %s #%s', event_type, event_id)

        return '', 204
    except Exception:
        # Roll back partial database work so the event can be retried safely.
        if connection:
            connection.rollback()

        # 500 keeps the delivery failed instead of marking unfinished work as done.
        abort(500)
    finally:
        # Close the database connection.
        if connection:
            connection.close()
```
