Skip to content

feat: POST /user/contacts — save a contact to the device addressbook - #162

Open
FlavioPulli wants to merge 1 commit into
evolution-foundation:developfrom
FlavioPulli:feat/save-contact-endpoint-develop
Open

feat: POST /user/contacts — save a contact to the device addressbook#162
FlavioPulli wants to merge 1 commit into
evolution-foundation:developfrom
FlavioPulli:feat/save-contact-endpoint-develop

Conversation

@FlavioPulli

@FlavioPulli FlavioPulli commented Aug 4, 2026

Copy link
Copy Markdown

WhatsApp syncs the contact list across devices via app state (the same channel as mute/pin/archive), and whatsmeow already applies incoming contact mutations back into Store.Contacts. The API exposes only the read side (GET /user/contacts); this adds the write side.

POST /user/contacts {phone, fullName, firstName?} builds a contact-index mutation on the critical_unblock_low patch carrying a ContactAction (FullName/FirstName + SaveOnPrimaryAddressbook: true, which asks the primary phone to also store the contact in the system addressbook) and sends it through the official Client.SendAppState primitive. After the resync SendAppState triggers, the saved contact shows up in GET /user/contacts like any contact saved on the phone itself.

Verified end to end on a paired Android device (contact appears in the phone's WhatsApp list and system addressbook); in our production since 2026-07-22.


Retargeted to develop (replaces #129), as requested by @iagocotta in #128 (comment).

Note that main and develop have no common ancestor — the GitHub API refuses to compare them (No common ancestor between main and develop) — so the base branch of the original PR could not simply be edited. This branch was created from develop and the commit cherry-picked onto it.

The import paths were changed from evolution-foundation/evolution-go to EvolutionAPI/evolution-go, which is the module path develop still declares in its go.mod. No other change.

Verified on this branch: go build ./... and go vet ./... both pass.

Summary by Sourcery

Add support for saving WhatsApp contacts to the device address book via a new POST /user/contacts endpoint wired through the user handler and service.

New Features:

  • Introduce POST /user/contacts API to create or update a contact in the WhatsApp contact list and device address book.

Enhancements:

  • Extend user handler and service interfaces with a SaveContact operation backed by whatsmeow app state mutations for contact syncing.

…sbook

WhatsApp syncs the contact list across devices via app state (the same
channel as mute/pin/archive), and whatsmeow already applies incoming
"contact" mutations back into Store.Contacts. The API exposes only the
read side (GET /user/contacts); this adds the write side: a
"contact"-index mutation on the critical_unblock_low patch carrying a
ContactAction (FullName/FirstName + SaveOnPrimaryAddressbook, which asks
the primary phone to also store the contact in the system addressbook),
sent through the official Client.SendAppState primitive.

After the resync SendAppState triggers, the saved contact shows up in
GET /user/contacts like any contact saved on the phone itself.

Battle-tested in production since 2026-07-22 (verified end to end on a
paired Android device: contact appears in the phone's WhatsApp contact
list and system addressbook).
@sourcery-ai

sourcery-ai Bot commented Aug 4, 2026

Copy link
Copy Markdown

Reviewer's Guide

Adds a POST /user/contacts endpoint that builds and sends a WhatsApp app-state contact mutation so the primary device saves a contact into both WhatsApp’s contact list and the system address book, wiring it through routes, handler, and service layers with basic validation and logging.

Sequence diagram for POST /user/contacts saving a contact via WhatsApp app state

sequenceDiagram
  actor User
  participant GinRouter
  participant UserHandler
  participant UserService
  participant WhatsAppClient

  User->>GinRouter: POST /user/contacts
  GinRouter->>UserHandler: SaveContact(ctx)
  UserHandler->>UserHandler: ctx.MustGet(instance)
  UserHandler->>UserHandler: ctx.ShouldBindBodyWithJSON(data)
  UserHandler->>UserService: SaveContact(data, instance)
  UserService->>UserService: ensureClientConnected(instance.Id)
  UserService->>WhatsAppClient: SendAppState(context.Background(), patch)
  alt SendAppState error
    WhatsAppClient-->>UserService: error
    UserService->>UserService: LogError(instance.Id, jid.String(), err)
    UserService-->>UserHandler: error
    UserHandler-->>User: 500 Internal Server Error
  else SendAppState success
    WhatsAppClient-->>UserService: ok
    UserService->>UserService: LogInfo(instance.Id, fullName, jid.String())
    UserService-->>UserHandler: nil
    UserHandler-->>User: 200 {message: success}
  end
Loading

File-Level Changes

Change Details Files
Introduce service-layer operation to create and send a WhatsApp app-state contact mutation that saves a contact to the device addressbook.
  • Define SaveContactStruct DTO with phone, fullName, and optional firstName fields mapped to JSON.
  • Implement userService.SaveContact to validate inputs, derive firstName when omitted, construct JID and appstate.PatchInfo for the critical_unblock_low contact index, and send it via Client.SendAppState.
  • Add contactMutationVersion constant and use waSyncAction.ContactAction fields (FullName, FirstName, SaveOnPrimaryAddressbook) to drive the mutation.
  • Integrate logging for success and error paths when sending app-state patches.
pkg/user/service/save_contact.go
pkg/user/service/user_service.go
Add HTTP handler and routing for POST /user/contacts that forwards validated payloads to the service method and exposes the new endpoint in the API.
  • Extend UserHandler interface with SaveContact method and wire it in the router under /user/contacts POST.
  • Implement user_handler.SaveContact to fetch the instance from context, bind JSON body into SaveContactStruct, perform basic field-length validation, call UserService.SaveContact, and return appropriate HTTP responses.
  • Annotate the handler with Swagger/OpenAPI-style comments including summary, description, tags, params, and response types.
pkg/routes/routes.go
pkg/user/handler/user_handler.go
pkg/user/handler/save_contact.go

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey - I've found 1 issue, and left some high level feedback:

  • In the HTTP handler, you bind into a *SaveContactStruct using ctx.ShouldBindBodyWithJSON(&data), which results in a pointer-to-pointer; consider binding into a value (var data user_service.SaveContactStruct and pass &data) to align with Gin’s binding expectations.
  • The handler performs its own phone/fullName presence check while the service also validates and returns the same error; you could centralize this validation in the service layer to avoid duplication and keep error behavior in one place.
  • In SaveContact, you use context.Background() for SendAppState; passing ctx.Request.Context() from the HTTP handler would let the operation be cancelled if the client disconnects or the request times out.
Prompt for AI Agents
Please address the comments from this code review:

## Overall Comments
- In the HTTP handler, you bind into a `*SaveContactStruct` using `ctx.ShouldBindBodyWithJSON(&data)`, which results in a pointer-to-pointer; consider binding into a value (`var data user_service.SaveContactStruct` and pass `&data`) to align with Gin’s binding expectations.
- The handler performs its own `phone`/`fullName` presence check while the service also validates and returns the same error; you could centralize this validation in the service layer to avoid duplication and keep error behavior in one place.
- In `SaveContact`, you use `context.Background()` for `SendAppState`; passing `ctx.Request.Context()` from the HTTP handler would let the operation be cancelled if the client disconnects or the request times out.

## Individual Comments

### Comment 1
<location path="pkg/user/handler/save_contact.go" line_range="35-36" />
<code_context>
+		return
+	}
+
+	var data *user_service.SaveContactStruct
+	err := ctx.ShouldBindBodyWithJSON(&data)
+	if err != nil {
+		ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
</code_context>
<issue_to_address>
**issue (bug_risk):** Binding into a pointer-to-pointer is likely incorrect and may prevent proper JSON deserialization.

`data` is declared as `*user_service.SaveContactStruct`, so `&data` is `**user_service.SaveContactStruct`, which Gin’s binders don’t expect and may break deserialization. Use a concrete value instead:

```go
var data user_service.SaveContactStruct
if err := ctx.ShouldBindBodyWithJSON(&data); err != nil {
    ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
    return
}
// pass &data to the service
```
</issue_to_address>

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

Comment on lines +35 to +36
var data *user_service.SaveContactStruct
err := ctx.ShouldBindBodyWithJSON(&data)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

issue (bug_risk): Binding into a pointer-to-pointer is likely incorrect and may prevent proper JSON deserialization.

data is declared as *user_service.SaveContactStruct, so &data is **user_service.SaveContactStruct, which Gin’s binders don’t expect and may break deserialization. Use a concrete value instead:

var data user_service.SaveContactStruct
if err := ctx.ShouldBindBodyWithJSON(&data); err != nil {
    ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
    return
}
// pass &data to the service

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant