GOWA - WhatsApp REST API with support for UI, Multi Account, Webhooks, and MCP, and Chatwoot. Built with Golang for efficient memory use.
Go botgogolanggolang-whatsappgolang-whatsapp-apirestrest-apiwhatsappwhatsapp-apiwhatsapp-api-gowhatsapp-multi-devicewhatsapp-web-multi-device
feat: forward incoming Presence (online/offline) events via webhook + presence subscribe endpoint (#868)
thealmogg3934feb7df77
diff --git a/docs/openapi.yaml b/docs/openapi.yamlindex 19abc313..41690b81 100644--- a/docs/openapi.yaml+++ b/docs/openapi.yaml@@ -890,6 +890,70 @@ paths:schema:$ref: '#/components/schemas/ErrorInternalServer'+ /user/presence/subscribe:+ post:+ operationId: userSubscribePresence+ tags:+ - user+ summary: Subscribe to contact presence+ description: |+ Subscribe the selected logged-in device to an individual contact's online/offline updates.+ Updates arrive through presence webhooks. For continuous tracking, set+ WHATSAPP_PRESENCE_ON_CONNECT=available and WHATSAPP_PRESENCE_PULSE_ENABLED=false.+ Keeping the device available suppresses phone push notifications.+ parameters:+ - $ref: '#/components/parameters/DeviceIdHeader'+ requestBody:+ required: true+ content:+ application/json:+ schema:+ type: object+ required:+ - phone+ properties:+ phone:+ type: string+ description: Individual contact phone number with country code+ example: '6289685028129'+ responses:+ '200':+ description: Subscription accepted. This does not guarantee contact presence delivery.+ content:+ application/json:+ schema:+ type: object+ properties:+ status:+ type: integer+ example: 200+ code:+ type: string+ example: SUCCESS+ message:+ type: string+ example: Success subscribe to user presence+ results:+ type: object+ properties:+ subscribed:+ type: boolean+ example: true+ jid:+ type: string+ example: '[email protected]'+ '400':+ description: Bad Request+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/ErrorBadRequest'+ '500':+ description: Internal Server Error+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/ErrorInternalServer'/user/info:get:operationId: userInfodiff --git a/docs/webhook-payload.md b/docs/webhook-payload.mdindex 629c262c..2fe5bd8e 100644--- a/docs/webhook-payload.md+++ b/docs/webhook-payload.md@@ -21,6 +21,7 @@ The following events can be received via webhook:| `message.ack` | Delivery and read receipts || `message.deleted` | Messages deleted for the user || `chat_presence` | Typing and recording indicators from contacts |+| `presence` | Online/offline status of subscribed contacts || `group.participants` | Group member join/leave/promote/demote events || `group.info` | Group name (subject) changed || `group.joined` | You were added to a group |@@ -190,7 +191,7 @@ All webhook payloads follow a consistent top-level structure:| **Field** | **Type** | **Description** ||--------------|----------|---------------------------------------------------------------------------------------------------------------------|-| `event` | string | Event type: `message`, `message.reaction`, `message.revoked`, `message.edited`, `message.ack`, `message.deleted`, `chat_presence`, `group.participants`, `group.info`, `group.joined`, `label.edit`, `label.association`, `newsletter.joined`, `newsletter.left`, `newsletter.message`, `newsletter.mute`, `call.offer` |+| `event` | string | Event type: `message`, `message.reaction`, `message.revoked`, `message.edited`, `message.ack`, `message.deleted`, `chat_presence`, `presence`, `group.participants`, `group.info`, `group.joined`, `label.edit`, `label.association`, `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 |@@ -575,6 +576,68 @@ Triggered when a user starts typing in a group chat.| `payload.media` | string | Media type: `""` (text message) or `"audio"` (voice recording) || `payload.is_group` | boolean | Whether this is a group chat |+## Presence Events++Presence events are triggered when a subscribed contact goes online or offline. Unlike chat presence+(typing), these require an explicit per-user subscription: call `POST /user/presence/subscribe` with+the contact's phone number first.++WhatsApp only delivers contact presence updates while your device is marked as available (online).+For continuous tracking, set both options below:++```env+WHATSAPP_PRESENCE_ON_CONNECT=available+WHATSAPP_PRESENCE_PULSE_ENABLED=false+```++The presence pulse is enabled by default. It marks the device unavailable after each pulse+(default: five minutes), which stops contact presence updates until the device becomes available again.+Disabling the pulse keeps it from overriding the available-on-connect setting.++Note: marking the device as available tells WhatsApp someone is actively using WhatsApp on the+linked device, which suppresses push notifications on your phone while the server runs. If phone+notifications matter, run the tracker on a secondary account or accept the trade-off.++```json+{+ "event": "presence",+ "device_id": "[email protected]",+ "timestamp": "2026-01-22T12:05:00Z",+ "payload": {+ "from": "[email protected]",+ "state": "unavailable",+ "last_seen": "2026-01-22T12:04:35Z"+ }+}+```++```json+{+ "event": "presence",+ "device_id": "[email protected]",+ "timestamp": "2026-01-22T12:10:00Z",+ "payload": {+ "from": "[email protected]",+ "state": "available"+ }+}+```++### Presence Event Fields++| **Field** | **Type** | **Description** |+|--------------------|----------|---------------------------------------------------------------------|+| `event` | string | Always `"presence"` for online/offline events |+| `device_id` | string | JID of the device that received this event |+| `timestamp` | string | RFC3339 formatted timestamp when the event was processed |+| `payload.from` | string | JID of the user whose presence changed (e.g., `[email protected]`) |+| `payload.from_lid` | string | LID of the user (if applicable) |+| `payload.state` | string | Presence state: `"available"` (online) or `"unavailable"` (offline) |+| `payload.last_seen`| string | RFC3339 last-seen timestamp; omitted when the user hides last seen |++**Note:** `payload.last_seen` reflects the contact's own last-seen privacy setting. When it is+hidden from you, the field is omitted on offline events.+## Label EventsLabel events are triggered when WhatsApp label metadata changes or a label is applied to or removed from a chat. Thesediff --git a/src/domains/user/account.go b/src/domains/user/account.goindex 03cc33c0..2a84cabb 100644--- a/src/domains/user/account.go+++ b/src/domains/user/account.go@@ -85,6 +85,15 @@ type CheckResponse struct {IsOnWhatsApp bool `json:"is_on_whatsapp"`}+type SubscribePresenceRequest struct {+ Phone string `json:"phone" query:"phone"`+}++type SubscribePresenceResponse struct {+ Subscribed bool `json:"subscribed"`+ JID string `json:"jid"`+}+type BusinessProfileRequest struct {Phone string `json:"phone" query:"phone"`}diff --git a/src/domains/user/interfaces.go b/src/domains/user/interfaces.goindex 915588d3..a7e0fbef 100644--- a/src/domains/user/interfaces.go+++ b/src/domains/user/interfaces.go@@ -9,6 +9,7 @@ type IUserInfo interface {Info(ctx context.Context, request InfoRequest) (response InfoResponse, err error)IsOnWhatsApp(ctx context.Context, request CheckRequest) (response CheckResponse, err error)BusinessProfile(ctx context.Context, request BusinessProfileRequest) (response BusinessProfileResponse, err error)+ SubscribePresence(ctx context.Context, request SubscribePresenceRequest) (response SubscribePresenceResponse, err error)}// IUserProfile handles user profile operationsdiff --git a/src/infrastructure/whatsapp/event_handler.go b/src/infrastructure/whatsapp/event_handler.goindex b9d28b10..f7130428 100644--- a/src/infrastructure/whatsapp/event_handler.go+++ b/src/infrastructure/whatsapp/event_handler.go@@ -59,7 +59,7 @@ func handler(ctx context.Context, instance *DeviceInstance, rawEvt any) {case *events.Archive:handleArchive(ctx, evt, chatStorageRepo, client)case *events.Presence:- handlePresence(ctx, evt)+ handlePresence(ctx, evt, instance.JID(), client)case *events.ChatPresence:handleChatPresence(ctx, evt, instance.JID(), client)case *events.HistorySync:@@ -368,18 +368,6 @@ func handleReceipt(ctx context.Context, evt *events.Receipt, deviceID string, cl}}-func handlePresence(_ context.Context, evt *events.Presence) {- if evt.Unavailable {- if evt.LastSeen.IsZero() {- log.Infof("%s is now offline", evt.From)- } else {- log.Infof("%s is now offline (last seen: %s)", evt.From, evt.LastSeen)- }- } else {- log.Infof("%s is now online", evt.From)- }-}-func handleAppState(ctx context.Context, evt *events.AppState, deviceID string, client *whatsmeow.Client) {log.Debugf("App state event: %+v / %+v", evt.Index, evt.SyncActionValue)diff --git a/src/infrastructure/whatsapp/event_presence.go b/src/infrastructure/whatsapp/event_presence.gonew file mode 100644index 00000000..917cc949--- /dev/null+++ b/src/infrastructure/whatsapp/event_presence.go@@ -0,0 +1,77 @@+package whatsapp++import (+ "context"+ "time"++ "github.com/sirupsen/logrus"+ "go.mau.fi/whatsmeow"+ "go.mau.fi/whatsmeow/types/events"+)++// handlePresence handles incoming global presence (online/offline) events.+// WhatsApp only sends these updates for users the client has explicitly+// subscribed to via SubscribePresence (see POST /user/presence/subscribe),+// and only while the client is marked as available.+func handlePresence(ctx context.Context, evt *events.Presence, deviceID string, client *whatsmeow.Client) {+ if evt.Unavailable {+ if evt.LastSeen.IsZero() {+ log.Infof("%s is now offline", evt.From)+ } else {+ log.Infof("%s is now offline (last seen: %s)", evt.From, evt.LastSeen)+ }+ } else {+ log.Infof("%s is now online", evt.From)+ }++ // Forward presence event to webhook+ go func(e *events.Presence, c *whatsmeow.Client) {+ webhookCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 30*time.Second)+ defer cancel()+ if err := forwardPresenceToWebhook(webhookCtx, e, deviceID, c); err != nil {+ logrus.Errorf("Failed to forward presence event to webhook: %v", err)+ }+ }(evt, client)+}++// createPresencePayload creates a webhook payload for presence (online/offline) events.+func createPresencePayload(ctx context.Context, evt *events.Presence, deviceID string, client *whatsmeow.Client) map[string]any {+ body := make(map[string]any)+ payload := make(map[string]any)++ // Resolve JID (convert LID to phone number if needed)+ fromJID := evt.From+ if fromJID.Server == "lid" {+ payload["from_lid"] = fromJID.ToNonAD().String()+ }+ normalizedFromJID := NormalizeJIDFromLID(ctx, fromJID, client)+ payload["from"] = normalizedFromJID.ToNonAD().String()++ // Online state: "unavailable" (offline) or "available" (online)+ if evt.Unavailable {+ payload["state"] = "unavailable"+ } else {+ payload["state"] = "available"+ }++ // Last seen: RFC3339 timestamp, omitted when unknown (user hides last seen)+ if !evt.LastSeen.IsZero() {+ payload["last_seen"] = evt.LastSeen.UTC().Format(time.RFC3339)+ }++ // Wrap in body structure+ body["event"] = "presence"+ body["timestamp"] = time.Now().Format(time.RFC3339)+ if deviceID != "" {+ body["device_id"] = deviceID+ }+ body["payload"] = payload++ return body+}++// forwardPresenceToWebhook forwards presence events to the configured webhook URLs.+func forwardPresenceToWebhook(ctx context.Context, evt *events.Presence, deviceID string, client *whatsmeow.Client) error {+ payload := createPresencePayload(ctx, evt, deviceID, client)+ return forwardPayloadToConfiguredWebhooks(ctx, payload, "presence")+}diff --git a/src/ui/rest/user.go b/src/ui/rest/user.goindex 2e45aa2d..64d7f839 100644--- a/src/ui/rest/user.go+++ b/src/ui/rest/user.go@@ -22,6 +22,7 @@ func InitRestUser(app fiber.Router, service domainUser.IUserUsecase) User {app.Get("/user/my/newsletters", rest.UserMyListNewsletter)app.Get("/user/my/contacts", rest.UserMyListContacts)app.Get("/user/check", rest.UserCheck)+ app.Post("/user/presence/subscribe", rest.UserSubscribePresence)app.Get("/user/business-profile", rest.UserBusinessProfile)return rest@@ -100,6 +101,26 @@ func (controller *User) UserMyPrivacySetting(c fiber.Ctx) error {})}+func (controller *User) UserSubscribePresence(c fiber.Ctx) error {+ var request domainUser.SubscribePresenceRequest+ err := c.Bind().Body(&request)+ utils.PanicIfNeeded(err)++ utils.SanitizePhone(&request.Phone)++ ctx := whatsapp.ContextWithDevice(c.Context(), getDeviceFromCtx(c))++ response, err := controller.Service.SubscribePresence(ctx, request)+ utils.PanicIfNeeded(err)++ return c.JSON(utils.ResponseData{+ Status: 200,+ Code: "SUCCESS",+ Message: "Success subscribe to user presence",+ Results: response,+ })+}+func (controller *User) UserMyListGroups(c fiber.Ctx) error {deviceVal := c.Locals("device")ctx := c.Context()diff --git a/src/usecase/user.go b/src/usecase/user.goindex 6dc48e71..1e3bd0df 100644--- a/src/usecase/user.go+++ b/src/usecase/user.go@@ -10,6 +10,7 @@ import ("sync""time"+ "github.com/aldinokemal/go-whatsapp-web-multidevice/config"domainChatStorage "github.com/aldinokemal/go-whatsapp-web-multidevice/domains/chatstorage"domainUser "github.com/aldinokemal/go-whatsapp-web-multidevice/domains/user""github.com/aldinokemal/go-whatsapp-web-multidevice/infrastructure/whatsapp"@@ -408,6 +409,52 @@ func (service serviceUser) IsOnWhatsApp(ctx context.Context, request domainUser.return response, nil}+func (service serviceUser) SubscribePresence(ctx context.Context, request domainUser.SubscribePresenceRequest) (response domainUser.SubscribePresenceResponse, err error) {+ if err = validations.ValidateSubscribePresence(ctx, request); err != nil {+ return response, err+ }++ client := whatsapp.ClientFromContext(ctx)+ if client == nil {+ return response, pkgError.ErrWaCLI+ }+ utils.MustLogin(client)++ utils.SanitizePhone(&request.Phone)++ dataWaRecipient, err := utils.ValidateJidWithLogin(client, request.Phone)+ if err != nil {+ return response, err+ }++ // Presence subscription is only valid for individual users; reject group /+ // newsletter JIDs (e.g. caused by over-length phone inputs) instead of+ // returning a false success.+ if dataWaRecipient.Server != types.DefaultUserServer {+ return response, pkgError.InvalidJID(fmt.Sprintf(+ "presence subscription requires a user phone number, got non-user JID %s",+ dataWaRecipient.ToNonAD().String()))+ }++ if err = client.SubscribePresence(ctx, dataWaRecipient); err != nil {+ return response, err+ }++ // whatsmeow requires this client to be marked as available (online) to+ // receive presence updates for other users. Do not override the operator's+ // configured presence-on-connect value — surface the requirement instead.+ if config.WhatsappPresenceOnConnect != "available" {+ logrus.Warnf("presence subscription: client presence-on-connect is %q; "++ "contact presence updates require WHATSAPP_PRESENCE_ON_CONNECT=available "++ "(note: marking the device available suppresses phone notifications)", config.WhatsappPresenceOnConnect)+ }++ response.Subscribed = true+ response.JID = dataWaRecipient.ToNonAD().String()++ return response, nil+}+func (service serviceUser) BusinessProfile(ctx context.Context, request domainUser.BusinessProfileRequest) (response domainUser.BusinessProfileResponse, err error) {err = validations.ValidateBusinessProfile(ctx, request)if err != nil {diff --git a/src/usecase/user_presence_test.go b/src/usecase/user_presence_test.gonew file mode 100644index 00000000..1211631d--- /dev/null+++ b/src/usecase/user_presence_test.go@@ -0,0 +1,25 @@+package usecase++import (+ "context"+ "testing"++ "github.com/aldinokemal/go-whatsapp-web-multidevice/config"+ domainUser "github.com/aldinokemal/go-whatsapp-web-multidevice/domains/user"+ pkgError "github.com/aldinokemal/go-whatsapp-web-multidevice/pkg/error"+ "github.com/stretchr/testify/require"+)++func TestSubscribePresenceRejectsBlankPhoneBeforeClient(t *testing.T) {+ original := config.WhatsappAccountValidation+ t.Cleanup(func() { config.WhatsappAccountValidation = original })+ for _, enabled := range []bool{false, true} {+ config.WhatsappAccountValidation = enabled+ for _, phone := range []string{"", " ", "\t\n"} {+ response, err := NewUserService(nil).SubscribePresence(context.Background(), domainUser.SubscribePresenceRequest{Phone: phone})+ var validationErr pkgError.ValidationError+ require.ErrorAs(t, err, &validationErr)+ require.False(t, response.Subscribed)+ }+ }+}diff --git a/src/validations/user_validation.go b/src/validations/user_validation.goindex ee06ba81..81613f24 100644--- a/src/validations/user_validation.go+++ b/src/validations/user_validation.go@@ -2,6 +2,7 @@ package validationsimport ("context"+ "strings"domainUser "github.com/aldinokemal/go-whatsapp-web-multidevice/domains/user"pkgError "github.com/aldinokemal/go-whatsapp-web-multidevice/pkg/error"@@ -19,6 +20,18 @@ func ValidateUserInfo(ctx context.Context, request domainUser.InfoRequest) errorreturn nil}++func ValidateSubscribePresence(ctx context.Context, request domainUser.SubscribePresenceRequest) error {+ request.Phone = strings.TrimSpace(request.Phone)+ err := validation.ValidateStructWithContext(ctx, &request,+ validation.Field(&request.Phone, validation.Required),+ )+ if err != nil {+ return pkgError.ValidationError(err.Error())+ }+ return nil+}+func ValidateUserAvatar(ctx context.Context, request domainUser.AvatarRequest) error {err := validation.ValidateStructWithContext(ctx, &request,validation.Field(&request.Phone, validation.Required),