SDK and n8n
The Luna API is plain HTTP with an OpenAPI specification, and you can call it from any language and any tool. In n8n, the path that works today uses only the standard nodes: a Webhook to receive, a Code to check the signature and an HTTP Request to send. The Node/TypeScript SDK and the dedicated n8n node are in preparation.
The API reference is the contract. The tools have no business rules: the 24-hour window, the plan capacity and the approved template are checked by the API, which answers with the reason.
n8n today: the standard nodes#
A workflow of four pieces, all built into n8n: the Webhook receives Luna’s event (with the raw body), the Code checks the signature, the Respond to Webhook returns 200 or 401, and the HTTP Request sends the reply through the API. You need an API key with messages:write and the origin number (metaPhoneNumberId, from GET /v1/numbers).
1. The Webhook node#
- HTTP Method:
POST. Path:luna(or whatever you prefer). - Respond: “Using ‘Respond to Webhook’ Node”. It is what lets you answer
401to a signature that does not match. - In Options, turn on Raw Body. This is the step that usually gets missed: the signature is calculated over the exact bytes of the body, and without that option n8n hands over the JSON already parsed and the calculation does not match. With it, the body arrives as binary data in the
dataproperty. - Activate the workflow and copy the Production URL. Register it as a Luna endpoint (
POST /v1/webhooks/endpoints, as in Quickstart) and keep the response’ssecret: it appears only once. n8n’s test URL does not work, because it only lives while you listen in the editor.
2. The Code node: check the signature#
Mode Run Once for All Items, JavaScript language. The code does the check that Receive events explains in words, and returns valid (true or false) and, if it holds, the event already parsed. Swap SECRET for the secret from the previous step.
const crypto = require('crypto');
const SECRET = 'whsec_PASTE_YOUR_SECRET_HERE'; // paste your endpoint secret here (whsec_...). In production, keep it in a credential or a variable.
const TOLERANCE_SECONDS = 300;
const header = $input.first().json.headers['x-luna-signature'] ?? ''; // the signature header (the Webhook node lowercases header names)
const raw = await this.helpers.getBinaryDataBuffer(0, 'data'); // the exact bytes that arrived: the Webhook node needs the Raw Body option on
const m = /^t=(\d{1,15}),/.exec(header);
if (!m) return [{ json: { valid: false } }];
const t = Number(m[1]);
// refuse what is too old (a captured delivery replayed later)
if (Math.abs(Math.floor(Date.now() / 1000) - t) > TOLERANCE_SECONDS) {
return [{ json: { valid: false } }];
}
// redo the calculation with your secret and compare it with each v1
const expected = crypto.createHmac('sha256', SECRET).update(t + '.').update(raw).digest();
let valid = false;
// during a secret rotation the header carries two v1 values: check them all
for (const [, hex] of header.matchAll(/v1=([0-9a-fA-F]{64})/g)) {
if (crypto.timingSafeEqual(Buffer.from(hex, 'hex'), expected)) valid = true;
}
// the next node reads valid and, if it is true, the event
return [{ json: { valid, event: valid ? JSON.parse(raw.toString('utf8')) : null } }];3. The HTTP Request node: send the reply#
After an “IF” node that lets through only what has valid true, and another that filters event.event_type equal to message.received, the HTTP Request calls the API:
| Field | Value |
|---|---|
| Method | POST |
| URL | https://api.lunahia.com.br/v1/messages |
Authorization header | Bearer hlsn_... (your key; in n8n, prefer a “Header Auth” credential) |
Idempotency-Key header | resp- followed by the received message’s id: with it, repeating the run does not send two replies |
| Body (JSON) | from (your number), to (the event’s wa_id) and text.body |
A ready-made workflow to import#
The JSON below is the whole workflow: Webhook, Code, IF, the two answers, the received-message filter and the HTTP Request. Copy it, and in n8n paste it on the canvas (Ctrl+V or Cmd+V) or use Import from File. Then swap the three PASTE_... values: the secret in the Code node, and the API key and the number in the HTTP Request.
{
"name": "Luna: reply to a received message",
"nodes": [
{
"parameters": {
"httpMethod": "POST",
"path": "luna",
"responseMode": "responseNode",
"options": {
"rawBody": true
}
},
"id": "5b0c1c1e-2f3a-4b5c-8d6e-7f8091a2b3c1",
"name": "Luna webhook",
"type": "n8n-nodes-base.webhook",
"typeVersion": 2,
"position": [
0,
300
],
"webhookId": "9d8c7b6a-5e4f-4a3b-9c2d-1e0f9a8b7c6d"
},
{
"parameters": {
"jsCode": "const crypto = require('crypto');\n\nconst SECRET = 'whsec_PASTE_YOUR_SECRET_HERE'; // paste your endpoint secret here (whsec_...). In production, keep it in a credential or a variable.\nconst TOLERANCE_SECONDS = 300;\n\nconst header = $input.first().json.headers['x-luna-signature'] ?? ''; // the signature header (the Webhook node lowercases header names)\nconst raw = await this.helpers.getBinaryDataBuffer(0, 'data'); // the exact bytes that arrived: the Webhook node needs the Raw Body option on\n\nconst m = /^t=(\\d{1,15}),/.exec(header);\nif (!m) return [{ json: { valid: false } }];\nconst t = Number(m[1]);\n\n// refuse what is too old (a captured delivery replayed later)\nif (Math.abs(Math.floor(Date.now() / 1000) - t) > TOLERANCE_SECONDS) {\n return [{ json: { valid: false } }];\n}\n\n// redo the calculation with your secret and compare it with each v1\nconst expected = crypto.createHmac('sha256', SECRET).update(t + '.').update(raw).digest();\nlet valid = false;\n// during a secret rotation the header carries two v1 values: check them all\nfor (const [, hex] of header.matchAll(/v1=([0-9a-fA-F]{64})/g)) {\n if (crypto.timingSafeEqual(Buffer.from(hex, 'hex'), expected)) valid = true;\n}\n\n// the next node reads valid and, if it is true, the event\nreturn [{ json: { valid, event: valid ? JSON.parse(raw.toString('utf8')) : null } }];"
},
"id": "6c1d2d2f-3a4b-4c5d-9e7f-8a9102b3c4d2",
"name": "Verify the signature",
"type": "n8n-nodes-base.code",
"typeVersion": 2,
"position": [
240,
300
]
},
{
"parameters": {
"conditions": {
"options": {
"caseSensitive": true,
"leftValue": "",
"typeValidation": "strict",
"version": 2
},
"conditions": [
{
"id": "a1b2c3d4-0001-4000-8000-000000000001",
"leftValue": "={{ $json.valid }}",
"rightValue": "",
"operator": {
"type": "boolean",
"operation": "true",
"singleValue": true
}
}
],
"combinator": "and"
},
"options": {}
},
"id": "7d2e3e30-4b5c-4d6e-8f80-9b0213c4d5e3",
"name": "Valid signature?",
"type": "n8n-nodes-base.if",
"typeVersion": 2.2,
"position": [
480,
300
]
},
{
"parameters": {
"respondWith": "noData",
"options": {
"responseCode": 200
}
},
"id": "8e3f4f41-5c6d-4e7f-9091-ac1324d5e6f4",
"name": "Answer 200",
"type": "n8n-nodes-base.respondToWebhook",
"typeVersion": 1.1,
"position": [
720,
200
]
},
{
"parameters": {
"respondWith": "noData",
"options": {
"responseCode": 401
}
},
"id": "9f405052-6d7e-4f80-a1a2-bd2435e6f705",
"name": "Answer 401",
"type": "n8n-nodes-base.respondToWebhook",
"typeVersion": 1.1,
"position": [
720,
420
]
},
{
"parameters": {
"conditions": {
"options": {
"caseSensitive": true,
"leftValue": "",
"typeValidation": "strict",
"version": 2
},
"conditions": [
{
"id": "a1b2c3d4-0002-4000-8000-000000000002",
"leftValue": "={{ $('Verify the signature').item.json.event.event_type === 'message.received' }}",
"rightValue": "",
"operator": {
"type": "boolean",
"operation": "true",
"singleValue": true
}
}
],
"combinator": "and"
},
"options": {}
},
"id": "a0516163-7e8f-4091-b2b3-ce3546f70816",
"name": "Is it a received message?",
"type": "n8n-nodes-base.if",
"typeVersion": 2.2,
"position": [
960,
200
]
},
{
"parameters": {
"method": "POST",
"url": "https://api.lunahia.com.br/v1/messages",
"sendHeaders": true,
"headerParameters": {
"parameters": [
{
"name": "Authorization",
"value": "Bearer hlsn_PASTE_YOUR_KEY_HERE"
},
{
"name": "Idempotency-Key",
"value": "=resp-{{ $('Verify the signature').item.json.event.message.id }}"
}
]
},
"sendBody": true,
"specifyBody": "json",
"jsonBody": "={{ JSON.stringify({ from: 'PASTE_YOUR_NUMBER_ID_HERE', to: $('Verify the signature').item.json.event.message.wa_id, text: { body: 'Got: ' + $('Verify the signature').item.json.event.message.text } }) }}",
"options": {}
},
"id": "b1627274-8f90-4102-83c4-df4657081927",
"name": "Send the reply",
"type": "n8n-nodes-base.httpRequest",
"typeVersion": 4.2,
"position": [
1200,
100
]
}
],
"connections": {
"Luna webhook": {
"main": [
[
{
"node": "Verify the signature",
"type": "main",
"index": 0
}
]
]
},
"Verify the signature": {
"main": [
[
{
"node": "Valid signature?",
"type": "main",
"index": 0
}
]
]
},
"Valid signature?": {
"main": [
[
{
"node": "Answer 200",
"type": "main",
"index": 0
}
],
[
{
"node": "Answer 401",
"type": "main",
"index": 0
}
]
]
},
"Answer 200": {
"main": [
[
{
"node": "Is it a received message?",
"type": "main",
"index": 0
}
]
]
},
"Is it a received message?": {
"main": [
[
{
"node": "Send the reply",
"type": "main",
"index": 0
}
]
]
}
},
"pinData": {},
"settings": {
"executionOrder": "v1"
}
}To build and test the workflow without sending a real message, use a test key in the HTTP Request: the send does not go to Meta, and Luna delivers the sent, delivered and read states to your webhook with test: true. See Test mode. An AI agent that replies with a model in the middle of the workflow follows the loop in AI agent.
Coming: the SDK and the dedicated node#
Node/TypeScript SDK#
The SDK is the typed client generated from the specification, with three additions: the production URL as default (criarLuna), error handling (exigir returns the body of a good response and throws LunaErro on a refusal, with status, codigo and docsUrl) and webhook signature verification. Every path and verb comes from the specification, so a route the API does not serve is a compile error.
import { criarLuna, exigir } from '@helsen/sdk';
const luna = criarLuna({ apiKey: process.env.LUNA_API_KEY });
const envio = exigir(
await luna.POST('/v1/messages', {
body: { from: '1000000000000001', to: '5511900000000', type: 'text', text: { body: 'Olá!' } },
}),
);
console.log(envio.id, envio.status);Check the webhook signature#
lerEvento checks the signature (x-luna-signature) over the exact bytes of the body and only then reads the JSON, returning the event typed by event_type. With a signature that does not match, it throws AssinaturaInvalida, and the body is not read. verificarAssinatura only returns true or false. During secret rotation, pass a list with the new and the old one. It is the same code Luna uses to sign, so the result agrees with the reference verifier in Receive events.
import express from 'express';
import { lerEvento, AssinaturaInvalida, CABECALHO_DA_ASSINATURA } from '@helsen/sdk';
const app = express();
// O corpo precisa chegar como bytes, sem passar por express.json() antes.
app.post('/luna', express.raw({ type: 'application/json' }), (req, res) => {
try {
const evento = lerEvento(req.body, req.headers[CABECALHO_DA_ASSINATURA], process.env.LUNA_WEBHOOK_SECRET);
if (evento.event_type === 'message.received') console.log(evento.message.text);
res.sendStatus(200);
} catch (erro) {
if (erro instanceof AssinaturaInvalida) return res.sendStatus(401);
throw erro;
}
});An event with test: true is a test event. See Test mode.
n8n node#
The package brings one credential and two nodes. The Luna API credential holds the key (hlsn_...) and the API URL, and its test button reads GET /v1/numbers, so the key needs the numbers:read scope. The Luna node sends text, sends a template and lists the numbers. The Luna Trigger starts the workflow when Luna delivers an event.
Send a message#
- Create the credential with your API key.
- In the Luna node, choose Message and Send Text, or Send Template. Fill in the origin number (the
metaPhoneNumberIdthat List Numbers returns), the recipient phone (digits only) and the content. - The output is the API’s
202, with the messageid. If the API refuses (for example409, text outside the 24-hour window), the node fails with its response; with "Continue on fail" on, the error becomes an item.
Receive events in n8n#
- Activate the workflow and copy the production URL of the Luna Trigger webhook.
- Register that URL as a Luna endpoint (
POST /v1/webhooks/endpoints). The response carries the secret once. - Paste the secret in the node’s "Signing Secret" field.
The node checks the signature over the exact bytes of the body and answers 401, without running the workflow, when it does not match. It does not register the endpoint by itself. You can filter by event type (comma separated, empty means all) and drop events with test: true.
Build the workflow without sending a real message#
Use a test key in the n8n credential, or in the SDK. Sending does not go to Meta, and Luna delivers the sent, delivered and read states to your webhook, with test: true. The n8n credential test button reads GET /v1/numbers and a test key does not pass it, but the send operations work. The Test mode guide explains it all.