Webhooks & Security
The DanDanPay Reseller API dispatches webhooks to your server upon key state transitions in the order lifecycle.
1. Webhook Subscription Management
Section titled “1. Webhook Subscription Management”Create Webhook: POST /v1/webhooks
Section titled “Create Webhook: POST /v1/webhooks”Register an endpoint URL on your server for a specific event type:
curl -X POST "https://api.dandanpay.net/v1/webhooks" \ -H "Authorization: Bearer YOUR_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "url": "https://api.myshop.com/webhooks/dandanpay", "event": "order.status_updated" }'Available Event Types (event)
Section titled “Available Event Types (event)”| Event | Description |
|---|---|
order.status_updated |
Order status updated (pending, processing, completed, error, failed) |
order.credentials_requested |
Supplier requested 2FA code (OTP/2FA) or device authorization link |
order.receipt-requested |
Goods delivered, awaiting customer confirmation (confirm-receipt) or dispute (dispute) |
Response 201 Created
Section titled “Response 201 Created”{ "id": "123e4567-e89b-12d3-a456-426614174000", "workspace_id": "019818ab-0000-7c55-9477-5020aebf7000", "event": "order.status_updated", "url": "https://api.myshop.com/webhooks/dandanpay", "secret": "whsec_019b4a2f8c7e9d1a3b5c7e9f...", "is_active": true, "created_at": "2026-09-13T10:00:00.000Z", "updated_at": "2026-09-13T10:00:00.000Z"}List Webhooks: GET /v1/webhooks
Section titled “List Webhooks: GET /v1/webhooks”curl -X GET "https://api.dandanpay.net/v1/webhooks" \ -H "Authorization: Bearer YOUR_API_KEY"Delete Webhook: DELETE /v1/webhooks/{id}
Section titled “Delete Webhook: DELETE /v1/webhooks/{id}”curl -X DELETE "https://api.dandanpay.net/v1/webhooks/123e4567-e89b-12d3-a456-426614174000" \ -H "Authorization: Bearer YOUR_API_KEY"Send Test Webhook: POST /v1/webhooks/{id}/test
Section titled “Send Test Webhook: POST /v1/webhooks/{id}/test”Sends a synthetic test event to your registered URL to verify reachability and signature computation:
curl -X POST "https://api.dandanpay.net/v1/webhooks/123e4567-e89b-12d3-a456-426614174000/test" \ -H "Authorization: Bearer YOUR_API_KEY"2. Inbound Request Headers
Section titled “2. Inbound Request Headers”Every webhook dispatched by DanDanPay contains the following HTTP headers:
POST /webhooks/dandanpay HTTP/1.1Host: api.myshop.comContent-Type: application/jsonX-Event-Type: order.status_updatedX-Event-Id: evt_019c8f00-0000-7000-8000-000000000001X-Timestamp: 1788516000X-Signature: sha256=4f2a7b8e9c0d1e2f3a4b5c6d7e8f9a0b1c2d3e4f5a6b7c8d9e0f1a2b3c4d5e6fX-Retry-Attempt: 0X-Event-Type: Event name (order.status_updated,order.credentials_requested,order.receipt-requested).X-Event-Id: Unique event ID. Crucial for idempotency & deduplication on your server.X-Timestamp: Unix timestamp in seconds when the request was dispatched. Prevents replay attacks.X-Signature: HMAC-SHA256 signature insha256=<hex_hash>format.X-Retry-Attempt: Delivery attempt count (0 is initial attempt, 1+ are retries).
3. Signature Verification (HMAC-SHA256)
Section titled “3. Signature Verification (HMAC-SHA256)”Verification algorithm:
- Capture the raw unparsed request body bytes before any JSON parsing.
- Build the signing string:
${X-Timestamp}.${RawBody}. - Compute the HMAC-SHA256 hash using your webhook
secret. - Compare your computed signature against
X-Signatureusing a constant-time comparison (timingSafeEqual).
import crypto from 'crypto';import express from 'express';
const app = express();
// IMPORTANT: Preserve raw request body bytes for signature calculationapp.use(express.json({ verify: (req: any, _res, buf) => { req.rawBody = buf; }}));
app.post('/webhooks/dandanpay', (req: any, res) => { const secret = process.env.DANDANPAY_WEBHOOK_SECRET!; const signature = req.headers['x-signature'] as string; const timestamp = req.headers['x-timestamp'] as string; const eventId = req.headers['x-event-id'] as string; const eventType = req.headers['x-event-type'] as string;
if (!signature || !timestamp) { return res.status(400).send('Missing signature headers'); }
// 1. Verify request timestamp freshness (prevent replay attacks, max 5 min) const now = Math.floor(Date.now() / 1000); if (Math.abs(now - parseInt(timestamp, 10)) > 300) { return res.status(400).send('Request timestamp expired'); }
// 2. Compute expected HMAC-SHA256 signature const payloadToSign = `${timestamp}.${req.rawBody.toString('utf-8')}`; const computedHash = crypto .createHmac('sha256', secret) .update(payloadToSign) .digest('hex'); const expectedSignature = `sha256=${computedHash}`;
// 3. Constant-time comparison const isValid = crypto.timingSafeEqual( Buffer.from(signature), Buffer.from(expectedSignature) );
if (!isValid) { return res.status(401).send('Invalid signature'); }
// 4. Deduplicate event using eventId // if (await isEventAlreadyProcessed(eventId)) return res.status(200).send('OK');
console.log(`Received event ${eventType}:`, req.body);
// Always return HTTP 200 OK return res.status(200).json({ success: true });});import hmacimport hashlibimport timefrom fastapi import FastAPI, Request, HTTPException, Header
app = FastAPI()WEBHOOK_SECRET = "whsec_your_secret_key"
@app.post("/webhooks/dandanpay")async def handle_webhook( request: Request, x_signature: str = Header(None), x_timestamp: str = Header(None), x_event_id: str = Header(None), x_event_type: str = Header(None)): if not x_signature or not x_timestamp: raise HTTPException(status_code=400, detail="Missing headers")
# 1. Verify timestamp freshness (within 5 minutes) if abs(time.time() - int(x_timestamp)) > 300: raise HTTPException(status_code=400, detail="Timestamp expired")
# 2. Compute signature from raw bytes raw_body = await request.body() data_to_sign = f"{x_timestamp}.".encode("utf-8") + raw_body computed_hash = hmac.new( WEBHOOK_SECRET.encode("utf-8"), data_to_sign, hashlib.sha256 ).hexdigest()
expected_sig = f"sha256={computed_hash}"
# 3. Constant-time comparison if not hmac.compare_digest(x_signature, expected_sig): raise HTTPException(status_code=401, detail="Invalid signature")
payload = await request.json() print(f"Received event {x_event_type}:", payload)
return {"success": True}<?php$secret = getenv('DANDANPAY_WEBHOOK_SECRET');
$signature = $_SERVER['HTTP_X_SIGNATURE'] ?? '';$timestamp = $_SERVER['HTTP_X_TIMESTAMP'] ?? '';$eventId = $_SERVER['HTTP_X_EVENT_ID'] ?? '';
if (empty($signature) || empty($timestamp)) { http_response_code(400); exit('Missing headers');}
// 1. Verify timestamp freshness (within 5 minutes)if (abs(time() - (int)$timestamp) > 300) { http_response_code(400); exit('Timestamp expired');}
// 2. Read raw request body$rawBody = file_get_contents('php://input');$payloadToSign = $timestamp . '.' . $rawBody;
$expectedHash = hash_hmac('sha256', $payloadToSign, $secret);$expectedSignature = 'sha256=' . $expectedHash;
// 3. Constant-time comparisonif (!hash_equals($signature, $expectedSignature)) { http_response_code(401); exit('Invalid signature');}
$data = json_decode($rawBody, true);// Process order update...
http_response_code(200);echo json_encode(['success' => true]);package main
import ( "crypto/hmac" "crypto/sha256" "encoding/hex" "fmt" "io" "math" "net/http" "os" "strconv" "time")
func webhookHandler(w http.ResponseWriter, r *http.Request) { secret := os.Getenv("DANDANPAY_WEBHOOK_SECRET") sigHeader := r.Header.Get("X-Signature") tsHeader := r.Header.Get("X-Timestamp")
ts, err := strconv.ParseInt(tsHeader, 10, 64) if err != nil || math.Abs(float64(time.Now().Unix()-ts)) > 300 { http.Error(w, "Invalid timestamp", http.StatusBadRequest) return }
body, err := io.ReadAll(r.Body) if err != nil { http.Error(w, "Cannot read body", http.StatusBadRequest) return }
mac := hmac.New(sha256.New, []byte(secret)) mac.Write([]byte(fmt.Sprintf("%s.%s", tsHeader, string(body)))) expected := "sha256=" + hex.EncodeToString(mac.Sum(nil))
if !hmac.Equal([]byte(sigHeader), []byte(expected)) { http.Error(w, "Invalid signature", http.StatusUnauthorized) return }
w.WriteHeader(http.StatusOK) w.Write([]byte(`{"success":true}`))}4. Event Payload Structures
Section titled “4. Event Payload Structures”order.status_updated
Section titled “order.status_updated”The payload contains an OrderResponseDto object:
{ "id": "019818bc-1285-7c55-9477-5020aebf7782", "offer_id": "01981de8-7cb4-7f54-8672-57eb8ee8b47e", "status": "completed", "price": "1.0958", "currency": "USD", "reason": null, "delivered_at": "2026-09-13T10:00:00.000Z", "client_confirmed_at": "2026-09-13T10:02:00.000Z", "disputed_at": null, "auto_confirm_at": null}order.credentials_requested
Section titled “order.credentials_requested”Provider request for OTP/2FA or login authorization:
{ "event_id": "evt_019c8f00-0000-7000-8000-000000000001", "event": "order.credentials_requested", "version": 1, "created_at": "2026-09-13T10:05:00.000Z", "data": { "order_id": "019818bc-1285-7c55-9477-5020aebf7782", "type": "otp", "is_repeat": false, "requested_at": "2026-09-13T10:05:00.000Z", "expires_in": 300, "expires_at": "2026-09-13T10:10:00.000Z" }}order.receipt-requested
Section titled “order.receipt-requested”Goods delivered and awaiting buyer confirmation:
{ "event_id": "evt_019c8f00-0000-7000-8000-000000000002", "event": "order.receipt-requested", "version": 1, "created_at": "2026-09-13T10:15:00.000Z", "data": { "order_id": "019818bc-1285-7c55-9477-5020aebf7782", "delivered_at": "2026-09-13T10:15:00.000Z", "auto_confirm_at": "2026-09-14T10:15:00.000Z", "screenshots": [ "https://cdn.dandanpay.net/proofs/screenshot1.jpg" ] }}