Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

feat(contacts): save, edit and remove addressbook contacts

Yudhi Armyndharis63c30dd4ec88
diff --git a/CHANGELOG.md b/CHANGELOG.md
index f862a9ef8..cf742015d 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -9,6 +9,17 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Added
+- **Addressbook contacts can be saved, edited and removed:**
+ `PUT /api/sessions/:sessionId/contacts/:contactId` with `{ firstName, lastName? }`, and
+ `DELETE` on the same path. Supported on both engines and exposed in all five SDKs as
+ `contacts.upsert` / `contacts.delete`. This writes the WhatsApp contact record only — it does not
+ block the contact or touch the chat.
+
+ The two engines address the entry differently — whatsapp-web.js by bare phone number, Baileys by
+ JID — so the adapters convert from the neutral contact id. Neither syncs through to the device
+ addressbook: both are called with their sync-to-device flag off, so the behaviour does not depend
+ on which engine is running.
+
- **`memberAddMode` on group settings — who may add participants.** `PUT /groups/:groupId/settings`
accepts `memberAddMode: "all" | "admins"`, `GET .../settings` reports it, and `GroupInfo` carries
it. Supported on both engines. Exposed on the `GroupSettings` shape in all five SDKs.
diff --git a/docs/06-api-specification.md b/docs/06-api-specification.md
index e18a7b201..0806a42f1 100644
--- a/docs/06-api-specification.md
+++ b/docs/06-api-specification.md
@@ -1889,6 +1889,45 @@ Resolve a contact id (e.g. an `@lid`) to a phone number (MSISDN digits), best-ef
**Errors:** `400` session is not started · `401` missing/invalid API key
+#### PUT /api/sessions/:sessionId/contacts/:contactId
+
+Save a contact to the account's addressbook, or edit an existing entry. This is the WhatsApp
+contact record — it does not block, delete, or otherwise touch the chat.
+
+**Auth:** API key (OPERATOR)
+
+**Path parameters**
+
+| Name | Type | Description |
+| --- | --- | --- |
+| sessionId | string | Session ID |
+| contactId | string | Contact ID (e.g. `[email protected]`) |
+
+**Request body** — `UpsertContactDto`
+
+| Field | Type | Required | Constraints | Description |
+| --- | --- | --- | --- | --- |
+| firstName | string | Yes | 1–100 chars | The contact's first name |
+| lastName | string | No | ≤ 100 chars | Omit for a single-name contact — WhatsApp allows those |
+
+**Response** `200` — `{ "success": true, "message": "Contact saved" }`
+
+> The entry is saved to the WhatsApp addressbook only; it is **not** synced through to the device
+> addressbook. Both engines are called with their sync-to-device flag off, so behaviour matches
+> across engines rather than depending on which one is running.
+
+**Errors:** `400` session not active or invalid request · `401` missing/invalid API key · `403` key lacks OPERATOR role
+
+#### DELETE /api/sessions/:sessionId/contacts/:contactId
+
+Remove a contact from the account's addressbook. Does not block the contact or delete the chat.
+
+**Auth:** API key (OPERATOR)
+
+**Response** `200` — `{ "success": true, "message": "Contact deleted" }`
+
+**Errors:** `400` session not active · `401` missing/invalid API key · `403` key lacks OPERATOR role
+
#### POST /api/sessions/:sessionId/contacts/:contactId/block
Block a contact.
diff --git a/docs/07-api-collection.md b/docs/07-api-collection.md
index f2ae59977..7cba93e10 100644
--- a/docs/07-api-collection.md
+++ b/docs/07-api-collection.md
@@ -548,6 +548,25 @@ curl -X GET "$BASE/api/sessions/$SESSION_ID/contacts/12345678901234@lid/phone" \
-H "X-API-Key: $API_KEY"
```
+#### PUT /api/sessions/:sessionId/contacts/:contactId
+
+Save or edit an addressbook contact.
+
+```bash
+curl -X PUT "$BASE/api/sessions/$SESSION_ID/contacts/[email protected]" \
+ -H "X-API-Key: $API_KEY" -H "Content-Type: application/json" \
+ -d '{"firstName":"Ada","lastName":"Lovelace"}'
+```
+
+#### DELETE /api/sessions/:sessionId/contacts/:contactId
+
+Remove an addressbook contact.
+
+```bash
+curl -X DELETE "$BASE/api/sessions/$SESSION_ID/contacts/[email protected]" \
+ -H "X-API-Key: $API_KEY"
+```
+
#### POST /api/sessions/:sessionId/contacts/:contactId/block
Block a contact (requires an OPERATOR key). Send an empty body.
diff --git a/docs/18-sdk-design.md b/docs/18-sdk-design.md
index abb672920..87ed2905c 100644
--- a/docs/18-sdk-design.md
+++ b/docs/18-sdk-design.md
@@ -30,7 +30,7 @@ All five SDKs expose the same fluent surface:
| --- | --- |
| `sessions` | list, get, create, delete, start, stop, logout, forceKill, getQrCode, requestPairingCode, stats |
| `messages` | list, sendText, sendImage/Video/Audio/Document/Sticker, sendLocation, sendContact, sendTemplate, sendPoll, reply, forward, react, delete, editMessage, history, reactions, media, pin, unpin, star, sendBulk, batchStatus, cancelBatch |
-| `contacts` | list, get, check, profilePicture, profilePictures, phone, block, unblock |
+| `contacts` | list, get, check, profilePicture, profilePictures, phone, upsert, delete, block, unblock |
| `groups` | list, get, create, joinGroup, add/remove/promote/demoteParticipants, setSubject, setDescription, getGroupSettings, updateGroupSettings, leave, inviteCode, revokeInviteCode |
| `webhooks` | list, get, create, update, delete, test |
| `chats` | list, markRead, markUnread, archive, clearMessages, delete, sendState |
diff --git a/docs/29-engine-capability-matrix.md b/docs/29-engine-capability-matrix.md
index c0da5f2ee..ebb685a99 100644
--- a/docs/29-engine-capability-matrix.md
+++ b/docs/29-engine-capability-matrix.md
@@ -168,8 +168,8 @@ These are hand-maintained and had drifted from the source before this pass; they
from `engine-capability-matrix.ts` rather than adjusted by hand. Re-derive them the same way when
adding a method, instead of incrementing the previous figure.
-- **86** interface methods, **172** adapter-cells (86 × 2 engines).
-- **155** supported cells; **17** not-available cells across **16** methods.
+- **88** interface methods, **176** adapter-cells (88 × 2 engines).
+- **159** supported cells; **17** not-available cells across **16** methods.
- Of the 17 not-available cells: **2 adapter-gaps** (fixable) + **15 library-limitations** + **0 uncertain**.
- **0 phantom-support rows** — every `not-available` row throws at the adapter boundary.
diff --git a/openapi.json b/openapi.json
index 9d63c32ee..6181d7dbe 100644
--- a/openapi.json
+++ b/openapi.json
@@ -3187,6 +3187,86 @@
"tags": [
"contacts"
]
+ },
+ "put": {
+ "operationId": "ContactController_upsertContact",
+ "parameters": [
+ {
+ "name": "sessionId",
+ "required": true,
+ "in": "path",
+ "description": "Session ID",
+ "schema": {
+ "type": "string"
+ }
+ },
+ {
+ "name": "contactId",
+ "required": true,
+ "in": "path",
+ "description": "Contact ID (e.g., [email protected])",
+ "schema": {
+ "type": "string"
+ }
+ }
+ ],
+ "requestBody": {
+ "required": true,
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/UpsertContactDto"
+ }
+ }
+ }
+ },
+ "responses": {
+ "200": {
+ "description": "Contact saved"
+ },
+ "400": {
+ "description": "Session not active or invalid request"
+ }
+ },
+ "summary": "Save a contact to the account's addressbook, or edit an existing entry",
+ "tags": [
+ "contacts"
+ ]
+ },
+ "delete": {
+ "operationId": "ContactController_deleteContact",
+ "parameters": [
+ {
+ "name": "sessionId",
+ "required": true,
+ "in": "path",
+ "description": "Session ID",
+ "schema": {
+ "type": "string"
+ }
+ },
+ {
+ "name": "contactId",
+ "required": true,
+ "in": "path",
+ "description": "Contact ID (e.g., [email protected])",
+ "schema": {
+ "type": "string"
+ }
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "Contact deleted"
+ },
+ "400": {
+ "description": "Session not active"
+ }
+ },
+ "summary": "Remove a contact from the account's addressbook",
+ "tags": [
+ "contacts"
+ ]
}
},
"/api/sessions/{sessionId}/contacts/check/{number}": {
@@ -7868,6 +7948,24 @@
}
}
},
+ "UpsertContactDto": {
+ "type": "object",
+ "properties": {
+ "firstName": {
+ "type": "string",
+ "description": "The contact's first name.",
+ "maxLength": 100
+ },
+ "lastName": {
+ "type": "string",
+ "description": "The contact's last name. Omit for a single-name contact — WhatsApp allows those.",
+ "maxLength": 100
+ }
+ },
+ "required": [
+ "firstName"
+ ]
+ },
"JoinGroupDto": {
"type": "object",
"properties": {
diff --git a/sdk/README.md b/sdk/README.md
index b15873206..edf235729 100644
--- a/sdk/README.md
+++ b/sdk/README.md
@@ -26,7 +26,7 @@ All five SDKs expose the same fluent resource surface:
| ---------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `sessions` | list, get, create, delete, start, stop, logout, forceKill, getQrCode, requestPairingCode, stats |
| `messages` | list, sendText, sendImage/Video/Audio/Document/Sticker, sendLocation, sendContact, sendTemplate, sendPoll, reply, forward, react, delete, editMessage, history, reactions, media, pin, unpin, star, sendBulk, batchStatus, cancelBatch |
-| `contacts` | list, get, check, profilePicture, profilePictures, phone, block, unblock |
+| `contacts` | list, get, check, profilePicture, profilePictures, phone, upsert, delete, block, unblock |
| `groups` | list, get, create, joinGroup, add/remove/promote/demoteParticipants, setSubject, setDescription, get/updateGroupSettings, leave, inviteCode, revokeInviteCode |
| `webhooks` | list, get, create, update, delete, test |
| `chats` | list, markRead, markUnread, archive, clearMessages, delete, sendState |
diff --git a/sdk/go/contacts.go b/sdk/go/contacts.go
index 334996861..0cb75419f 100644
--- a/sdk/go/contacts.go
+++ b/sdk/go/contacts.go
@@ -75,6 +75,24 @@ func (s *ContactsService) Phone(ctx context.Context, sessionID, contactID string
}
// Block blocks a contact.
+// Upsert saves a contact to the addressbook, or edits an existing entry.
+func (s *ContactsService) Upsert(ctx context.Context, sessionID, contactID string, body UpsertContactRequest) (*SuccessResult, error) {
+ var out SuccessResult
+ if err := s.client.do(ctx, "PUT", s.base(sessionID)+"/"+pathEscape(contactID), nil, body, &out); err != nil {
+ return nil, err
+ }
+ return &out, nil
+}
+
+// Delete removes a contact from the addressbook.
+func (s *ContactsService) Delete(ctx context.Context, sessionID, contactID string) (*SuccessResult, error) {
+ var out SuccessResult
+ if err := s.client.do(ctx, "DELETE", s.base(sessionID)+"/"+pathEscape(contactID), nil, nil, &out); err != nil {
+ return nil, err
+ }
+ return &out, nil
+}
+
func (s *ContactsService) Block(ctx context.Context, sessionID, contactID string) (*SuccessResult, error) {
var out SuccessResult
err := s.client.do(ctx, "POST", s.base(sessionID)+"/"+pathEscape(contactID)+"/block", nil, nil, &out)
diff --git a/sdk/go/routing_test.go b/sdk/go/routing_test.go
index 9d74c4203..0acb02f11 100644
--- a/sdk/go/routing_test.go
+++ b/sdk/go/routing_test.go
@@ -57,6 +57,8 @@ func TestRouting(t *testing.T) {
{"Contacts.ProfilePicture", func(c *Client) { c.Contacts.ProfilePicture(ctx, "s1", "u1") }, "GET", "/api/sessions/s1/contacts/u1/profile-picture"},
{"Contacts.ProfilePictures", func(c *Client) { c.Contacts.ProfilePictures(ctx, "s1", []string{"u1"}) }, "GET", "/api/sessions/s1/contacts/profile-pictures"},
{"Contacts.Phone", func(c *Client) { c.Contacts.Phone(ctx, "s1", "u1") }, "GET", "/api/sessions/s1/contacts/u1/phone"},
+ {"Contacts.Upsert", func(c *Client) { c.Contacts.Upsert(ctx, "s1", "c1", UpsertContactRequest{}) }, "PUT", "/api/sessions/s1/contacts/c1"},
+ {"Contacts.Delete", func(c *Client) { c.Contacts.Delete(ctx, "s1", "c1") }, "DELETE", "/api/sessions/s1/contacts/c1"},
{"Contacts.Block", func(c *Client) { c.Contacts.Block(ctx, "s1", "u1") }, "POST", "/api/sessions/s1/contacts/u1/block"},
{"Contacts.Unblock", func(c *Client) { c.Contacts.Unblock(ctx, "s1", "u1") }, "DELETE", "/api/sessions/s1/contacts/u1/block"},
diff --git a/sdk/go/types_contact.go b/sdk/go/types_contact.go
index 5e3ce8ee3..d259dafc6 100644
--- a/sdk/go/types_contact.go
+++ b/sdk/go/types_contact.go
@@ -48,3 +48,10 @@ func (q *ListContactsQuery) values() url.Values {
setInt(v, "offset", q.Offset)
return v
}
+
+// UpsertContactRequest saves or edits an addressbook contact. LastName may be
+// empty for a single-name contact.
+type UpsertContactRequest struct {
+ FirstName string `json:"firstName"`
+ LastName string `json:"lastName,omitempty"`
+}
diff --git a/sdk/java/src/main/java/com/rmyndharis/openwa/model/UpsertContactRequest.java b/sdk/java/src/main/java/com/rmyndharis/openwa/model/UpsertContactRequest.java
new file mode 100644
index 000000000..7e2ebc101
--- /dev/null
+++ b/sdk/java/src/main/java/com/rmyndharis/openwa/model/UpsertContactRequest.java
@@ -0,0 +1,28 @@
+package com.rmyndharis.openwa.model;
+
+/** Request body for saving or editing an addressbook contact. */
+public record UpsertContactRequest(String firstName, String lastName) {
+ public static Builder builder() {
+ return new Builder();
+ }
+
+ public static final class Builder {
+ private String firstName;
+ private String lastName;
+
+ public Builder firstName(String v) {
+ this.firstName = v;
+ return this;
+ }
+
+ /** Omit for a single-name contact. */
+ public Builder lastName(String v) {
+ this.lastName = v;
+ return this;
+ }
+
+ public UpsertContactRequest build() {
+ return new UpsertContactRequest(firstName, lastName);
+ }
+ }
+}
diff --git a/sdk/java/src/main/java/com/rmyndharis/openwa/resources/ContactsResource.java b/sdk/java/src/main/java/com/rmyndharis/openwa/resources/ContactsResource.java
index 2cb3ea508..b7f988b02 100644
--- a/sdk/java/src/main/java/com/rmyndharis/openwa/resources/ContactsResource.java
+++ b/sdk/java/src/main/java/com/rmyndharis/openwa/resources/ContactsResource.java
@@ -11,6 +11,7 @@ import com.rmyndharis.openwa.model.ListContactsQuery;
import com.rmyndharis.openwa.model.ProfilePictureResponse;
import com.rmyndharis.openwa.model.ProfilePicturesResponse;
import com.rmyndharis.openwa.model.SuccessResult;
+import com.rmyndharis.openwa.model.UpsertContactRequest;
import java.util.List;
import java.util.Map;
@@ -95,6 +96,26 @@ public final class ContactsResource {
SuccessResult.class);
}
+ /** Save a contact to the addressbook, or edit an existing entry. Requires an OPERATOR key. */
+ public SuccessResult upsert(String sessionId, String contactId, UpsertContactRequest body) {
+ return client.request(
+ HttpMethod.PUT,
+ "/api/sessions/" + encodeSegment(sessionId) + "/contacts/" + encodeSegment(contactId),
+ null,
+ body,
+ SuccessResult.class);
+ }
+
+ /** Remove a contact from the addressbook. Requires an OPERATOR key. */
+ public SuccessResult delete(String sessionId, String contactId) {
+ return client.request(
+ HttpMethod.DELETE,
+ "/api/sessions/" + encodeSegment(sessionId) + "/contacts/" + encodeSegment(contactId),
+ null,
+ null,
+ SuccessResult.class);
+ }
+
/** Unblock a contact. Requires an OPERATOR-level key. */
public SuccessResult unblock(String sessionId, String contactId) {
return client.request(
diff --git a/sdk/java/src/test/java/com/rmyndharis/openwa/resources/ContactsResourceTest.java b/sdk/java/src/test/java/com/rmyndharis/openwa/resources/ContactsResourceTest.java
index f443ea8c0..a1e300abe 100644
--- a/sdk/java/src/test/java/com/rmyndharis/openwa/resources/ContactsResourceTest.java
+++ b/sdk/java/src/test/java/com/rmyndharis/openwa/resources/ContactsResourceTest.java
@@ -7,6 +7,7 @@ import static org.junit.jupiter.api.Assertions.assertTrue;
import com.rmyndharis.openwa.ClientConfig;
import com.rmyndharis.openwa.OpenWAClient;
import com.rmyndharis.openwa.http.HttpMethod;
+import com.rmyndharis.openwa.model.UpsertContactRequest;
import com.rmyndharis.openwa.model.ListContactsQuery;
import com.rmyndharis.openwa.model.ProfilePicturesResponse;
import com.rmyndharis.openwa.support.MockTransport;
@@ -94,4 +95,16 @@ class ContactsResourceTest {
assertEquals("http://h/api/sessions/s/contacts/[email protected]/block", tx.lastRequest().url());
assertEquals(HttpMethod.DELETE, tx.lastRequest().method());
}
+
+ @Test
+ void addressbookUpsertAndDelete() {
+ tx.respond(200, "{\"success\":true}");
+ client.contacts.upsert("s", "[email protected]", UpsertContactRequest.builder().firstName("Ada").build());
+ assertEquals("http://h/api/sessions/s/contacts/[email protected]", tx.lastRequest().url());
+ assertEquals(HttpMethod.PUT, tx.lastRequest().method());
+
+ tx.respond(200, "{\"success\":true}");
+ client.contacts.delete("s", "[email protected]");
+ assertEquals(HttpMethod.DELETE, tx.lastRequest().method());
+ }
}
diff --git a/sdk/javascript/src/resources/contacts.ts b/sdk/javascript/src/resources/contacts.ts
index ea2557ffa..fb8693e75 100644
--- a/sdk/javascript/src/resources/contacts.ts
+++ b/sdk/javascript/src/resources/contacts.ts
@@ -8,6 +8,7 @@
import { encodeSegment } from '../http.js';
import type { OpenWAClient } from '../client.js';
import type {
+ UpsertContactRequest,
CheckNumberResponse,
ContactPhoneResponse,
ContactRecord,
@@ -85,6 +86,26 @@ export class ContactsResource {
});
}
+ /**
+ * Save a contact to the account's addressbook, or edit an existing entry.
+ * Requires an OPERATOR-level key.
+ */
+ upsert(sessionId: string, contactId: string, body: UpsertContactRequest): Promise<SuccessResult> {
+ return this.client.request<SuccessResult>({
+ method: 'PUT',
+ path: `/api/sessions/${encodeSegment(sessionId)}/contacts/${encodeSegment(contactId)}`,
+ body,
+ });
+ }
+
+ /** Remove a contact from the account's addressbook. Requires an OPERATOR-level key. */
+ delete(sessionId: string, contactId: string): Promise<SuccessResult> {
+ return this.client.request<SuccessResult>({
+ method: 'DELETE',
+ path: `/api/sessions/${encodeSegment(sessionId)}/contacts/${encodeSegment(contactId)}`,
+ });
+ }
+
/** Unblock a contact. Requires an OPERATOR-level key. */
unblock(sessionId: string, contactId: string): Promise<SuccessResult> {
return this.client.request<SuccessResult>({
diff --git a/sdk/javascript/src/types.ts b/sdk/javascript/src/types.ts
index 88a151f67..cd3fc738d 100644
--- a/sdk/javascript/src/types.ts
+++ b/sdk/javascript/src/types.ts
@@ -188,6 +188,13 @@ export interface PinMessageRequest {
durationSeconds?: PinDurationSeconds;
}
+export interface UpsertContactRequest {
+ /** The contact's first name. */
+ firstName: string;
+ /** Omit for a single-name contact. */
+ lastName?: string;
+}
+
export interface ArchiveChatRequest {
chatId: Jid;
/** true to archive, false to unarchive. */
diff --git a/sdk/javascript/test/resources.test.ts b/sdk/javascript/test/resources.test.ts
index 725487d20..b978f8b3c 100644
--- a/sdk/javascript/test/resources.test.ts
+++ b/sdk/javascript/test/resources.test.ts
@@ -281,6 +281,21 @@ describe('ChatsResource.clearMessages', () => {
});
});
+describe('ContactsResource addressbook', () => {
+ it('PUTs the contact and DELETEs it by the same path', async () => {
+ const t = new MockTransport()
+ .on('PUT', /\/contacts\/[^/]+$/, { body: { success: true } })
+ .on('DELETE', /\/contacts\/[^/]+$/, { body: { success: true } });
+ const c = client(t);
+ await c.contacts.upsert('s', '[email protected]', { firstName: 'Ada' });
+ expect(t.lastCall!.method).toBe('PUT');
+ expect(t.lastCall!.url).toBe('http://x/api/sessions/s/contacts/[email protected]');
+ expect(t.lastCall!.body).toEqual({ firstName: 'Ada' });
+ await c.contacts.delete('s', '[email protected]');
+ expect(t.lastCall!.method).toBe('DELETE');
+ });
+});
+
describe('ChatsResource.archive', () => {
it('posts chatId and the archive flag', async () => {
const t = new MockTransport().on('POST', /\/chats\/archive$/, { body: { success: true } });
diff --git a/sdk/php/src/Resources/ContactsResource.php b/sdk/php/src/Resources/ContactsResource.php
index 18a3142f0..19482e1e2 100644
--- a/sdk/php/src/Resources/ContactsResource.php
+++ b/sdk/php/src/Resources/ContactsResource.php
@@ -74,6 +74,27 @@ class ContactsResource
return $this->http->request('POST', "/api/sessions/{$this->http->encodeSegment($sessionId)}/contacts/{$this->http->encodeSegment($contactId)}/block");
}
+ /**
+ * Save a contact to the addressbook, or edit an existing entry. Requires an OPERATOR key.
+ *
+ * @param array<string,mixed> $body firstName and an optional lastName.
+ * @return array<string,mixed>
+ */
+ public function upsert(string $sessionId, string $contactId, array $body): array
+ {
+ return $this->http->request('PUT', "/api/sessions/{$this->http->encodeSegment($sessionId)}/contacts/{$this->http->encodeSegment($contactId)}", [], $body) ?? [];
+ }
+
+ /**
+ * Remove a contact from the addressbook. Requires an OPERATOR key.
+ *
+ * @return array<string,mixed>
+ */
+ public function delete(string $sessionId, string $contactId): array
+ {
+ return $this->http->request('DELETE', "/api/sessions/{$this->http->encodeSegment($sessionId)}/contacts/{$this->http->encodeSegment($contactId)}") ?? [];
+ }
+
/** @return array<string,mixed> */
public function unblock(string $sessionId, string $contactId): array
{
diff --git a/sdk/php/tests/ResourcesTest.php b/sdk/php/tests/ResourcesTest.php
index 8de131ea6..02b535288 100644
--- a/sdk/php/tests/ResourcesTest.php
+++ b/sdk/php/tests/ResourcesTest.php
@@ -248,6 +248,19 @@ class ResourcesTest extends TestCase
$this->assertSame('/api/sessions/s/chats/[email protected]/messages', $backend->lastCall()['path']);
}
+ public function testContactsAddressbook(): void
+ {
+ $backend = new MockBackend();
+ $backend->on(200, ['success' => true]);
+ $backend->on(200, ['success' => true]);
+ $client = $backend->makeClient();
+ $client->contacts->upsert('s', '[email protected]', ['firstName' => 'Ada']);
+ $this->assertSame('PUT', $backend->lastCall()['method']);
+ $this->assertSame('/api/sessions/s/contacts/[email protected]', $backend->lastCall()['path']);
+ $client->contacts->delete('s', '[email protected]');
+ $this->assertSame('DELETE', $backend->lastCall()['method']);
+ }
+
public function testChatsArchive(): void
{
$backend = new MockBackend();
diff --git a/sdk/python/openwa/resources/contacts.py b/sdk/python/openwa/resources/contacts.py
index 7af29c4d5..0bcf9ea40 100644
--- a/sdk/python/openwa/resources/contacts.py
+++ b/sdk/python/openwa/resources/contacts.py
@@ -9,6 +9,7 @@ from typing import TYPE_CHECKING, TypedDict
from .._http import quote_segment
from ..types import (
+ UpsertContactRequest,
CheckNumberResponse,
ContactPhoneResponse,
ContactRecord,
@@ -57,5 +58,17 @@ class ContactsResource:
def block(self, session_id: str, contact_id: str) -> SuccessResult:
return self._http.request("POST", f"/api/sessions/{quote_segment(session_id)}/contacts/{quote_segment(contact_id)}/block")
+ def upsert(self, session_id: str, contact_id: str, body: UpsertContactRequest) -> SuccessResult:
+ """Save a contact to the addressbook, or edit an existing entry (OPERATOR)."""
+ return self._http.request(
+ "PUT", f"/api/sessions/{quote_segment(session_id)}/contacts/{quote_segment(contact_id)}", body=body
+ )
+
+ def delete(self, session_id: str, contact_id: str) -> SuccessResult:
+ """Remove a contact from the addressbook (OPERATOR)."""
+ return self._http.request(
+ "DELETE", f"/api/sessions/{quote_segment(session_id)}/contacts/{quote_segment(contact_id)}"
+ )
+
def unblock(self, session_id: str, contact_id: str) -> SuccessResult:
return self._http.request("DELETE", f"/api/sessions/{quote_segment(session_id)}/contacts/{quote_segment(contact_id)}/block")
diff --git a/sdk/python/openwa/types.py b/sdk/python/openwa/types.py
index ad4ed4e41..f35b7e73e 100644
--- a/sdk/python/openwa/types.py
+++ b/sdk/python/openwa/types.py
@@ -643,6 +643,13 @@ class PinMessageRequest(TypedDict, total=False):
durationSeconds: int
+class UpsertContactRequest(TypedDict, total=False):
+ """Save or edit an addressbook contact. lastName is optional."""
+
+ firstName: str
+ lastName: str
+
+
class ArchiveChatRequest(TypedDict):
"""Archive or unarchive a chat."""
diff --git a/sdk/python/tests/test_sdk.py b/sdk/python/tests/test_sdk.py
index 49115923b..83545e503 100644
--- a/sdk/python/tests/test_sdk.py
+++ b/sdk/python/tests/test_sdk.py
@@ -561,6 +561,16 @@ class TestChatsAndHealth:
assert backend.last_call.method == "DELETE"
assert backend.last_call.url == "http://localhost:2785/api/sessions/s/chats/[email protected]/messages"
+ def test_contacts_addressbook(self):
+ backend = MockBackend().on("PUT", "/contacts/", body={"success": True})
+ backend.on("DELETE", "/contacts/", body={"success": True})
+ client = make_client(backend)
+ client.contacts.upsert("s", "[email protected]", {"firstName": "Ada"})
+ assert backend.last_call.method == "PUT"
+ assert backend.last_call.url == "http://localhost:2785/api/sessions/s/contacts/[email protected]"
+ client.contacts.delete("s", "[email protected]")
+ assert backend.last_call.method == "DELETE"
+
def test_chats_archive(self):
backend = MockBackend().on("POST", "/chats/archive", body={"success": True})
make_client(backend).chats.archive("s", {"chatId": "[email protected]", "archive": True})
diff --git a/src/engine/adapters/baileys-contacts.ts b/src/engine/adapters/baileys-contacts.ts
index 55a77bd30..98e0e9415 100644
--- a/src/engine/adapters/baileys-contacts.ts
+++ b/src/engine/adapters/baileys-contacts.ts
@@ -43,6 +43,24 @@ export class BaileysContacts {
}
}
+ async upsertContact(contactId: string, firstName: string, lastName = ''): Promise<void> {
+ this.host.ensureReady();
+ const fullName = [firstName, lastName].filter(Boolean).join(' ');
+ // Baileys addresses the entry by JID, unlike whatsapp-web.js which wants a bare phone number.
+ // saveOnPrimaryAddressbook stays false to match the wwjs default (syncToAddressbook=false):
+ // writing through to the device addressbook is a heavier action than saving the contact.
+ await this.sock().addOrEditContact(contactId, {
+ firstName,
+ fullName,
+ saveOnPrimaryAddressbook: false,
+ });
+ }
+
+ async deleteContact(contactId: string): Promise<void> {
+ this.host.ensureReady();
+ await this.sock().removeContact(contactId);
+ }
+
async blockContact(contactId: string): Promise<void> {
this.host.ensureReady();
await this.sock().updateBlockStatus(contactId, 'block');
diff --git a/src/engine/adapters/baileys.adapter.spec.ts b/src/engine/adapters/baileys.adapter.spec.ts
index 0356a4849..ab8722777 100644
--- a/src/engine/adapters/baileys.adapter.spec.ts
+++ b/src/engine/adapters/baileys.adapter.spec.ts
@@ -49,6 +49,8 @@ class FakeSock extends EventEmitter {
public updateProfileStatus = jest.fn().mockResolvedValue(undefined);
public updateProfilePicture = jest.fn().mockResolvedValue(undefined);
public updateBlockStatus = jest.fn().mockResolvedValue(undefined);
+ public addOrEditContact = jest.fn().mockResolvedValue(undefined);
+ public removeContact = jest.fn().mockResolvedValue(undefined);
public readMessages = jest.fn().mockResolvedValue(undefined);
public chatModify = jest.fn().mockResolvedValue(undefined);
public addChatLabel = jest.fn().mockResolvedValue(undefined);
@@ -3736,6 +3738,32 @@ describe('BaileysAdapter sendSeen + markUnread + deleteChat', () => {
expect(fakeSock.chatModify).not.toHaveBeenCalled();
});
+ it('upsertContact addresses the entry by JID and composes fullName', async () => {
+ const adapter = await readyWithMessage();
+ await adapter.upsertContact('[email protected]', 'Ada', 'Lovelace');
+ // Baileys wants the JID here, unlike whatsapp-web.js which wants a bare phone number.
+ expect(fakeSock.addOrEditContact).toHaveBeenCalledWith('[email protected]', {
+ firstName: 'Ada',
+ fullName: 'Ada Lovelace',
+ saveOnPrimaryAddressbook: false,
+ });
+ });
+
+ it('upsertContact leaves no trailing space in fullName for a single-name contact', async () => {
+ const adapter = await readyWithMessage();
+ await adapter.upsertContact('[email protected]', 'Ada');
+ expect(fakeSock.addOrEditContact).toHaveBeenCalledWith(
+ expect.objectContaining({ fullName: 'Ada' }),
+ );
+ });
+
+ it('deleteContact removes by JID', async () => {
+ const adapter = await readyWithMessage();
+ await adapter.deleteContact('[email protected]');
+ expect(fakeSock.removeContact).toHaveBeenCalledWith('[email protected]');
+ });
+
it.each([true, false])('archiveChat(%s) modifies the chat with the last message', async archive => {
const adapter = await readyWithMessage();
const ok = await adapter.archiveChat('[email protected]', archive);
diff --git a/src/engine/adapters/baileys.adapter.ts b/src/engine/adapters/baileys.adapter.ts
index 4f62f7edc..d0dde9e86 100644
--- a/src/engine/adapters/baileys.adapter.ts
+++ b/src/engine/adapters/baileys.adapter.ts
@@ -433,6 +433,14 @@ export class BaileysAdapter implements IWhatsAppEngine {
return this.contacts.blockContact(contactId);
}
+ async upsertContact(contactId: string, firstName: string, lastName?: string): Promise<void> {
+ return this.contacts.upsertContact(contactId, firstName, lastName);
+ }
+
+ async deleteContact(contactId: string): Promise<void> {
+ return this.contacts.deleteContact(contactId);
+ }
+
async unblockContact(contactId: string): Promise<void> {
return this.contacts.unblockContact(contactId);
}
diff --git a/src/engine/adapters/whatsapp-web-js.adapter.spec.ts b/src/engine/adapters/whatsapp-web-js.adapter.spec.ts
index 1c1433160..d0d53ca42 100644
--- a/src/engine/adapters/whatsapp-web-js.adapter.spec.ts
+++ b/src/engine/adapters/whatsapp-web-js.adapter.spec.ts
@@ -744,6 +744,26 @@ describe('WhatsAppWebJsAdapter channel-JID guard (#554 — wwebjs Channel lacks
});
});
+ describe('addressbook contacts', () => {
+ it('passes a bare PHONE NUMBER, not the JID — wwjs addresses the entry by number', async () => {
+ const saveOrEditAddressbookContact = jest.fn().mockResolvedValue(undefined);
+ await readyAdapter({ saveOrEditAddressbookContact }).upsertContact('[email protected]', 'Ada', 'Lovelace');
+ expect(saveOrEditAddressbookContact).toHaveBeenCalledWith('628123', 'Ada', 'Lovelace');
+ });
+
+ it("sends an empty last name rather than undefined, which would stringify to 'undefined'", async () => {
+ const saveOrEditAddressbookContact = jest.fn().mockResolvedValue(undefined);
+ await readyAdapter({ saveOrEditAddressbookContact }).upsertContact('[email protected]', 'Ada');
+ expect(saveOrEditAddressbookContact).toHaveBeenCalledWith('628123', 'Ada', '');
+ });
+
+ it('deletes by phone number too', async () => {
+ const deleteAddressbookContact = jest.fn().mockResolvedValue(undefined);
+ await readyAdapter({ deleteAddressbookContact }).deleteContact('[email protected]');
+ expect(deleteAddressbookContact).toHaveBeenCalledWith('628123');
+ });
+ });
+
describe('setGroupMemberAddMode', () => {
const groupChat = (over: Record<string, unknown> = {}) => ({
getChatById: jest.fn().mockResolvedValue({ isGroup: true, ...over }),
diff --git a/src/engine/adapters/whatsapp-web-js.adapter.ts b/src/engine/adapters/whatsapp-web-js.adapter.ts
index 6f1c347a2..5140275ff 100644
--- a/src/engine/adapters/whatsapp-web-js.adapter.ts
+++ b/src/engine/adapters/whatsapp-web-js.adapter.ts
@@ -1465,6 +1465,14 @@ export class WhatsAppWebJsAdapter extends EventEmitter implements IWhatsAppEngin
return this.contacts.blockContact(contactId);
}
+ upsertContact(contactId: string, firstName: string, lastName?: string): Promise<void> {
+ return this.contacts.upsertContact(contactId, firstName, lastName);
+ }
+
+ deleteContact(contactId: string): Promise<void> {
+ return this.contacts.deleteContact(contactId);
+ }
+
// Unblock Contact
unblockContact(contactId: string): Promise<void> {
return this.contacts.unblockContact(contactId);
diff --git a/src/engine/adapters/wwebjs-contacts.ts b/src/engine/adapters/wwebjs-contacts.ts
index 1cd559a38..8e5f83cbc 100644
--- a/src/engine/adapters/wwebjs-contacts.ts
+++ b/src/engine/adapters/wwebjs-contacts.ts
@@ -1,6 +1,7 @@
import { type Client } from 'whatsapp-web.js';
import { Contact } from '../interfaces/whatsapp-engine.interface';
import { EngineTransportError } from '../../common/errors/engine-transport.error';
+import { userPart } from '../identity/wa-id';
import { type WwebjsEngineHost } from './wwebjs-host';
/**
@@ -85,6 +86,23 @@ export class WwebjsContacts {
}
}
+ async upsertContact(contactId: string, firstName: string, lastName = ''): Promise<void> {
+ this.host.ensureReady();
+ // wwjs addresses the addressbook entry by PHONE NUMBER, not JID (Client.js:3266). lastName is
+ // positional and required there, so an absent one is passed as an empty string rather than
+ // undefined, which would land in the page-side payload as the literal string "undefined".
+ // syncToAddressbook is left at its default (false): writing to the device addressbook is a
+ // heavier, separately-consented action than saving the WhatsApp contact.
+ await this.client().saveOrEditAddressbookContact(userPart(contactId), firstName, lastName);
+ this.host.logger.log(`Saved addressbook contact ${contactId}`);
+ }
+
+ async deleteContact(contactId: string): Promise<void> {
+ this.host.ensureReady();
+ await this.client().deleteAddressbookContact(userPart(contactId));
+ this.host.logger.log(`Deleted addressbook contact ${contactId}`);
+ }
+
async blockContact(contactId: string): Promise<void> {
this.host.ensureReady();
const contact = await this.client().getContactById(contactId);
diff --git a/src/engine/engine-capability-matrix.ts b/src/engine/engine-capability-matrix.ts
index aa33d5033..8d28ba18a 100644
--- a/src/engine/engine-capability-matrix.ts
+++ b/src/engine/engine-capability-matrix.ts
@@ -78,6 +78,12 @@ export const ENGINE_CAPABILITY_MATRIX: Record<string, MethodCapability> = {
},
createGroup: { wwjs: { status: 'supported' }, baileys: { status: 'supported' } },
deleteChat: { wwjs: { status: 'supported' }, baileys: { status: 'supported' } },
+ deleteContact: {
+ wwjs: { status: 'supported' },
+ baileys: { status: 'supported' },
+ evidence:
+ 'wwjs Client.deleteAddressbookContact(phoneNumber) → void (index.d.ts:320; the parameter is misspelled `honeNumber` upstream, positional so harmless); baileys removeContact(jid) (Socket/chats.d.ts:67). wwjs addresses the entry by PHONE, baileys by JID — the adapter converts',
+ },
deleteMessage: { wwjs: { status: 'supported' }, baileys: { status: 'supported' } },
deleteStatus: { wwjs: { status: 'supported' }, baileys: { status: 'supported' } },
demoteParticipants: {
@@ -312,6 +318,12 @@ export const ENGINE_CAPABILITY_MATRIX: Record<string, MethodCapability> = {
evidence:
"wwjs Client.subscribeToChannel(channelId) → boolean (index.d.ts:71; Client.js:2533) takes a CHANNEL id, not the interface's invite code, and getChannelByInviteCode(inviteCode) (index.d.ts:103; Client.js:1707) is the invite→channel bridge — the adapter used to pass the invite code straight in and fabricate a Channel from the returned boolean; now an honest EngineNotSupportedError pending a verified two-step wiring; baileys newsletterMetadata('invite', code) + newsletterFollow (Socket/newsletter.d.ts)",
},
+ upsertContact: {
+ wwjs: { status: 'supported' },
+ baileys: { status: 'supported' },
+ evidence:
+ "wwjs Client.saveOrEditAddressbookContact(phoneNumber, firstName, lastName, syncToAddressbook=false) → void (index.d.ts:293-299; Client.js:3266) — lastName is positional and required, so an absent one is passed as ''; baileys addOrEditContact(jid, IContactAction{firstName,fullName,saveOnPrimaryAddressbook}) (Socket/chats.d.ts:66; WAProto IContactAction:11812)",
+ },
unblockContact: { wwjs: { status: 'supported' }, baileys: { status: 'supported' } },
unpinMessage: {
wwjs: { status: 'supported' },
diff --git a/src/engine/interfaces/whatsapp-engine.interface.ts b/src/engine/interfaces/whatsapp-engine.interface.ts
index f012a752f..e4f6431d9 100644
--- a/src/engine/interfaces/whatsapp-engine.interface.ts
+++ b/src/engine/interfaces/whatsapp-engine.interface.ts
@@ -750,6 +750,15 @@ export interface IWhatsAppEngine {
blockContact(contactId: string): Promise<void>;
unblockContact(contactId: string): Promise<void>;
+ /**
+ * Save a contact to the account's addressbook, or edit an existing entry. `contactId` is a
+ * neutral JID; whatsapp-web.js addresses the entry by phone number and Baileys by JID, so the
+ * adapters convert. An empty `lastName` is normal — WhatsApp stores single-name contacts.
+ */
+ upsertContact(contactId: string, firstName: string, lastName?: string): Promise<void>;
+ /** Remove a contact from the account's addressbook. Does not block or delete the chat. */
+ deleteContact(contactId: string): Promise<void>;
+
// Profile (own account)
/** Set the account's display name. */
setProfileName(name: string): Promise<void>;
diff --git a/src/modules/contact/contact.controller.ts b/src/modules/contact/contact.controller.ts
index 0f16d8bd6..00ac1f90a 100644
--- a/src/modules/contact/contact.controller.ts
+++ b/src/modules/contact/contact.controller.ts
@@ -1,8 +1,9 @@
-import { Controller, Get, Post, Delete, Param, Query, HttpCode, HttpStatus } from '@nestjs/common';
+import { Body, Controller, Get, Post, Put, Delete, Param, Query, HttpCode, HttpStatus } from '@nestjs/common';
import { ApiTags, ApiOperation, ApiResponse, ApiParam, ApiQuery } from '@nestjs/swagger';
import { ContactService } from './contact.service';
import { RequireRole } from '../auth/decorators/auth.decorators';
import { ApiKeyRole } from '../auth/entities/api-key.entity';
+import { UpsertContactDto } from './dto/upsert-contact.dto';
@ApiTags('contacts')
@Controller('sessions/:sessionId/contacts')
@@ -117,6 +118,37 @@ export class ContactController {
return { contactId, phone };
}
+ @Put(':contactId')
+ @RequireRole(ApiKeyRole.OPERATOR)
+ @HttpCode(HttpStatus.OK)
+ @ApiOperation({ summary: "Save a contact to the account's addressbook, or edit an existing entry" })
+ @ApiParam({ name: 'sessionId', description: 'Session ID' })
+ @ApiParam({ name: 'contactId', description: 'Contact ID (e.g., [email protected])' })
+ @ApiResponse({ status: 200, description: 'Contact saved' })
+ @ApiResponse({ status: 400, description: 'Session not active or invalid request' })
+ async upsertContact(
+ @Param('sessionId') sessionId: string,
+ @Param('contactId') contactId: string,
+ @Body() dto: UpsertContactDto,
+ ) {
+ await this.contactService.upsertContact(sessionId, contactId, dto.firstName, dto.lastName);
+ return { success: true, message: 'Contact saved' };
+ }
+
+ // Two path segments on the sibling route (`:contactId/block`) keep this single-segment DELETE
+ // from shadowing the unblock route, whichever order they are declared in.
+ @Delete(':contactId')
+ @RequireRole(ApiKeyRole.OPERATOR)
+ @ApiOperation({ summary: "Remove a contact from the account's addressbook" })
+ @ApiParam({ name: 'sessionId', description: 'Session ID' })
+ @ApiParam({ name: 'contactId', description: 'Contact ID (e.g., [email protected])' })
+ @ApiResponse({ status: 200, description: 'Contact deleted' })
+ @ApiResponse({ status: 400, description: 'Session not active' })
+ async deleteContact(@Param('sessionId') sessionId: string, @Param('contactId') contactId: string) {
+ await this.contactService.deleteContact(sessionId, contactId);
+ return { success: true, message: 'Contact deleted' };
+ }
+
@Post(':contactId/block')
@RequireRole(ApiKeyRole.OPERATOR)
@HttpCode(HttpStatus.OK)
diff --git a/src/modules/contact/contact.service.ts b/src/modules/contact/contact.service.ts
index 4177bfaf3..b081d762c 100644
--- a/src/modules/contact/contact.service.ts
+++ b/src/modules/contact/contact.service.ts
@@ -101,6 +101,14 @@ export class ContactService {
return this.getEngine(sessionId).blockContact(contactId);
}
+ upsertContact(sessionId: string, contactId: string, firstName: string, lastName?: string) {
+ return this.getEngine(sessionId).upsertContact(contactId, firstName, lastName);
+ }
+
+ deleteContact(sessionId: string, contactId: string) {
+ return this.getEngine(sessionId).deleteContact(contactId);
+ }
+
unblockContact(sessionId: string, contactId: string) {
return this.getEngine(sessionId).unblockContact(contactId);
}
diff --git a/src/modules/contact/dto/upsert-contact.dto.ts b/src/modules/contact/dto/upsert-contact.dto.ts
new file mode 100644
index 000000000..748f3b8b7
--- /dev/null
+++ b/src/modules/contact/dto/upsert-contact.dto.ts
@@ -0,0 +1,22 @@
+import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
+import { IsOptional, IsString, MaxLength, MinLength } from 'class-validator';
+
+/** Cap on each addressbook name part. Mirrors CONTACT_NAME_MAX_LENGTH on the send-contact DTO. */
+export const ADDRESSBOOK_NAME_MAX_LENGTH = 100;
+
+export class UpsertContactDto {
+ @ApiProperty({ description: "The contact's first name.", maxLength: ADDRESSBOOK_NAME_MAX_LENGTH })
+ @IsString()
+ @MinLength(1)
+ @MaxLength(ADDRESSBOOK_NAME_MAX_LENGTH)
+ firstName: string;
+
+ @ApiPropertyOptional({
+ description: "The contact's last name. Omit for a single-name contact — WhatsApp allows those.",
+ maxLength: ADDRESSBOOK_NAME_MAX_LENGTH,
+ })
+ @IsOptional()
+ @IsString()
+ @MaxLength(ADDRESSBOOK_NAME_MAX_LENGTH)
+ lastName?: string;
+}