# Webhooks

Empfangen Sie Zahlungsereignisse direkt auf Ihrem Server.

## Ziel erstellen

POST`/webhooks.php`

Terminal
```
curl "https://circus-pay.com/api/webhooks.php" \
  -H "Authorization: Bearer $CIRCUSPAY_SECRET_KEY" \
  -H "Content-Type: application/json" \
  --data '{
  "url": "https://example.com/webhooks/circuspay",
  "events": [
    "payment.succeeded",
    "payment.failed",
    "payment.refunded"
  ],
  "description": "Boutique principale"
}'
```

JavaScript
```
const response = await fetch("https://circus-pay.com/api/webhooks.php", {
  method: "POST",
  headers: {
    Authorization: `Bearer ${process.env.CIRCUSPAY_SECRET_KEY}`,
    "Content-Type": "application/json"
  },
  body: JSON.stringify({
  "url": "https://example.com/webhooks/circuspay",
  "events": [
    "payment.succeeded",
    "payment.failed",
    "payment.refunded"
  ],
  "description": "Boutique principale"
})
});
const result = await response.json();
if (!response.ok || !result.success) {
  throw new Error(result.error || "API request failed");
}
console.log(result);
```

PHP
```
<?php
$ch = curl_init("https://circus-pay.com/api/webhooks.php");
curl_setopt_array($ch, [
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_TIMEOUT => 20,
  CURLOPT_HTTPHEADER => [
    "Authorization: Bearer " . getenv("CIRCUSPAY_SECRET_KEY"),
    "Content-Type: application/json",
  ],
  CURLOPT_POST => true,
  CURLOPT_POSTFIELDS => '{
  "url": "https://example.com/webhooks/circuspay",
  "events": [
    "payment.succeeded",
    "payment.failed",
    "payment.refunded"
  ],
  "description": "Boutique principale"
}',
]);
$raw = curl_exec($ch);
if ($raw === false) { throw new RuntimeException(curl_error($ch)); }
$status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
$result = json_decode($raw, true, 512, JSON_THROW_ON_ERROR);
if ($status >= 400 || empty($result["success"])) {
  throw new RuntimeException($result["error"] ?? "API request failed");
}
```

Python
```
import os, requests

response = requests.post(
    "https://circus-pay.com/api/webhooks.php",
    headers={"Authorization": "Bearer " + os.environ["CIRCUSPAY_SECRET_KEY"]},
    json={'url': 'https://example.com/webhooks/circuspay', 'events': ['payment.succeeded', 'payment.failed', 'payment.refunded'], 'description': 'Boutique principale'},
    timeout=20,
)
response.raise_for_status()
result = response.json()
if not result.get("success"):
    raise RuntimeError(result.get("error", "API request failed"))
print(result)
```

Speichern Sie das bei der Erstellung erhaltene `webhook.secret` in `CIRCUSPAY_WEBHOOK_SECRET`. Es prüft Signaturen und ist nicht Ihr API-Schlüssel.

## Signatur prüfen

`X-ONIPAY-Signature` enthält den hexadezimalen HMAC-SHA256 des unveränderten HTTP-Bodys, berechnet mit dem Webhook-Geheimnis. Prüfen Sie exakt den empfangenen Body vor erneuter JSON-Kodierung.

PHP · Signaturprüfung
```
<?php
$raw = file_get_contents('php://input');
$received = $_SERVER['HTTP_X_ONIPAY_SIGNATURE'] ?? '';
$secret = getenv('CIRCUSPAY_WEBHOOK_SECRET');
if (!$secret || !preg_match('/^[a-f0-9]{64}$/', $received)) {
    http_response_code(400); exit;
}
$expected = hash_hmac('sha256', $raw, $secret);
if (!hash_equals($expected, $received)) {
    http_response_code(400); exit;
}
$event = json_decode($raw, true);
if (!is_array($event)) { http_response_code(400); exit; }
// Persist the event durably before returning 2xx.
// Deduplicate fulfilment by your order + transaction reference.
// Verify order, amount, currency and final status server-side.
// Return 5xx if durable processing/queuing fails.

```

**Wichtig**

Dieses Beispiel prüft nur die Signatur. Ergänzen Sie dauerhafte Speicherung, Deduplizierung und Bestelllogik, bevor Sie mit 2xx antworten. Das HTTP-Zustellzeitlimit beträgt 10 Sekunden.

## Ereignisse verarbeiten

| Parameter | Beschreibung | 
| --- | --- |

