Webhooks
Verificação de assinatura
Verificação do HMAC em Node, Python, PHP e Go.
Todo webhook do PagPay é assinado. Verifique a assinatura antes de processar o evento: sem isso, qualquer pessoa que descubra a sua URL poderia enviar eventos falsos.
Como verificar
O header X-PagPay-Signature vem assim:
X-PagPay-Signature: sha256=<hex>
<hex> é o HMAC-SHA256 (hexadecimal minúsculo) do corpo bruto da requisição, com o seu webhook_signing_secret (whsec_..., no painel do PagPay) como chave. Ele é diferente da sua secret key da API.
- Leia o corpo bruto, antes de qualquer parse de JSON.
- Calcule
sha256=mais o HMAC-SHA256 hexadecimal do corpo. - Compare com o header em tempo constante (
crypto.timingSafeEqualno Node,hmac.compare_digestno Python,hash_equalsno PHP,hmac.Equalno Go). - Se for diferente, responda
401e não processe. - Se for igual, deduplique por
event_ide processe.
Cuidados
- Use o corpo bruto. Se você faz parse do JSON e serializa de novo, a ordem das chaves e os espaços mudam e o HMAC não bate. No Express, use
express.rawna rota do webhook (nãoexpress.json()); no Flask,request.get_data(); no PHP,file_get_contents('php://input'); no Go,io.ReadAll(r.Body). - Rotação do segredo. Ao rotacionar no painel do PagPay, o segredo antigo deixa de valer, inclusive para retries de eventos antigos. Atualize o servidor logo em seguida. Eventos recusados nesse intervalo entram no retry.
- Nunca coloque o segredo no front-end, em repositório ou em log.
Vetor de teste
Use para validar a sua implementação.
- Segredo:
whsec_test_secret_do_not_use - Corpo (324 bytes, uma linha, sem quebra no final):
{"data": {"id": "0b6f2f0e-6d0a-4c53-9d2e-3a1f6c9d7a10", "fee": 99, "amount": 10000, "status": "completed", "net_amount": 9901, "external_id": "pedido-1042", "completed_at": "2026-11-27T14:03:21.000Z"}, "type": "deposit.completed", "event_id": "7c9e6679-7425-40de-944b-e07fc1f90ae7", "created_at": "2026-11-27T14:03:21.482Z"}
- Assinatura esperada (valor do header):
sha256=92029aaf9f0b1af39a6b6ff9c823e9aa14f890641f1951a1b6b1bdf8d09eb3d8
Com o corpo e o header exatos acima, aceite. Com um byte alterado, sem o prefixo sha256= ou com o header ausente, rejeite (401).
Exemplos completos
Cada exemplo verifica a assinatura, deduplica por event_id e responde 200. A deduplicação usa memória só para simplificar: em produção, grave o event_id em uma tabela com restrição de unicidade. O segredo vem de PAGPAY_WEBHOOK_SECRET.
- Node.js (Express)
- Python (Flask)
- PHP
- Go (net/http)
import crypto from "node:crypto";
import express from "express";
const SECRET = process.env.PAGPAY_WEBHOOK_SECRET; // whsec_...
const processed = new Set(); // em produção: tabela com UNIQUE(event_id)
function isValidSignature(rawBody, header) {
if (typeof header !== "string" || !header.startsWith("sha256=")) return false;
const expected = crypto.createHmac("sha256", SECRET).update(rawBody).digest();
const received = Buffer.from(header.slice("sha256=".length), "hex");
// timingSafeEqual exige tamanhos iguais
return (
received.length === expected.length &&
crypto.timingSafeEqual(expected, received)
);
}
const app = express();
// express.raw entrega req.body como Buffer, com os bytes exatos recebidos.
app.post(
"/webhooks/pagpay",
express.raw({ type: "application/json", limit: "1mb" }),
(req, res) => {
if (!isValidSignature(req.body, req.get("X-PagPay-Signature"))) {
return res.status(401).json({ error: "invalid_signature" });
}
const event = JSON.parse(req.body.toString("utf8"));
if (processed.has(event.event_id)) {
return res.sendStatus(200); // duplicado: já tratado
}
processed.add(event.event_id);
// Enfileire o trabalho e responda rápido.
console.log("evento", event.type, event.event_id);
res.sendStatus(200);
},
);
app.listen(3000);
import hashlib
import hmac
import json
import os
from flask import Flask, request
SECRET = os.environ["PAGPAY_WEBHOOK_SECRET"].encode() # whsec_...
processed = set() # em produção: tabela com UNIQUE(event_id)
app = Flask(__name__)
def is_valid_signature(raw_body: bytes, header: str) -> bool:
if not header or not header.startswith("sha256="):
return False
expected = "sha256=" + hmac.new(SECRET, raw_body, hashlib.sha256).hexdigest()
return hmac.compare_digest(expected, header)
@app.post("/webhooks/pagpay")
def pagpay_webhook():
raw_body = request.get_data() # bytes exatos, antes de qualquer parse
if not is_valid_signature(raw_body, request.headers.get("X-PagPay-Signature", "")):
return {"error": "invalid_signature"}, 401
event = json.loads(raw_body)
if event["event_id"] in processed:
return "", 200 # duplicado: já tratado
processed.add(event["event_id"])
# Enfileire o trabalho e responda rápido.
print("evento", event["type"], event["event_id"])
return "", 200
<?php
// Ponto de entrada: POST /webhooks/pagpay
$secret = getenv('PAGPAY_WEBHOOK_SECRET'); // whsec_...
$rawBody = file_get_contents('php://input'); // bytes exatos
$header = isset($_SERVER['HTTP_X_PAGPAY_SIGNATURE']) ? $_SERVER['HTTP_X_PAGPAY_SIGNATURE'] : '';
$expected = 'sha256=' . hash_hmac('sha256', $rawBody, $secret);
if (!hash_equals($expected, $header)) {
http_response_code(401);
echo json_encode(array('error' => 'invalid_signature'));
exit;
}
$event = json_decode($rawBody, true);
// Deduplicação: em produção, INSERT em tabela com UNIQUE(event_id).
$store = sys_get_temp_dir() . '/pagpay_event_' . md5($event['event_id']);
if (file_exists($store)) {
http_response_code(200); // duplicado: já tratado
exit;
}
touch($store);
// Enfileire o trabalho e responda rápido.
error_log('evento ' . $event['type'] . ' ' . $event['event_id']);
http_response_code(200);
package main
import (
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"io"
"log"
"net/http"
"os"
"strings"
"sync"
)
var (
secret = []byte(os.Getenv("PAGPAY_WEBHOOK_SECRET")) // whsec_...
mu sync.Mutex
processed = map[string]bool{} // em produção: tabela com UNIQUE(event_id)
)
func validSignature(body []byte, header string) bool {
encoded, ok := strings.CutPrefix(header, "sha256=")
if !ok {
return false
}
received, err := hex.DecodeString(encoded)
if err != nil {
return false
}
mac := hmac.New(sha256.New, secret)
mac.Write(body)
return hmac.Equal(mac.Sum(nil), received) // tempo constante
}
func handler(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
return
}
body, err := io.ReadAll(http.MaxBytesReader(w, r.Body, 1<<20)) // bytes exatos
if err != nil {
http.Error(w, "bad request", http.StatusBadRequest)
return
}
if !validSignature(body, r.Header.Get("X-PagPay-Signature")) {
http.Error(w, `{"error":"invalid_signature"}`, http.StatusUnauthorized)
return
}
var event struct {
EventID string `json:"event_id"`
Type string `json:"type"`
}
if err := json.Unmarshal(body, &event); err != nil {
http.Error(w, "bad request", http.StatusBadRequest)
return
}
mu.Lock()
duplicate := processed[event.EventID]
processed[event.EventID] = true
mu.Unlock()
if duplicate {
w.WriteHeader(http.StatusOK) // duplicado: já tratado
return
}
// Enfileire o trabalho e responda rápido.
log.Printf("evento %s %s", event.Type, event.EventID)
w.WriteHeader(http.StatusOK)
}
func main() {
http.HandleFunc("/webhooks/pagpay", handler)
log.Fatal(http.ListenAndServe(":3000", nil))
}
Resumo
Corpo bruto, comparação em tempo constante, 401 se a assinatura for inválida, deduplicação por event_id e resposta 2xx rápida (Webhooks).