This commit is contained in:
53
src/controllers/webhook.controller.ts
Normal file
53
src/controllers/webhook.controller.ts
Normal file
@@ -0,0 +1,53 @@
|
||||
import { Request, Response } from 'express';
|
||||
import { sendToN8n } from '../services/n8n.service';
|
||||
|
||||
export const handleTinyOrderUpdate = async (req: Request, res: Response): Promise<void> => {
|
||||
try {
|
||||
// 1. Security Check: Verify token from Tiny
|
||||
const expectedToken = process.env.TINY_WEBHOOK_SECRET;
|
||||
const providedToken = req.query.token;
|
||||
|
||||
if (expectedToken && providedToken !== expectedToken) {
|
||||
console.warn('Unauthorized webhook attempt. Invalid or missing token.');
|
||||
res.status(401).json({ error: 'Unauthorized' });
|
||||
return;
|
||||
}
|
||||
|
||||
let payload = req.body;
|
||||
|
||||
// Parse 'dados' if it comes as a JSON string
|
||||
if (typeof payload.dados === 'string') {
|
||||
try {
|
||||
payload.dados = JSON.parse(payload.dados);
|
||||
} catch (e) {
|
||||
console.error('Could not parse "dados" as JSON string.', e);
|
||||
}
|
||||
}
|
||||
|
||||
console.log('Received webhook from Tiny:', JSON.stringify(payload, null, 2));
|
||||
|
||||
// Acknowledge Tiny immediately
|
||||
res.status(200).send('OK');
|
||||
|
||||
if (!payload || Object.keys(payload).length === 0) {
|
||||
console.warn('Received empty payload from Tiny webhook.');
|
||||
return;
|
||||
}
|
||||
|
||||
const transformedData = {
|
||||
source: 'tiny_webhook_middleware',
|
||||
event: payload.tipo || 'atualizacao_pedido',
|
||||
dados: payload.dados,
|
||||
raw_payload: payload
|
||||
};
|
||||
|
||||
// Forward to n8n asynchronously
|
||||
await sendToN8n(transformedData);
|
||||
|
||||
} catch (error) {
|
||||
console.error('Error handling Tiny webhook:', error);
|
||||
if (!res.headersSent) {
|
||||
res.status(500).json({ error: 'Internal server error processing webhook.' });
|
||||
}
|
||||
}
|
||||
};
|
||||
Reference in New Issue
Block a user