| `payment.succeeded` | Zahlung prüfen und Bestellung genau einmal bestätigen. | 
| `payment.failed` | Fehlgeschlagenen Versuch speichern, ohne die Bestellung zu bestätigen. | 
| `payment.refunded` | Erstattungsstatus synchronisieren. | 
| `webhook.test` | Technischer Test des Ziels. Löst keine Bestellauslieferung aus. | 

Zahlungsereignisse verwenden eine Hülle mit `type`, `created` und `data`. Der Inhalt von `data` hängt vom Ablauf ab. Gehen Sie nicht von einem einheitlichen Schema aus; gleichen Sie Referenzen mit Ihren Transaktionen ab.

## Empfang testen

POST`/webhooks.php?action=test`

Terminal
```
curl "https://circus-pay.com/api/webhooks.php?action=test" \
  -H "Authorization: Bearer $CIRCUSPAY_SECRET_KEY" \
  -H "Content-Type: application/json" \
  --data '{
  "id": 123
}'
```

JavaScript
```
const response = await fetch("https://circus-pay.com/api/webhooks.php?action=test", {
  method: "POST",
  headers: {
    Authorization: `Bearer ${process.env.CIRCUSPAY_SECRET_KEY}`,
    "Content-Type": "application/json"
  },
  body: JSON.stringify({
  "id": 123
})
});
const result = await response.json();
if (!response.ok || !result.success) {
  throw new Error(result.error || "API request failed");
}
console.log(result);
```

PHP
```
<?php
$ch = curl_init("https://circus-pay.com/api/webhooks.php?action=test");
curl_setopt_array($ch, [
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_TIMEOUT => 20,
  CURLOPT_HTTPHEADER => [
    "Authorization: Bearer " . getenv("CIRCUSPAY_SECRET_KEY"),
    "Content-Type: application/json",
  ],
  CURLOPT_POST => true,
  CURLOPT_POSTFIELDS => '{
  "id": 123
}',
]);
$raw = curl_exec($ch);
if ($raw === false) { throw new RuntimeException(curl_error($ch)); }
$status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
$result = json_decode($raw, true, 512, JSON_THROW_ON_ERROR);
if ($status >= 400 || empty($result["success"])) {
  throw new RuntimeException($result["error"] ?? "API request failed");
}
```

Python
```
import os, requests

response = requests.post(
    "https://circus-pay.com/api/webhooks.php?action=test",
    headers={"Authorization": "Bearer " + os.environ["CIRCUSPAY_SECRET_KEY"]},
    json={'id': 123},
    timeout=20,
)
response.raise_for_status()
result = response.json()
if not result.get("success"):
    raise RuntimeError(result.get("error", "API request failed"))
print(result)
```

## Zustellungen prüfen

GET`/webhooks.php?id=123&logs=1`

Terminal
```
curl "https://circus-pay.com/api/webhooks.php?id=123&logs=1" \
  -H "Authorization: Bearer $CIRCUSPAY_SECRET_KEY"
```

JavaScript
```
const response = await fetch("https://circus-pay.com/api/webhooks.php?id=123&logs=1", {
  method: "GET",
  headers: {
    Authorization: `Bearer ${process.env.CIRCUSPAY_SECRET_KEY}`
  }
});
const result = await response.json();
if (!response.ok || !result.success) {
  throw new Error(result.error || "API request failed");
}
console.log(result);
```

PHP
```
<?php
$ch = curl_init("https://circus-pay.com/api/webhooks.php?id=123&logs=1");
curl_setopt_array($ch, [
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_TIMEOUT => 20,
  CURLOPT_HTTPHEADER => [
    "Authorization: Bearer " . getenv("CIRCUSPAY_SECRET_KEY"),
    "Content-Type: application/json",
  ],
]);
$raw = curl_exec($ch);
if ($raw === false) { throw new RuntimeException(curl_error($ch)); }
$status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
$result = json_decode($raw, true, 512, JSON_THROW_ON_ERROR);
if ($status >= 400 || empty($result["success"])) {
  throw new RuntimeException($result["error"] ?? "API request failed");
}
```

Python
```
import os, requests

response = requests.get(
    "https://circus-pay.com/api/webhooks.php?id=123&logs=1",
    headers={"Authorization": "Bearer " + os.environ["CIRCUSPAY_SECRET_KEY"]},
    timeout=20,
)
response.raise_for_status()
result = response.json()
if not result.get("success"):
    raise RuntimeError(result.get("error", "API request failed"))
print(result)
```

Ersetzen Sie 123 durch Ihre Webhook-ID. Die Antwort `logs` enthält die letzten 50 Zustellungen mit HTTP-Code, Dauer und eventuellen Fehlern.
