Push Notifications to Webhook

Android · HTTPS · Webhooks

Tus notificaciones. Tus webhooks.

Reenvía notificaciones de las apps Android que elijas a tus webhooks HTTPS. Filtra por palabras, consulta los envíos y mantén el control.

Android 12+ · Publicación en preparación
push2hook

Elige qué sale del móvil

No se seleccionan apps automáticamente. Elige apps, palabras opcionales y el destino de cada integración.

Comprueba cada envío

El historial en directo distingue pendientes, enviando, entregadas y fallidas. Puedes reenviar incluso después de una entrega correcta.

Mantén tu automatización

La captura continúa al salir de la pantalla. Cerrar y detener para captura y envíos hasta volver a abrir la app.

Preparada para tu webhook

HTTPS, firma HMAC-SHA256 opcional, envíos solo con Wi-Fi y conservación local configurable.

Primeros pasos

1

Revisa y acepta

Lee el aviso y acepta si quieres activar la captura. Después puedes retirar el consentimiento en Ajustes.

2

Concede acceso a notificaciones

Android solicita un permiso independiente. El aviso de estado y los ajustes de batería ayudan a comprobar el funcionamiento en segundo plano.

3

Elige apps y un webhook

Introduce una URL HTTPS en Ajustes y selecciona apps y palabras opcionales. Cada app puede tener su propia URL.

4

Consulta el envío

Abre Capturas para ver estado, intentos y JSON. Prueba primero la demo ficticia antes de conectar tu integración.

push2hook · 01-statuspush2hook · 02-capturespush2hook · 03-details

Lo que envía la app

Ejemplo del cuerpo: X-Device-Id debe coincidir con deviceId. X-Timestamp es la hora Unix actual en segundos, no capturedAt.

POST application/jsonHTTPSJSON
POST /webhook HTTP/1.1
Content-Type: application/json; charset=utf-8
X-Device-Id: my-phone
X-Timestamp: <unix-seconds>
X-Signature: <Base64 HMAC-SHA256>
Descargar código
{
  "schemaVersion": 1,
  "payloadMode": "minimal",
  "demo": false,
  "deviceId": "my-phone",
  "eventId": "stable-event-id",
  "capturedAt": "2026-10-19T10:30:00Z",
  "source": {
    "packageName": "com.example.orders",
    "appName": "Orders",
    "postTime": 1792405800000
  },
  "notification": {
    "title": "Order ready",
    "text": "Example order #1042",
    "subText": null,
    "textLines": null
  },
  "ranking": null
}

X-Signature = Base64(HMAC-SHA256(secret, timestamp + "." + rawBody))

Ver receptor del servidor

Receptor en tu servidor

Tu servidor recibe el POST anterior. Elige Node.js, PHP o Python para validar y guardar la notificación.

Ver JSON de envío

Node.js 20+, sin dependencias. Ejecuta node receiver.mjs detrás de un proxy HTTPS; escucha solo en 127.0.0.1:8000 (o PORT).

Descargar código
// Node.js 20+, standard library only. Run behind an HTTPS reverse proxy:
// node receiver.mjs (listens on 127.0.0.1:8000, or PORT).
// Configure PUSH2HOOK_DEVICE_ID, PUSH2HOOK_SECRET (32+ UTF-8 bytes),
// PUSH2HOOK_INBOX: an existing private directory outside the web root.
import { createServer } from 'node:http';
import { createHash, createHmac, randomUUID, timingSafeEqual } from 'node:crypto';
import * as fs from 'node:fs/promises';
import { isAbsolute, join } from 'node:path';
import { TextDecoder } from 'node:util';

const MAX_BODY = 1048576;
const isObject = value => value !== null && typeof value === 'object' && !Array.isArray(value);

