# Verify WordPress.com webhooks

WordPress.com doesn't sign its webhooks, so there's no signature to check and no secret to find: its webhook form takes only an action, fields and a URL. Your endpoint can't prove that a delivery came from WordPress.com. The code below does what you can do instead, which is to put a long random token in the URL and compare it on every request. Re-fetch anything important from the REST API.

These pages cover the built-in webhooks on WordPress.com sites. They don't apply to plugin-enabled sites or to self-hosted WordPress, which needs a plugin such as [WP Webhooks](https://wordpress.org/plugins/wp-webhooks/). [WooCommerce](/webhooks/woocommerce) has its own signed webhooks.

Agent skill: `npx skills add hookdeck/webhook-skills --skill wordpress-com-webhooks` ([details](https://hookdeck.com/webhooks/wordpress-com/skill))

> Independent reference generated from hookdeck/webhook-registry (commit a24c8d9, 19 Nov 2026). [WordPress.com's official docs](https://wordpress.com/support/webhooks/).

[Overview](https://hookdeck.com/webhooks/wordpress-com) · [Webhook events (3)](https://hookdeck.com/webhooks/wordpress-com/events) · [MCP events](https://hookdeck.com/webhooks/wordpress-com/mcp-events) · [Verify signatures](https://hookdeck.com/webhooks/wordpress-com/verify) · [Production guide](https://hookdeck.com/webhooks/wordpress-com/guide-duplicates-retries-timeouts) · [Agent skill](https://hookdeck.com/webhooks/wordpress-com/skill)

## The facts

| Fact | Value | Source |
|---|---|---|
| Signature header | `None (unsigned)` | [WordPress.com docs](https://wordpress.com/support/webhooks/) |
| What to build | `Nothing to verify: protect the endpoint yourself` | [WordPress.com docs](https://wordpress.com/support/webhooks/) |
| Key | `none` | [WordPress.com docs](https://wordpress.com/support/webhooks/) |

## Code

### Express

From [webhook-skills: skills/wordpress-com-webhooks/examples/express/src/index.js](https://github.com/hookdeck/webhook-skills/blob/9b7c561086c41940e310ef131b09928c1e7508b4/skills/wordpress-com-webhooks/examples/express/src/index.js)

```javascript
// Generated with: wordpress-com-webhooks skill
// https://github.com/hookdeck/webhook-skills
require('dotenv').config();
const express = require('express');
const crypto = require('crypto');

// WordPress.com webhooks (Settings -> Webhooks, the native
// /wp-admin/options-general.php?page=webhooks feature) are UNSIGNED:
//
//   1. There is NO signature, NO secret, NO timestamp and NO handshake. Do not
//      write an HMAC verifier and do not look for X-WordPress-Signature,
//      X-WP-Signature or X-WPCOM-Signature — none of them exist.
//      (X-WC-Webhook-Signature is WooCommerce, a different product.)
//   2. The body is a FLAT application/x-www-form-urlencoded key/value set — no
//      JSON envelope, no `type`, no `data` object, no event id. The
//      discriminator is the `hook` field.
//   3. Only the fields the admin ticked are sent, and every value is a STRING.
//      Guard every access and coerce numerics explicitly.
//
// The practical control is a random token YOU put in the registered URL's query
// string, compared in constant time. It is not provider authentication.

const WEBHOOK_PATH = '/webhooks/wordpress-com';

// The three documented hooks. There are no others — no post_updated,
// delete_post, user_register or wp_insert_post.
const HOOKS = {
  PUBLISH_POST: 'publish_post',
  PUBLISH_PAGE: 'publish_page',
  COMMENT_POST: 'comment_post',
};

const app = express();

/**
 * Timing-safe string comparison that tolerates a length mismatch
 * (crypto.timingSafeEqual throws when the buffer lengths differ).
 */
function safeEqual(a, b) {
  const ab = Buffer.from(a);
  const bb = Buffer.from(b);
  return ab.length === bb.length && crypto.timingSafeEqual(ab, bb);
}

/**
 * Compare the token YOU added to the registered webhook URL
 * (https://example.com/webhooks/wordpress-com?token=<random>).
 *
 * This is NOT a WordPress.com signature — WordPress.com signs nothing. The env
 * var is read per request so the process fails CLOSED the moment it is missing,
 * rather than silently accepting everything.
 *
 * @param {unknown} provided - the `token` query param
 * @returns {boolean} true when it matches
 * @throws {Error} when WORDPRESS_COM_WEBHOOK_TOKEN is not configured
 */
function verifyUrlToken(provided) {
  const expected = process.env.WORDPRESS_COM_WEBHOOK_TOKEN;
  if (!expected) {
    // Fail CLOSED. An unconfigured endpoint must never accept every request.
    throw new Error('WORDPRESS_COM_WEBHOOK_TOKEN is not set');
  }
  if (typeof provided !== 'string') return false; // absent, or repeated (array)
  return safeEqual(provided, expected);
}

/**
 * Build a dedupe key for a delivery.
 *
 * publish_post / publish_page fire on the initial publish AND on every later
 * edit of a published item, and there is no delivery-id header, so the same `ID`
 * arrives repeatedly. post_modified_gmt (when the admin ticked it) distinguishes
 * one edit from the next.
 *
 * @param {string} hook
 * @param {Record<string, unknown>} fields
 * @returns {string|null}
 */
function dedupeKey(hook, fields) {
  if (hook === HOOKS.COMMENT_POST) {
    return fields.comment_ID ? `${hook}:${fields.comment_ID}` : null;
  }
  if (!fields.ID) return null;
  return `${hook}:${fields.ID}:${fields.post_modified_gmt || 'unknown'}`;
}

/**
 * Re-fetch the authoritative post from the WordPress.com REST API.
 *
 * The delivery is unsigned, so the payload is an untrusted HINT: anyone who
 * learns the URL can POST arbitrary values at you. Re-read anything you are
 * going to act on. Returns null when WORDPRESS_COM_SITE is not configured.
 *
 * @param {string} postId
 * @returns {Promise<object|null>}
 */
async function fetchPost(postId) {
  const site = process.env.WORDPRESS_COM_SITE;
  if (!site) return null;

  const response = await fetch(
    `https://public-api.wordpress.com/rest/v1.1/sites/${encodeURIComponent(site)}/posts/${encodeURIComponent(postId)}`
  );
  if (!response.ok) throw new Error(`REST API returned ${response.status}`);
  return response.json();
}

// --- Event handlers (one per documented hook) -------------------------------

async function handlePublishPost(fields) {
  // Every value is a string, and only ticked fields are present.
  console.log(`Post published/updated: ${fields.ID ?? 'unknown ID'} — ${fields.post_title ?? '(post_title not selected)'}`);
  console.log(`  status=${fields.post_status ?? 'n/a'} url=${fields.post_url ?? 'n/a'}`);
  // Your code: upsert keyed on fields.ID (see dedupeKey), then act on the
  // authoritative record from fetchPost(fields.ID).
}

async function handlePublishPage(fields) {
  console.log(`Page published/updated: ${fields.ID ?? 'unknown ID'} — ${fields.post_title ?? '(post_title not selected)'}`);
  // Your code: same upsert-by-ID treatment as posts.
}

async function handleCommentPost(fields) {
  // comment_approved is a STRING: '1' approved, '0' pending moderation, 'spam'.
  // Comments can arrive before moderation — never publish comment_content blindly.
  const approved = fields.comment_approved;
  const state = approved === '1' ? 'approved' : approved === 'spam' ? 'spam' : 'pending';
  console.log(`Comment ${fields.comment_ID ?? 'unknown'} on post ${fields.comment_post_ID ?? 'unknown'} (${state})`);
  // Your code: only surface comment_content once approved === '1'.
}

/**
 * Dispatch on the `hook` field — the payload's only discriminator.
 *
 * An unknown hook is logged and treated as handled: the caller still answers
 * 2xx, because rejecting gains nothing from a sender with no documented retry
 * policy.
 *
 * @param {string} hook
 * @param {Record<string, unknown>} fields
 * @returns {Promise<{ known: boolean, key: string|null }>}
 */
async function dispatch(hook, fields) {
  const key = dedupeKey(hook, fields);
  switch (hook) {
    case HOOKS.PUBLISH_POST:
      await handlePublishPost(fields);
      return { known: true, key };
    case HOOKS.PUBLISH_PAGE:
      await handlePublishPage(fields);
      return { known: true, key };
    case HOOKS.COMMENT_POST:
      await handleCommentPost(fields);
      return { known: true, key };
    default:
      // Only three hooks are documented; log anything else and move on.
      console.warn(`Unhandled WordPress.com hook: ${hook}`);
      return { known: false, key };
  }
}

// --- Middleware -------------------------------------------------------------

/**
 * Validate the URL token BEFORE any body parsing happens.
 */
function requireUrlToken(req, res, next) {
  let ok;
  try {
    ok = verifyUrlToken(req.query.token);
  } catch (err) {
    console.error(`WordPress.com webhook misconfigured: ${err.message}`);
    // Fail closed — do not process a delivery we cannot authenticate at all.
    return res.status(500).send('Webhook token not configured');
  }
  if (!ok) {
    console.error('WordPress.com webhook rejected: URL token missing or mismatched');
    return res.status(401).send('Invalid webhook token');
  }
  return next();
}

// WordPress.com sends application/x-www-form-urlencoded (inferred from the
// HookPress lineage, whose sender hands a PHP array to wp_remote_post ->
// http_build_query). `extended: true` also decodes bracketed arrays such as
// post_category[0]=1&post_category[1]=5.
const parseForm = express.urlencoded({ extended: true });
// Defensive only: accept a JSON body too if one ever shows up. Do NOT document
// JSON as what WordPress.com sends.
const parseJson = express.json();

app.post(WEBHOOK_PATH, requireUrlToken, parseForm, parseJson, (req, res) => {
  const fields = req.body && typeof req.body === 'object' ? req.body : {};

  // `hook` is the ONLY field WordPress.com always includes. There is no `type`,
  // no `event`, and nothing nested to read it out of.
  const hook = typeof fields.hook === 'string' ? fields.hook : null;
  if (!hook) {
    console.error('WordPress.com webhook rejected: no `hook` field in the body');
    return res.status(400).send('Missing hook field');
  }

  // Acknowledge FIRST. HookPress sends synchronously inside the WordPress action
  // (WordPress.com's implementation may differ), and no retry policy is
  // documented, so never hold the response open for your own work.
  res.status(200).send('OK');

  // Then process out of band. In production hand this to a queue.
  Promise.resolve()
    .then(() => dispatch(hook, fields))
    .then(({ key }) => {
      if (key) console.log(`Processed ${key}`);
    })
    .catch((err) => console.error(`WordPress.com webhook processing failed: ${err.message}`));
});

// Malformed JSON (or an oversized body) surfaces here rather than as a 500.
app.use(WEBHOOK_PATH, (err, req, res, next) => {
  if (err) {
    console.error(`WordPress.com webhook body could not be parsed: ${err.message}`);
    return res.status(400).send('Invalid body');
  }
  return next();
});

// Health check endpoint
app.get('/health', (req, res) => {
  res.json({ status: 'ok' });
});

module.exports = {
  app,
  HOOKS,
  verifyUrlToken,
  dedupeKey,
  dispatch,
  fetchPost,
  handlePublishPost,
  handlePublishPage,
  handleCommentPost,
};

// Start the server only when run directly (not when imported for testing)
if (require.main === module) {
  const PORT = process.env.PORT || 3000;
  if (!process.env.WORDPRESS_COM_WEBHOOK_TOKEN) {
    console.warn(
      'WORDPRESS_COM_WEBHOOK_TOKEN is not set — every delivery will be answered ' +
        'with 500 (fail closed). Generate one with `openssl rand -hex 32` and add ' +
        '?token=<value> to the URL you register in Settings -> Webhooks.'
    );
  }
  app.listen(PORT, () => {
    console.log(`Server running on http://localhost:${PORT}`);
    console.log(`Webhook endpoint: POST http://localhost:${PORT}${WEBHOOK_PATH}?token=...`);
  });
}
```

### Next.js

From [webhook-skills: skills/wordpress-com-webhooks/examples/nextjs/app/webhooks/wordpress-com/route.ts](https://github.com/hookdeck/webhook-skills/blob/9b7c561086c41940e310ef131b09928c1e7508b4/skills/wordpress-com-webhooks/examples/nextjs/app/webhooks/wordpress-com/route.ts)

```typescript
// Generated with: wordpress-com-webhooks skill
// https://github.com/hookdeck/webhook-skills
import { NextRequest } from 'next/server';
import crypto from 'crypto';

// WordPress.com webhooks (Settings -> Webhooks, the native
// /wp-admin/options-general.php?page=webhooks feature) are UNSIGNED:
//
//   1. There is NO signature, NO secret, NO timestamp and NO handshake. Do not
//      write an HMAC verifier and do not look for X-WordPress-Signature,
//      X-WP-Signature or X-WPCOM-Signature — none of them exist.
//      (X-WC-Webhook-Signature is WooCommerce, a different product.)
//   2. The body is a FLAT application/x-www-form-urlencoded key/value set — no
//      JSON envelope, no `type`, no `data` object, no event id. The
//      discriminator is the `hook` field.
//   3. Only the fields the admin ticked are sent, and every value is a STRING.
//
// The practical control is a random token YOU put in the registered URL's query
// string, compared in constant time. It is not provider authentication.

/** The three documented hooks. There are no others. */
export const HOOKS = {
  PUBLISH_POST: 'publish_post',
  PUBLISH_PAGE: 'publish_page',
  COMMENT_POST: 'comment_post',
} as const;

/** A parsed delivery: flat, string-valued, every key optional except `hook`. */
export type Fields = Record<string, string | string[]>;

function safeEqual(a: string, b: string): boolean {
  const ab = Buffer.from(a);
  const bb = Buffer.from(b);
  // Length-guard first: timingSafeEqual throws on a length mismatch.
  return ab.length === bb.length && crypto.timingSafeEqual(ab, bb);
}

/**
 * Compare the token YOU added to the registered webhook URL
 * (https://example.com/webhooks/wordpress-com?token=<random>).
 *
 * NOT a WordPress.com signature — WordPress.com signs nothing. Throws when the
 * env var is missing so the route fails CLOSED instead of accepting everything.
 */
export function verifyUrlToken(provided: string | null): boolean {
  const expected = process.env.WORDPRESS_COM_WEBHOOK_TOKEN;
  if (!expected) throw new Error('WORDPRESS_COM_WEBHOOK_TOKEN is not set');
  if (provided === null) return false;
  return safeEqual(provided, expected);
}

/**
 * Parse the raw body into flat fields.
 *
 * application/x-www-form-urlencoded is the expected format (inferred from the
 * HookPress lineage, whose sender hands a PHP array to wp_remote_post ->
 * http_build_query). JSON is accepted defensively only — do not document it as
 * what WordPress.com sends.
 *
 * Bracket-encoded arrays (post_category[0]=1&post_category[1]=5) and repeated
 * keys are grouped into string arrays.
 */
export function parseFields(rawBody: string, contentType: string | null): Fields {
  if (contentType && contentType.toLowerCase().includes('application/json')) {
    const parsed = JSON.parse(rawBody) as unknown;
    if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) {
      throw new Error('JSON body is not an object');
    }
    // Normalise to strings — WordPress.com sends strings on the form-encoded path.
    const out: Fields = {};
    for (const [key, value] of Object.entries(parsed as Record<string, unknown>)) {
      out[key] = Array.isArray(value) ? value.map(String) : String(value);
    }
    return out;
  }

  const out: Fields = {};
  for (const [key, value] of new URLSearchParams(rawBody)) {
    const bracketed = /^([^[]+)\[\d*\]$/.exec(key);
    const name = bracketed ? bracketed[1] : key;
    const existing = out[name];
    if (bracketed || existing !== undefined) {
      const list = Array.isArray(existing) ? existing : existing === undefined ? [] : [existing];
      list.push(value);
      out[name] = list;
    } else {
      out[name] = value;
    }
  }
  return out;
}

/** Read a single-valued field, ignoring repeated/bracketed values. */
function one(fields: Fields, key: string): string | undefined {
  const value = fields[key];
  return typeof value === 'string' ? value : undefined;
}

/**
 * Build a dedupe key.
 *
 * publish_post / publish_page fire on the initial publish AND on every later
 * edit of a published item, and there is no delivery-id header, so the same `ID`
 * arrives repeatedly.
 */
export function dedupeKey(hook: string, fields: Fields): string | null {
  if (hook === HOOKS.COMMENT_POST) {
    const id = one(fields, 'comment_ID');
    return id ? `${hook}:${id}` : null;
  }
  const id = one(fields, 'ID');
  if (!id) return null;
  return `${hook}:${id}:${one(fields, 'post_modified_gmt') ?? 'unknown'}`;
}

/**
 * Re-fetch the authoritative post from the WordPress.com REST API.
 *
 * The delivery is unsigned, so the payload is an untrusted HINT. Returns null
 * when WORDPRESS_COM_SITE is not configured.
 */
export async function fetchPost(postId: string): Promise<unknown | null> {
  const site = process.env.WORDPRESS_COM_SITE;
  if (!site) return null;

  const response = await fetch(
    `https://public-api.wordpress.com/rest/v1.1/sites/${encodeURIComponent(site)}/posts/${encodeURIComponent(postId)}`
  );
  if (!response.ok) throw new Error(`REST API returned ${response.status}`);
  return response.json();
}

// --- Event handlers (one per documented hook) -------------------------------

async function handlePublishPost(fields: Fields): Promise<void> {
  console.log(
    `Post published/updated: ${one(fields, 'ID') ?? 'unknown ID'} — ${one(fields, 'post_title') ?? '(post_title not selected)'}`
  );
  // Your code: upsert keyed on ID (see dedupeKey), then act on fetchPost(ID).
}

async function handlePublishPage(fields: Fields): Promise<void> {
  console.log(
    `Page published/updated: ${one(fields, 'ID') ?? 'unknown ID'} — ${one(fields, 'post_title') ?? '(post_title not selected)'}`
  );
}

async function handleCommentPost(fields: Fields): Promise<void> {
  // comment_approved is a STRING: '1' approved, '0' pending moderation, 'spam'.
  // Comments can arrive before moderation — never publish comment_content blindly.
  const approved = one(fields, 'comment_approved');
  const state = approved === '1' ? 'approved' : approved === 'spam' ? 'spam' : 'pending';
  console.log(
    `Comment ${one(fields, 'comment_ID') ?? 'unknown'} on post ${one(fields, 'comment_post_ID') ?? 'unknown'} (${state})`
  );
}

/**
 * Dispatch on the `hook` field — the payload's only discriminator. An unknown
 * hook is logged and still acknowledged with 2xx.
 */
export async function dispatch(
  hook: string,
  fields: Fields
): Promise<{ known: boolean; key: string | null }> {
  const key = dedupeKey(hook, fields);
  switch (hook) {
    case HOOKS.PUBLISH_POST:
      await handlePublishPost(fields);
      return { known: true, key };
    case HOOKS.PUBLISH_PAGE:
      await handlePublishPage(fields);
      return { known: true, key };
    case HOOKS.COMMENT_POST:
      await handleCommentPost(fields);
      return { known: true, key };
    default:
      console.warn(`Unhandled WordPress.com hook: ${hook}`);
      return { known: false, key };
  }
}

export async function POST(request: NextRequest) {
  // 1. Validate the URL token before touching the body.
  try {
    if (!verifyUrlToken(request.nextUrl.searchParams.get('token'))) {
      console.error('WordPress.com webhook rejected: URL token missing or mismatched');
      return new Response('Invalid webhook token', { status: 401 });
    }
  } catch (err) {
    console.error(`WordPress.com webhook misconfigured: ${(err as Error).message}`);
    // Fail CLOSED — never accept a delivery we cannot authenticate at all.
    return new Response('Webhook token not configured', { status: 500 });
  }

  // 2. Parse the flat form-encoded body. `await request.formData()` also works;
  // reading the text keeps the JSON fallback (and any logging) on one path.
  let fields: Fields;
  try {
    fields = parseFields(await request.text(), request.headers.get('content-type'));
  } catch (err) {
    console.error(`WordPress.com webhook body could not be parsed: ${(err as Error).message}`);
    return new Response('Invalid body', { status: 400 });
  }

  // 3. `hook` is the only field WordPress.com always includes.
  const hook = one(fields, 'hook');
  if (!hook) {
    console.error('WordPress.com webhook rejected: no `hook` field in the body');
    return new Response('Missing hook field', { status: 400 });
  }

  // 4. Dispatch. No retries are documented, so keep the work short — in
  // production push it onto a queue (or use `after()`) and acknowledge at once.
  try {
    const { key } = await dispatch(hook, fields);
    if (key) console.log(`Processed ${key}`);
  } catch (err) {
    console.error(`WordPress.com webhook processing failed: ${(err as Error).message}`);
  }

  return new Response('OK', { status: 200 });
}
```

### FastAPI

From [webhook-skills: skills/wordpress-com-webhooks/examples/fastapi/main.py](https://github.com/hookdeck/webhook-skills/blob/9b7c561086c41940e310ef131b09928c1e7508b4/skills/wordpress-com-webhooks/examples/fastapi/main.py)

```python
# Generated with: wordpress-com-webhooks skill
# https://github.com/hookdeck/webhook-skills
import hmac
import json
import os
import re
from typing import Any, Dict, List, Optional, Sequence, Tuple, Union

import httpx
from dotenv import load_dotenv
from fastapi import FastAPI, Request, Response

load_dotenv()

# WordPress.com webhooks (Settings -> Webhooks, the native
# /wp-admin/options-general.php?page=webhooks feature) are UNSIGNED:
#
#   1. There is NO signature, NO secret, NO timestamp and NO handshake. Do not
#      write an HMAC verifier and do not look for X-WordPress-Signature,
#      X-WP-Signature or X-WPCOM-Signature — none of them exist.
#      (X-WC-Webhook-Signature is WooCommerce, a different product.)
#   2. The body is a FLAT application/x-www-form-urlencoded key/value set — no
#      JSON envelope, no `type`, no `data` object, no event id. The
#      discriminator is the `hook` field.
#   3. Only the fields the admin ticked are sent, and every value is a STRING.
#
# The practical control is a random token YOU put in the registered URL's query
# string, compared in constant time. It is not provider authentication.

app = FastAPI(title="WordPress.com Webhook Handler")

# The three documented hooks. There are no others — no post_updated,
# delete_post, user_register or wp_insert_post.
PUBLISH_POST = "publish_post"
PUBLISH_PAGE = "publish_page"
COMMENT_POST = "comment_post"

# A parsed delivery: flat, string-valued, every key optional except `hook`.
Fields = Dict[str, Union[str, List[str]]]

_BRACKETED = re.compile(r"^([^\[]+)\[\d*\]$")


def verify_url_token(provided: Optional[str]) -> bool:
    """
    Compare the token YOU added to the registered webhook URL
    (https://example.com/webhooks/wordpress-com?token=<random>).

    This is NOT a WordPress.com signature — WordPress.com signs nothing. Raises
    when the env var is missing so the endpoint fails CLOSED rather than
    accepting everything.
    """
    expected = os.getenv("WORDPRESS_COM_WEBHOOK_TOKEN")
    if not expected:
        raise RuntimeError("WORDPRESS_COM_WEBHOOK_TOKEN is not set")
    if not provided:
        return False
    # Compare BYTES, not str: hmac.compare_digest() raises TypeError on str
    # values containing non-ASCII characters, and the token is attacker-supplied.
    return hmac.compare_digest(provided.encode("utf-8"), expected.encode("utf-8"))


def group_fields(items: Sequence[Tuple[str, str]]) -> Fields:
    """
    Flatten form items into fields, grouping bracket-encoded arrays.

    http_build_query encodes array-valued fields such as post_category as
    `post_category[0]=1&post_category[1]=5`, so those (and any repeated key) are
    collected into a list.
    """
    fields: Fields = {}
    for key, value in items:
        match = _BRACKETED.match(key)
        name = match.group(1) if match else key
        existing = fields.get(name)
        if match or existing is not None:
            if isinstance(existing, list):
                existing.append(value)
            elif existing is None:
                fields[name] = [value]
            else:
                fields[name] = [existing, value]
        else:
            fields[name] = value
    return fields


def parse_json_fields(raw_body: bytes) -> Fields:
    """
    Parse a JSON body defensively.

    WordPress.com is expected to send application/x-www-form-urlencoded (inferred
    from the HookPress lineage, whose sender hands a PHP array to
    wp_remote_post -> http_build_query). JSON is accepted only as a cheap
    fallback — do not document it as what WordPress.com sends.
    """
    parsed = json.loads(raw_body)
    if not isinstance(parsed, dict):
        raise ValueError("JSON body is not an object")
    fields: Fields = {}
    for key, value in parsed.items():
        # Normalise to strings, matching the form-encoded path.
        fields[key] = [str(item) for item in value] if isinstance(value, list) else str(value)
    return fields


def one(fields: Fields, key: str) -> Optional[str]:
    """Read a single-valued field, ignoring repeated/bracketed values."""
    value = fields.get(key)
    return value if isinstance(value, str) else None


def dedupe_key(hook: str, fields: Fields) -> Optional[str]:
    """
    Build a dedupe key.

    publish_post / publish_page fire on the initial publish AND on every later
    edit of a published item, and there is no delivery-id header, so the same
    `ID` arrives repeatedly. post_modified_gmt (when the admin ticked it)
    distinguishes one edit from the next.
    """
    if hook == COMMENT_POST:
        comment_id = one(fields, "comment_ID")
        return f"{hook}:{comment_id}" if comment_id else None
    post_id = one(fields, "ID")
    if not post_id:
        return None
    return f"{hook}:{post_id}:{one(fields, 'post_modified_gmt') or 'unknown'}"


async def fetch_post(post_id: str) -> Optional[Dict[str, Any]]:
    """
    Re-fetch the authoritative post from the WordPress.com REST API.

    The delivery is unsigned, so the payload is an untrusted HINT: anyone who
    learns the URL can POST arbitrary values at you. Returns None when
    WORDPRESS_COM_SITE is not configured.
    """
    site = os.getenv("WORDPRESS_COM_SITE")
    if not site:
        return None

    async with httpx.AsyncClient() as client:
        response = await client.get(
            f"https://public-api.wordpress.com/rest/v1.1/sites/{site}/posts/{post_id}"
        )
    response.raise_for_status()
    return response.json()


# --- Event handlers (one per documented hook) --------------------------------


async def handle_publish_post(fields: Fields) -> None:
    print(
        f"Post published/updated: {one(fields, 'ID') or 'unknown ID'} — "
        f"{one(fields, 'post_title') or '(post_title not selected)'}"
    )
    # Your code: upsert keyed on ID (see dedupe_key), then act on fetch_post(ID).


async def handle_publish_page(fields: Fields) -> None:
    print(
        f"Page published/updated: {one(fields, 'ID') or 'unknown ID'} — "
        f"{one(fields, 'post_title') or '(post_title not selected)'}"
    )


async def handle_comment_post(fields: Fields) -> None:
    # comment_approved is a STRING: '1' approved, '0' pending moderation, 'spam'.
    # Comments can arrive before moderation — never publish comment_content blindly.
    approved = one(fields, "comment_approved")
    state = "approved" if approved == "1" else "spam" if approved == "spam" else "pending"
    print(
        f"Comment {one(fields, 'comment_ID') or 'unknown'} on post "
        f"{one(fields, 'comment_post_ID') or 'unknown'} ({state})"
    )


async def dispatch(hook: str, fields: Fields) -> Tuple[bool, Optional[str]]:
    """
    Dispatch on the `hook` field — the payload's only discriminator.

    An unknown hook is logged and the caller still answers 2xx: rejecting gains
    nothing from a sender with no documented retry policy.

    Returns (known, dedupe_key).
    """
    key = dedupe_key(hook, fields)
    if hook == PUBLISH_POST:
        await handle_publish_post(fields)
    elif hook == PUBLISH_PAGE:
        await handle_publish_page(fields)
    elif hook == COMMENT_POST:
        await handle_comment_post(fields)
    else:
        print(f"Unhandled WordPress.com hook: {hook}")
        return False, key
    return True, key


@app.post("/webhooks/wordpress-com")
async def handle_wordpress_com_webhook(request: Request) -> Response:
    """Receive a WordPress.com webhook: unsigned, flat, form-encoded."""
    # 1. Validate the URL token before touching the body.
    try:
        if not verify_url_token(request.query_params.get("token")):
            print("WordPress.com webhook rejected: URL token missing or mismatched")
            return Response("Invalid webhook token", status_code=401, media_type="text/plain")
    except RuntimeError as err:
        print(f"WordPress.com webhook misconfigured: {err}")
        # Fail CLOSED — never accept a delivery we cannot authenticate at all.
        return Response("Webhook token not configured", status_code=500, media_type="text/plain")

    # 2. Parse the flat body. `await request.form()` handles
    # application/x-www-form-urlencoded (it needs python-multipart installed).
    content_type = (request.headers.get("content-type") or "").lower()
    try:
        if "application/json" in content_type:
            fields = parse_json_fields(await request.body())
        else:
            form = await request.form()
            fields = group_fields([(k, str(v)) for k, v in form.multi_items()])
    except (ValueError, UnicodeDecodeError) as err:
        print(f"WordPress.com webhook body could not be parsed: {err}")
        return Response("Invalid body", status_code=400, media_type="text/plain")

    # 3. `hook` is the only field WordPress.com always includes. There is no
    # `type`, no `event`, and nothing nested to read it out of.
    hook = one(fields, "hook")
    if not hook:
        print("WordPress.com webhook rejected: no `hook` field in the body")
        return Response("Missing hook field", status_code=400, media_type="text/plain")

    # 4. Dispatch. No retry policy is documented, so keep this short — in
    # production hand the work to a background task or queue and acknowledge now.
    try:
        _known, key = await dispatch(hook, fields)
        if key:
            print(f"Processed {key}")
    except Exception as err:  # noqa: BLE001 - never leak a 500 to the sender
        print(f"WordPress.com webhook processing failed: {err}")

    return Response("OK", status_code=200, media_type="text/plain")


@app.get("/health")
async def health() -> Dict[str, str]:
    return {"status": "ok"}


if __name__ == "__main__":
    import uvicorn

    if not os.getenv("WORDPRESS_COM_WEBHOOK_TOKEN"):
        print(
            "WORDPRESS_COM_WEBHOOK_TOKEN is not set — every delivery will be answered "
            "with 500 (fail closed). Generate one with `openssl rand -hex 32` and add "
            "?token=<value> to the URL you register in Settings -> Webhooks."
        )
    uvicorn.run(app, host="0.0.0.0", port=8000)
```

Or install the WordPress.com webhooks skill: `npx skills add hookdeck/webhook-skills --skill wordpress-com-webhooks`

## Common failures

- **Checking for a signature header.** WordPress.com's docs describe no signature header, so a handler that requires one rejects every delivery. `X-WC-Webhook-Signature` belongs to WooCommerce, a different product.
- **Token missing from the saved URL.** If you rotate the token in your app, change the URL on the webhook too, or every delivery fails the check. WordPress.com's docs don't mention query strings in webhook URLs, so send one real delivery to confirm the token arrives.
- **Token not set in your environment.** The handlers below return a 500 when the token isn't configured, so that an unconfigured endpoint can't accept everything. Set it wherever your handler runs.
- **Parsing the body as JSON.** WordPress.com doesn't name a content type, and HookPress, the plugin it was built from, sends form data. A JSON-only body parser can then leave the body empty, so read the `Content-Type` header of a real delivery first.

From [Hookdeck's WordPress.com guide](https://hookdeck.com/webhooks/wordpress-com/guide-duplicates-retries-timeouts).

---

Not affiliated with WordPress.com. Facts are compiled from public sources and linked inline. [View as JSON](https://hookdeck.com/webhooks/wordpress-com.json) · [Report a correction](https://hookdeck.com/contact)
