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(call): add API endpoint for rejecting incoming calls (#735)
No Namecf6f2b0be342
diff --git a/docs/openapi.yaml b/docs/openapi.yamlindex 26be3a77..31a7bdc5 100644--- a/docs/openapi.yaml+++ b/docs/openapi.yaml@@ -21,6 +21,8 @@ tags:description: Send Message (Text/Image/File/Video).- name: messagedescription: Message manipulation (revoke/react/update).+ - name: call+ description: Call management (reject incoming calls)- name: chatdescription: Chat conversations and messaging- name: group@@ -1914,6 +1916,64 @@ paths:schema:$ref: '#/components/schemas/ErrorInternalServer'+ /call/reject:+ post:+ operationId: rejectCall+ tags:+ - call+ summary: Reject an incoming call+ 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+ parameters:+ - $ref: '#/components/parameters/DeviceIdHeader'+ requestBody:+ required: true+ content:+ application/json:+ schema:+ type: object+ required:+ - caller_jid+ - call_id+ properties:+ caller_jid:+ type: string+ example: '[email protected]'+ description: JID of the caller (from webhook `payload.from`)+ call_id:+ type: string+ example: 'ABC123DEF456'+ description: Unique call identifier (from webhook `payload.call_id`)+ responses:+ '200':+ description: Call rejected successfully+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/GenericResponse'+ '400':+ description: Bad Request (missing or invalid fields)+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/ErrorBadRequest'+ '500':+ description: Internal Server Error (call already ended, not connected, etc.)+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/ErrorInternalServer'+/chats:get:operationId: listChatsdiff --git a/docs/webhook-payload.md b/docs/webhook-payload.mdindex 3b6c1b0f..d14dbece 100644--- a/docs/webhook-payload.md+++ b/docs/webhook-payload.md@@ -652,6 +652,107 @@ WHATSAPP_AUTO_REJECT_CALL=true./whatsapp rest --auto-reject-call=true```+### Reject Call via API++In addition to auto-rejecting all calls, you can programmatically reject specific calls using the REST API. This is useful when you want to apply custom logic (e.g., time-of-day rules, caller whitelists, or agent availability checks).++**Endpoint:** `POST /call/reject`++**Headers:**+```http+X-Device-Id: <device_id>+Content-Type: application/json+```++**Request Body:**+```json+{+ "caller_jid": "[email protected]",+ "call_id": "ABC123DEF456"+}+```++**Where to get these values:**++When you receive a `call.offer` webhook event, extract the values from the payload:++```json+{+ "event": "call.offer",+ "device_id": "[email protected]",+ "payload": {+ "call_id": "ABC123DEF456",+ "from": "[email protected]",+ "auto_rejected": false+ }+}+```++- `caller_jid` → Use `payload.from` from the webhook+- `call_id` → Use `payload.call_id` from the webhook++**Example (curl):**++```bash+curl -X POST http://localhost:3000/call/reject \+ -H "X-Device-Id: [email protected]" \+ -H "Content-Type: application/json" \+ -d '{+ "caller_jid": "[email protected]",+ "call_id": "ABC123DEF456"+ }'+```++**Example (JavaScript/Node.js):**++```javascript+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', {+ caller_jid: payload.from,+ call_id: payload.call_id+ }, {+ headers: {+ 'X-Device-Id': device_id,+ 'Content-Type': 'application/json'+ }+ });+ console.log(`Rejected call from ${payload.from}`);+ } catch (error) {+ console.error('Failed to reject call:', error.message);+ }+ }+ }++ res.sendStatus(200);+});+```++**Important Notes:**++- **Timing:** The call must still be ringing. Rejection will fail if the call has already ended or been answered.+- **Device-scoped:** The `X-Device-Id` header is required and must match the device that received the call.+- **Error handling:** If the call has already ended, the API will return an error. Handle this gracefully in your application.+- **Complementary to auto-reject:** If `WHATSAPP_AUTO_REJECT_CALL=true`, all calls are rejected automatically before the webhook is sent. The API is for selective rejection when auto-reject is disabled.++**Webhook Integration Pattern:**++1. Enable `call.offer` in `WHATSAPP_WEBHOOK_EVENTS`+2. Set up a webhook receiver endpoint in your application+3. When a `call.offer` event arrives, apply your business logic+4. If the call should be rejected, call `POST /call/reject` with the values from the webhook payload+5. The call is rejected on WhatsApp, and the caller sees a "declined" status+## Media Messages### Image Messagediff --git a/src/cmd/rest.go b/src/cmd/rest.goindex 1b6cbab2..9ab5ecfa 100644--- a/src/cmd/rest.go+++ b/src/cmd/rest.go@@ -141,6 +141,7 @@ func restServer(_ *cobra.Command, _ []string) {registerDeviceScopedRoutes := func(r fiber.Router) {rest.InitRestApp(r, appUsecase)+ rest.InitRestCall(r, callUsecase)rest.InitRestChat(r, chatUsecase)rest.InitRestSend(r, sendUsecase)rest.InitRestUser(r, userUsecase)diff --git a/src/cmd/root.go b/src/cmd/root.goindex 4d341c13..da1d09e9 100644--- a/src/cmd/root.go+++ b/src/cmd/root.go@@ -13,6 +13,7 @@ import ("github.com/aldinokemal/go-whatsapp-web-multidevice/config"domainApp "github.com/aldinokemal/go-whatsapp-web-multidevice/domains/app"+ domainCall "github.com/aldinokemal/go-whatsapp-web-multidevice/domains/call"domainChat "github.com/aldinokemal/go-whatsapp-web-multidevice/domains/chat"domainChatStorage "github.com/aldinokemal/go-whatsapp-web-multidevice/domains/chatstorage"domainDevice "github.com/aldinokemal/go-whatsapp-web-multidevice/domains/device"@@ -46,6 +47,7 @@ var (// UsecaseappUsecase domainApp.IAppUsecase+ callUsecase domainCall.ICallUsecasechatUsecase domainChat.IChatUsecasesendUsecase domainSend.ISendUsecaseuserUsecase domainUser.IUserUsecase@@ -571,6 +573,7 @@ func initApp() {// UsecaseappUsecase = usecase.NewAppService(chatStorageRepo, dm)+ callUsecase = usecase.NewCallService()chatUsecase = usecase.NewChatService(chatStorageRepo)sendUsecase = usecase.NewSendService(appUsecase, chatStorageRepo)userUsecase = usecase.NewUserService(chatStorageRepo)diff --git a/src/domains/call/call.go b/src/domains/call/call.gonew file mode 100644index 00000000..224864db--- /dev/null+++ b/src/domains/call/call.go@@ -0,0 +1,12 @@+package call++import "context"++type ICallUsecase interface {+ RejectCall(ctx context.Context, callerJID string, callID string) error+}++type RejectCallRequest struct {+ CallerJID string `json:"caller_jid" form:"caller_jid"`+ CallID string `json:"call_id" form:"call_id"`+}diff --git a/src/ui/rest/call.go b/src/ui/rest/call.gonew file mode 100644index 00000000..730248c1--- /dev/null+++ b/src/ui/rest/call.go@@ -0,0 +1,38 @@+package rest++import (+ domainCall "github.com/aldinokemal/go-whatsapp-web-multidevice/domains/call"+ "github.com/aldinokemal/go-whatsapp-web-multidevice/infrastructure/whatsapp"+ "github.com/aldinokemal/go-whatsapp-web-multidevice/pkg/utils"+ "github.com/gofiber/fiber/v2"+)++type Call struct {+ Service domainCall.ICallUsecase+}++func InitRestCall(app fiber.Router, service domainCall.ICallUsecase) Call {+ rest := Call{Service: service}+ app.Post("/call/reject", rest.RejectCall)+ return rest+}++func (controller *Call) RejectCall(c *fiber.Ctx) error {+ var request domainCall.RejectCallRequest+ err := c.BodyParser(&request)+ utils.PanicIfNeeded(err)++ err = controller.Service.RejectCall(+ whatsapp.ContextWithDevice(c.UserContext(), getDeviceFromCtx(c)),+ request.CallerJID,+ request.CallID,+ )+ utils.PanicIfNeeded(err)++ return c.JSON(utils.ResponseData{+ Status: 200,+ Code: "SUCCESS",+ Message: "Call rejected successfully",+ Results: nil,+ })+}diff --git a/src/usecase/call.go b/src/usecase/call.gonew file mode 100644index 00000000..6d5f9cac--- /dev/null+++ b/src/usecase/call.go@@ -0,0 +1,48 @@+package usecase++import (+ "context"+ "fmt"+ "time"++ domainCall "github.com/aldinokemal/go-whatsapp-web-multidevice/domains/call"+ "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/pkg/utils"+ "github.com/aldinokemal/go-whatsapp-web-multidevice/validations"+ "github.com/sirupsen/logrus"+)++type serviceCall struct{}++func NewCallService() domainCall.ICallUsecase {+ return &serviceCall{}+}++func (service serviceCall) RejectCall(ctx context.Context, callerJID string, callID string) error {+ if err := validations.ValidateRejectCall(ctx, callerJID, callID); err != nil {+ return err+ }++ client := whatsapp.ClientFromContext(ctx)+ if client == nil {+ return pkgError.ErrWaCLI+ }++ utils.MustLogin(client)+ parsedJID, err := utils.ParseJID(callerJID)+ if err != nil {+ return err+ }++ rejectCtx, cancel := context.WithTimeout(ctx, 10*time.Second)+ defer cancel()++ if err := client.RejectCall(rejectCtx, parsedJID, callID); err != nil {+ logrus.WithError(err).Error("Failed to reject call")+ return fmt.Errorf("failed to reject call: %w", err)+ }++ logrus.Info("Rejected call successfully")+ return nil+}diff --git a/src/validations/call_validation.go b/src/validations/call_validation.gonew file mode 100644index 00000000..5cdb87ab--- /dev/null+++ b/src/validations/call_validation.go@@ -0,0 +1,29 @@+package validations++import (+ "context"+ "strings"++ domainCall "github.com/aldinokemal/go-whatsapp-web-multidevice/domains/call"+ pkgError "github.com/aldinokemal/go-whatsapp-web-multidevice/pkg/error"+ validation "github.com/go-ozzo/ozzo-validation/v4"+)++func ValidateRejectCall(ctx context.Context, callerJID string, callID string) error {+ callerJID = strings.TrimSpace(callerJID)+ callID = strings.TrimSpace(callID)+ request := domainCall.RejectCallRequest{+ CallerJID: callerJID,+ CallID: callID,+ }+ err := validation.ValidateStructWithContext(ctx, &request,+ validation.Field(&request.CallerJID, validation.Required),+ validation.Field(&request.CallID, validation.Required),+ )++ if err != nil {+ return pkgError.ValidationError(err.Error())+ }++ return nil+}diff --git a/src/views/components/CallReject.js b/src/views/components/CallReject.jsnew file mode 100644index 00000000..08afa5ae--- /dev/null+++ b/src/views/components/CallReject.js@@ -0,0 +1,114 @@+export default {+ name: 'CallReject',+ data() {+ return {+ phone: '',+ call_id: '',+ loading: false,+ }+ },+ computed: {+ caller_jid() {+ const trimmed = this.phone.trim().replace(/\s+/g, '');+ if (trimmed.includes('@')) {+ return trimmed;+ }+ return trimmed + window.TYPEUSER;+ }+ },+ methods: {+ openModal() {+ $('#modalCallReject').modal({+ onApprove: function () {+ return false;+ }+ }).modal('show');+ },+ isValidForm() {+ if (!this.phone.trim()) {+ return false;+ }+ if (!this.call_id.trim()) {+ return false;+ }+ return true;+ },+ async handleSubmit() {+ if (!this.isValidForm() || this.loading) {+ return;+ }+ try {+ let response = await this.submitApi()+ showSuccessInfo(response)+ $('#modalCallReject').modal('hide');+ } catch (err) {+ showErrorInfo(err)+ }+ },+ async submitApi() {+ this.loading = true;+ try {+ const payload = {+ caller_jid: this.caller_jid,+ call_id: this.call_id.trim(),+ }+ let response = await window.http.post(`/call/reject`, payload)+ this.handleReset();+ return response.data.message;+ } catch (error) {+ if (error.response) {+ throw new Error(error.response.data.message);+ }+ throw new Error(error.message);+ } finally {+ this.loading = false;+ }+ },+ handleReset() {+ this.phone = '';+ this.call_id = '';+ },+ },+ template: `+ <div class="red card" @click="openModal()" style="cursor: pointer">+ <div class="content">+ <a class="ui red right ribbon label">Call</a>+ <div class="header">Reject Call</div>+ <div class="description">+ Reject an incoming call by providing the caller JID and call ID from the webhook+ </div>+ </div>+ </div>++ <!-- Modal CallReject -->+ <div class="ui small modal" id="modalCallReject">+ <i class="close icon"></i>+ <div class="header">+ Reject Incoming Call+ </div>+ <div class="content">+ <form class="ui form" @submit.prevent>+ <div class="field">+ <label>Caller Phone Number</label>+ <input v-model="phone" type="text" placeholder="e.g. 628912345678"+ 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"+ aria-label="call id">+ </div>+ </form>+ </div>+ <div class="actions">+ <button class="ui approve negative right labeled icon button" :class="{'loading': this.loading, 'disabled': !isValidForm() || loading}"+ @click="handleSubmit">+ Reject Call+ <i class="phone slash icon"></i>+ </button>+ </div>+ </div>+ `+}diff --git a/src/views/index.html b/src/views/index.htmlindex d6fb5385..1451fe1b 100644--- a/src/views/index.html+++ b/src/views/index.html@@ -112,6 +112,14 @@<message-read></message-read></div>+ <div class="ui horizontal divider">+ Call+ </div>++ <div class="ui three column doubling grid cards">+ <call-reject></call-reject>+ </div>+<div class="ui horizontal divider">Group</div>@@ -249,6 +257,7 @@import ChatList from "{{ .AppBasePath }}/components/ChatList.js";import ChatMessages from "{{ .AppBasePath }}/components/ChatMessages.js";import DeviceManager from "{{ .AppBasePath }}/components/DeviceManager.js";+ import CallReject from "{{ .AppBasePath }}/components/CallReject.js";const showErrorInfo = (message) => {$('body').toast({@@ -278,6 +287,7 @@NewsletterList,AccountAvatar, AccountUserInfo, AccountPrivacy, AccountChangeAvatar, AccountContact, AccountChangePushName, AccountUserCheck, AccountBusinessProfile,ChatPinManager, ChatDisappearingManager, ChatList, ChatMessages,+ CallReject,DeviceManager},delimiters: ['[[', ']]'],