const server = createServer(async (request, response) => {
  const reply = (status, message = '') => {
    request.resume();
    const body = message ? JSON.stringify({ error: message }) : '';
    response.writeHead(status, {
      'Content-Type': 'application/json; charset=utf-8',
      'Cache-Control': 'no-store', 'X-Content-Type-Options': 'nosniff',
      'Content-Length': Buffer.byteLength(body), ...(status === 405 ? { Allow: 'POST' } : {}),
    });
    response.end(body);
  };
  const header = name => typeof request.headers[name] === 'string' ? request.headers[name] : '';
  let temporary;
  try {
    if (request.method !== 'POST') return reply(405, 'POST required');
    if (header('content-type').split(';', 1)[0].trim().toLowerCase() !== 'application/json') {
      return reply(415, 'application/json required');
    }
    const device = process.env.PUSH2HOOK_DEVICE_ID || '';
    const secret = Buffer.from(process.env.PUSH2HOOK_SECRET || '', 'utf8');
    const inbox = process.env.PUSH2HOOK_INBOX || '';
    if (!device || secret.length < 32 || !isAbsolute(inbox) || !(await fs.stat(inbox)).isDirectory()) {
      return reply(503, 'Receiver not configured');
    }
    const timestamp = header('x-timestamp');
    const signature = header('x-signature');
    if (header('x-device-id') !== device || !/^[0-9]{1,12}$/.test(timestamp)
        || Math.abs(Math.floor(Date.now() / 1000) - Number(timestamp)) > 300
        || !/^[A-Za-z0-9+/]{43}=$/.test(signature)) {
      return reply(401, 'Authentication failed');
    }
    const length = header('content-length');
    if (!/^[0-9]{1,10}$/.test(length)) return reply(411, 'Content-Length required');
    if (Number(length) > MAX_BODY) return reply(413, 'Body too large');
    const chunks = [];
    let size = 0;
    for await (const chunk of request) {
      size += chunk.length;
      if (size > MAX_BODY) return reply(413, 'Body too large');
      chunks.push(chunk);
    }
    const raw = Buffer.concat(chunks);
    if (raw.length !== Number(length)) return reply(400, 'Incomplete body');

    // HMAC uses ORIGINAL bytes. Never parse/re-serialize JSON before verification.
    const expected = createHmac('sha256', secret).update(timestamp + '.', 'utf8').update(raw).digest();
    const supplied = Buffer.from(signature, 'base64');
    if (supplied.length !== 32 || !timingSafeEqual(expected, supplied)) {
      return reply(401, 'Authentication failed');
    }
    let data;
    try {
      data = JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(raw));
    } catch {
      return reply(400, 'Invalid JSON');
    }
    if (!isObject(data) || data.schemaVersion !== 1 || data.deviceId !== device || data.demo !== false
        || typeof data.eventId !== 'string' || data.eventId.length < 1 || data.eventId.length > 200
        || /[^A-Za-z0-9._:-]/.test(data.eventId) || !isObject(data.source)
        || typeof data.source.packageName !== 'string' || !data.source.packageName
        || Buffer.byteLength(data.source.packageName, 'utf8') > 255
        || !isObject(data.notification) || Object.keys(data.notification).length === 0) {
      return reply(400, 'Invalid notification or device mismatch');
    }

    // Publish a complete private inbox file atomically, without overwriting an
    // existing device + eventId. Process these files asynchronously.
    const key = createHash('sha256').update(device + '\0' + data.eventId, 'utf8').digest('hex');
    const target = join(inbox, key + '.json');
    temporary = join(inbox, '.pending-' + randomUUID());
    const output = await fs.open(temporary, 'wx', 0o600);
    try {
      await output.writeFile(raw);
      await output.sync();
    } finally {
      await output.close();
    }
    let duplicate = false;
    try {
      await fs.link(temporary, target);
    } catch (error) {
      if (error.code !== 'EEXIST' || !(await fs.stat(target)).isFile()) throw error;
      duplicate = true;
    }
    reply(duplicate ? 204 : 202);
  } catch {
    // A failed write must return 5xx so push2hook can retry.
    if (!response.headersSent) reply(503, 'Storage unavailable');
  } finally {
    if (temporary) await fs.unlink(temporary).catch(() => {});
  }
});
server.requestTimeout = 15000;
server.headersTimeout = 10000;
server.listen(Number(process.env.PORT || 8000), '127.0.0.1');

PHP 8.1+, sin extensiones adicionales. Sirve receiver.php mediante tu servidor HTTPS y configura las variables en PHP-FPM.

Descargar código
<?php
declare(strict_types=1);

// PHP 8.1+. Configure these variables in the PHP-FPM process environment.
// PUSH2HOOK_DEVICE_ID, PUSH2HOOK_SECRET (32+ bytes), PUSH2HOOK_INBOX.
// Serve behind HTTPS. The inbox directory must be private and outside the web root.
header('Content-Type: application/json; charset=utf-8');
header('Cache-Control: no-store');
header('X-Content-Type-Options: nosniff');

