Updated on November 24, 2026
TOTVS Protheus does not talk to the official WhatsApp Business API directly: a middleware sits between them (your own service or an integration platform) that reads ERP events, sends Meta-approved templates and writes the result back. On the TOTVS side, the bridge is the Protheus REST server, enabled in appserver.ini, with Basic or Bearer token authentication. On the WhatsApp side, it is a template POST and a status webhook.
Below: REST setup according to TDN (the TOTVS developer network), an entry point that feeds an outbox table, a REST service in AdvPL and a worker that sends the template. The general ERP overview is in WhatsApp API ERP integration.
Does TOTVS have its own WhatsApp product?
On the TOTVS website, the “Atendimento e Chatbot” (customer service and chatbot) menu points to RD Atendimento (RD Station Conversas), from RD Station, one of the business units TOTVS lists. According to the product page, it works with the official WhatsApp Business API. In the official pages we checked, we found no native Protheus feature that sends WhatsApp templates from billing or finance events. TOTVS iPaaS, presented as a systems integration tool, can play the middleware role.
Architecture: Protheus, queue and WhatsApp
| Step | Where it runs | What it does |
|---|---|---|
| 1. Event | Protheus (entry point or job) | Writes a row to an outbox table |
| 2. Read | Middleware | Queries the table through Protheus REST |
| 3. Queue | Middleware | Enqueues each send with a unique key |
| 4. Send | Worker | Calls the WhatsApp API with the template |
| 5. Write-back | Worker | Stores the wamid in Protheus through REST |
| 6. Status | Webhook | Receives delivered, read or failed and updates Protheus |
With an outbox table, the ERP only does a local RecLock. Queues, retries and idempotency are covered in WhatsApp API integration architecture.
Want to try it while you read? Create a Vectalk account and send your first message through the official API. Create free account →
Step 1: enable REST in Protheus
The TDN page 01. Configuração (in Portuguese) describes the AdvPL REST server. A minimal appserver.ini:
[GENERAL]
MAXSTRINGSIZE=10
[ONSTART]
JOBS=HTTPJOB
REFRESHRATE=120
[HTTPJOB]
MAIN=HTTP_START
ENVIRONMENT=environment
[HTTPV11]
Enable=1
Sockets=HTTPREST
[HTTPREST]
Port=8080
URIs=HTTPURI
Security=1
[HTTPURI]
URL=/rest
PrepareIn=All
Instances=2,5
What matters from TDN:
MAXSTRINGSIZEwith a minimum value of 10 is required for requests larger than 1 MB.- Since release 12.1.33, services require authentication when the
Securitykey is missing; since the October 2024 release, the key can no longer be changed and authentication is always required. - With
PrepareIn=All, the company group and branch come in thetenantIdheader (e.g.,T1,D MG 01), as described in REST com ERP Microsiga Protheus. - TLS 1.2 and 1.3 are enabled with the
TLS1_2andTLS1_3keys in[HTTPREST].
Step 2: authenticate with a token
Basic auth sends the username and password on every request. The TDN access token API describes the /api/oauth2/v1/token endpoint, with username and password sent as headers:
curl -X POST "https://erp.yourcompany.com:8080/rest/api/oauth2/v1/token?grant_type=password" \
-H "username: whatsapp.integration" \
-H "password: $PROTHEUS_PASS"
The response contains access_token, refresh_token, token_type: "Bearer" and expires_in: 3600. The access token lasts one hour and the refresh token 24 hours; neither can be changed. To renew, call the same endpoint with grant_type=refresh_token&refresh_token=.... Use a dedicated integration user with minimal access.
Step 3: standard APIs or your own service
TOTVS publishes standard APIs in the /api/<segment>/v1/<resource> format. The FAT0321 page documents, for example, /api/crm/v1/customerVendor (customers, table SA1) and /api/fat/v1/carrier (carriers). The TOTVS API implementation guide defines pagination with page and pageSize and responses with items and hasNext.
For WhatsApp, though, you need “what changed and has not been notified yet”. The cleanest path is a custom outbox table and your own REST service.
The M460FIM entry point
According to TDN, M460FIM runs after the outbound invoice is saved (MATA461), outside the transaction, and receives the number, series, customer and store in PARAMIXB. The example writes the row to table ZW1, which you create in the data dictionary (field names are illustrative):
#INCLUDE "PROTHEUS.CH"
User Function M460FIM()
Local aArea := GetArea()
Local cDoc := PARAMIXB[1]
Local cSerie := PARAMIXB[2]
Local cCli := PARAMIXB[3]
Local cLoja := PARAMIXB[4]
DbSelectArea("SA1")
DbSetOrder(1)
If DbSeek(xFilial("SA1") + cCli + cLoja)
RecLock("ZW1", .T.)
ZW1->ZW1_FILIAL := xFilial("ZW1")
ZW1->ZW1_CHAVE := "NF" + cSerie + cDoc
ZW1->ZW1_EVENTO := "NF_EMITIDA"
ZW1->ZW1_NOME := SA1->A1_NOME
ZW1->ZW1_FONE := AllTrim(SA1->A1_DDD) + AllTrim(SA1->A1_TEL)
ZW1->ZW1_STATUS := "P"
MsUnLock()
EndIf
RestArea(aArea)
Return Nil
Other triggers on TDN: M410STTS runs after the sales order changes are saved and receives the operation (3 = insert). MT410TOK is a validation entry point (it can block the save): do not use it to send messages. For invoices about to fall due, a daily job on table SE1 (E1_VENCREA, E1_SALDO) works better than an entry point.
The REST service that exposes the queue
The TDN page Criando uma classe REST shows the WSRESTFUL syntax. A service with a GET for pending rows and a POST to store the result:
#INCLUDE "TOTVS.CH"
#INCLUDE "RESTFUL.CH"
WSRESTFUL waoutbox DESCRIPTION "WhatsApp outbox"
WSMETHOD GET PEND DESCRIPTION "Pending" PATH "/waoutbox"
WSMETHOD POST STAT DESCRIPTION "Send result" PATH "/waoutbox/{chave}"
END WSRESTFUL
WSMETHOD GET PEND WSSERVICE waoutbox
Local cAli := GetNextAlias()
Local cJson := "["
::SetContentType("application/json")
BeginSQL Alias cAli
SELECT ZW1_CHAVE, ZW1_EVENTO, ZW1_NOME, ZW1_FONE
FROM %table:ZW1% ZW1
WHERE ZW1.ZW1_STATUS = 'P' AND ZW1.%notdel%
EndSQL
While (cAli)->(!Eof())
cJson += If(Len(cJson) > 1, ",", "") + '{"chave":"' + AllTrim((cAli)->ZW1_CHAVE) + ;
'","evento":"' + AllTrim((cAli)->ZW1_EVENTO) + ;
'","nome":"' + StrTran(AllTrim((cAli)->ZW1_NOME), '"', '') + ;
'","fone":"' + AllTrim((cAli)->ZW1_FONE) + '"}'
(cAli)->(DbSkip())
EndDo
(cAli)->(DbCloseArea())
::SetResponse(cJson + "]")
Return .T.
WSMETHOD POST STAT WSSERVICE waoutbox
Local jBody := JsonObject():New()
jBody:FromJson(::GetContent())
DbSelectArea("ZW1")
DbSetOrder(1) // ZW1_FILIAL + ZW1_CHAVE
If !DbSeek(xFilial("ZW1") + ::aURLParms[1])
SetRestFault(404, "key not found")
Return .F.
EndIf
RecLock("ZW1", .F.)
ZW1->ZW1_STATUS := jBody:GetJsonText("status")
ZW1->ZW1_WAMID := jBody:GetJsonText("wamid")
MsUnLock()
::SetResponse('{"ok":true}')
Return .T.
A REST class compiled after HTTP_START is only published after the AppServer restarts. For TL++, the page Migração WsRESTful para REST tlppCore shows the same service with the @Get and @Post annotations, oRest:getBodyRequest() and oRest:setResponse().
Step 4: the worker that sends the template
The worker gets the token, reads pending rows, sends the template and returns the wamid. It uses the Vectalk URL; with the Cloud API directly, swap in Meta’s URL.
const PROTHEUS = process.env.PROTHEUS_URL; // e.g. https://erp.yourcompany.com:8080/rest
const sent = new Map(); // in production: Redis or the middleware database
async function protheus(path, opts = {}) {
const r = await fetch(`${PROTHEUS}${path}`, opts);
if (!r.ok) throw new Error(`${path}: ${r.status}`);
return r.json();
}
async function sendTemplate(item) {
const r = await fetch("https://apis.vectalk.com.br/api/messages", {
method: "POST",
headers: { Authorization: `Bearer ${process.env.VECTALK_TOKEN}`, "Content-Type": "application/json" },
body: JSON.stringify({
messaging_product: "whatsapp",
to: "55" + item.fone.replace(/\D/g, ""),
type: "template",
template: {
name: "nf_emitida",
language: { code: "pt_BR" },
components: [{ type: "body", parameters: [item.nome, item.chave.slice(2)].map((text) => ({ type: "text", text })) }],
},
}),
});
return r.json();
}
async function run() {
const { access_token } = await protheus("/api/oauth2/v1/token?grant_type=password", {
method: "POST",
headers: { username: process.env.PROTHEUS_USER, password: process.env.PROTHEUS_PASS },
});
const headers = { Authorization: `Bearer ${access_token}`, tenantId: "T1,D MG 01", "Content-Type": "application/json" };
for (const item of await protheus("/waoutbox", { headers })) {
let wamid = sent.get(item.chave); // already sent: only the ERP write-back is missing
if (!wamid) {
const res = await sendTemplate(item);
wamid = res.messages?.[0]?.id;
if (!wamid) { console.error(item.chave, res.error?.message); continue; }
sent.set(item.chave, wamid);
}
await protheus(`/waoutbox/${item.chave}`, { method: "POST", headers, body: JSON.stringify({ status: "E", wamid }) });
}
}
run();
Production notes:
- Idempotency. The outbox key (
NF+ series + number) is the idempotency key. Store the key andwamidin the middleware database before updating Protheus: if the write-backPOSTfails, the next run does not resend. - Phone numbers. Normalize
A1_DDD+A1_TEL(leading zero, dashes, the extra ninth digit on Brazilian mobiles) and drop anything that does not have 12 or 13 digits including country code55. - Throughput. The Cloud API supports up to 80 messages per second per phone number by default and returns error
130429above that (throughput). - Retries. 5xx and network errors go back to the queue with growing backoff; an invalid template or number becomes status
Fin Protheus.
Variables and buttons: how to send a WhatsApp template message via the API.
Step 5: status webhook back to Protheus
The sent, delivered, read or failed status arrives at the webhook with the same wamid returned at send time. The middleware finds the key by wamid and calls POST /waoutbox/{chave}. Meta retries failed webhook deliveries for up to 7 days and warns this can produce duplicate notifications, according to the webhooks overview: return 200 quickly, process later and ignore repeated statuses. See WhatsApp API webhooks and how to handle duplicate webhooks. To track delivery rate per event, see how to monitor deliveries.
Use cases in Protheus
| Event | Trigger | Template (likely category) |
|---|---|---|
| Outbound invoice (NF) issued | M460FIM | “Hi {{1}}. Your invoice {{2}} has been issued” (utility) |
| Sales order created | M410STTS with operation 3 | Order confirmation (utility) |
| Invoice about to fall due | Daily job on SE1 | Reminder of the customer’s own invoice (utility) |
| Sales rep alert | M410STTS | Internal alert with the order number (utility) |
Payment reminders only for the customer’s own invoices: the WhatsApp Business Messaging Policy prohibits collecting third-party debt. To design the reminder sequence, see WhatsApp billing reminders. Meta sets the category at approval, and a notice mixed with an offer becomes marketing, per template categorization.
How much it costs
In Meta’s rate card for Brazilian numbers in effect since October 1, 2026, utility costs BRL 0.0350 per message and marketing BRL 0.3217. Since that date, utility templates are charged even inside the customer service window and do not count toward the free tier of 1,000 service messages per month per number. Example: 3,000 invoices a month with one notice each is BRL 105.00 in Meta fees, if all are delivered. Run your numbers in the WhatsApp API pricing calculator and check the rules on Meta’s pricing page.
How to do this with Vectalk
Vectalk is a proxy for Meta’s official Cloud API: the worker calls POST https://apis.vectalk.com.br/api/messages with the same template JSON as Meta (send template docs) and your endpoint receives the same Meta webhooks (webhook docs). In the dashboard you create templates (there is a Template Library), generate API keys and check logs. Billing is prepaid: each delivered message is deducted from your balance, and you do not add a card with Meta.
Vectalk has no native inbox, bulk sending or AI, and no ready-made Protheus connector: the integration is the middleware described here. The foundation: official WhatsApp API guide. Sign up at apps.vectalk.com.br/register. Another ERP: Conta Azul + WhatsApp.
Frequently asked questions
Can I call the WhatsApp API directly from AdvPL?
Yes, with an AdvPL HTTP client, but errors, retries and network waits then run inside the ERP. With an outbox table, sending happens outside.
Should I use Basic or Bearer on Protheus REST?
TDN recommends Bearer: the username and password only travel in the call to /api/oauth2/v1/token. The token lasts one hour and is renewed with the refresh_token, which lasts 24 hours.
Protheus is on the internal network. Will the webhook work?
The webhook reaches the middleware, which needs a public HTTPS address. Protheus REST can stay reachable only by the middleware, through a VPN or an IP allowlist.
Official sources checked on November 24, 2026: TDN: REST configuration, TDN: REST with ERP Microsiga Protheus, TDN: access token, TDN: creating a REST class, TDN: WsRESTful to tlppCore REST migration, TDN: FAT0321, TDN: M460FIM, TDN: M410STTS, TOTVS iPaaS, RD Atendimento, Webhooks (Meta), Throughput (Meta), Template categorization (Meta), Pricing (Meta), WhatsApp Business Messaging Policy, Vectalk documentation.
Put your business on the official WhatsApp
Create your account, connect your number to the official API (you can keep the app with coexistence) and start serving customers and sending messages.
