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: add per-device webhook support (#671)

Mohamed Habib0de046629e82
diff --git a/docs/openapi.yaml b/docs/openapi.yaml
index 5ce9e4b1..1f521d7e 100644
--- a/docs/openapi.yaml
+++ b/docs/openapi.yaml
@@ -334,6 +334,10 @@ paths:
type: string
description: Optional custom device ID. If not provided, one will be generated.
example: 'my-custom-device-id'
+ webhook_url:
+ type: string
+ description: Optional device-specific webhook URL. If set, events for this device will be sent here instead of the global webhook.
+ example: 'https://device-webhook.example.com/handler'
responses:
'200':
description: OK
@@ -603,6 +607,137 @@ paths:
schema:
$ref: '#/components/schemas/ErrorInternalServer'
+ /devices/{device_id}/webhook:
+ get:
+ operationId: getDeviceWebhook
+ tags:
+ - device
+ summary: Get device webhook URL
+ description: Get the webhook URL configured for a specific device. Returns empty if no device-specific webhook is set.
+ parameters:
+ - name: device_id
+ in: path
+ required: true
+ schema:
+ type: string
+ description: Device ID
+ responses:
+ '200':
+ description: OK
+ content:
+ application/json:
+ schema:
+ type: object
+ properties:
+ status:
+ type: integer
+ example: 200
+ code:
+ type: string
+ example: SUCCESS
+ message:
+ type: string
+ example: Device webhook retrieved
+ results:
+ type: object
+ properties:
+ device_id:
+ type: string
+ description: The device ID
+ example: 'my-device'
+ webhook_url:
+ type: string
+ description: The configured webhook URL (empty if not set)
+ example: 'https://example.com/webhook'
+ '404':
+ description: Device not found
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/ErrorNotFound'
+ '500':
+ description: Internal Server Error
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/ErrorInternalServer'
+ patch:
+ operationId: updateDeviceWebhook
+ tags:
+ - device
+ summary: Set device webhook URL
+ description: |
+ Set a custom webhook URL for a specific device. When set, webhook events for this device
+ will be sent to this URL instead of the global webhook URL.
+
+ Set to empty string to clear and use the global webhook.
+ parameters:
+ - name: device_id
+ in: path
+ required: true
+ schema:
+ type: string
+ description: Device ID
+ requestBody:
+ required: true
+ content:
+ application/json:
+ schema:
+ type: object
+ properties:
+ webhook_url:
+ type: string
+ description: Custom webhook URL to use for this device. Set to empty string to clear.
+ example: 'https://example.com/webhook'
+ required:
+ - webhook_url
+ responses:
+ '200':
+ description: OK
+ content:
+ application/json:
+ schema:
+ type: object
+ properties:
+ status:
+ type: integer
+ example: 200
+ code:
+ type: string
+ example: SUCCESS
+ message:
+ type: string
+ example: Device webhook updated
+ results:
+ type: object
+ properties:
+ device_id:
+ type: string
+ description: The device ID
+ example: 'my-device'
+ webhook_url:
+ type: string
+ description: The configured webhook URL
+ example: 'https://example.com/webhook'
+ '400':
+ description: Bad Request
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/ErrorBadRequest'
+ '404':
+ description: Device not found
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/ErrorNotFound'
+ '500':
+ description: Internal Server Error
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/ErrorInternalServer'
+
/user/info:
get:
operationId: userInfo
@@ -786,12 +921,12 @@ paths:
summary: User My List Groups
description: |
Get all groups that the authenticated user has joined.
-
+
⚠️ **Known Limitation**: This endpoint returns a maximum of 500 groups due to a WhatsApp protocol limitation.
The underlying whatsmeow library's `GetJoinedGroups()` function sends a single query to WhatsApp servers,
which enforces this limit. This is not a bug in this API - it's a constraint imposed by WhatsApp's
multi-device protocol. Users with more than 500 groups will only receive the first 500 groups.
-
+
For more details, see: https://github.com/tulir/whatsmeow/blob/main/group.go
externalDocs:
description: WhatsApp protocol limitation reference (whatsmeow source)
@@ -922,7 +1057,7 @@ paths:
application/json:
schema:
$ref: '#/components/schemas/ErrorInternalServer'
-
+
/send/message:
post:
operationId: sendMessage
@@ -2024,12 +2159,12 @@ paths:
description: |
Programmatically reject a specific incoming call. This endpoint allows selective call rejection
based on your application logic (e.g., time-of-day rules, caller whitelists, agent availability).
-
+
The call must still be ringing — rejection will fail if the call has already ended or been answered.
-
+
This is complementary to the auto-reject feature (`WHATSAPP_AUTO_REJECT_CALL=true`) which rejects
all incoming calls globally. Use this API for fine-grained control.
-
+
**Required fields from webhook:**
- `caller_jid`: Use `payload.from` from the `call.offer` webhook event
- `call_id`: Use `payload.call_id` from the `call.offer` webhook event
@@ -2352,7 +2487,7 @@ paths:
application/json:
schema:
$ref: '#/components/schemas/ErrorInternalServer'
-
+
/chat/{chat_jid}/disappearing:
post:
operationId: setDisappearingTimer
@@ -2400,7 +2535,7 @@ paths:
application/json:
schema:
$ref: '#/components/schemas/ErrorInternalServer'
-
+
/chat/{chat_jid}/archive:
post:
operationId: archiveChat
@@ -2460,7 +2595,7 @@ paths:
application/json:
schema:
$ref: '#/components/schemas/ErrorInternalServer'
-
+
/group/info:
get:
operationId: groupInfo
@@ -3977,6 +4112,10 @@ components:
jid:
type: string
example: '[email protected]'
+ webhook_url:
+ type: string
+ description: Device-specific webhook URL (empty if not set)
+ example: 'https://device-webhook.example.com/handler'
created_at:
type: string
format: date-time
@@ -4470,7 +4609,7 @@ components:
close_time:
type: string
example: '18:00'
-
+
ChatListResponse:
type: object
properties:
diff --git a/docs/per-device-webhook-plan.md b/docs/per-device-webhook-plan.md
new file mode 100644
index 00000000..954bcf73
--- /dev/null
+++ b/docs/per-device-webhook-plan.md
@@ -0,0 +1,149 @@
+# Per-Device Webhook Implementation Plan
+
+## Status: IMPLEMENTED
+
+## Overview
+
+Add per-device webhook support where each device can have its own webhook URL. If a device has no custom webhook URL, it falls back to the global webhook.
+
+## Flow Diagram
+
+```text
+┌─────────────────────────────────────────────────────────────────────────────┐
+│ WHATSAPP EVENT RECEIVED │
+└─────────────────────────────────────────────────────────────────────────────┘
+ │
+ ▼
+┌─────────────────────────────────────────────────────────────────────────────┐
+│ event_handler.go :: handler() │
+│ - Routes event to appropriate handler (message, receipt, etc.) │
+└─────────────────────────────────────────────────────────────────────────────┘
+ │
+ ▼
+┌─────────────────────────────────────────────────────────────────────────────┐
+│ Event-specific handler (e.g., event_message_handler.go) │
+│ - Creates webhook payload with device_id │
+│ - Calls forwardMessageToWebhook() │
+└─────────────────────────────────────────────────────────────────────────────┘
+ │
+ ▼
+┌─────────────────────────────────────────────────────────────────────────────┐
+│ webhook_forward.go :: forwardPayloadToConfiguredWebhooks() │
+│ ┌───────────────────────────────────────────────────────────────────────┐ │
+│ │ STEP 1: Extract device JID from payload["device_id"] │ │
+│ │ STEP 2: Call getWebhookURLsForDevice(deviceJID) │ │
+│ │ - Looks up device record by JID │ │
+│ │ - If device has custom webhook_url, return it only │ │
+│ │ - Otherwise return global config.WhatsappWebhook │ │
+│ └───────────────────────────────────────────────────────────────────────┘ │
+└─────────────────────────────────────────────────────────────────────────────┘
+ │
+ ▼
+ ┌───────────────┴───────────────┐
+ │ │
+ ▼ ▼
+ ┌──────────────────┐ ┌────────────────────────┐
+ │ Device has custom │ │ Device webhook is NULL │
+ │ webhook_url? │ │ or empty? │
+ └──────────────────────┘ └─────────────────────────┘
+ │ │
+ YES │ │ YES
+ ▼ ▼
+ ┌────────────────────────┐ ┌─────────────────────────┐
+ │ Use device webhook URL │ │ Use global config │
+ │ (override global) │ │ WhatsappWebhook[] │
+ └────────────────────────┘ └─────────────────────────┘
+ │ │
+ └───────────────┬───────────────┘
+ │
+ ▼
+┌─────────────────────────────────────────────────────────────────────────────┐
+│ webhook_forward.go :: forwardToWebhooks() │
+│ - Iterates webhook URLs │
+│ - For each URL: submitWebhook() with HMAC signature │
+│ - 5 retries with exponential backoff │
+└─────────────────────────────────────────────────────────────────────────────┘
+ │
+ ▼
+ ┌───────────────┴───────────────┐
+ │ │
+ ▼ ▼
+ ┌──────────────────┐ ┌────────────────────────┐
+ │ All webhooks │ │ Some webhooks failed │
+ │ succeeded │ │ (partial failure OK) │
+ └──────────────────┘ └────────────────────────┘
+```
+
+## API Flow: Set Device Webhook
+
+```text
+Client REST API UseCase Repository
+ │ │ │ │
+ │ PATCH /devices/:id/webhook│ │ │
+ │ { "webhook_url": "..." } │ │ │
+ │─────────────────────────>│ │ │
+ │ │ SetDeviceWebhook() │ │
+ │ │──────────────────────────>│ │
+ │ │ │ SetDeviceWebhookURL() │
+ │ │ │────────────────────────>│
+ │ │ │ │
+ │ │ │ │
+ │ 200 OK │ │ │
+ │<─────────────────────────│ │ │
+ │ │ │ │
+```
+
+## Files Modified
+
+| File | Change |
+|------|--------|
+| `domains/chatstorage/chatstorage.go` | Added `WebhookURL *string` to `DeviceRecord` struct |
+| `domains/chatstorage/interfaces.go` | Added `GetDeviceRecordByJID`, `SetDeviceWebhookURL`, `GetDeviceWebhookURL` |
+| `infrastructure/chatstorage/sqlite_repository.go` | Added migration #17, updated queries, implemented new methods |
+| `infrastructure/whatsapp/chatstorage_wrapper.go` | Added wrapper methods for new interface methods |
+| `infrastructure/whatsapp/webhook_forward.go` | Added `getWebhookURLsForDevice()`, updated forwarding logic |
+| `infrastructure/whatsapp/device_manager.go` | Added `GetStorage()` method |
+| `domains/device/interfaces.go` | Added `SetDeviceWebhook`, `GetDeviceWebhook` to `IDeviceUsecase` |
+| `usecase/device.go` | Implemented `SetDeviceWebhook`, `GetDeviceWebhook` |
+| `ui/rest/device.go` | Added `PATCH /devices/:device_id/webhook`, `GET /devices/:device_id/webhook` |
+| `infrastructure/whatsapp/webhook_forward_test.go` | Added per-device webhook tests |
+| `usecase/device_test.go` | Added device service tests |
+| `docs/openapi.yaml` | Added webhook API documentation |
+
+## Database Changes
+
+**Migration #17** adds `webhook_url TEXT DEFAULT ''` column to `devices` table.
+
+## API Endpoints
+
+- `PATCH /devices/{device_id}/webhook` - Set device-specific webhook URL
+ - Body: `{ "webhook_url": "https://example.com/webhook" }`
+ - Set to empty string `""` to clear and use global webhook
+
+- `GET /devices/{device_id}/webhook` - Get device-specific webhook URL
+ - Returns empty string if not set (use global)
+
+## Testing
+
+### Unit Tests
+
+**`infrastructure/whatsapp/webhook_forward_test.go`:**
+- `TestGetWebhookURLsForDevice_NoDeviceJID` - Returns global webhook when device JID is empty
+- `TestGetWebhookURLsForDevice_DeviceNotFound` - Falls back to global when device not found
+- `TestGetWebhookURLsForDevice_FallbackToGlobal` - Falls back to global when device has no custom webhook
+- `TestForwardPayloadToConfiguredWebhooks_WithDeviceSpecificWebhook` - Uses device-specific webhook when set
+- `TestForwardPayloadToConfiguredWebhooks_DeviceWebhookCleared_FallsBackToGlobal` - Falls back to global when device webhook is cleared
+
+**`usecase/device_test.go`:**
+- `TestDeviceServiceInterface` - Verifies interface implementation
+- `TestSetDeviceWebhook_InvalidManager` - Error handling for nil manager
+- `TestGetDeviceWebhook_InvalidManager` - Error handling for nil manager
+- `TestGetDeviceWebhook_DeviceNotFound` - Error handling for missing device
+- `TestSetDeviceWebhook_DeviceNotFound` - Error handling for missing device
+
+## OpenAPI Documentation
+
+Added to `docs/openapi.yaml`:
+
+- `GET /devices/{device_id}/webhook` - Get device webhook URL
+- `PATCH /devices/{device_id}/webhook` - Set device webhook URL
diff --git a/docs/webhook-payload.md b/docs/webhook-payload.md
index d14dbece..f5821683 100644
--- a/docs/webhook-payload.md
+++ b/docs/webhook-payload.md
@@ -116,7 +116,7 @@ def verify_webhook_signature(payload, signature, secret):
payload,
hashlib.sha256
).hexdigest()
-
+
received_signature = signature.replace('sha256=', '')
return hmac.compare_digest(expected_signature, received_signature)
```
@@ -711,11 +711,11 @@ const axios = require('axios');
// When you receive a call.offer webhook event
app.post('/webhook', async (req, res) => {
const { event, payload, device_id } = req.body;
-
+
if (event === 'call.offer' && !payload.auto_rejected) {
// Apply your custom logic here
const shouldReject = checkBusinessHours() || isBlacklisted(payload.from);
-
+
if (shouldReject) {
try {
await axios.post('http://localhost:3000/call/reject', {
@@ -733,7 +733,7 @@ app.post('/webhook', async (req, res) => {
}
}
}
-
+
res.sendStatus(200);
});
```
diff --git a/readme.md b/readme.md
index 65aa21e7..f33bd596 100644
--- a/readme.md
+++ b/readme.md
@@ -114,6 +114,12 @@ Download:
- `--webhook="http://yourwebhook.site/handler"`, or you can simplify
- `-w="http://yourwebhook.site/handler"`
- for more detail, see [Webhook Payload Documentation](./docs/webhook-payload.md)
+- **Per-Device Webhook** - Each device can have its own webhook URL
+ - Set via API: `PATCH /devices/:device_id/webhook` with `{"webhook_url": "https://device-webhook.site/handler"}`
+ - Get via API: `GET /devices/:device_id/webhook`
+ - When a device has a custom webhook, events for that device are sent to the device-specific URL
+ - When no device webhook is set, events fall back to the global webhook (`--webhook`)
+ - Set to empty string `""` via PATCH to clear and use global webhook
- Webhook Secret
Our webhook will be sent to you with an HMAC header and a sha256 default key `secret`.
@@ -543,6 +549,8 @@ You can fork or edit this source code !
| ✅ | Logout Device | POST | /devices/:device_id/logout |
| ✅ | Reconnect Device | POST | /devices/:device_id/reconnect |
| ✅ | Get Device Status | GET | /devices/:device_id/status |
+| ✅ | Get Device Webhook | GET | /devices/:device_id/webhook |
+| ✅ | Set Device Webhook | PATCH | /devices/:device_id/webhook |
| ✅ | Login with Scan QR | GET | /app/login |
| ✅ | Login With Pair Code | GET | /app/login-with-code |
| ✅ | Passkey Pairing Status | GET | /app/passkey |
diff --git a/src/domains/chatstorage/chatstorage.go b/src/domains/chatstorage/chatstorage.go
index a5187779..cca9c836 100644
--- a/src/domains/chatstorage/chatstorage.go
+++ b/src/domains/chatstorage/chatstorage.go
@@ -100,11 +100,23 @@ type MediaInfo struct {
// DeviceRecord tracks a registered device for persistence purposes.
type DeviceRecord struct {
- DeviceID string `db:"device_id"`
- DisplayName string `db:"display_name"`
- JID string `db:"jid"`
- CreatedAt time.Time `db:"created_at"`
- UpdatedAt time.Time `db:"updated_at"`
+ DeviceID string `db:"device_id"`
+ DisplayName string `db:"display_name"`
+ JID string `db:"jid"`
+ WebhookURL *string `db:"webhook_url"`
+ WebhookSecret string `db:"webhook_secret"`
+ WebhookEvents string `db:"webhook_events"`
+ WebhookInsecureSkipVerify bool `db:"webhook_insecure_skip_verify"`
+ CreatedAt time.Time `db:"created_at"`
+ UpdatedAt time.Time `db:"updated_at"`
+}
+
+// DeviceWebhookConfig holds the complete webhook configuration for a device.
+type DeviceWebhookConfig struct {
+ WebhookURL *string `json:"webhook_url,omitempty"`
+ WebhookSecret string `json:"webhook_secret,omitempty"`
+ WebhookEvents string `json:"webhook_events,omitempty"`
+ WebhookInsecureSkipVerify bool `json:"webhook_insecure_skip_verify,omitempty"`
}
// MessageFilter represents query filters for messages
diff --git a/src/domains/chatstorage/interfaces.go b/src/domains/chatstorage/interfaces.go
index c4fde14f..350bfd53 100644
--- a/src/domains/chatstorage/interfaces.go
+++ b/src/domains/chatstorage/interfaces.go
@@ -65,7 +65,17 @@ type IChatStorageRepository interface {
SaveDeviceRecord(record *DeviceRecord) error
ListDeviceRecords() ([]*DeviceRecord, error)
GetDeviceRecord(deviceID string) (*DeviceRecord, error)
+ // GetDeviceRecordByJID fetches a device record by its JID.
+ GetDeviceRecordByJID(jid string) (*DeviceRecord, error)
DeleteDeviceRecord(deviceID string) error
+ // SetDeviceWebhookURL sets the webhook URL for a device.
+ SetDeviceWebhookURL(deviceID string, webhookURL *string) error
+ // GetDeviceWebhookURL retrieves the webhook URL for a device.
+ GetDeviceWebhookURL(deviceID string) (*string, error)
+ // SetDeviceWebhookConfig sets the full webhook configuration for a device.
+ SetDeviceWebhookConfig(deviceID string, config *DeviceWebhookConfig) error
+ // GetDeviceWebhookConfig retrieves the full webhook configuration for a device.
+ GetDeviceWebhookConfig(deviceID string) (*DeviceWebhookConfig, error)
// Schema operations
InitializeSchema() error
diff --git a/src/domains/device/interfaces.go b/src/domains/device/interfaces.go
index 66b33e0a..2547166d 100644
--- a/src/domains/device/interfaces.go
+++ b/src/domains/device/interfaces.go
@@ -1,16 +1,28 @@
package device
-import "context"
+import (
+ "context"
+
+ "github.com/aldinokemal/go-whatsapp-web-multidevice/domains/chatstorage"
+)
// IDeviceUsecase defines device lifecycle operations.
type IDeviceUsecase interface {
ListDevices(ctx context.Context) ([]Device, error)
GetDevice(ctx context.Context, deviceID string) (*Device, error)
- AddDevice(ctx context.Context, deviceID string) (*Device, error)
+ AddDevice(ctx context.Context, deviceID string, webhookURL string) (*Device, error)
RemoveDevice(ctx context.Context, deviceID string) error
LoginDevice(ctx context.Context, deviceID string) error
LoginDeviceWithCode(ctx context.Context, deviceID string, phone string) (string, error)
LogoutDevice(ctx context.Context, deviceID string) error
ReconnectDevice(ctx context.Context, deviceID string) error
GetStatus(ctx context.Context, deviceID string) (isConnected bool, isLoggedIn bool, err error)
+ // SetDeviceWebhook sets the webhook URL for a specific device.
+ SetDeviceWebhook(ctx context.Context, deviceID string, webhookURL string) error
+ // GetDeviceWebhook retrieves the webhook URL for a specific device.
+ GetDeviceWebhook(ctx context.Context, deviceID string) (string, error)
+ // SetDeviceWebhookConfig sets the complete webhook configuration for a specific device.
+ SetDeviceWebhookConfig(ctx context.Context, deviceID string, config *chatstorage.DeviceWebhookConfig) error
+ // GetDeviceWebhookConfig retrieves the complete webhook configuration for a specific device.
+ GetDeviceWebhookConfig(ctx context.Context, deviceID string) (*chatstorage.DeviceWebhookConfig, error)
}
diff --git a/src/infrastructure/chatstorage/sqlite_repository.go b/src/infrastructure/chatstorage/sqlite_repository.go
index 1b61c96c..5c0e6c40 100644
--- a/src/infrastructure/chatstorage/sqlite_repository.go
+++ b/src/infrastructure/chatstorage/sqlite_repository.go
@@ -1163,6 +1163,38 @@ func (r *SQLiteRepository) GetDeviceRecord(deviceID string) (*domainChatStorage.
return rec, nil
}
+// GetDeviceRecordByJID fetches a device registration by WhatsApp JID.
+func (r *SQLiteRepository) GetDeviceRecordByJID(jid string) (*domainChatStorage.DeviceRecord, error) {
+ if strings.TrimSpace(jid) == "" {
+ return nil, fmt.Errorf("jid is required")
+ }
+
+ rec := &domainChatStorage.DeviceRecord{}
+ err := r.db.QueryRow(`
+ SELECT device_id, display_name, jid, webhook_url, COALESCE(webhook_secret, ''), COALESCE(webhook_events, ''), COALESCE(webhook_insecure_skip_verify, FALSE), created_at, updated_at
+ FROM devices
+ WHERE jid = ?
+ LIMIT 1
+ `, jid).Scan(
+ &rec.DeviceID,
+ &rec.DisplayName,
+ &rec.JID,
+ &rec.WebhookURL,
+ &rec.WebhookSecret,
+ &rec.WebhookEvents,
+ &rec.WebhookInsecureSkipVerify,
+ &rec.CreatedAt,
+ &rec.UpdatedAt,
+ )
+ if err == sql.ErrNoRows {
+ return nil, nil
+ }
+ if err != nil {
+ return nil, err
+ }
+ return rec, nil
+}
+
// DeleteDeviceRecord removes a device registration entry.
func (r *SQLiteRepository) DeleteDeviceRecord(deviceID string) error {
if strings.TrimSpace(deviceID) == "" {
@@ -1172,6 +1204,101 @@ func (r *SQLiteRepository) DeleteDeviceRecord(deviceID string) error {
return err
}
+// SetDeviceWebhookURL updates or clears the webhook URL for a device.
+// Use nil for webhookURL to clear the device-specific webhook (forces fallback to global).
+// Returns sql.ErrNoRows if the device does not exist.
+func (r *SQLiteRepository) SetDeviceWebhookURL(deviceID string, webhookURL *string) error {
+ if strings.TrimSpace(deviceID) == "" {
+ return fmt.Errorf("device id is required")
+ }
+ result, err := r.db.Exec(`
+ UPDATE devices SET webhook_url = ?, updated_at = ?
+ WHERE device_id = ?
+ `, webhookURL, time.Now(), deviceID)
+ if err != nil {
+ return err
+ }
+ rowsAffected, err := result.RowsAffected()
+ if err != nil {
+ return err
+ }
+ if rowsAffected == 0 {
+ return sql.ErrNoRows
+ }
+ return nil
+}
+
+// GetDeviceWebhookURL retrieves the configured webhook URL for a device.
+// Returns (*string, nil) with the URL if set, (nil, nil) if no device-specific webhook is configured,
+// or (nil, error) on storage errors. Empty string in database is treated as nil (no override).
+func (r *SQLiteRepository) GetDeviceWebhookURL(deviceID string) (*string, error) {
+ if strings.TrimSpace(deviceID) == "" {
+ return nil, fmt.Errorf("device id is required")
+ }
+ var webhookURL string
+ err := r.db.QueryRow(`
+ SELECT COALESCE(webhook_url, '') FROM devices WHERE device_id = ? LIMIT 1
+ `, deviceID).Scan(&webhookURL)
+ if err == sql.ErrNoRows {
+ return nil, nil
+ }
+ if err != nil {
+ return nil, err
+ }
+ if webhookURL == "" {
+ return nil, nil
+ }
+ return &webhookURL, nil
+}
+
+// SetDeviceWebhookConfig updates the complete webhook configuration for a device.
+// Returns sql.ErrNoRows if the device does not exist.
+func (r *SQLiteRepository) SetDeviceWebhookConfig(deviceID string, config *domainChatStorage.DeviceWebhookConfig) error {
+ if strings.TrimSpace(deviceID) == "" {
+ return fmt.Errorf("device id is required")
+ }
+ if config == nil {
+ return fmt.Errorf("webhook config is required")
+ }
+
+ var webhookURL *string
+ if config.WebhookURL != nil && *config.WebhookURL != "" {
+ webhookURL = config.WebhookURL
+ }
+
+ _, err := r.db.Exec(`
+ UPDATE devices
+ SET webhook_url = ?, webhook_secret = ?, webhook_events = ?, webhook_insecure_skip_verify = ?, updated_at = ?
+ WHERE device_id = ?
+ `, webhookURL, config.WebhookSecret, config.WebhookEvents, config.WebhookInsecureSkipVerify, time.Now(), deviceID)
+ if err != nil {
+ return err
+ }
+ return nil
+}
+
+// GetDeviceWebhookConfig retrieves the complete webhook configuration for a device.
+// Returns (nil, nil) if no device-specific webhook configuration is set.
+func (r *SQLiteRepository) GetDeviceWebhookConfig(deviceID string) (*domainChatStorage.DeviceWebhookConfig, error) {
+ if strings.TrimSpace(deviceID) == "" {
+ return nil, fmt.Errorf("device id is required")
+ }
+ var config domainChatStorage.DeviceWebhookConfig
+ var webhookURL *string
+ err := r.db.QueryRow(`
+ SELECT webhook_url, COALESCE(webhook_secret, ''), COALESCE(webhook_events, ''), COALESCE(webhook_insecure_skip_verify, FALSE)
+ FROM devices WHERE device_id = ? LIMIT 1
+ `, deviceID).Scan(&webhookURL, &config.WebhookSecret, &config.WebhookEvents, &config.WebhookInsecureSkipVerify)
+ if err == sql.ErrNoRows {
+ return nil, nil
+ }
+ if err != nil {
+ return nil, err
+ }
+ config.WebhookURL = webhookURL
+ return &config, nil
+}
+
// GetChatNameWithPushName determines the appropriate name for a chat with pushname support
func (r *SQLiteRepository) GetChatNameWithPushName(jid types.JID, chatJID string, senderUser string, pushName string) string {
// First, check if chat already exists with a name
@@ -2109,5 +2236,17 @@ func (r *SQLiteRepository) getMigrations() []string {
// Migration 30: Store WhatsApp media direct paths for downloads
`ALTER TABLE messages ADD COLUMN direct_path TEXT DEFAULT ''`,
+
+ // Migration 31: Store per-device webhook URL overrides
+ `ALTER TABLE devices ADD COLUMN webhook_url TEXT DEFAULT NULL`,
+
+ // Migration 32: Store per-device webhook signature secret
+ `ALTER TABLE devices ADD COLUMN webhook_secret TEXT DEFAULT ''`,
+
+ // Migration 33: Store per-device webhook event allow-list
+ `ALTER TABLE devices ADD COLUMN webhook_events TEXT DEFAULT ''`,
+
+ // Migration 34: Store per-device webhook TLS verification override
+ `ALTER TABLE devices ADD COLUMN webhook_insecure_skip_verify BOOLEAN DEFAULT FALSE`,
}
}
diff --git a/src/infrastructure/chatstorage/sqlite_repository_test.go b/src/infrastructure/chatstorage/sqlite_repository_test.go
index 90e29695..746baae4 100644
--- a/src/infrastructure/chatstorage/sqlite_repository_test.go
+++ b/src/infrastructure/chatstorage/sqlite_repository_test.go
@@ -45,6 +45,51 @@ func TestSQLiteRepositoryInitializesMessageReactionsSchema(t *testing.T) {
}
}
+func TestSQLiteRepositoryGetsDeviceWebhookConfigByJID(t *testing.T) {
+ repo := newTestSQLiteRepository(t)
+
+ webhookURL := "https://device-webhook.example.com"
+ if err := repo.SaveDeviceRecord(&domainChatStorage.DeviceRecord{
+ DeviceID: "session-a",
+ DisplayName: "Session A",
+ }); err != nil {
+ t.Fatalf("save device record: %v", err)
+ }
+
+ if err := repo.SetDeviceWebhookConfig("session-a", &domainChatStorage.DeviceWebhookConfig{
+ WebhookURL: &webhookURL,
+ WebhookSecret: "device-secret",
+ WebhookEvents: "message,message.ack",
+ WebhookInsecureSkipVerify: true,
+ }); err != nil {
+ t.Fatalf("set device webhook config: %v", err)
+ }
+
+ record, err := repo.GetDeviceRecordByJID("[email protected]")
+ if err != nil {
+ t.Fatalf("get device record by jid: %v", err)
+ }
+ if record == nil {
+ t.Fatal("expected device record")
+ }
+ if record.DeviceID != "session-a" {
+ t.Fatalf("expected session-a, got %q", record.DeviceID)
+ }
+ if record.WebhookURL == nil || *record.WebhookURL != webhookURL {
+ t.Fatalf("expected webhook URL %q, got %v", webhookURL, record.WebhookURL)
+ }
+ if record.WebhookSecret != "device-secret" {
+ t.Fatalf("expected device secret, got %q", record.WebhookSecret)
+ }
+ if record.WebhookEvents != "message,message.ack" {
+ t.Fatalf("expected webhook events, got %q", record.WebhookEvents)
+ }
+ if !record.WebhookInsecureSkipVerify {
+ t.Fatal("expected insecure skip verify to be true")
+ }
+}
+
func TestSQLiteRepositoryStoresUpdatesRemovesAndHydratesReactions(t *testing.T) {
repo := newTestSQLiteRepository(t)
deviceID := "[email protected]"
diff --git a/src/infrastructure/whatsapp/chatstorage_wrapper.go b/src/infrastructure/whatsapp/chatstorage_wrapper.go
index b2f32507..e042c9c0 100644
--- a/src/infrastructure/whatsapp/chatstorage_wrapper.go
+++ b/src/infrastructure/whatsapp/chatstorage_wrapper.go
@@ -261,10 +261,40 @@ func (r *deviceChatStorage) ListDeviceRecords() ([]*domainChatStorage.DeviceReco
return r.base.ListDeviceRecords()
}
+// GetDeviceRecord delegates to the base repository.
func (r *deviceChatStorage) GetDeviceRecord(deviceID string) (*domainChatStorage.DeviceRecord, error) {
return r.base.GetDeviceRecord(deviceID)
}
+// GetDeviceRecordByJID fetches a device record by its JID.
+func (r *deviceChatStorage) GetDeviceRecordByJID(jid string) (*domainChatStorage.DeviceRecord, error) {
+ return r.base.GetDeviceRecordByJID(jid)
+}
+
+// DeleteDeviceRecord delegates to the base repository.
func (r *deviceChatStorage) DeleteDeviceRecord(deviceID string) error {
return r.base.DeleteDeviceRecord(deviceID)
}
+
+// SetDeviceWebhookURL sets or clears the webhook URL for a device.
+// Pass a nil webhookURL to clear the device-specific webhook (falls back to global).
+// Pass a non-nil string pointer to set a device-specific webhook override.
+func (r *deviceChatStorage) SetDeviceWebhookURL(deviceID string, webhookURL *string) error {
+ return r.base.SetDeviceWebhookURL(deviceID, webhookURL)
+}
+
+// GetDeviceWebhookURL retrieves the configured webhook URL for a device.
+// Returns nil if no device-specific webhook is set (caller should use global).
+func (r *deviceChatStorage) GetDeviceWebhookURL(deviceID string) (*string, error) {
+ return r.base.GetDeviceWebhookURL(deviceID)
+}
+
+// SetDeviceWebhookConfig sets the complete webhook configuration for a device.
+func (r *deviceChatStorage) SetDeviceWebhookConfig(deviceID string, config *domainChatStorage.DeviceWebhookConfig) error {
+ return r.base.SetDeviceWebhookConfig(deviceID, config)
+}
+
+// GetDeviceWebhookConfig retrieves the complete webhook configuration for a device.
+func (r *deviceChatStorage) GetDeviceWebhookConfig(deviceID string) (*domainChatStorage.DeviceWebhookConfig, error) {
+ return r.base.GetDeviceWebhookConfig(deviceID)
+}
diff --git a/src/infrastructure/whatsapp/device_manager.go b/src/infrastructure/whatsapp/device_manager.go
index 17e5f972..47a995d2 100644
--- a/src/infrastructure/whatsapp/device_manager.go
+++ b/src/infrastructure/whatsapp/device_manager.go
@@ -765,3 +765,11 @@ func (m *DeviceManager) StoreInfo() (dbURI, keysURI string) {
}
return config.DBURI, config.DBKeysURI
}
+
+// GetStorage returns the chat storage repository.
+func (m *DeviceManager) GetStorage() domainChatStorage.IChatStorageRepository {
+ if m == nil {
+ return nil
+ }
+ return m.storage
+}
diff --git a/src/infrastructure/whatsapp/event_call.go b/src/infrastructure/whatsapp/event_call.go
index 8f6bd502..86f8af45 100644
--- a/src/infrastructure/whatsapp/event_call.go
+++ b/src/infrastructure/whatsapp/event_call.go
@@ -42,16 +42,14 @@ func handleCallOffer(ctx context.Context, evt *events.CallOffer, chatStorageRepo
}
}
- // Forward call event to webhook if configured
- if len(config.WhatsappWebhook) > 0 {
- go func(e *events.CallOffer, c *whatsmeow.Client, rejected bool) {
- webhookCtx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
- defer cancel()
- if err := forwardCallOfferToWebhook(webhookCtx, e, deviceID, c, rejected); err != nil {
- logrus.Errorf("Failed to forward call event to webhook: %v", err)
- }
- }(evt, client, autoRejected)
- }
+ // Forward call event to webhook
+ go func(e *events.CallOffer, c *whatsmeow.Client, rejected bool) {
+ webhookCtx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
+ defer cancel()
+ if err := forwardCallOfferToWebhook(webhookCtx, e, deviceID, c, rejected); err != nil {
+ logrus.Errorf("Failed to forward call event to webhook: %v", err)
+ }
+ }(evt, client, autoRejected)
}
// createCallOfferPayload creates a webhook payload for incoming call events
diff --git a/src/infrastructure/whatsapp/event_chat_presence.go b/src/infrastructure/whatsapp/event_chat_presence.go
index bcd3cef0..c12e04dd 100644
--- a/src/infrastructure/whatsapp/event_chat_presence.go
+++ b/src/infrastructure/whatsapp/event_chat_presence.go
@@ -4,7 +4,6 @@ import (
"context"
"time"
- "github.com/aldinokemal/go-whatsapp-web-multidevice/config"
"github.com/sirupsen/logrus"
"go.mau.fi/whatsmeow"
"go.mau.fi/whatsmeow/types"
@@ -25,16 +24,14 @@ func handleChatPresence(ctx context.Context, evt *events.ChatPresence, deviceID
log.Infof("%s stopped typing in %s", evt.Sender.ToNonAD(), evt.Chat.ToNonAD())
}
- // Forward chat presence event to webhook if configured
- if len(config.WhatsappWebhook) > 0 {
- go func(e *events.ChatPresence, c *whatsmeow.Client) {
- webhookCtx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
- defer cancel()
- if err := forwardChatPresenceToWebhook(webhookCtx, e, deviceID, c); err != nil {
- logrus.Errorf("Failed to forward chat_presence event to webhook: %v", err)
- }
- }(evt, client)
- }
+ // Forward chat presence event to webhook
+ go func(e *events.ChatPresence, c *whatsmeow.Client) {
+ webhookCtx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
+ defer cancel()
+ if err := forwardChatPresenceToWebhook(webhookCtx, e, deviceID, c); err != nil {
+ logrus.Errorf("Failed to forward chat_presence event to webhook: %v", err)
+ }
+ }(evt, client)
}
// createChatPresencePayload creates a webhook payload for chat presence (typing) events.
diff --git a/src/infrastructure/whatsapp/event_group.go b/src/infrastructure/whatsapp/event_group.go
index bb4bde2b..a32287ca 100644
--- a/src/infrastructure/whatsapp/event_group.go
+++ b/src/infrastructure/whatsapp/event_group.go
@@ -5,7 +5,6 @@ import (
"fmt"
"time"
- "github.com/aldinokemal/go-whatsapp-web-multidevice/config"
"github.com/sirupsen/logrus"
"go.mau.fi/whatsmeow"
"go.mau.fi/whatsmeow/types"
@@ -84,15 +83,14 @@ func forwardGroupInfoToWebhook(ctx context.Context, evt *events.GroupInfo, devic
func handleJoinedGroup(ctx context.Context, evt *events.JoinedGroup, deviceID string, client *whatsmeow.Client) {
log.Infof("Joined group %s (reason: %s, type: %s)", evt.JID, evt.Reason, evt.Type)
- if len(config.WhatsappWebhook) > 0 {
- go func(e *events.JoinedGroup, c *whatsmeow.Client) {
- webhookCtx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
- defer cancel()
- if err := forwardJoinedGroupToWebhook(webhookCtx, e, deviceID, c); err != nil {
- logrus.Errorf("Failed to forward joined group event to webhook: %v", err)
- }
- }(evt, client)
- }
+ // Forward joined group event to webhook
+ go func(e *events.JoinedGroup, c *whatsmeow.Client) {
+ webhookCtx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
+ defer cancel()
+ if err := forwardJoinedGroupToWebhook(webhookCtx, e, deviceID, c); err != nil {
+ logrus.Errorf("Failed to forward joined group event to webhook: %v", err)
+ }
+ }(evt, client)
}
// forwardJoinedGroupToWebhook forwards the JoinedGroup event to configured webhooks
diff --git a/src/infrastructure/whatsapp/event_handler.go b/src/infrastructure/whatsapp/event_handler.go
index 1fac6431..f89dab82 100644
--- a/src/infrastructure/whatsapp/event_handler.go
+++ b/src/infrastructure/whatsapp/event_handler.go
@@ -107,15 +107,13 @@ func handleDeleteForMe(ctx context.Context, evt *events.DeleteForMe, chatStorage
}
// Send webhook notification for delete event
- if len(config.WhatsappWebhook) > 0 {
- go func(c *whatsmeow.Client) {
- webhookCtx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
- defer cancel()
- if err := forwardDeleteToWebhook(webhookCtx, evt, message, deviceID, c); err != nil {
- log.Errorf("Failed to forward delete event to webhook: %v", err)
- }
- }(client)
- }
+ go func(c *whatsmeow.Client) {
+ webhookCtx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
+ defer cancel()
+ if err := forwardDeleteToWebhook(webhookCtx, evt, message, deviceID, c); err != nil {
+ log.Errorf("Failed to forward delete event to webhook: %v", err)
+ }
+ }(client)
}
func resolvePresenceOnConnect() (types.Presence, bool) {
@@ -289,7 +287,7 @@ func handleReceipt(ctx context.Context, evt *events.Receipt, deviceID string, cl
// Forward receipt (ack) event to webhook or Chatwoot if configured
// Note: Receipt events are not rate limited as they are critical for message delivery status
- if (len(config.WhatsappWebhook) > 0 || (config.ChatwootEnabled && config.ChatwootMessageRead)) && sendReceipt {
+ if sendReceipt {
go func(e *events.Receipt, c *whatsmeow.Client) {
webhookCtx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
@@ -349,14 +347,12 @@ func handleGroupInfo(ctx context.Context, evt *events.GroupInfo, deviceID string
log.Infof("Group %s: %d users demoted at %s", evt.JID, len(evt.Demote), evt.Timestamp)
}
- // Forward group info event to webhook if configured
- if len(config.WhatsappWebhook) > 0 {
- go func(e *events.GroupInfo, c *whatsmeow.Client) {
- webhookCtx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
- defer cancel()
- if err := forwardGroupInfoToWebhook(webhookCtx, e, deviceID, c); err != nil {
- logrus.Errorf("Failed to forward group info event to webhook: %v", err)
- }
- }(evt, client)
- }
+ // Forward group info event to webhook
+ go func(e *events.GroupInfo, c *whatsmeow.Client) {
+ webhookCtx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
+ defer cancel()
+ if err := forwardGroupInfoToWebhook(webhookCtx, e, deviceID, c); err != nil {
+ logrus.Errorf("Failed to forward group info event to webhook: %v", err)
+ }
+ }(evt, client)
}
diff --git a/src/infrastructure/whatsapp/event_message_handler.go b/src/infrastructure/whatsapp/event_message_handler.go
index bb46e5b4..488b936f 100644
--- a/src/infrastructure/whatsapp/event_message_handler.go
+++ b/src/infrastructure/whatsapp/event_message_handler.go
@@ -163,14 +163,18 @@ func handleWebhookForward(ctx context.Context, evt *events.Message, client *what
}
}
- if (len(config.WhatsappWebhook) > 0 || config.ChatwootEnabled) &&
- !strings.Contains(evt.Info.SourceString(), "broadcast") {
- go func(e *events.Message, c *whatsmeow.Client) {
- webhookCtx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
- defer cancel()
- if err := forwardMessageToWebhook(webhookCtx, c, e); err != nil {
- logrus.Error("Failed forward to webhook: ", err)
- }
- }(evt, client)
+ if !config.ChatwootEnabled &&
+ strings.Contains(evt.Info.SourceString(), "broadcast") {
+ return
}
+
+ // Forward to webhook if any webhook is configured (global or per-device)
+ // The forwardPayloadToConfiguredWebhooks function itself handles the no-op case
+ go func(e *events.Message, c *whatsmeow.Client) {
+ webhookCtx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
+ defer cancel()
+ if err := forwardMessageToWebhook(webhookCtx, c, e); err != nil {
+ logrus.Error("Failed forward to webhook: ", err)
+ }
+ }(evt, client)
}
diff --git a/src/infrastructure/whatsapp/event_message_handler_test.go b/src/infrastructure/whatsapp/event_message_handler_test.go
index 4ef4f9b5..05fc35da 100644
--- a/src/infrastructure/whatsapp/event_message_handler_test.go
+++ b/src/infrastructure/whatsapp/event_message_handler_test.go
@@ -39,7 +39,7 @@ func TestHandleMessageReactionStoresReactionAndForwardsWebhook(t *testing.T) {
repo := &messageHandlerRepoSpy{}
done := make(chan map[string]any, 1)
- submitWebhookFn = func(_ context.Context, payload map[string]any, _ string) error {
+ submitWebhookFn = func(_ context.Context, payload map[string]any, _ string, _ *domainChatStorage.DeviceWebhookConfig) error {
done <- payload
return nil
}
diff --git a/src/infrastructure/whatsapp/event_newsletter.go b/src/infrastructure/whatsapp/event_newsletter.go
index a0603513..39c12d8a 100644
--- a/src/infrastructure/whatsapp/event_newsletter.go
+++ b/src/infrastructure/whatsapp/event_newsletter.go
@@ -4,7 +4,6 @@ import (
"context"
"time"
- "github.com/aldinokemal/go-whatsapp-web-multidevice/config"
"github.com/sirupsen/logrus"
"go.mau.fi/whatsmeow"
"go.mau.fi/whatsmeow/types/events"
@@ -14,60 +13,52 @@ import (
func handleNewsletterJoin(ctx context.Context, evt *events.NewsletterJoin, deviceID string, client *whatsmeow.Client) {
log.Infof("Joined newsletter %s", evt.ID)
- if len(config.WhatsappWebhook) > 0 {
- go func(e *events.NewsletterJoin) {
- webhookCtx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
- defer cancel()
- if err := forwardNewsletterJoinToWebhook(webhookCtx, e, deviceID); err != nil {
- logrus.Errorf("Failed to forward newsletter join to webhook: %v", err)
- }
- }(evt)
- }
+ go func(e *events.NewsletterJoin) {
+ webhookCtx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
+ defer cancel()
+ if err := forwardNewsletterJoinToWebhook(webhookCtx, e, deviceID); err != nil {
+ logrus.Errorf("Failed to forward newsletter join to webhook: %v", err)
+ }
+ }(evt)
}
// handleNewsletterLeave handles when you leave/unsubscribe from a newsletter
func handleNewsletterLeave(ctx context.Context, evt *events.NewsletterLeave, deviceID string, client *whatsmeow.Client) {
log.Infof("Left newsletter %s (role: %s)", evt.ID, evt.Role)
- if len(config.WhatsappWebhook) > 0 {
- go func(e *events.NewsletterLeave) {
- webhookCtx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
- defer cancel()
- if err := forwardNewsletterLeaveToWebhook(webhookCtx, e, deviceID); err != nil {
- logrus.Errorf("Failed to forward newsletter leave to webhook: %v", err)
- }
- }(evt)
- }
+ go func(e *events.NewsletterLeave) {
+ webhookCtx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
+ defer cancel()
+ if err := forwardNewsletterLeaveToWebhook(webhookCtx, e, deviceID); err != nil {
+ logrus.Errorf("Failed to forward newsletter leave to webhook: %v", err)
+ }
+ }(evt)
}
// handleNewsletterLiveUpdate handles new messages in newsletters
func handleNewsletterLiveUpdate(ctx context.Context, evt *events.NewsletterLiveUpdate, deviceID string, client *whatsmeow.Client) {
log.Infof("Newsletter %s: %d new message(s)", evt.JID, len(evt.Messages))
- if len(config.WhatsappWebhook) > 0 {
- go func(e *events.NewsletterLiveUpdate) {
- webhookCtx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
- defer cancel()
- if err := forwardNewsletterLiveUpdateToWebhook(webhookCtx, e, deviceID); err != nil {
- logrus.Errorf("Failed to forward newsletter live update to webhook: %v", err)
- }
- }(evt)
- }
+ go func(e *events.NewsletterLiveUpdate) {
+ webhookCtx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
+ defer cancel()
+ if err := forwardNewsletterLiveUpdateToWebhook(webhookCtx, e, deviceID); err != nil {
+ logrus.Errorf("Failed to forward newsletter live update to webhook: %v", err)
+ }
+ }(evt)
}
// handleNewsletterMuteChange handles newsletter mute setting changes
func handleNewsletterMuteChange(ctx context.Context, evt *events.NewsletterMuteChange, deviceID string, client *whatsmeow.Client) {
log.Infof("Newsletter %s mute changed to: %s", evt.ID, evt.Mute)
- if len(config.WhatsappWebhook) > 0 {
- go func(e *events.NewsletterMuteChange) {
- webhookCtx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
- defer cancel()
- if err := forwardNewsletterMuteChangeToWebhook(webhookCtx, e, deviceID); err != nil {
- logrus.Errorf("Failed to forward newsletter mute change to webhook: %v", err)
- }
- }(evt)
- }
+ go func(e *events.NewsletterMuteChange) {
+ webhookCtx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
+ defer cancel()
+ if err := forwardNewsletterMuteChangeToWebhook(webhookCtx, e, deviceID); err != nil {
+ logrus.Errorf("Failed to forward newsletter mute change to webhook: %v", err)
+ }
+ }(evt)
}
// Webhook forwarding functions
diff --git a/src/infrastructure/whatsapp/webhook.go b/src/infrastructure/whatsapp/webhook.go
index 4dc85a49..51783b29 100644
--- a/src/infrastructure/whatsapp/webhook.go
+++ b/src/infrastructure/whatsapp/webhook.go
@@ -11,16 +11,30 @@ import (
"time"
"github.com/aldinokemal/go-whatsapp-web-multidevice/config"
+ "github.com/aldinokemal/go-whatsapp-web-multidevice/domains/chatstorage"
pkgError "github.com/aldinokemal/go-whatsapp-web-multidevice/pkg/error"
"github.com/aldinokemal/go-whatsapp-web-multidevice/pkg/utils"
"github.com/sirupsen/logrus"
)
-func submitWebhook(ctx context.Context, payload map[string]any, url string) error {
+func submitWebhook(ctx context.Context, payload map[string]any, url string, webhookConfig *chatstorage.DeviceWebhookConfig) error {
+ // Determine effective config - use device-specific if set, otherwise fall back to global
+ insecureSkipVerify := config.WhatsappWebhookInsecureSkipVerify
+ webhookSecret := config.WhatsappWebhookSecret
+
+ if webhookConfig != nil {
+ if webhookConfig.WebhookInsecureSkipVerify {
+ insecureSkipVerify = true
+ }
+ if webhookConfig.WebhookSecret != "" {
+ webhookSecret = webhookConfig.WebhookSecret
+ }
+ }
+
// Configure HTTP client with optional TLS skip verification
transport := &http.Transport{
TLSClientConfig: &tls.Config{
- InsecureSkipVerify: config.WhatsappWebhookInsecureSkipVerify,
+ InsecureSkipVerify: insecureSkipVerify,
},
}
client := &http.Client{
@@ -38,7 +52,7 @@ func submitWebhook(ctx context.Context, payload map[string]any, url string) erro
return pkgError.WebhookError(fmt.Sprintf("error when create http object %v", err))
}
- secretKey := []byte(config.WhatsappWebhookSecret)
+ secretKey := []byte(webhookSecret)
signature, err := utils.GetMessageDigestOrSignature(postBody, secretKey)
if err != nil {
return pkgError.WebhookError(fmt.Sprintf("error when create signature %v", err))
diff --git a/src/infrastructure/whatsapp/webhook_forward.go b/src/infrastructure/whatsapp/webhook_forward.go
index 1dcbdfe0..0545596c 100644
--- a/src/infrastructure/whatsapp/webhook_forward.go
+++ b/src/infrastructure/whatsapp/webhook_forward.go
@@ -85,7 +85,14 @@ func getContactMutex(phone string) *sync.Mutex {
// It only returns an error when all webhook deliveries fail. Partial failures are logged and suppressed so
// successful targets still receive the event.
func forwardPayloadToConfiguredWebhooks(ctx context.Context, payload map[string]any, eventName string) error {
- webhookAllowed := len(config.WhatsappWebhookEvents) == 0 || isEventWhitelisted(eventName)
+ deviceJID, _ := payload["device_id"].(string)
+ webhookConfig, err := getWebhookConfigForDevice(deviceJID)
+ if err != nil {
+ logrus.Warnf("Failed to get webhook config for device %s: %v", deviceJID, err)
+ return err
+ }
+
+ webhookAllowed := isEventWhitelistedForDevice(eventName, webhookConfig)
chatwootAllowed := config.ChatwootEnabled && shouldForwardEventToChatwoot(eventName) && isEventWhitelistedForChatwoot(eventName)
if !webhookAllowed && !chatwootAllowed {
@@ -93,6 +100,11 @@ func forwardPayloadToConfiguredWebhooks(ctx context.Context, payload map[string]
return nil
}
+ webhookURLs := getWebhookURLsFromConfig(webhookConfig)
+ if len(webhookURLs) == 0 {
+ webhookURLs = config.WhatsappWebhook
+ }
+
// 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,
@@ -102,9 +114,9 @@ func forwardPayloadToConfiguredWebhooks(ctx context.Context, payload map[string]
addWebhookSessionID(payload)
}
- var err error
+ var webhookErr error
if webhookAllowed {
- err = forwardToWebhooks(ctx, payload, eventName)
+ webhookErr = forwardToWebhooks(ctx, payload, eventName, webhookURLs, webhookConfig)
} else {
logrus.Debugf("Skipping event %s for configured webhooks, but allowing Chatwoot", eventName)
}
@@ -113,7 +125,69 @@ func forwardPayloadToConfiguredWebhooks(ctx context.Context, payload map[string]
go forwardToChatwoot(ctx, payload, eventName)
}
- return err
+ return webhookErr
+}
+
+// webhookStorageForTest is injectable for unit testing without a real DeviceManager.
+var webhookStorageForTest func(deviceJID string) (*domainChatStorage.DeviceRecord, error)
+
+// getDeviceRecordForTest resolves the device record, using test override if set.
+func getDeviceRecordForTest(deviceJID string) (*domainChatStorage.DeviceRecord, error) {
+ if webhookStorageForTest != nil {
+ return webhookStorageForTest(deviceJID)
+ }
+ dm := GetDeviceManager()
+ if dm != nil && dm.storage != nil {
+ return dm.storage.GetDeviceRecordByJID(deviceJID)
+ }
+ return nil, nil
+}
+
+// getWebhookConfigForDevice returns the webhook configuration to use for a given device.
+// If the device has a custom webhook config, it returns that config.
+// Otherwise, it returns nil (caller should use global config).
+func getWebhookConfigForDevice(deviceJID string) (*domainChatStorage.DeviceWebhookConfig, error) {
+ if deviceJID == "" {
+ return nil, nil
+ }
+
+ record, err := getDeviceRecordForTest(deviceJID)
+ if err != nil {
+ return nil, fmt.Errorf("failed to get device record: %w", err)
+ }
+ if record != nil && record.WebhookURL != nil && *record.WebhookURL != "" {
+ logrus.Debugf("Using device-specific webhook config for %s", deviceJID)
+ return &domainChatStorage.DeviceWebhookConfig{
+ WebhookURL: record.WebhookURL,
+ WebhookSecret: record.WebhookSecret,
+ WebhookEvents: record.WebhookEvents,
+ WebhookInsecureSkipVerify: record.WebhookInsecureSkipVerify,
+ }, nil
+ }
+
+ return nil, nil
+}
+
+// getWebhookURLsFromConfig extracts webhook URLs from the config.
+func getWebhookURLsFromConfig(config *domainChatStorage.DeviceWebhookConfig) []string {
+ if config == nil || config.WebhookURL == nil || *config.WebhookURL == "" {
+ return nil
+ }
+ return []string{*config.WebhookURL}
+}
+
+// isEventWhitelistedForDevice checks if an event is whitelisted for a specific device.
+// Uses device-specific events if set, otherwise falls back to global config.
+func isEventWhitelistedForDevice(eventName string, deviceConfig *domainChatStorage.DeviceWebhookConfig) bool {
+ if deviceConfig != nil && deviceConfig.WebhookEvents != "" {
+ for _, allowed := range strings.Split(deviceConfig.WebhookEvents, ",") {
+ if strings.EqualFold(strings.TrimSpace(allowed), eventName) {
+ return true
+ }
+ }
+ return false
+ }
+ return len(config.WhatsappWebhookEvents) == 0 || isEventWhitelisted(eventName)
}
// addWebhookSessionID injects the operator-facing session id into a webhook
@@ -151,8 +225,11 @@ func sessionIDForJID(jid string) string {
return ""
}
-func forwardToWebhooks(ctx context.Context, payload map[string]any, eventName string) error {
- total := len(config.WhatsappWebhook)
+// forwardToWebhooks delivers the payload to each URL in the webhookURLs slice.
+// It logs successes and failures, returning an error only if all deliveries fail.
+// Partial failures (some succeed, some fail) are logged but do not cause a return error.
+func forwardToWebhooks(ctx context.Context, payload map[string]any, eventName string, webhookURLs []string, webhookConfig *domainChatStorage.DeviceWebhookConfig) error {
+ total := len(webhookURLs)
logrus.Infof("Forwarding %s to %d configured webhook(s)", eventName, total)
if total == 0 {
@@ -163,8 +240,8 @@ func forwardToWebhooks(ctx context.Context, payload map[string]any, eventName st
failed []string
successes int
)
- for _, url := range config.WhatsappWebhook {
- if err := submitWebhookFn(ctx, payload, url); err != nil {
+ for _, url := range webhookURLs {
+ if err := submitWebhookFn(ctx, payload, url, webhookConfig); err != nil {
failed = append(failed, fmt.Sprintf("%s: %v", url, err))
logrus.Warnf("Failed forwarding %s to %s: %v", eventName, url, err)
continue
diff --git a/src/infrastructure/whatsapp/webhook_forward_test.go b/src/infrastructure/whatsapp/webhook_forward_test.go
index 8830b1f4..6fe4dd2b 100644
--- a/src/infrastructure/whatsapp/webhook_forward_test.go
+++ b/src/infrastructure/whatsapp/webhook_forward_test.go
@@ -8,16 +8,16 @@ import (
"testing"
"github.com/aldinokemal/go-whatsapp-web-multidevice/config"
- domainChatStorage "github.com/aldinokemal/go-whatsapp-web-multidevice/domains/chatstorage"
+ "github.com/aldinokemal/go-whatsapp-web-multidevice/domains/chatstorage"
"github.com/aldinokemal/go-whatsapp-web-multidevice/infrastructure/chatwoot"
)
type chatwootForwardQueueTestRepo struct {
- domainChatStorage.IChatStorageRepository
- events []*domainChatStorage.ChatwootForwardEvent
+ chatstorage.IChatStorageRepository
+ events []*chatstorage.ChatwootForwardEvent
}
-func (r *chatwootForwardQueueTestRepo) EnqueueChatwootForwardEvent(event *domainChatStorage.ChatwootForwardEvent) error {
+func (r *chatwootForwardQueueTestRepo) EnqueueChatwootForwardEvent(event *chatstorage.ChatwootForwardEvent) error {
cloned := *event
r.events = append(r.events, &cloned)
return nil
@@ -32,7 +32,7 @@ func TestForwardPayloadToConfiguredWebhooks_NoWebhooksConfigured(t *testing.T) {
defer func() { config.WhatsappWebhook = originalWebhooks }()
originalSubmit := submitWebhookFn
- submitWebhookFn = func(context.Context, map[string]any, string) error {
+ submitWebhookFn = func(context.Context, map[string]any, string, *chatstorage.DeviceWebhookConfig) error {
t.Fatal("submitWebhookFn should not be invoked when no webhooks are configured")
return nil
}
@@ -53,7 +53,7 @@ func TestForwardPayloadToConfiguredWebhooks_PartialFailure(t *testing.T) {
originalSubmit := submitWebhookFn
var attempts []string
- submitWebhookFn = func(_ context.Context, _ map[string]any, url string) error {
+ submitWebhookFn = func(_ context.Context, _ map[string]any, url string, _ *chatstorage.DeviceWebhookConfig) error {
attempts = append(attempts, url)
if strings.Contains(url, "fail") {
return errors.New("boom")
@@ -80,7 +80,7 @@ func TestForwardPayloadToConfiguredWebhooks_AllFail(t *testing.T) {
defer func() { config.WhatsappWebhook = originalWebhooks }()
originalSubmit := submitWebhookFn
- submitWebhookFn = func(_ context.Context, _ map[string]any, url string) error {
+ submitWebhookFn = func(_ context.Context, _ map[string]any, url string, _ *chatstorage.DeviceWebhookConfig) error {
return errors.New("failure for " + url)
}
defer func() { submitWebhookFn = originalSubmit }()
@@ -105,7 +105,7 @@ func TestForwardPayloadToConfiguredWebhooks_EventWhitelist_FilteredOut(t *testin
called := false
originalSubmit := submitWebhookFn
- submitWebhookFn = func(context.Context, map[string]any, string) error {
+ submitWebhookFn = func(context.Context, map[string]any, string, *chatstorage.DeviceWebhookConfig) error {
called = true
return nil
}
@@ -134,7 +134,7 @@ func TestForwardPayloadToConfiguredWebhooks_EventWhitelist_Allowed(t *testing.T)
called := false
originalSubmit := submitWebhookFn
- submitWebhookFn = func(context.Context, map[string]any, string) error {
+ submitWebhookFn = func(context.Context, map[string]any, string, *chatstorage.DeviceWebhookConfig) error {
called = true
return nil
}
@@ -163,7 +163,7 @@ func TestForwardPayloadToConfiguredWebhooks_EmptyWhitelist_AllowsAll(t *testing.
called := false
originalSubmit := submitWebhookFn
- submitWebhookFn = func(context.Context, map[string]any, string) error {
+ submitWebhookFn = func(context.Context, map[string]any, string, *chatstorage.DeviceWebhookConfig) error {
called = true
return nil
}
@@ -192,7 +192,7 @@ func TestForwardPayloadToConfiguredWebhooks_WhitelistCaseInsensitive(t *testing.
called := 0
originalSubmit := submitWebhookFn
- submitWebhookFn = func(context.Context, map[string]any, string) error {
+ submitWebhookFn = func(context.Context, map[string]any, string, *chatstorage.DeviceWebhookConfig) error {
called++
return nil
}
@@ -293,6 +293,219 @@ func TestExtractStructuredMessageContentWithContactsArrayPayload(t *testing.T) {
}
}
+func TestGetWebhookConfigForDevice_NoDeviceID(t *testing.T) {
+ originalWebhooks := config.WhatsappWebhook
+ config.WhatsappWebhook = []string{"https://global-webhook.com"}
+ defer func() { config.WhatsappWebhook = originalWebhooks }()
+
+ config, err := getWebhookConfigForDevice("")
+ if err != nil {
+ t.Fatalf("expected no error, got %v", err)
+ }
+ if config != nil {
+ t.Fatalf("expected nil config for empty deviceID, got %v", config)
+ }
+}
+
+func TestGetWebhookConfigForDevice_DeviceNotFound(t *testing.T) {
+ originalWebhooks := config.WhatsappWebhook
+ config.WhatsappWebhook = []string{"https://global-webhook.com"}
+ defer func() { config.WhatsappWebhook = originalWebhooks }()
+
+ originalStorageForTest := webhookStorageForTest
+ webhookStorageForTest = func(deviceJID string) (*chatstorage.DeviceRecord, error) {
+ return nil, nil // not found, no error
+ }
+ defer func() { webhookStorageForTest = originalStorageForTest }()
+
+ config, err := getWebhookConfigForDevice("[email protected]")
+ if err != nil {
+ t.Fatalf("expected no error, got %v", err)
+ }
+ if config != nil {
+ t.Fatalf("expected nil config when device not found, got %v", config)
+ }
+}
+
+func TestGetWebhookConfigForDevice_FallbackToGlobal(t *testing.T) {
+ originalWebhooks := config.WhatsappWebhook
+ config.WhatsappWebhook = []string{"https://global-webhook.com"}
+ defer func() { config.WhatsappWebhook = originalWebhooks }()
+
+ originalStorageForTest := webhookStorageForTest
+ emptyURL := ""
+ webhookStorageForTest = func(deviceJID string) (*chatstorage.DeviceRecord, error) {
+ return &chatstorage.DeviceRecord{
+ DeviceID: deviceJID,
+ WebhookURL: &emptyURL,
+ }, nil
+ }
+ defer func() { webhookStorageForTest = originalStorageForTest }()
+
+ config, err := getWebhookConfigForDevice("[email protected]")
+ if err != nil {
+ t.Fatalf("expected no error, got %v", err)
+ }
+ if config != nil {
+ t.Fatalf("expected nil config when device has no webhook, got %v", config)
+ }
+}
+
+func TestGetWebhookConfigForDevice_DeviceSpecificOverride(t *testing.T) {
+ deviceWebhookURL := "https://device-specific-webhook.com"
+ originalWebhooks := config.WhatsappWebhook
+ config.WhatsappWebhook = []string{"https://global-webhook.com"}
+ defer func() { config.WhatsappWebhook = originalWebhooks }()
+
+ originalStorageForTest := webhookStorageForTest
+ webhookStorageForTest = func(deviceJID string) (*chatstorage.DeviceRecord, error) {
+ return &chatstorage.DeviceRecord{
+ DeviceID: deviceJID,
+ WebhookURL: &deviceWebhookURL,
+ }, nil
+ }
+ defer func() { webhookStorageForTest = originalStorageForTest }()
+
+ config, err := getWebhookConfigForDevice("[email protected]")
+ if err != nil {
+ t.Fatalf("expected no error, got %v", err)
+ }
+ if config == nil {
+ t.Fatal("expected non-nil config when device has webhook")
+ }
+ if config.WebhookURL == nil || *config.WebhookURL != deviceWebhookURL {
+ t.Fatalf("expected device-specific webhook %s, got %v", deviceWebhookURL, config.WebhookURL)
+ }
+}
+
+func TestForwardPayloadToConfiguredWebhooks_WithDeviceSpecificWebhook(t *testing.T) {
+ ctx := context.Background()
+ deviceWebhookURL := "https://device-specific-webhook.com"
+ payload := map[string]any{
+ "foo": "bar",
+ "device_id": "[email protected]",
+ }
+
+ originalWebhooks := config.WhatsappWebhook
+ config.WhatsappWebhook = []string{"https://global-webhook.com"}
+ defer func() { config.WhatsappWebhook = originalWebhooks }()
+
+ originalStorageForTest := webhookStorageForTest
+ webhookStorageForTest = func(deviceJID string) (*chatstorage.DeviceRecord, error) {
+ return &chatstorage.DeviceRecord{
+ DeviceID: deviceJID,
+ WebhookURL: &deviceWebhookURL,
+ }, nil
+ }
+ defer func() { webhookStorageForTest = originalStorageForTest }()
+
+ var calledURLs []string
+ originalSubmit := submitWebhookFn
+ submitWebhookFn = func(_ context.Context, _ map[string]any, url string, _ *chatstorage.DeviceWebhookConfig) error {
+ calledURLs = append(calledURLs, url)
+ return nil
+ }
+ defer func() { submitWebhookFn = originalSubmit }()
+
+ if err := forwardPayloadToConfiguredWebhooks(ctx, payload, "test"); err != nil {
+ t.Fatalf("expected no error, got %v", err)
+ }
+
+ if len(calledURLs) != 1 {
+ t.Fatalf("expected 1 webhook call (device-specific override), got %d", len(calledURLs))
+ }
+ if calledURLs[0] != deviceWebhookURL {
+ t.Fatalf("expected device-specific webhook %s, got %s", deviceWebhookURL, calledURLs[0])
+ }
+}
+
+func TestForwardPayloadToConfiguredWebhooks_DeviceWebhookCleared_FallsBackToGlobal(t *testing.T) {
+ ctx := context.Background()
+ payload := map[string]any{
+ "foo": "bar",
+ "device_id": "[email protected]",
+ }
+
+ originalWebhooks := config.WhatsappWebhook
+ config.WhatsappWebhook = []string{"https://global-webhook.com"}
+ defer func() { config.WhatsappWebhook = originalWebhooks }()
+
+ originalStorageForTest := webhookStorageForTest
+ emptyURL := ""
+ webhookStorageForTest = func(deviceJID string) (*chatstorage.DeviceRecord, error) {
+ return &chatstorage.DeviceRecord{
+ DeviceID: deviceJID,
+ WebhookURL: &emptyURL,
+ }, nil
+ }
+ defer func() { webhookStorageForTest = originalStorageForTest }()
+
+ var calledURLs []string
+ originalSubmit := submitWebhookFn
+ submitWebhookFn = func(_ context.Context, _ map[string]any, url string, _ *chatstorage.DeviceWebhookConfig) error {
+ calledURLs = append(calledURLs, url)
+ return nil
+ }
+ defer func() { submitWebhookFn = originalSubmit }()
+
+ if err := forwardPayloadToConfiguredWebhooks(ctx, payload, "test"); err != nil {
+ t.Fatalf("expected no error, got %v", err)
+ }
+
+ if len(calledURLs) != 1 {
+ t.Fatalf("expected 1 webhook call (global fallback), got %d", len(calledURLs))
+ }
+ if calledURLs[0] != "https://global-webhook.com" {
+ t.Fatalf("expected global webhook, got %s", calledURLs[0])
+ }
+}
+
+// TestForwardPayloadToConfiguredWebhooks_DeviceWebhookOnly_NoGlobal verifies that when
+// no global webhook is configured but a device-specific webhook is set, events are
+// forwarded to the device-specific webhook. This is the primary path aldinokemal asked
+// to verify: "the feature should work when only a device webhook is set."
+func TestForwardPayloadToConfiguredWebhooks_DeviceWebhookOnly_NoGlobal(t *testing.T) {
+ ctx := context.Background()
+ deviceWebhookURL := "https://device-only-webhook.example.com"
+ payload := map[string]any{
+ "foo": "bar",
+ "device_id": "[email protected]",
+ }
+
+ // Ensure no global webhook is configured
+ originalWebhooks := config.WhatsappWebhook
+ config.WhatsappWebhook = nil
+ defer func() { config.WhatsappWebhook = originalWebhooks }()
+
+ originalStorageForTest := webhookStorageForTest
+ webhookStorageForTest = func(deviceJID string) (*chatstorage.DeviceRecord, error) {
+ return &chatstorage.DeviceRecord{
+ DeviceID: deviceJID,
+ WebhookURL: &deviceWebhookURL,
+ }, nil
+ }
+ defer func() { webhookStorageForTest = originalStorageForTest }()
+
+ var calledURLs []string
+ originalSubmit := submitWebhookFn
+ submitWebhookFn = func(_ context.Context, _ map[string]any, url string, _ *chatstorage.DeviceWebhookConfig) error {
+ calledURLs = append(calledURLs, url)
+ return nil
+ }
+ defer func() { submitWebhookFn = originalSubmit }()
+
+ if err := forwardPayloadToConfiguredWebhooks(ctx, payload, "message"); err != nil {
+ t.Fatalf("expected no error when only device webhook is set, got %v", err)
+ }
+
+ if len(calledURLs) != 1 {
+ t.Fatalf("expected 1 webhook call (device-specific only), got %d calls: %v", len(calledURLs), calledURLs)
+ }
+ if calledURLs[0] != deviceWebhookURL {
+ t.Fatalf("expected device-specific webhook %s, got %s", deviceWebhookURL, calledURLs[0])
+ }
+}
+
// 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.
@@ -365,7 +578,7 @@ func TestForwardPayloadInjectsSessionID(t *testing.T) {
var captured map[string]any
originalSubmit := submitWebhookFn
- submitWebhookFn = func(_ context.Context, payload map[string]any, _ string) error {
+ submitWebhookFn = func(_ context.Context, payload map[string]any, _ string, _ *chatstorage.DeviceWebhookConfig) error {
captured = payload
return nil
}
diff --git a/src/pkg/error/app_error.go b/src/pkg/error/app_error.go
index 97d89cb1..9be47313 100644
--- a/src/pkg/error/app_error.go
+++ b/src/pkg/error/app_error.go
@@ -67,11 +67,28 @@ func (err sessionSavedError) StatusCode() int {
return http.StatusInternalServerError
}
+type notFoundError string
+
+func (err notFoundError) Error() string {
+ return string(err)
+}
+
+// ErrCode will return the error code based on the error data type
+func (err notFoundError) ErrCode() string {
+ return "NOT_FOUND"
+}
+
+// StatusCode will return the HTTP status code based on the error data type
+func (err notFoundError) StatusCode() int {
+ return http.StatusNotFound
+}
+
var (
ErrAlreadyLoggedIn = LoginError("you are already logged in.")
ErrNotConnected = AuthError("you are not connect to services server, please reconnect")
ErrNotLoggedIn = AuthError("you are not logged in")
ErrReconnect = AuthError("reconnect error")
ErrQrChannel = qrChannelError("QR channel error")
- ErrSessionSaved = sessionSavedError("your session have been saved, please wait to connect 2 second and refresh again")
+ ErrSessionSaved = sessionSavedError("your session have been saved, please wait to connect 2 second and refresh again")
+ ErrDeviceNotFound = notFoundError("device not found")
)
diff --git a/src/ui/rest/device.go b/src/ui/rest/device.go
index 9a9fd7dc..1c854799 100644
--- a/src/ui/rest/device.go
+++ b/src/ui/rest/device.go
@@ -1,6 +1,7 @@
package rest
import (
+ "github.com/aldinokemal/go-whatsapp-web-multidevice/domains/chatstorage"
"github.com/aldinokemal/go-whatsapp-web-multidevice/domains/device"
"github.com/aldinokemal/go-whatsapp-web-multidevice/pkg/utils"
"github.com/gofiber/fiber/v2"
@@ -24,6 +25,8 @@ func InitRestDevice(app fiber.Router, service device.IDeviceUsecase) Device {
app.Post("/devices/:device_id/logout", rest.LogoutDevice)
app.Post("/devices/:device_id/reconnect", rest.ReconnectDevice)
app.Get("/devices/:device_id/status", rest.Status)
+ app.Patch("/devices/:device_id/webhook", rest.UpdateDeviceWebhook)
+ app.Get("/devices/:device_id/webhook", rest.GetDeviceWebhook)
return rest
}
@@ -55,7 +58,8 @@ func (handler *Device) GetDevice(c *fiber.Ctx) error {
func (handler *Device) AddDevice(c *fiber.Ctx) error {
var req struct {
- DeviceID string `json:"device_id"`
+ DeviceID string `json:"device_id"`
+ WebhookURL string `json:"webhook_url"`
}
if err := c.BodyParser(&req); err != nil {
@@ -67,7 +71,7 @@ func (handler *Device) AddDevice(c *fiber.Ctx) error {
})
}
- device, err := handler.Service.AddDevice(c.UserContext(), req.DeviceID)
+ device, err := handler.Service.AddDevice(c.UserContext(), req.DeviceID, req.WebhookURL)
utils.PanicIfNeeded(err)
result := map[string]any{
@@ -76,6 +80,7 @@ func (handler *Device) AddDevice(c *fiber.Ctx) error {
"jid": device.JID,
"state": device.State,
"created_at": device.CreatedAt,
+ "webhook_url": req.WebhookURL,
}
return c.JSON(utils.ResponseData{
@@ -170,3 +175,80 @@ func (handler *Device) Status(c *fiber.Ctx) error {
},
})
}
+
+// UpdateDeviceWebhook handles PATCH /devices/:device_id/webhook.
+func (handler *Device) UpdateDeviceWebhook(c *fiber.Ctx) error {
+ deviceID := c.Params("device_id")
+ var req struct {
+ WebhookURL *string `json:"webhook_url"`
+ WebhookSecret string `json:"webhook_secret"`
+ WebhookEvents string `json:"webhook_events"`
+ WebhookInsecureSkipVerify bool `json:"webhook_insecure_skip_verify"`
+ }
+
+ if err := c.BodyParser(&req); err != nil {
+ return c.Status(fiber.StatusBadRequest).JSON(utils.ResponseData{
+ Status: 400,
+ Code: "BAD_REQUEST",
+ Message: "Invalid request body",
+ Results: nil,
+ })
+ }
+
+ if req.WebhookURL == nil {
+ return c.Status(fiber.StatusBadRequest).JSON(utils.ResponseData{
+ Status: 400,
+ Code: "BAD_REQUEST",
+ Message: "webhook_url is required",
+ Results: nil,
+ })
+ }
+
+ config := &chatstorage.DeviceWebhookConfig{
+ WebhookURL: req.WebhookURL,
+ WebhookSecret: req.WebhookSecret,
+ WebhookEvents: req.WebhookEvents,
+ WebhookInsecureSkipVerify: req.WebhookInsecureSkipVerify,
+ }
+
+ err := handler.Service.SetDeviceWebhookConfig(c.UserContext(), deviceID, config)
+ utils.PanicIfNeeded(err)
+
+ return c.JSON(utils.ResponseData{
+ Status: 200,
+ Code: "SUCCESS",
+ Message: "Device webhook updated",
+ Results: map[string]any{
+ "device_id": deviceID,
+ "webhook_url": *req.WebhookURL,
+ "webhook_secret": req.WebhookSecret,
+ "webhook_events": req.WebhookEvents,
+ "webhook_insecure_skip_verify": req.WebhookInsecureSkipVerify,
+ },
+ })
+}
+
+// GetDeviceWebhook handles GET /devices/:device_id/webhook.
+func (handler *Device) GetDeviceWebhook(c *fiber.Ctx) error {
+ deviceID := c.Params("device_id")
+ config, err := handler.Service.GetDeviceWebhookConfig(c.UserContext(), deviceID)
+ utils.PanicIfNeeded(err)
+
+ webhookURL := ""
+ if config != nil && config.WebhookURL != nil {
+ webhookURL = *config.WebhookURL
+ }
+
+ return c.JSON(utils.ResponseData{
+ Status: 200,
+ Code: "SUCCESS",
+ Message: "Device webhook retrieved",
+ Results: map[string]any{
+ "device_id": deviceID,
+ "webhook_url": webhookURL,
+ "webhook_secret": func() string { if config != nil { return config.WebhookSecret }; return "" }(),
+ "webhook_events": func() string { if config != nil { return config.WebhookEvents }; return "" }(),
+ "webhook_insecure_skip_verify": func() bool { if config != nil { return config.WebhookInsecureSkipVerify }; return false }(),
+ },
+ })
+}
diff --git a/src/usecase/device.go b/src/usecase/device.go
index 48e5ea32..c9cc3422 100644
--- a/src/usecase/device.go
+++ b/src/usecase/device.go
@@ -4,8 +4,10 @@ import (
"context"
"fmt"
+ "github.com/aldinokemal/go-whatsapp-web-multidevice/domains/chatstorage"
domainDevice "github.com/aldinokemal/go-whatsapp-web-multidevice/domains/device"
"github.com/aldinokemal/go-whatsapp-web-multidevice/infrastructure/whatsapp"
+ pkgError "github.com/aldinokemal/go-whatsapp-web-multidevice/pkg/error"
"github.com/aldinokemal/go-whatsapp-web-multidevice/ui/websocket"
"github.com/aldinokemal/go-whatsapp-web-multidevice/validations"
"github.com/sirupsen/logrus"
@@ -45,7 +47,7 @@ func (s *serviceDevice) GetDevice(_ context.Context, deviceID string) (*domainDe
return nil, fmt.Errorf("device %s not found", deviceID)
}
-func (s *serviceDevice) AddDevice(ctx context.Context, deviceID string) (*domainDevice.Device, error) {
+func (s *serviceDevice) AddDevice(ctx context.Context, deviceID string, webhookURL string) (*domainDevice.Device, error) {
if s.manager == nil {
return nil, fmt.Errorf("device manager not initialized")
}
@@ -54,6 +56,17 @@ func (s *serviceDevice) AddDevice(ctx context.Context, deviceID string) (*domain
if err != nil {
return nil, err
}
+
+ // Set device-specific webhook if provided
+ if webhookURL != "" {
+ storage := s.manager.GetStorage()
+ if storage != nil {
+ if err := storage.SetDeviceWebhookURL(deviceID, &webhookURL); err != nil {
+ logrus.Warnf("Failed to set webhook for device %s: %v", deviceID, err)
+ }
+ }
+ }
+
device := convertInstance(inst)
return &device, nil
}
@@ -163,6 +176,128 @@ func (s *serviceDevice) GetStatus(_ context.Context, deviceID string) (bool, boo
return false, false, fmt.Errorf("device %s not found", deviceID)
}
+// SetDeviceWebhook sets the webhook URL for a specific device.
+func (s *serviceDevice) SetDeviceWebhook(ctx context.Context, deviceID string, webhookURL string) error {
+ if s.manager == nil {
+ return fmt.Errorf("device manager not initialized")
+ }
+
+ _, ok := s.manager.GetDevice(deviceID)
+ if !ok {
+ return pkgError.ErrDeviceNotFound
+ }
+
+ storage := s.manager.GetStorage()
+ if storage == nil {
+ return fmt.Errorf("storage not available")
+ }
+
+ var urlPtr *string
+ if webhookURL != "" {
+ urlPtr = &webhookURL
+ }
+
+ // Use deviceID (the actual device identifier) for webhook persistence
+ if err := storage.SetDeviceWebhookURL(deviceID, urlPtr); err != nil {
+ return fmt.Errorf("failed to set device webhook: %w", err)
+ }
+
+ websocket.Broadcast <- websocket.BroadcastMessage{
+ Code: "DEVICE_WEBHOOK_UPDATED",
+ Message: fmt.Sprintf("Device %s webhook updated", deviceID),
+ Result: map[string]any{
+ "device_id": deviceID,
+ "webhook_url": webhookURL,
+ },
+ }
+
+ return nil
+}
+
+// GetDeviceWebhook retrieves the webhook URL for a specific device.
+func (s *serviceDevice) GetDeviceWebhook(ctx context.Context, deviceID string) (string, error) {
+ if s.manager == nil {
+ return "", fmt.Errorf("device manager not initialized")
+ }
+
+ _, ok := s.manager.GetDevice(deviceID)
+ if !ok {
+ return "", fmt.Errorf("device %s not found", deviceID)
+ }
+
+ storage := s.manager.GetStorage()
+ if storage == nil {
+ return "", fmt.Errorf("storage not available")
+ }
+
+ // Use deviceID (the actual device identifier) for webhook retrieval
+ webhookURL, err := storage.GetDeviceWebhookURL(deviceID)
+ if err != nil {
+ return "", fmt.Errorf("failed to get device webhook: %w", err)
+ }
+
+ if webhookURL == nil {
+ return "", nil
+ }
+
+ return *webhookURL, nil
+}
+
+// SetDeviceWebhookConfig sets the complete webhook configuration for a specific device.
+func (s *serviceDevice) SetDeviceWebhookConfig(ctx context.Context, deviceID string, config *chatstorage.DeviceWebhookConfig) error {
+ if s.manager == nil {
+ return fmt.Errorf("device manager not initialized")
+ }
+
+ _, ok := s.manager.GetDevice(deviceID)
+ if !ok {
+ return pkgError.ErrDeviceNotFound
+ }
+
+ storage := s.manager.GetStorage()
+ if storage == nil {
+ return fmt.Errorf("storage not available")
+ }
+
+ if err := storage.SetDeviceWebhookConfig(deviceID, config); err != nil {
+ return fmt.Errorf("failed to set device webhook config: %w", err)
+ }
+
+ websocket.Broadcast <- websocket.BroadcastMessage{
+ Code: "DEVICE_WEBHOOK_CONFIG_UPDATED",
+ Message: fmt.Sprintf("Device %s webhook config updated", deviceID),
+ Result: map[string]any{
+ "device_id": deviceID,
+ },
+ }
+
+ return nil
+}
+
+// GetDeviceWebhookConfig retrieves the complete webhook configuration for a specific device.
+func (s *serviceDevice) GetDeviceWebhookConfig(ctx context.Context, deviceID string) (*chatstorage.DeviceWebhookConfig, error) {
+ if s.manager == nil {
+ return nil, fmt.Errorf("device manager not initialized")
+ }
+
+ _, ok := s.manager.GetDevice(deviceID)
+ if !ok {
+ return nil, pkgError.ErrDeviceNotFound
+ }
+
+ storage := s.manager.GetStorage()
+ if storage == nil {
+ return nil, fmt.Errorf("storage not available")
+ }
+
+ config, err := storage.GetDeviceWebhookConfig(deviceID)
+ if err != nil {
+ return nil, fmt.Errorf("failed to get device webhook config: %w", err)
+ }
+
+ return config, nil
+}
+
func convertInstance(inst *whatsapp.DeviceInstance) domainDevice.Device {
if inst == nil {
return domainDevice.Device{}
diff --git a/src/usecase/device_test.go b/src/usecase/device_test.go
new file mode 100644
index 00000000..26c7ccec
--- /dev/null
+++ b/src/usecase/device_test.go
@@ -0,0 +1,36 @@
+package usecase
+
+import (
+ "context"
+ "testing"
+
+ domainDevice "github.com/aldinokemal/go-whatsapp-web-multidevice/domains/device"
+)
+
+func TestDeviceServiceInterface(t *testing.T) {
+ var _ domainDevice.IDeviceUsecase = (*serviceDevice)(nil)
+}
+
+func TestSetDeviceWebhook_InvalidManager(t *testing.T) {
+ svc := &serviceDevice{manager: nil}
+ err := svc.SetDeviceWebhook(context.Background(), "test-device", "https://example.com/webhook")
+ if err == nil {
+ t.Fatal("expected error when manager is nil")
+ }
+ if err.Error() != "device manager not initialized" {
+ t.Fatalf("unexpected error: %v", err)
+ }
+}
+
+func TestGetDeviceWebhook_InvalidManager(t *testing.T) {
+ svc := &serviceDevice{manager: nil}
+ _, err := svc.GetDeviceWebhook(context.Background(), "test-device")
+ if err == nil {
+ t.Fatal("expected error when manager is nil")
+ }
+ if err.Error() != "device manager not initialized" {
+ t.Fatalf("unexpected error: %v", err)
+ }
+}
+
+
diff --git a/src/views/components/CallReject.js b/src/views/components/CallReject.js
index 08afa5ae..0adfeae6 100644
--- a/src/views/components/CallReject.js
+++ b/src/views/components/CallReject.js
@@ -79,7 +79,7 @@ export default {
</div>
</div>
</div>
-
+
<!-- Modal CallReject -->
<div class="ui small modal" id="modalCallReject">
<i class="close icon"></i>
@@ -94,7 +94,7 @@ export default {
aria-label="caller phone number">
<input :value="caller_jid" disabled aria-label="caller jid">
</div>
-
+
<div class="field">
<label>Call ID</label>
<input v-model="call_id" type="text" placeholder="Call ID from webhook event"
diff --git a/src/views/components/DeviceManager.js b/src/views/components/DeviceManager.js
index 6d281c14..c8ae808a 100644
--- a/src/views/components/DeviceManager.js
+++ b/src/views/components/DeviceManager.js
@@ -13,7 +13,11 @@ export default {
deviceIdInput: '',
isCreatingDevice: false,
deviceToDelete: { id: '', jid: '', state: '' },
- isDeleting: false
+ isDeleting: false,
+ webhookUrlInput: '',
+ webhookSecretInput: '',
+ webhookEventsInput: '',
+ webhookInsecureSkipVerify: false
}
},
computed: {
@@ -53,10 +57,26 @@ export default {
try {
this.isCreatingDevice = true;
const payload = this.deviceIdInput ? {device_id: this.deviceIdInput} : {};
+ if (this.webhookUrlInput) {
+ payload.webhook_url = this.webhookUrlInput;
+ }
+ if (this.webhookSecretInput) {
+ payload.webhook_secret = this.webhookSecretInput;
+ }
+ if (this.webhookEventsInput) {
+ payload.webhook_events = this.webhookEventsInput;
+ }
+ if (this.webhookInsecureSkipVerify) {
+ payload.webhook_insecure_skip_verify = this.webhookInsecureSkipVerify;
+ }
const res = await window.http.post('/devices', payload);
const deviceID = res.data?.results?.id || res.data?.results?.device_id || this.deviceIdInput;
this.setDeviceContext(deviceID);
this.deviceIdInput = '';
+ this.webhookUrlInput = '';
+ this.webhookSecretInput = '';
+ this.webhookEventsInput = '';
+ this.webhookInsecureSkipVerify = false;
} catch (err) {
const msg = err.response?.data?.message || err.message || 'Failed to create device';
showErrorInfo(msg);
@@ -146,22 +166,42 @@ export default {
</div>
</h3>
<div class="ui form">
- <div class="two fields">
+ <div class="fields">
<div class="field">
<label>Device ID (optional)</label>
<input type="text" v-model="deviceIdInput" placeholder="Leave empty to auto-generate">
</div>
+ </div>
+ <div class="fields">
+ <div class="field">
+ <label>Webhook URL (optional)</label>
+ <input type="text" v-model="webhookUrlInput" placeholder="https://your-webhook.com/handler">
+ </div>
<div class="field">
- <label>Actions</label>
- <div class="ui buttons">
- <button class="ui primary button" :class="{loading: isCreatingDevice}" @click="createDevice">
- Create device
- </button>
- <div class="or"></div>
- <button class="ui button" @click="useDeviceFromInput">Use this device</button>
+ <label>Webhook Secret (optional)</label>
+ <input type="text" v-model="webhookSecretInput" placeholder="secret-key">
+ </div>
+ </div>
+ <div class="fields">
+ <div class="field">
+ <label>Webhook Events (optional, comma-separated)</label>
+ <input type="text" v-model="webhookEventsInput" placeholder="message,message.ack,group.participants">
+ </div>
+ <div class="field">
+ <label>Skip TLS Verify</label>
+ <div class="ui checkbox">
+ <input type="checkbox" v-model="webhookInsecureSkipVerify">
+ <label></label>
</div>
</div>
</div>
+ <div class="ui buttons">
+ <button class="ui primary button" :class="{loading: isCreatingDevice}" @click="createDevice">
+ Create device
+ </button>
+ <div class="or"></div>
+ <button class="ui button" @click="useDeviceFromInput">Use this device</button>
+ </div>
</div>
<div class="ui divider"></div>