function reply(int $status, string $message = ''): never {
    http_response_code($status);
    if ($message !== '') echo json_encode(['error' => $message]);
    exit;
}

if (($_SERVER['REQUEST_METHOD'] ?? '') !== 'POST') {
    header('Allow: POST');
    reply(405, 'POST required');
}
if (strtolower(trim(explode(';', $_SERVER['CONTENT_TYPE'] ?? '')[0])) !== 'application/json') {
    reply(415, 'application/json required');
}

$device = getenv('PUSH2HOOK_DEVICE_ID') ?: '';
$secret = getenv('PUSH2HOOK_SECRET') ?: '';
$inbox = getenv('PUSH2HOOK_INBOX') ?: '';
if ($device === '' || strlen($secret) < 32 || $inbox === '' || $inbox[0] !== '/' || !is_dir($inbox)) {
    reply(503, 'Receiver not configured');
}

$deviceHeader = $_SERVER['HTTP_X_DEVICE_ID'] ?? '';
$timestamp = $_SERVER['HTTP_X_TIMESTAMP'] ?? '';
$signature = $_SERVER['HTTP_X_SIGNATURE'] ?? '';
$now = time();
if (!hash_equals($device, $deviceHeader) || !preg_match('/\A[0-9]{1,12}\z/', $timestamp) ||
    abs($now - (int)$timestamp) > 300 || strlen($signature) > 128) {
    reply(401, 'Authentication failed');
}

const MAX_BODY = 1048576;
if ((int)($_SERVER['CONTENT_LENGTH'] ?? 0) > MAX_BODY) reply(413, 'Body too large');
$raw = file_get_contents('php://input', false, null, 0, MAX_BODY + 1);
if ($raw === false || strlen($raw) > MAX_BODY) reply(413, 'Body too large');

// Sign the ORIGINAL bytes: never decode/re-encode JSON before checking HMAC.
// Base64(HMAC-SHA256(UTF8(secret), UTF8(timestamp + ".") + rawBody)).
$supplied = base64_decode($signature, true);
$expected = hash_hmac('sha256', $timestamp . '.' . $raw, $secret, true);
if ($supplied === false || strlen($supplied) !== 32 || !hash_equals($expected, $supplied)) {
    reply(401, 'Authentication failed');
}

try {
    $data = json_decode($raw, true, 64, JSON_THROW_ON_ERROR);
} catch (JsonException $error) {
    reply(400, 'Invalid JSON');
}
if (!is_array($data) || ($data['schemaVersion'] ?? null) !== 1 ||
    ($data['deviceId'] ?? null) !== $device || ($data['demo'] ?? null) !== false ||
    !is_string($data['eventId'] ?? null) ||
    !preg_match('/\A[A-Za-z0-9._:-]{1,200}\z/', $data['eventId']) ||
    !is_array($data['source'] ?? null) || !is_string($data['source']['packageName'] ?? null) ||
    $data['source']['packageName'] === '' || strlen($data['source']['packageName']) > 255 ||
    !is_array($data['notification'] ?? null) || array_is_list($data['notification'])) {
    reply(400, 'Invalid notification or device mismatch');
}

// A persistent inbox, keyed by device + eventId. Retries are acknowledged without
// storing a second copy. Process these files asynchronously in your automation.
$path = $inbox . '/' . hash('sha256', $device . "\0" . $data['eventId']) . '.json';
$temporary = null;
$lock = null;
$output = null;
$duplicate = false;
$oldMask = umask(0077);
try {
    $lock = @fopen($inbox . '/.lock', 'c');
    if ($lock === false || !flock($lock, LOCK_EX)) throw new RuntimeException();
    $duplicate = is_file($path);
    if (!$duplicate) {
        $temporary = tempnam($inbox, '.pending-');
        if ($temporary === false) throw new RuntimeException();
        $output = fopen($temporary, 'wb');
        if ($output === false) throw new RuntimeException();
        $offset = 0;
        while ($offset < strlen($raw)) {
            $written = fwrite($output, substr($raw, $offset));
            if ($written === false || $written === 0) throw new RuntimeException();
            $offset += $written;
        }
        if (!fflush($output) || !fsync($output)) throw new RuntimeException();
        fclose($output);
        $output = null;
        if (!rename($temporary, $path)) throw new RuntimeException();
        $temporary = null;
    }
} catch (Throwable $error) {
    // A 5xx response asks push2hook to retry; never acknowledge failed storage.
    $failed = true;
} finally {
    if (is_resource($output)) fclose($output);
    if (is_string($temporary) && is_file($temporary)) unlink($temporary);
    if (is_resource($lock)) { flock($lock, LOCK_UN); fclose($lock); }
    umask($oldMask);
}
if (isset($failed)) reply(503, 'Storage unavailable');
reply($duplicate ? 204 : 202);

