# A webhook receiver

Receive webhooks: every delivery is checked (its signature and its time) before it is trusted.

The whole program, in each language. Set `PHOENIXPERPS_WEBHOOK_SECRET` to your endpoint's signing secret (`ppwhsec_...`) and run it. Then point a webhook endpoint (dashboard, Developers, Webhooks) at https://<this machine>/webhooks (port 8080 here).

```typescript
import { createServer } from 'node:http';
import { WebhookVerificationError, Webhooks } from '@phoenixperps/sdk';

const secret = process.env.PHOENIXPERPS_WEBHOOK_SECRET;
if (!secret) throw new Error("Set PHOENIXPERPS_WEBHOOK_SECRET to the endpoint's signing secret.");

createServer((req, res) => {
  if (req.method !== 'POST' || req.url !== '/webhooks') {
    res.writeHead(404).end();
    return;
  }
  const chunks: Buffer[] = [];
  req.on('data', (c: Buffer) => chunks.push(c));
  req.on('end', () => {
    try {
      const event = Webhooks.verify(Buffer.concat(chunks), req.headers, secret); // the body exactly as received
      if (event.type === 'webhook.ping') console.log(`a test delivery (${event.environment})`);
      else console.log(`${event.type} on ${event.account_id}: ${JSON.stringify(event.data)}`);
      res.writeHead(200).end();
    } catch (err) {
      if (!(err instanceof WebhookVerificationError)) throw err;
      console.log(`refused a delivery: ${err.code}`);
      res.writeHead(400).end();
    }
  });
}).listen(8080, () => console.log('listening on :8080/webhooks'));
```

```python
import json
import os
from http.server import BaseHTTPRequestHandler, HTTPServer

from phoenixperps import WebhookVerificationError, Webhooks

SECRET = os.environ.get("PHOENIXPERPS_WEBHOOK_SECRET") or ""
if not SECRET:
    raise SystemExit("Set PHOENIXPERPS_WEBHOOK_SECRET to the endpoint's signing secret.")


class Receiver(BaseHTTPRequestHandler):
    def do_POST(self) -> None:
        if self.path != "/webhooks":
            self.send_response(404)
            self.end_headers()
            return
        raw = self.rfile.read(int(self.headers.get("Content-Length", 0)))
        try:
            event = Webhooks.verify(raw, dict(self.headers), SECRET)  # the body exactly as received
        except WebhookVerificationError as err:
            print(f"refused a delivery: {err.code}")
            self.send_response(400)
            self.end_headers()
            return
        test = " (a test)" if event.get("test") else ""  # webhook.ping (no account), or a delivery resent as a test
        print(f'{event["type"]}{test} on {event.get("account_id") or "-"}: {json.dumps(event["data"])}')
        self.send_response(200)
        self.end_headers()


print("listening on :8080/webhooks")
HTTPServer(("", 8080), Receiver).serve_forever()
```

```go
package main

import (
	"encoding/json"
	"errors"
	"fmt"
	"io"
	"log"
	"net/http"
	"os"
	"time"

	phoenixperps "github.com/phoenixperps/sdk/go"
)

func main() {
	secret := os.Getenv("PHOENIXPERPS_WEBHOOK_SECRET")
	if secret == "" {
		log.Fatal("Set PHOENIXPERPS_WEBHOOK_SECRET to the endpoint's signing secret.")
	}
	http.HandleFunc("POST /webhooks", func(w http.ResponseWriter, r *http.Request) {
		raw, err := io.ReadAll(io.LimitReader(r.Body, 1<<20))
		if err != nil {
			w.WriteHeader(http.StatusBadRequest)
			return
		}
		event, err := phoenixperps.VerifyWebhook(raw, r.Header, []string{secret}, 5*time.Minute) // the body exactly as received
		var bad *phoenixperps.Error
		if errors.Is(err, phoenixperps.ErrWebhookVerification) && errors.As(err, &bad) {
			fmt.Printf("refused a delivery: %s\n", bad.Code) // missing_headers, stale, bad_signature or bad_body
			w.WriteHeader(http.StatusBadRequest)
			return
		}
		if err != nil {
			w.WriteHeader(http.StatusInternalServerError)
			return
		}
		account := "no account" // a webhook.ping (the Test button) names none
		if event.AccountID != nil {
			account = *event.AccountID
		}
		data, _ := json.Marshal(event.Data)
		fmt.Printf("%s on %s (%s): %s\n", event.Type, account, event.Environment, data)
		w.WriteHeader(http.StatusOK)
	})
	fmt.Println("listening on :8080/webhooks")
	log.Fatal(http.ListenAndServe(":8080", nil))
}
```

```csharp
#:package PhoenixPerps.Sdk@1.0.0
using System.Net;
using PhoenixPerps;

var secret = Environment.GetEnvironmentVariable("PHOENIXPERPS_WEBHOOK_SECRET")
    ?? throw new InvalidOperationException("Set PHOENIXPERPS_WEBHOOK_SECRET to the endpoint's signing secret.");

using var listener = new HttpListener();
listener.Prefixes.Add("http://localhost:8080/webhooks/");
listener.Start();
Console.WriteLine("listening on localhost:8080/webhooks");
while (true)
{
    var ctx = await listener.GetContextAsync();
    if (ctx.Request.HttpMethod != "POST")
    {
        ctx.Response.StatusCode = 404;
        ctx.Response.Close();
        continue;
    }
    using var reader = new StreamReader(ctx.Request.InputStream, ctx.Request.ContentEncoding);
    var raw = await reader.ReadToEndAsync(); // the body exactly as received
    var headers = ctx.Request.Headers.AllKeys.Where(k => k is not null).ToDictionary(k => k!.ToLowerInvariant(), k => ctx.Request.Headers[k]!);
    try
    {
        var e = Webhooks.Verify(raw, headers, secret); // the event, with its environment and test flag (webhook.ping is one)
        Console.WriteLine($"{e.Type}{(e.Test == true ? " (test)" : "")} on {e.AccountId ?? "-"} ({e.Environment}): {string.Join(" ", e.Data.Select(kv => $"{kv.Key}={kv.Value.GetRawText()}"))}");
        ctx.Response.StatusCode = 200;
    }
    catch (WebhookVerificationException err)
    {
        Console.WriteLine($"refused a delivery: {err.Code}");
        ctx.Response.StatusCode = 400;
    }
    ctx.Response.Close();
}
```

