Skip to content

GOWA - WhatsApp REST API with support for UI, Multi Account, Webhooks, and MCP, and Chatwoot. Built with Golang for efficient memory use.

feat(api): add session_id to webhooks and jid to app responses (#578) (#717)

Aldino Kemal1316f706e614
diff --git a/docs/openapi.yaml b/docs/openapi.yaml
index cc88797f..ee870b1a 100644
--- a/docs/openapi.yaml
+++ b/docs/openapi.yaml
@@ -183,7 +183,11 @@ paths:
description: Whether the device is logged in to WhatsApp
device_id:
type: string
- description: The device ID
+ description: Session ID registered via POST /devices
+ example: 'org_2'
+ jid:
+ type: string
+ description: WhatsApp JID of the logged-in account (empty until login)
example: '[email protected]'
'400':
description: Bad Request
@@ -3659,7 +3663,12 @@ components:
example: 'Aldino Kemal'
device:
type: string
- example: '628960561XXX.0:[email protected]'
+ description: Session ID registered via POST /devices (stable across restarts)
+ example: 'org_2'
+ jid:
+ type: string
+ description: WhatsApp JID of the logged-in account (empty until login)
+ example: '[email protected]'
# Device Management Schemas (v8)
DeviceListResponse:
diff --git a/docs/webhook-payload.md b/docs/webhook-payload.md
index dd0cac22..3b6c1b0f 100644
--- a/docs/webhook-payload.md
+++ b/docs/webhook-payload.md
@@ -129,6 +129,7 @@ All webhook payloads follow a consistent top-level structure:
{
"event": "message",
"device_id": "[email protected]",
+ "session_id": "org_2",
"payload": {
// Event-specific fields
}
@@ -137,11 +138,12 @@ All webhook payloads follow a consistent top-level structure:
### Top-Level Fields
-| **Field** | **Type** | **Description** |
-|-------------|----------|---------------------------------------------------------------------------------------------------------------------|
-| `event` | string | Event type: `message`, `message.reaction`, `message.revoked`, `message.edited`, `message.ack`, `message.deleted`, `chat_presence`, `group.participants`, `group.joined`, `newsletter.joined`, `newsletter.left`, `newsletter.message`, `newsletter.mute`, `call.offer` |
-| `device_id` | string | JID of the device that received this event (e.g., `[email protected]`) |
-| `payload` | object | Event-specific payload data |
+| **Field** | **Type** | **Description** |
+|--------------|----------|---------------------------------------------------------------------------------------------------------------------|
+| `event` | string | Event type: `message`, `message.reaction`, `message.revoked`, `message.edited`, `message.ack`, `message.deleted`, `chat_presence`, `group.participants`, `group.joined`, `newsletter.joined`, `newsletter.left`, `newsletter.message`, `newsletter.mute`, `call.offer` |
+| `device_id` | string | JID of the device that received this event (e.g., `[email protected]`) |
+| `session_id` | string | Session ID registered via `POST /devices` (e.g., `org_2`), for correlating the event back to a tenant. Omitted when the JID can't be mapped to a session. |
+| `payload` | object | Event-specific payload data |
### Common Payload Fields
diff --git a/src/domains/app/app.go b/src/domains/app/app.go
index 41178fb1..4854a9ee 100644
--- a/src/domains/app/app.go
+++ b/src/domains/app/app.go
@@ -18,6 +18,7 @@ type IAppUsecase interface {
type DevicesResponse struct {
Name string `json:"name"`
Device string `json:"device"`
+ JID string `json:"jid"`
}
type LoginResponse struct {
diff --git a/src/infrastructure/whatsapp/webhook_forward.go b/src/infrastructure/whatsapp/webhook_forward.go
index fdbb4bb4..1dcbdfe0 100644
--- a/src/infrastructure/whatsapp/webhook_forward.go
+++ b/src/infrastructure/whatsapp/webhook_forward.go
@@ -24,6 +24,10 @@ var (
// 1:1 JID from the WhatsApp contact store. It is a seam so tests can stub
// the lookup without a real client/store.
contactDisplayNameFn = lookupContactDisplayName
+ // sessionIDForJIDFn resolves the operator-facing session id (the device_id
+ // registered via POST /devices, e.g. "org_2") for a connected WhatsApp JID.
+ // It is a seam so tests can stub the device-manager lookup.
+ sessionIDForJIDFn = sessionIDForJID
)
// mutexShardCount is the number of mutex shards for contact synchronization.
@@ -89,6 +93,15 @@ func forwardPayloadToConfiguredWebhooks(ctx context.Context, payload map[string]
return nil
}
+ // Enrich the payload with the operator-facing session id so multi-tenant
+ // consumers can correlate a webhook (whose device_id is the WhatsApp JID)
+ // back to the session id they registered via POST /devices. Done here,
+ // synchronously, before the Chatwoot goroutine is spawned below, so the
+ // shared payload map is never mutated concurrently.
+ if webhookAllowed {
+ addWebhookSessionID(payload)
+ }
+
var err error
if webhookAllowed {
err = forwardToWebhooks(ctx, payload, eventName)
@@ -103,6 +116,41 @@ func forwardPayloadToConfiguredWebhooks(ctx context.Context, payload map[string]
return err
}
+// addWebhookSessionID injects the operator-facing session id into a webhook
+// payload, derived from its device_id (the WhatsApp JID). It is a no-op when the
+// JID can't be mapped to a session (single-session deployments before login, or
+// JIDs not tracked by the device manager) or when session_id is already present,
+// keeping the change backward-compatible: device_id stays the JID.
+func addWebhookSessionID(payload map[string]any) {
+ if payload == nil {
+ return
+ }
+ if _, exists := payload["session_id"]; exists {
+ return
+ }
+ jid, _ := payload["device_id"].(string)
+ if sessionID := sessionIDForJIDFn(jid); sessionID != "" {
+ payload["session_id"] = sessionID
+ }
+}
+
+// sessionIDForJID resolves the session id registered via POST /devices for a
+// connected WhatsApp JID, using the global device manager. Returns "" when no
+// manager or matching instance is available.
+func sessionIDForJID(jid string) string {
+ if jid == "" {
+ return ""
+ }
+ dm := GetDeviceManager()
+ if dm == nil {
+ return ""
+ }
+ if inst, ok := dm.getDeviceByJID(jid); ok && inst != nil {
+ return inst.ID()
+ }
+ return ""
+}
+
func forwardToWebhooks(ctx context.Context, payload map[string]any, eventName string) error {
total := len(config.WhatsappWebhook)
logrus.Infof("Forwarding %s to %d configured webhook(s)", eventName, total)
diff --git a/src/infrastructure/whatsapp/webhook_forward_test.go b/src/infrastructure/whatsapp/webhook_forward_test.go
index e468a05c..8830b1f4 100644
--- a/src/infrastructure/whatsapp/webhook_forward_test.go
+++ b/src/infrastructure/whatsapp/webhook_forward_test.go
@@ -292,3 +292,93 @@ func TestExtractStructuredMessageContentWithContactsArrayPayload(t *testing.T) {
t.Fatalf("extractStructuredMessageContent() = %q, want %q", got, want)
}
}
+
+// TestAddWebhookSessionID pins the issue #578 enrichment: webhook payloads gain a
+// session_id derived from their device_id (JID) so multi-tenant consumers can map
+// an event back to the session they registered, while device_id stays the JID.
+func TestAddWebhookSessionID(t *testing.T) {
+ orig := sessionIDForJIDFn
+ defer func() { sessionIDForJIDFn = orig }()
+
+ t.Run("injects session_id resolved from device_id", func(t *testing.T) {
+ sessionIDForJIDFn = func(jid string) string {
+ if jid == "[email protected]" {
+ return "org_2"
+ }
+ return ""
+ }
+ payload := map[string]any{"device_id": "[email protected]"}
+ addWebhookSessionID(payload)
+ if payload["session_id"] != "org_2" {
+ t.Fatalf("expected session_id=org_2, got %v", payload["session_id"])
+ }
+ // device_id must remain the JID (backward-compatible).
+ if payload["device_id"] != "[email protected]" {
+ t.Fatalf("device_id must be unchanged, got %v", payload["device_id"])
+ }
+ })
+
+ t.Run("no session_id when JID is unmapped", func(t *testing.T) {
+ sessionIDForJIDFn = func(string) string { return "" }
+ payload := map[string]any{"device_id": "[email protected]"}
+ addWebhookSessionID(payload)
+ if _, ok := payload["session_id"]; ok {
+ t.Fatalf("expected no session_id for unmapped JID, got %v", payload["session_id"])
+ }
+ })
+
+ t.Run("does not overwrite an existing session_id", func(t *testing.T) {
+ sessionIDForJIDFn = func(string) string { return "resolved" }
+ payload := map[string]any{"device_id": "[email protected]", "session_id": "preset"}
+ addWebhookSessionID(payload)
+ if payload["session_id"] != "preset" {
+ t.Fatalf("expected existing session_id to be preserved, got %v", payload["session_id"])
+ }
+ })
+}
+
+// TestSessionIDForJIDEmpty pins the empty-JID guard: it must short-circuit to ""
+// before touching the device manager, regardless of global manager state.
+func TestSessionIDForJIDEmpty(t *testing.T) {
+ if got := sessionIDForJID(""); got != "" {
+ t.Fatalf("expected empty session id for empty jid, got %q", got)
+ }
+}
+
+// TestForwardPayloadInjectsSessionID verifies the session id is enriched in the
+// real forward path before reaching the webhook submitter.
+func TestForwardPayloadInjectsSessionID(t *testing.T) {
+ ctx := context.Background()
+
+ originalWebhooks := config.WhatsappWebhook
+ config.WhatsappWebhook = []string{"https://test.com"}
+ defer func() { config.WhatsappWebhook = originalWebhooks }()
+
+ origResolve := sessionIDForJIDFn
+ sessionIDForJIDFn = func(jid string) string {
+ if jid == "[email protected]" {
+ return "org_2"
+ }
+ return ""
+ }
+ defer func() { sessionIDForJIDFn = origResolve }()
+
+ var captured map[string]any
+ originalSubmit := submitWebhookFn
+ submitWebhookFn = func(_ context.Context, payload map[string]any, _ string) error {
+ captured = payload
+ return nil
+ }
+ defer func() { submitWebhookFn = originalSubmit }()
+
+ payload := map[string]any{"event": "message", "device_id": "[email protected]"}
+ if err := forwardPayloadToConfiguredWebhooks(ctx, payload, "message"); err != nil {
+ t.Fatalf("unexpected error: %v", err)
+ }
+ if captured == nil {
+ t.Fatal("expected submitWebhookFn to be invoked")
+ }
+ if captured["session_id"] != "org_2" {
+ t.Fatalf("expected forwarded payload session_id=org_2, got %v", captured["session_id"])
+ }
+}
diff --git a/src/ui/rest/app.go b/src/ui/rest/app.go
index 823e672d..25803299 100644
--- a/src/ui/rest/app.go
+++ b/src/ui/rest/app.go
@@ -130,6 +130,7 @@ func (handler *App) ConnectionStatus(c *fiber.Ctx) error {
"is_connected": isConnected,
"is_logged_in": isLoggedIn,
"device_id": device.ID(),
+ "jid": device.JID(),
},
})
}
diff --git a/src/usecase/app.go b/src/usecase/app.go
index bccfe778..e84ec927 100644
--- a/src/usecase/app.go
+++ b/src/usecase/app.go
@@ -257,6 +257,7 @@ func (service *serviceApp) FetchDevices(_ context.Context) (response []domainApp
response = append(response, domainApp.DevicesResponse{
Name: name,
Device: inst.ID(),
+ JID: inst.JID(),
})
}