Python 3.10+, Linux/macOS. Publica application con un servidor WSGI de producción detrás de HTTPS. python3 receiver.py es solo un servidor de desarrollo local.

Descargar código
"""Python 3.10+, Linux/macOS. Expose application through a WSGI server + HTTPS.

Configure PUSH2HOOK_DEVICE_ID, PUSH2HOOK_SECRET (32+ UTF-8 bytes), PUSH2HOOK_INBOX.
The inbox must be an existing private directory, outside your web root.
python3 receiver.py starts a loopback-only DEVELOPMENT server, port 8000.
"""
import base64
import binascii
import fcntl
import hashlib
import hmac
import json
import os
from pathlib import Path
import re
import tempfile
import time
from http import HTTPStatus

MAX_BODY = 1048576


def application(environ, start_response):
    def reply(status, message=""):
        body = json.dumps({"error": message}).encode() if message else b""
        headers = [("Content-Type", "application/json; charset=utf-8"),
                   ("Cache-Control", "no-store"), ("X-Content-Type-Options", "nosniff"),
                   ("Content-Length", str(len(body)))]
        if status == 405:
            headers.append(("Allow", "POST"))
        start_response(f"{status} {HTTPStatus(status).phrase}", headers)
        return [body]

    if environ.get("REQUEST_METHOD") != "POST":
        return reply(405, "POST required")
    if environ.get("CONTENT_TYPE", "").split(";", 1)[0].strip().lower() != "application/json":
        return reply(415, "application/json required")

    device = os.environ.get("PUSH2HOOK_DEVICE_ID", "")
    secret = os.environ.get("PUSH2HOOK_SECRET", "").encode("utf-8")
    inbox = Path(os.environ.get("PUSH2HOOK_INBOX", "."))
    if not device or len(secret) < 32 or not inbox.is_absolute() or not inbox.is_dir():
        return reply(503, "Receiver not configured")

    device_header = environ.get("HTTP_X_DEVICE_ID", "")
    timestamp = environ.get("HTTP_X_TIMESTAMP", "")
    signature = environ.get("HTTP_X_SIGNATURE", "")
    now = int(time.time())
    if (not hmac.compare_digest(device.encode("utf-8"), device_header.encode("utf-8"))
            or not re.fullmatch(r"[0-9]{1,12}", timestamp)
            or abs(now - int(timestamp)) > 300 or len(signature) > 128):
        return reply(401, "Authentication failed")

    length = environ.get("CONTENT_LENGTH", "")
    if not re.fullmatch(r"[0-9]{1,10}", length):
        return reply(411, "Content-Length required")
    length = int(length)
    if length > MAX_BODY:
        return reply(413, "Body too large")
    raw = environ["wsgi.input"].read(length)
    if len(raw) != length:
        return reply(400, "Incomplete body")

    # Verify ORIGINAL bytes; do not decode/re-encode JSON before checking HMAC.
    expected = hmac.digest(secret, timestamp.encode("ascii") + b"." + raw, "sha256")
    try:
        supplied = base64.b64decode(signature, validate=True)
    except (ValueError, binascii.Error):
        return reply(401, "Authentication failed")
    if len(supplied) != 32 or not hmac.compare_digest(expected, supplied):
        return reply(401, "Authentication failed")

    try:
        data = json.loads(raw.decode("utf-8"))
    except (ValueError, UnicodeError, RecursionError):
        return reply(400, "Invalid JSON")
    if (not isinstance(data, dict) or type(data.get("schemaVersion")) is not int
            or data["schemaVersion"] != 1 or data.get("deviceId") != device
            or data.get("demo") is not False or not isinstance(data.get("eventId"), str)
            or not re.fullmatch(r"[A-Za-z0-9._:-]{1,200}", data["eventId"])
            or not isinstance(data.get("source"), dict)
            or not isinstance(data["source"].get("packageName"), str)
            or not 1 <= len(data["source"]["packageName"].encode("utf-8")) <= 255
            or not isinstance(data.get("notification"), dict) or not data["notification"]):
        return reply(400, "Invalid notification or device mismatch")

    # Stable inbox key: acknowledge retries, but never store a second copy.
    key = hashlib.sha256((device + "\0" + data["eventId"]).encode("utf-8")).hexdigest()
    target = inbox / f"{key}.json"
    temporary = None
    try:
        descriptor = os.open(inbox / ".lock", os.O_CREAT | os.O_WRONLY, 0o600)
        with os.fdopen(descriptor, "wb") as lock:
            fcntl.flock(lock, fcntl.LOCK_EX)
            duplicate = target.is_file()
            if not duplicate:
                descriptor, temporary = tempfile.mkstemp(prefix=".pending-", dir=inbox)
                with os.fdopen(descriptor, "wb") as output:
                    output.write(raw)
                    output.flush()
                    os.fsync(output.fileno())
                os.replace(temporary, target)
                temporary = None
    except OSError:
        # 5xx asks push2hook to retry. A failed write must never return success.
        return reply(503, "Storage unavailable")
    finally:
        if temporary is not None:
            Path(temporary).unlink(missing_ok=True)
    return reply(204 if duplicate else 202)


