Configurar el webhook
Registra la URL donde te avisamos cuando un comprobante de la empresa queda resuelto.
Autenticación: token Bearer de cuenta (empresas:manage).
Ejemplo
Copiar
curl -X PATCH https://api.xmlperu.dev/v1/companies/20123456789/webhook \
-H "Authorization: Bearer $TOKEN_CUENTA" \
-H "Accept: application/json" \
-H "Content-Type: application/json" \
-d '{
"url": "https://tu-sistema.com/webhooks/cpe"
}'Copiar
<?php
$token_cuenta = 'pega-aqui-tu-token';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://api.xmlperu.dev/v1/companies/20123456789/webhook');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PATCH');
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Authorization: Bearer ' . $token_cuenta,
'Accept: application/json',
'Content-Type: application/json',
]);
curl_setopt($ch, CURLOPT_POSTFIELDS, <<<JSON
{
"url": "https://tu-sistema.com/webhooks/cpe"
}
JSON);
$response = curl_exec($ch);
curl_close($ch);
$data = json_decode($response, true);Copiar
const TOKEN_CUENTA = 'pega-aqui-tu-token';
const res = await fetch('https://api.xmlperu.dev/v1/companies/20123456789/webhook', {
method: 'PATCH',
headers: {
Authorization: `Bearer ${TOKEN_CUENTA}`,
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
"url": "https://tu-sistema.com/webhooks/cpe"
}),
});
const data = await res.json();Copiar
import requests
TOKEN_CUENTA = "pega-aqui-tu-token"
headers = {
"Authorization": f"Bearer {TOKEN_CUENTA}",
"Accept": "application/json",
}
payload = {
"url": "https://tu-sistema.com/webhooks/cpe"
}
res = requests.patch("https://api.xmlperu.dev/v1/companies/20123456789/webhook", json=payload, headers=headers)
data = res.json()Copiar
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
var tokenCuenta = "pega-aqui-tu-token";
using var client = new HttpClient();
using var request = new HttpRequestMessage(HttpMethod.Patch, "https://api.xmlperu.dev/v1/companies/20123456789/webhook");
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", tokenCuenta);
request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var json = """
{
"url": "https://tu-sistema.com/webhooks/cpe"
}
""";
request.Content = new StringContent(json, Encoding.UTF8, "application/json");
using var response = await client.SendAsync(request);
var data = await response.Content.ReadAsStringAsync();Respuesta
200 Configuradoapplication/json
Guarda el
secret ahora: no se vuelve a mostrar.{
"success": true,
"message": "Webhook configurado.",
"data": {
"webhook": {
"url": "https://mi-sistema.com/webhooks/cpe",
"event": "cpe.resolved",
"secret": "a3f19e2c…48 caracteres…",
"note": "Guarda el secret ahora: no se vuelve a mostrar. Cada entrega llega con la cabecera X-Firma = HMAC-SHA256(cuerpo, secret)."
}
}
}200 Desactivadoapplication/json
{
"success": true,
"message": "Webhook desactivado."
}Parámetros
En la URL
| Nombre | Tipo | Descripción |
|---|---|---|
| ruc* | string | RUC de la empresa (11 dígitos). |
En el cuerpo (JSON)
| Nombre | Tipo | Descripción |
|---|---|---|
| url* | string | URL https pública que recibirá los avisos, o `null` para desactivar. |
* Obligatorio.
Ten en cuenta
- Avisamos cuando el comprobante queda aceptado, observado o rechazado. El evento es
cpe.resolved. - El aviso trae el mismo
documentque devuelve GET /v1/cpe/{external_id}. - El
secretse muestra una sola vez. Guárdalo: sirve para verificar la firma de cada aviso. - Verifica siempre la firma (cabecera
X-Firma). - Un aviso puede perderse. Si no llega, consulta el comprobante.
Qué recibe tu servidor
Un POST con estas cabeceras:
POST /webhooks/cpe HTTP/1.1
Content-Type: application/json
X-Event: cpe.resolved
X-Entrega: 9c2f1b7e-… ← id único de esta entrega
X-Firma: 3f2a9c… ← HMAC-SHA256(cuerpo, secret)
Y este cuerpo:
{
"event": "cpe.resolved",
"sent_at": "2026-08-22T15:04:05-05:00",
"ruc": "20123456789",
"document": {
"external_id": "9c2f1b7e-…",
"filename": "20123456789-01-F001-123",
"document_type_id": "01",
"series": "F001",
"number": 123,
"status_code": "09",
"status": "rejected",
"resolved": true,
"ticket": null,
"result": {
"code": "2335",
"message": "El XML no contiene información en el campo Total valor de venta",
"origin": "sunat",
"action": "correct",
"reached_sunat": true
}
}
}
Verificar la firma
Calcula el HMAC-SHA256 del cuerpo tal como llega, antes de convertirlo a
JSON, y compáralo con X-Firma:
const crypto = require('crypto')
function esAutentico(cuerpoCrudo, firmaRecibida, secret) {
const esperada = crypto.createHmac('sha256', secret).update(cuerpoCrudo).digest('hex')
return crypto.timingSafeEqual(Buffer.from(esperada), Buffer.from(firmaRecibida))
}
$esperada = hash_hmac('sha256', $cuerpoCrudo, $secret);
$ok = hash_equals($esperada, $firmaRecibida);
Si la firma no coincide, descarta el aviso.
Recomendaciones
- Responde
2xxenseguida y procesa después. Si tardas más de 10 s, reintentamos. - Acepta avisos repetidos. Un reintento puede llegar cuando ya procesaste el
primero. Usa
X-Entregao elexternal_idpara detectarlo. - No dependas solo del webhook. Si tu servidor estuvo caído durante todos los
reintentos, el aviso se pierde. El comprobante sigue disponible con
GET /v1/cpe/{external_id}.
Errores
422 URL no válidaapplication/json
{
"success": false,
"message": "La URL del webhook debe ser pública: no se aceptan hosts locales ni rangos privados."
}Casos especiales
Solo te afectan si usas esa opción.
- URL. Debe ser
httpsy pública. No se aceptan hosts locales ni redes privadas. - Reintentos. Si tu servidor no responde
2xxen 10 s, reintentamos 5 veces, con esperas de 30 s a 30 min. - Cambiar la URL. Registrar una URL nueva genera un
secretnuevo. - Desactivar. Envía
"url": null. - Muchas empresas. Registra uno solo para toda la cuenta. La empresa que tenga el suyo lo conserva.