```java
import com.phoenixperpsfunding.sdk.Webhooks;
import com.phoenixperpsfunding.sdk.gen.WebhookPayload;
import com.sun.net.httpserver.HttpServer;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

final class Example11 {
    public static void main(String[] args) throws IOException {
        String secret = System.getenv("PHOENIXPERPS_WEBHOOK_SECRET");
        if (secret == null || secret.isEmpty()) throw new IllegalStateException("Set PHOENIXPERPS_WEBHOOK_SECRET to the endpoint's signing secret.");

        HttpServer server = HttpServer.create(new InetSocketAddress(8080), 0);
        server.createContext("/webhooks", exchange -> {
            int status;
            if (!"POST".equals(exchange.getRequestMethod())) {
                status = 404;
            } else {
                String raw = new String(exchange.getRequestBody().readAllBytes(), StandardCharsets.UTF_8); // the body exactly as received
                Map<String, String> headers = new HashMap<>();
                exchange.getRequestHeaders().forEach((k, v) -> headers.put(k.toLowerCase(Locale.ROOT), v.get(0)));
                try {
                    WebhookPayload e = Webhooks.verify(raw, headers, secret); // webhook.ping (test true) included
                    System.out.printf("%s%s on %s: %s%n", e.type(), Boolean.TRUE.equals(e.test()) ? " (a test)" : "", e.accountId(), e.data());
                    status = 200;
                } catch (Webhooks.VerificationException err) {
                    System.out.printf("refused a delivery: %s%n", err.code());
                    status = 400;
                }
            }
            exchange.sendResponseHeaders(status, -1);
            exchange.close();
        });
        server.start();
        System.out.println("listening on :8080/webhooks");
    }
}
```

```rust
use std::io::{BufRead, BufReader, Read, Write};
use std::net::TcpListener;

use phoenixperps::verify_webhook;

fn main() -> std::io::Result<()> {
    let secret = std::env::var("PHOENIXPERPS_WEBHOOK_SECRET").expect("Set PHOENIXPERPS_WEBHOOK_SECRET to the endpoint's signing secret.");
    let listener = TcpListener::bind("0.0.0.0:8080")?;
    println!("listening on :8080/webhooks");
    for stream in listener.incoming() {
        let mut stream = stream?;
        let mut reader = BufReader::new(stream.try_clone()?);
        let mut request_line = String::new();
        reader.read_line(&mut request_line)?;
        let mut headers: Vec<(String, String)> = Vec::new();
        loop {
            let mut line = String::new();
            reader.read_line(&mut line)?;
            let line = line.trim_end();
            if line.is_empty() {
                break;
            }
            if let Some((k, v)) = line.split_once(':') {
                headers.push((k.trim().to_ascii_lowercase(), v.trim().to_string()));
            }
        }
        let length = headers.iter().find(|(k, _)| k == "content-length").and_then(|(_, v)| v.parse().ok()).unwrap_or(0usize);
        let mut body = vec![0; length.min(1 << 20)];
        reader.read_exact(&mut body)?;
        let status = if !request_line.starts_with("POST /webhooks ") {
            "404 Not Found"
        } else {
            match verify_webhook(&String::from_utf8_lossy(&body), headers, &[secret.as_str()], None, None) {
                Ok(event) => {
                    // webhook.ping (a test) names no account
                    println!("{} on {}: {:?}", event.r#type, event.account_id.as_deref().unwrap_or("-"), event.data);
                    "200 OK"
                }
                Err(err) => {
                    println!("refused a delivery: {}", err.code);
                    "400 Bad Request"
                }
            }
        };
        write!(stream, "HTTP/1.1 {status}\r\ncontent-length: 0\r\nconnection: close\r\n\r\n")?;
    }
    Ok(())
}
```

```php
<?php
require 'vendor/autoload.php';

use PhoenixPerps\WebhookVerificationException;
use PhoenixPerps\Webhooks;

$secret = getenv('PHOENIXPERPS_WEBHOOK_SECRET');
if (!$secret) {
    http_response_code(500);
    error_log("Set PHOENIXPERPS_WEBHOOK_SECRET to the endpoint's signing secret.");
    exit;
}
if ($_SERVER['REQUEST_METHOD'] !== 'POST' || parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH) !== '/webhooks') {
    http_response_code(404);
    exit;
}

$raw = file_get_contents('php://input'); // the body exactly as received
$headers = array_change_key_case(getallheaders(), CASE_LOWER);
try {
    $event = Webhooks::verify($raw, $headers, $secret); // the WebhookPayload: the event, its environment, test
    // a webhook.ping (the Test button) names no account
    error_log(sprintf('%s on %s (%s): %s', $event->type, $event->accountId ?? 'no account', $event->environment, json_encode($event->data)));
    http_response_code(200);
} catch (WebhookVerificationException $err) {
    error_log("refused a delivery: {$err->errorCode}"); // missing_headers, stale, bad_signature or bad_body
    http_response_code(400);
}
```