if __name__ == "__main__":
    from wsgiref.simple_server import make_server
    with make_server("127.0.0.1", int(os.environ.get("PORT", "8000")), application) as server:
        server.serve_forever()
Configurar el receptor y sus respuestas

En la app configura tu URL HTTPS, el dispositivo my-phone y un secreto HMAC aleatorio de al menos 32 caracteres. Usa los mismos valores en el proceso del servidor. Emplea un secreto distinto por dispositivo; no es la clave de firma Android.

Variables del servidor (sustituye el secreto; crea una carpeta privada fuera de la raíz web, con permiso de escritura para el receptor):

PUSH2HOOK_DEVICE_ID=my-phone
PUSH2HOOK_SECRET='PASTE_YOUR_RANDOM_SECRET_HERE'
PUSH2HOOK_INBOX=/var/lib/push2hook/inbox

Validaciones: POST y JSON, dispositivo configurado, fecha dentro de ±5 minutos, HMAC-SHA256 en Base64 sobre los bytes originales, comparación de firma en tiempo constante, deviceId del JSON coincidente, esquema y eventId. Sincroniza los relojes del móvil y del servidor.

Un evento válido se guarda en un fichero JSON privado y devuelve 202. Procesa esos ficheros desde tu automatización. La publicación atómica de los ficheros evita guardar duplicados; el mismo dispositivo y eventId devuelve 204. Borrar un fichero también elimina su registro de deduplicación. Aplica tu política de conservación y mantén privada esa carpeta.

La app considera 2xx correcto, reintenta errores 5xx o de red (también 408/429) y marca el resto de 4xx como fallidos. El reenvío manual conserva eventId: estos receptores confirman un evento existente sin procesarlo de nuevo. Nunca ejecutes el texto de una notificación como código ni órdenes de consola.

Ver la demostración en un móvil real

Seis idiomas según el móvil: inglés, español, francés, alemán, portugués e italiano. También puedes elegir el idioma de la app en los ajustes de Android.

¿push2hook recibe mis notificaciones?

Las notificaciones reales van a las URLs HTTPS que configures. La demo opcional envía solo un ejemplo ficticio generado a manuelpeliz.es, con un identificador fijo de demostración.

¿Funciona con la app cerrada?

Salir de la pantalla mantiene la captura. Los permisos, la red, las restricciones de batería y las políticas del dispositivo afectan a los envíos. Forzar detención desde Android para la app.

¿Puedo reenviar una notificación ya entregada?

Sí. Conserva el eventId y el JSON originales. Tu webhook puede deduplicar ese identificador; revisa las reglas del receptor.

¿Es una app para vigilar personas?

Es una herramienta de automatización de tus propias notificaciones. No está diseñada para vigilancia oculta ni para monitorizar a otras personas.