Verificar firma
La incluida en cada solicitud firmada contiene una marca de tiempo y una o más firmas. La marca de tiempo va precedida del prefijo t=, y cada firma va precedida de un esquema. Los esquemas comienzan con v, seguido de un número entero. Los esquemas válidos son v1 y v2.
MONEI-Signature: t=1492774577,v1=5257a869e7ecebeda32affa62cdca3fa51cad7e77a0e56ff536d0ce8e108d8bd,v2=1b622e9c31804ad429912b4a8c10bbcd38e1a169158ed34ac27b54b0848623c0
Esquemas de firma
MONEI genera firmas utilizando un código de autenticación de mensajes basado en hash (HMAC) con SHA-256. Cada esquema firma el mismo contenido con un secreto distinto:
| Esquema | Secreto | Cuándo lo incluye la cabecera |
|---|---|---|
v1 | La clave de API por defecto de tu cuenta (pk_live_ o pk_test_). Un webhook de cuenta de una cuenta sin clave de API usa el secreto heredado del destino. | Cuando existe uno de estos secretos |
v2 | Un secreto de firma: el secreto de firma del destino del webhook (whsec_…), o el secreto de firma de la clave de API con permisos limitados (mksec_…) que creó el pago o la suscripción | Webhooks de cuenta de un destino con secreto de firma, y callbacks de pagos y suscripciones que creó una clave con permisos limitados |
La clave del HMAC es la cadena completa del secreto, con su prefijo (pk_, whsec_ o mksec_). No decodifiques el secreto.
Después de renovar el secreto de firma de un destino, la cabecera tiene dos firmas v2 durante 24 horas: primero la del secreto nuevo y después la del antiguo. La firma es válida cuando una de ellas coincide con tu secreto.
La cabecera puede tener más elementos que t y v1, y un elemento puede faltar. No compares la cabecera completa con un patrón estricto como t=…,v1=…. Divide la cabecera y lee cada elemento por su clave.
Para protegerte contra ataques de degradación, comprueba solo el esquema del secreto que tienes. Con un secreto de firma, comprueba v2 y nunca recurras a v1. Con tu clave de API, comprueba v1. Ignora todos los demás esquemas.
MONEI firma v1 con la clave de API por defecto de tu cuenta, también para los pagos que crea una clave de API con permisos limitados. Una clave con permisos limitados (mk_) no puede verificar v1. Para verificar estos callbacks sin la clave de API por defecto, comprueba v2 con el secreto de firma de la clave con permisos limitados.
Un callback no tiene v2 cuando el pago o la suscripción se creó con la clave de API por defecto o en el dashboard, o cuando la clave con permisos limitados que lo creó está revocada. Para verificar cada cambio de estado sin la clave de API por defecto, usa un webhook de cuenta: MONEI lo firma con el secreto de firma del destino, sea cual sea la clave que creó el pago.
Verificación de firmas con nuestras bibliotecas oficiales
Usa una de nuestras bibliotecas oficiales para verificar las firmas. La verificación se realiza proporcionando el payload de la solicitud y la cabecera MONEI-Signature. Si la verificación falla, MONEI devuelve un error.
- Node.js
- PHP
- Python
import express from 'express';
import {Monei, PaymentStatus} from '@monei-js/node-sdk';
// Set your api key. Remember to switch to your live api key in production!
// See your api key here: https://dashboard.monei.com/settings/api
const monei = new Monei('YOUR_API_KEY');
// This example uses Express to receive webhooks
const app = express();
// Endpoint to handle MONEI webhooks
app.post('/checkout/callback', express.raw({type: 'application/json'}), (req, res) => {
const signature = req.headers['monei-signature'];
try {
// Verify the signature using the raw request body and the header
const payment = monei.verifySignature(req.body.toString(), signature);
// Optional: Log the received payment status
console.log(`Webhook received for Payment ID: ${payment.id}, Status: ${payment.status}`);
// Update your order status based on the payment status
if (payment.status === PaymentStatus.SUCCEEDED) {
// Payment successful - fulfill the order
console.log(`Payment ${payment.id} succeeded. Fulfilling order...`);
// Update your database, send confirmation email, etc.
} else if (payment.status === PaymentStatus.FAILED) {
// Payment failed - notify the customer
console.log(`Payment ${payment.id} failed. Notifying customer...`);
// Log the failure, update your database, etc.
} else if (payment.status === PaymentStatus.AUTHORIZED) {
// Payment is authorized but not yet captured
console.log(`Payment ${payment.id} authorized. Capture if needed.`);
// You might want to capture it later using monei.payments.capture()
} else if (payment.status === PaymentStatus.CANCELED) {
// Payment was canceled by the user or system
console.log(`Payment ${payment.id} was canceled.`);
// Update your database accordingly
} else {
// Handle other potential statuses if necessary
console.log(`Unhandled payment status: ${payment.status} for Payment ${payment.id}`);
}
// Acknowledge receipt of the webhook with a 200 OK status
res.status(200).json({received: true});
} catch (error) {
// Handle signature verification failure
console.error('Invalid webhook signature:', error.message);
// Respond with 401 Unauthorized if the signature is invalid
res.status(401).json({error: 'Invalid signature'});
}
});
// Start the server
app.listen(3000, () => {
console.log(`Server listening on port 3000`);
});
<?php
require_once(__DIR__ . '/vendor/autoload.php');
use Monei\Model\PaymentStatus;
use Monei\ApiException;
// Replace YOUR_API_KEY with your actual MONEI API key
$monei = new Monei\MoneiClient('YOUR_API_KEY');
// Parse raw body for signature verification
$rawBody = file_get_contents('php://input');
$signature = $_SERVER['HTTP_MONEI_SIGNATURE'] ?? '';
try {
// Verify the signature
// verifySignature returns the validated Payment object or throws ApiException
$payment = $monei->verifySignature($rawBody, $signature);
// Optional: Log the received payment status
error_log('Webhook received for Payment ID: ' . $payment->getId() . ', Status: ' . $payment->getStatus());
// Update your order status based on the payment status
if ($payment->getStatus() === PaymentStatus::SUCCEEDED) {
// Payment successful - fulfill the order
error_log('Payment ' . $payment->getId() . ' succeeded. Fulfilling order...');
// Update your database, send confirmation email, etc.
} else if ($payment->getStatus() === PaymentStatus::FAILED) {
// Payment failed - notify the customer
error_log('Payment ' . $payment->getId() . ' failed. Notifying customer...');
// Log the failure, update your database, etc.
} else if ($payment->getStatus() === PaymentStatus::AUTHORIZED) {
// Payment is authorized but not yet captured
error_log('Payment ' . $payment->getId() . ' authorized. Capture if needed.');
// You can capture it later using $monei->payments->capture(...)
} else if ($payment->getStatus() === PaymentStatus::CANCELED) {
// Payment was canceled
error_log('Payment ' . $payment->getId() . ' was canceled.');
// Update your database accordingly
} else {
// Handle other potential statuses if necessary
error_log('Unhandled payment status: ' . $payment->getStatus() . ' for Payment ' . $payment->getId());
}
// Acknowledge receipt of the webhook with a 200 OK status
http_response_code(200);
header('Content-Type: application/json'); // Ensure JSON header
echo json_encode(['received' => true]);
} catch (ApiException $e) {
// Handle signature verification failure (ApiException specifically)
error_log('Invalid webhook signature: ' . $e->getMessage());
http_response_code(401); // Respond with 401 Unauthorized
header('Content-Type: application/json'); // Ensure JSON header
echo json_encode(['error' => 'Invalid signature']);
exit(); // Stop script execution after sending error response
} catch (Exception $e) {
// Handle any other unexpected errors during processing
error_log('Webhook processing error: ' . $e->getMessage());
http_response_code(500); // Respond with 500 Internal Server Error
header('Content-Type: application/json');
echo json_encode(['error' => 'Internal server error']);
exit();
}
?>
import os
import Monei
from Monei.exceptions import ApiException
from flask import Flask, request, abort, jsonify
# Replace YOUR_API_KEY with your actual MONEI API key
monei_client = Monei.MoneiClient(api_key="YOUR_API_KEY")
app = Flask(__name__)
# Update route and function name
@app.route('/checkout/callback', methods=['POST'])
def callback():
signature = request.headers.get('MONEI-Signature') # Use correct header key
# Check if signature header exists (optional but good practice)
if not signature:
print("MONEI-Signature header missing")
return jsonify({'error': 'Missing MONEI-Signature header'}), 400
try:
# Verify the signature using raw request data (bytes)
payment = monei_client.verify_signature(request.data, signature)
# Optional: Log the received payment status
payment_id = payment.get('id')
payment_status = payment.get('status')
print(f"Webhook received for Payment ID: {payment_id}, Status: {payment_status}")
# Update your order status based on the payment status
if payment_status == 'SUCCEEDED':
# Payment successful - fulfill the order
print(f"Payment {payment_id} succeeded. Fulfilling order...")
# Update your database, send confirmation email, etc.
pass # Placeholder from user snippet
elif payment_status == 'FAILED':
# Payment failed - notify the customer
print(f"Payment {payment_id} failed. Notifying customer...")
# Log the failure, update your database, etc.
pass # Placeholder from user snippet
elif payment_status == 'AUTHORIZED':
# Payment is authorized but not yet captured
print(f"Payment {payment_id} authorized. Capture if needed.")
# You can capture it later
pass # Placeholder from user snippet
elif payment_status == 'CANCELED':
# Payment was canceled
print(f"Payment {payment_id} was canceled.")
pass # Placeholder from user snippet
else:
print(f"Unhandled payment status: {payment_status} for Payment {payment_id}")
# Acknowledge receipt of the webhook
return jsonify({'received': True}), 200
except ApiException as e: # Invalid or missing signature
print(f"Invalid webhook signature: {e}")
# Return 401 Unauthorized as requested
return jsonify({'error': 'Invalid signature'}), 401
except Exception as e: # Catch other potential errors during processing
print(f"Webhook processing error: {e}")
# Return 500 Internal Server Error for other issues
return jsonify({'error': 'Internal server error'}), 500
if __name__ == '__main__':
app.run(port=3000)
Verificar v2 con un secreto de firma
Las bibliotecas de Node.js, PHP y Python aceptan el secreto de firma como tercer argumento. Cuando das un secreto, la biblioteca comprueba v2 y no usa v1. Sin secreto, la biblioteca comprueba v1 con tu clave de API, como hasta ahora.
- Node.js
- PHP
- Python
// signingSecret is the whsec_… or mksec_… secret from your configuration
const payload = monei.verifySignature(req.body.toString(), signature, signingSecret);
// $signingSecret is the whsec_… or mksec_… secret from your configuration
$payload = $monei->verifySignature($rawBody, $signature, $signingSecret);
# signing_secret is the whsec_… or mksec_… secret from your configuration
payload = monei_client.verify_signature(request.data, signature, signing_secret)
Cuando añades un destino de webhook, MONEI envía una solicitud webhook.test antes de que puedas ver el secreto de firma del destino. Responde a esta solicitud con un estado 2xx, también cuando aún no puedes verificar su firma. No la proceses:
- Node.js
- PHP
- Python
app.post('/webhook', express.raw({type: 'application/json'}), (req, res) => {
const signature = req.headers['monei-signature'];
let payload;
try {
payload = monei.verifySignature(req.body.toString(), signature, signingSecret);
} catch (error) {
let event;
try {
event = JSON.parse(req.body.toString());
} catch {
// The body is not JSON
}
// Acknowledge the test request, but do not process it
res.status(event?.type === 'webhook.test' ? 200 : 401).end();
return;
}
// Process the payload
res.status(200).json({received: true});
});
try {
$payload = $monei->verifySignature($rawBody, $signature, $signingSecret);
} catch (ApiException $e) {
$event = json_decode($rawBody);
// Acknowledge the test request, but do not process it
http_response_code(isset($event->type) && $event->type === 'webhook.test' ? 200 : 401);
exit;
}
import json
from Monei.exceptions import ApiException
@app.route('/webhook', methods=['POST'])
def webhook():
signature = request.headers.get('MONEI-Signature')
try:
payload = monei_client.verify_signature(request.data, signature, signing_secret)
except ApiException:
try:
event = json.loads(request.data)
except ValueError:
event = {} # The body is not JSON
# Acknowledge the test request, but do not process it
return '', 200 if isinstance(event, dict) and event.get('type') == 'webhook.test' else 401
# Process the payload
return {'received': True}, 200
Verificación manual de firmas
Paso 1: Extrae la marca de tiempo y la firma de la cabecera
Divide la cabecera usando el carácter , como separador para obtener una lista de elementos. Luego divide cada elemento usando el carácter = como separador para obtener un par prefijo-valor.
El valor del prefijo t corresponde a la marca de tiempo. v1 corresponde a la firma hecha con tu clave de API. Cada v2 corresponde a una firma hecha con un secreto de firma. Conserva todos los v2: la cabecera puede tener dos. Puedes descartar todos los demás elementos.
Paso 2: Prepara la cadena signed_payload
La cadena signed_payload se crea concatenando:
- La marca de tiempo (como cadena de texto)
- El carácter
. - El payload JSON real (es decir, el cuerpo de la solicitud)
Paso 3: Determina la firma esperada
Calcula un con la función hash SHA256. Usa la cadena signed_payload como mensaje. Como clave, usa la clave de API de tu cuenta para v1, o el secreto de firma para v2. Usa la cadena completa del secreto, con su prefijo, como bytes UTF-8.
Puedes encontrar tu clave API en MONEI Dashboard → Configuración → Acceso a API.
Ves el secreto de firma de un destino de webhook en la página del destino, en MONEI Dashboard → Configuración → Webhooks. MONEI muestra el secreto de firma de una clave con permisos limitados una sola vez, cuando creas la clave.
Paso 4: Compara las firmas
Compara la firma de la cabecera con la firma esperada. Para v2, la firma es válida cuando un v2 de la cabecera coincide. Para una coincidencia exacta, calcula la diferencia entre la marca de tiempo actual y la marca de tiempo recibida, y decide si la diferencia está dentro de tu margen de tolerancia.
Fija ese margen pensando en los reintentos. Un callback de pago se firma una sola vez, así que cada reintento lleva la marca de tiempo original y puede llegar horas después. Los webhooks de cuenta se vuelven a firmar en cada reenvío.
Para protegerte contra ataques de temporización, usa una comparación de cadenas en tiempo constante para comparar la firma esperada con la firma recibida.