Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
feat(sdk): expose per-call send idempotency keys
Yudhi Armyndharis90dfa5e74aff
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 34afdd5ae..859fa835b 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -10,6 +10,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0### Added- Add bounded webhook failure redrive with optional payload retention.+- Expose caller-supplied send idempotency keys in all five SDKs.### Fixeddiff --git a/sdk/go/README.md b/sdk/go/README.mdindex 1e99f241d..b1c4c32b4 100644--- a/sdk/go/README.md+++ b/sdk/go/README.md@@ -272,3 +272,14 @@ Cutting a release:> take it back, and the only remedy is to publish a higher version (and, if the> bad one must be discouraged, a `retract` directive in `go.mod`). Tag a commit> that is already green on `main`.++## Send idempotency++Supply a unique caller-owned key for one logical send and reuse it when retrying that same call. Keys contain 1-255 visible ASCII characters; unrelated calls must use different keys. The SDK forwards the key without changing its retry policy or generating one automatically.++```go+ctx := openwa.WithIdempotencyKey(context.Background(), "order-123")+_, err := client.Messages.SendText(ctx, sessionID, openwa.SendTextRequest{ChatID: "[email protected]", Text: "Hello"})+```++The gateway supports text, image, video, audio, document, sticker, location, contact, template, poll, reply and forward sends. Completed calls replay their response; pending or uncertain outcomes return 409, and a changed request with the same key returns 422. The gateway retains keys for 24 hours. Bulk, product and button operations have no such guarantee. Omit the key to preserve existing behavior.diff --git a/sdk/go/client.go b/sdk/go/client.goindex abb7b505e..e955fec05 100644--- a/sdk/go/client.go+++ b/sdk/go/client.go@@ -237,6 +237,15 @@ func (c *Client) call(ctx context.Context, method, path string, query url.Valuesreturn nil}+type idempotencyContextKey struct{}++// WithIdempotencyKey supplies a caller-owned key for one logical send. Reuse+// this context for its retries and choose another key for an unrelated send.+// Only the gateway's documented idempotent send routes interpret the header.+func WithIdempotencyKey(ctx context.Context, key string) context.Context {+ return context.WithValue(ctx, idempotencyContextKey{}, key)+}+// doRaw performs the request and returns the response body and Content-Type.// Any non-2xx status (including an unfollowed 3xx) is an error.//@@ -268,10 +277,19 @@ func (c *Client) doRaw(ctx context.Context, method, path string, query url.ValuerawURL += sep + query.Encode()}+ key, hasKey := ctx.Value(idempotencyContextKey{}).(string)+ if hasKey {+ if len(key) < 1 || len(key) > 255 || strings.IndexFunc(key, func(r rune) bool { return r < 0x21 || r > 0x7e }) >= 0 {+ return nil, "", errors.New("openwa: idempotency key must contain 1-255 visible ASCII characters")+ }+ }req, err := http.NewRequestWithContext(ctx, method, rawURL, reader)if err != nil {return nil, "", fmt.Errorf("openwa: building request: %w", err)}+ if hasKey {+ req.Header.Set("Idempotency-Key", key)+ }if body != nil {req.Header.Set("Content-Type", "application/json")req.ContentLength = int64(len(bodyBytes))diff --git a/sdk/go/client_test.go b/sdk/go/client_test.goindex 8ff66398d..801ccf152 100644--- a/sdk/go/client_test.go+++ b/sdk/go/client_test.go@@ -1748,3 +1748,53 @@ func TestDoPathWithQueryAppendsQueryValues(t *testing.T) {t.Errorf("query = %q, want %q", got, "limit=5&name=x")}}++func TestSendIdempotencyKey(t *testing.T) {+ rt := &recordTransport{status: 200, body: `{"messageId":"m","timestamp":1}`}+ c := newTestClient(t, rt, WithHeader("idempotency-key", "default"))+ for _, segment := range []string{"send-text", "send-image", "send-video", "send-audio", "send-document", "send-sticker", "send-location", "send-contact", "send-template", "send-poll", "reply", "forward"} {+ ctx := WithIdempotencyKey(context.Background(), segment)+ if _, err := c.Messages.send(ctx, "s", segment, map[string]string{"chatId": "x"}); err != nil {+ t.Fatal(err)+ }+ if got := rt.lastReq.Header.Values("Idempotency-Key"); len(got) != 1 || got[0] != segment {+ t.Fatalf("%s: %v", segment, got)+ }+ if string(rt.lastRaw) != `{"chatId":"x"}` {+ t.Fatalf("body changed: %s", rt.lastRaw)+ }+ }+ if _, err := c.Messages.SendText(context.Background(), "s", SendTextRequest{}); err != nil {+ t.Fatal(err)+ }+ if got := rt.lastReq.Header.Get("Idempotency-Key"); got != "default" {+ t.Fatalf("default mutated: %s", got)+ }+ for _, key := range []string{"", "a b", "a\n", "é", strings.Repeat("x", 256)} {+ rt.lastReq = nil+ if _, err := c.Messages.SendText(WithIdempotencyKey(context.Background(), key), "s", SendTextRequest{}); err == nil {+ t.Fatalf("accepted %q", key)+ }+ if rt.lastReq != nil {+ t.Fatalf("transport called for %q", key)+ }+ }+}++func TestRetryKeepsIdempotencyKey(t *testing.T) {+ var keys []string+ rt := RoundTripperFunc(func(req *http.Request) (*http.Response, error) {+ keys = append(keys, req.Header.Get("Idempotency-Key"))+ return &http.Response{StatusCode: 503, Header: http.Header{}, Body: io.NopCloser(strings.NewReader(`{}`)), Request: req}, nil+ })+ c := newTestClient(t, rt, WithRetry(RetryPolicy{MaxRetries: 2, BaseDelay: time.Millisecond, MaxDelay: time.Millisecond, RetryableStatuses: []int{503}}))+ _, _ = c.Messages.SendText(WithIdempotencyKey(context.Background(), "stable"), "s", SendTextRequest{})+ if len(keys) != 3 {+ t.Fatalf("attempts: %v", keys)+ }+ for _, key := range keys {+ if key != "stable" {+ t.Fatalf("keys: %v", keys)+ }+ }+}diff --git a/sdk/java/README.md b/sdk/java/README.mdindex e4cafe0be..385cb98c4 100644--- a/sdk/java/README.md+++ b/sdk/java/README.md@@ -213,3 +213,13 @@ Cutting a release:tag. The SDK has its own version line — the monorepo's `v*` tags are the appversion and never trigger an SDK publish.3. The workflow builds, signs, and publishes; Central syncs within a few hours.++## Send idempotency++Supply a unique caller-owned key for one logical send and reuse it when retrying that same call. Keys contain 1-255 visible ASCII characters; unrelated calls must use different keys. The SDK forwards the key without changing its retry policy or generating one automatically.++```java+client.messages.sendText(sessionId, new SendTextRequest("[email protected]", "Hello"), "order-123");+```++The gateway supports text, image, video, audio, document, sticker, location, contact, template, poll, reply and forward sends. Completed calls replay their response; pending or uncertain outcomes return 409, and a changed request with the same key returns 422. The gateway retains keys for 24 hours. Bulk, product and button operations have no such guarantee. Omit the key to preserve existing behavior.diff --git a/sdk/java/src/main/java/com/rmyndharis/openwa/OpenWAClient.java b/sdk/java/src/main/java/com/rmyndharis/openwa/OpenWAClient.javaindex 082697df3..7abbf70f2 100644--- a/sdk/java/src/main/java/com/rmyndharis/openwa/OpenWAClient.java+++ b/sdk/java/src/main/java/com/rmyndharis/openwa/OpenWAClient.java@@ -36,6 +36,7 @@ import com.rmyndharis.openwa.resources.WebhooksResource;import java.io.IOException;import java.lang.reflect.Array;import java.nio.charset.StandardCharsets;+import java.util.LinkedHashMap;import java.util.List;import java.util.Map;@@ -117,9 +118,14 @@ public final class OpenWAClient {* be JSON; a non-JSON body surfaces as a tidy {@link OpenWAError}, never a raw* Gson exception.*/- @SuppressWarnings("unchecked")public <T> T request(HttpMethod method, String path, Object query, Object body, Class<T> type) {- HttpResponseData res = execute(method, path, query, body);+ return request(method, path, query, body, type, null);+ }++ /** Issue a request with an optional caller-supplied send idempotency key. */+ @SuppressWarnings("unchecked")+ public <T> T request(HttpMethod method, String path, Object query, Object body, Class<T> type, String idempotencyKey) {+ HttpResponseData res = execute(method, path, query, body, idempotencyKey);String text = utf8(res.body());if (res.status() == 204 || text.isEmpty()) {return null;@@ -209,8 +215,26 @@ public final class OpenWAClient {}private HttpResponseData execute(HttpMethod method, String path, Object query, Object body) {+ return execute(method, path, query, body, null);+ }++ private HttpResponseData execute(HttpMethod method, String path, Object query, Object body, String idempotencyKey) {+ Map<String, String> defaults = config.defaultHeaders;+ if (idempotencyKey != null) {+ boolean valid = !idempotencyKey.isEmpty() && idempotencyKey.length() <= 255;+ for (int i = 0; valid && i < idempotencyKey.length(); i++) {+ char value = idempotencyKey.charAt(i);+ valid = value >= 0x21 && value <= 0x7e;+ }+ if (!valid) {+ throw new IllegalArgumentException("OpenWA: idempotencyKey must be 1-255 visible ASCII characters");+ }+ defaults = new LinkedHashMap<>(defaults);+ defaults.keySet().removeIf(name -> name.equalsIgnoreCase("Idempotency-Key"));+ }String url = Http.buildUrl(config.baseUrl, path, query, gson);- Map<String, String> headers = Http.mergeHeaders(config.defaultHeaders, null, config.apiKey);+ Map<String, String> headers = Http.mergeHeaders(+ defaults, idempotencyKey == null ? null : Map.of("Idempotency-Key", idempotencyKey), config.apiKey);String bodyJson = body != null ? bodySerializer(body).toJson(body) : null;HttpRequestData reqData = new HttpRequestData(method, url, headers, bodyJson, config.timeout);HttpResponseData res;diff --git a/sdk/java/src/main/java/com/rmyndharis/openwa/resources/MessagesResource.java b/sdk/java/src/main/java/com/rmyndharis/openwa/resources/MessagesResource.javaindex b00de0a63..32fde8e82 100644--- a/sdk/java/src/main/java/com/rmyndharis/openwa/resources/MessagesResource.java+++ b/sdk/java/src/main/java/com/rmyndharis/openwa/resources/MessagesResource.java@@ -59,27 +59,44 @@ public final class MessagesResource {/** Send a text message. */public MessageResponse sendText(String sessionId, SendTextRequest body) {+ return sendText(sessionId, body, null);+ }++ public MessageResponse sendText(String sessionId, SendTextRequest body, String idempotencyKey) {return client.request(HttpMethod.POST,"/api/sessions/" + encodeSegment(sessionId) + "/messages/send-text",null,body,- MessageResponse.class);+ MessageResponse.class,+ idempotencyKey);}/** Send an image (url or base64). */public MessageResponse sendImage(String sessionId, SendMediaRequest body) {- return sendMedia(sessionId, "send-image", body);+ return sendImage(sessionId, body, null);+ }++ public MessageResponse sendImage(String sessionId, SendMediaRequest body, String idempotencyKey) {+ return sendMedia(sessionId, "send-image", body, idempotencyKey);}/** Send a video (url or base64). */public MessageResponse sendVideo(String sessionId, SendMediaRequest body) {- return sendMedia(sessionId, "send-video", body);+ return sendVideo(sessionId, body, null);+ }++ public MessageResponse sendVideo(String sessionId, SendMediaRequest body, String idempotencyKey) {+ return sendMedia(sessionId, "send-video", body, idempotencyKey);}/** Send an audio file (url or base64). */public MessageResponse sendAudio(String sessionId, SendAudioRequest body) {- return sendMedia(sessionId, "send-audio", body);+ return sendAudio(sessionId, body, null);+ }++ public MessageResponse sendAudio(String sessionId, SendAudioRequest body, String idempotencyKey) {+ return sendMedia(sessionId, "send-audio", body, idempotencyKey);}/**@@ -88,62 +105,95 @@ public final class MessagesResource {* whatsapp-web.js.*/public MessageResponse sendDocument(String sessionId, SendMediaRequest body) {- return sendMedia(sessionId, "send-document", body);+ return sendDocument(sessionId, body, null);+ }++ public MessageResponse sendDocument(String sessionId, SendMediaRequest body, String idempotencyKey) {+ return sendMedia(sessionId, "send-document", body, idempotencyKey);}/** Send a sticker (url or base64). */public MessageResponse sendSticker(String sessionId, SendMediaRequest body) {- return sendMedia(sessionId, "send-sticker", body);+ return sendSticker(sessionId, body, null);+ }++ public MessageResponse sendSticker(String sessionId, SendMediaRequest body, String idempotencyKey) {+ return sendMedia(sessionId, "send-sticker", body, idempotencyKey);}/** Send a location. */public MessageResponse sendLocation(String sessionId, SendLocationRequest body) {+ return sendLocation(sessionId, body, null);+ }++ public MessageResponse sendLocation(String sessionId, SendLocationRequest body, String idempotencyKey) {return client.request(HttpMethod.POST,"/api/sessions/" + encodeSegment(sessionId) + "/messages/send-location",null,body,- MessageResponse.class);+ MessageResponse.class,+ idempotencyKey);}/** Send a contact card. */public MessageResponse sendContact(String sessionId, SendContactRequest body) {+ return sendContact(sessionId, body, null);+ }++ public MessageResponse sendContact(String sessionId, SendContactRequest body, String idempotencyKey) {return client.request(HttpMethod.POST,"/api/sessions/" + encodeSegment(sessionId) + "/messages/send-contact",null,body,- MessageResponse.class);+ MessageResponse.class,+ idempotencyKey);}/** Render and send a stored message template. */public MessageResponse sendTemplate(String sessionId, SendTemplateRequest body) {+ return sendTemplate(sessionId, body, null);+ }++ public MessageResponse sendTemplate(String sessionId, SendTemplateRequest body, String idempotencyKey) {return client.request(HttpMethod.POST,"/api/sessions/" + encodeSegment(sessionId) + "/messages/send-template",null,body,- MessageResponse.class);+ MessageResponse.class,+ idempotencyKey);}/** Send a native WhatsApp poll (2–12 options). */public MessageResponse sendPoll(String sessionId, SendPollRequest body) {+ return sendPoll(sessionId, body, null);+ }++ public MessageResponse sendPoll(String sessionId, SendPollRequest body, String idempotencyKey) {return client.request(HttpMethod.POST,"/api/sessions/" + encodeSegment(sessionId) + "/messages/send-poll",null,body,- MessageResponse.class);+ MessageResponse.class,+ idempotencyKey);}/** Reply to a specific message. */public MessageResponse reply(String sessionId, ReplyMessageRequest body) {+ return reply(sessionId, body, null);+ }++ public MessageResponse reply(String sessionId, ReplyMessageRequest body, String idempotencyKey) {return client.request(HttpMethod.POST,"/api/sessions/" + encodeSegment(sessionId) + "/messages/reply",null,body,- MessageResponse.class);+ MessageResponse.class,+ idempotencyKey);}/**@@ -161,12 +211,17 @@ public final class MessagesResource {/** Forward a message to another chat. */public MessageResponse forward(String sessionId, ForwardMessageRequest body) {+ return forward(sessionId, body, null);+ }++ public MessageResponse forward(String sessionId, ForwardMessageRequest body, String idempotencyKey) {return client.request(HttpMethod.POST,"/api/sessions/" + encodeSegment(sessionId) + "/messages/forward",null,body,- MessageResponse.class);+ MessageResponse.class,+ idempotencyKey);}/** React to a message (an empty {@code emoji} removes the reaction). */@@ -328,11 +383,16 @@ public final class MessagesResource {/** POST {@code /messages/send-<kind>} for the five media send helpers. */private MessageResponse sendMedia(String sessionId, String kind, Object body) {+ return sendMedia(sessionId, kind, body, null);+ }++ private MessageResponse sendMedia(String sessionId, String kind, Object body, String idempotencyKey) {return client.request(HttpMethod.POST,"/api/sessions/" + encodeSegment(sessionId) + "/messages/" + kind,null,body,- MessageResponse.class);+ MessageResponse.class,+ idempotencyKey);}}diff --git a/sdk/java/src/test/java/com/rmyndharis/openwa/resources/MessagesResourceTest.java b/sdk/java/src/test/java/com/rmyndharis/openwa/resources/MessagesResourceTest.javaindex a0e6e2478..56aa237cf 100644--- a/sdk/java/src/test/java/com/rmyndharis/openwa/resources/MessagesResourceTest.java+++ b/sdk/java/src/test/java/com/rmyndharis/openwa/resources/MessagesResourceTest.java@@ -2,6 +2,9 @@ package com.rmyndharis.openwa.resources;import static org.junit.jupiter.api.Assertions.assertArrayEquals;import static org.junit.jupiter.api.Assertions.assertEquals;+import static org.junit.jupiter.api.Assertions.assertFalse;+import static org.junit.jupiter.api.Assertions.assertSame;+import static org.junit.jupiter.api.Assertions.assertThrows;import static org.junit.jupiter.api.Assertions.assertTrue;import com.rmyndharis.openwa.ClientConfig;@@ -34,8 +37,10 @@ import com.rmyndharis.openwa.model.VotePollRequest;import com.rmyndharis.openwa.model.UnpinMessageRequest;import com.rmyndharis.openwa.support.MockTransport;import java.nio.charset.StandardCharsets;+import java.util.LinkedHashMap;import java.util.List;import java.util.Map;+import java.util.function.Consumer;import org.junit.jupiter.api.Test;class MessagesResourceTest {@@ -45,6 +50,91 @@ class MessagesResourceTest {private static final String MSG = "{\"messageId\":\"m1\",\"timestamp\":123}";+ @Test+ void sendsKeepKeysLocalToEachCallAndPreserveJson() {+ var media = SendMediaRequest.builder().chatId("[email protected]").url("http://media").caption("caption").build();+ Map<String, Consumer<String>> sends = new LinkedHashMap<>();+ sends.put("send-text", key -> client.messages.sendText(+ "s", SendTextRequest.builder().chatId("[email protected]").text("hi").mentions(List.of("[email protected]")).build(), key));+ sends.put("send-image", key -> client.messages.sendImage("s", media, key));+ sends.put("send-video", key -> client.messages.sendVideo("s", media, key));+ sends.put("send-audio", key -> client.messages.sendAudio(+ "s", SendAudioRequest.builder().chatId("[email protected]").url("http://audio").ptt(true).build(), key));+ sends.put("send-document", key -> client.messages.sendDocument(+ "s", SendMediaRequest.builder().chatId("[email protected]").base64("YQ==")+ .mimetype("application/pdf").filename("a.pdf").build(), key));+ sends.put("send-sticker", key -> client.messages.sendSticker("s", media, key));+ sends.put("send-location", key -> client.messages.sendLocation(+ "s", SendLocationRequest.builder().chatId("[email protected]").latitude(1.0).longitude(2.0).build(), key));+ sends.put("send-contact", key -> client.messages.sendContact(+ "s", SendContactRequest.builder().chatId("[email protected]").contactName("A").contactNumber("628").build(), key));+ sends.put("send-template", key -> client.messages.sendTemplate(+ "s", SendTemplateRequest.builder().chatId("[email protected]").templateName("welcome")+ .vars(Map.of("name", "A")).build(), key));+ sends.put("send-poll", key -> client.messages.sendPoll(+ "s", SendPollRequest.builder().chatId("[email protected]").name("Question").options(List.of("A", "B")).build(), key));+ sends.put("reply", key -> client.messages.reply(+ "s", ReplyMessageRequest.builder().chatId("[email protected]").quotedMessageId("q").text("reply").build(), key));+ sends.put("forward", key -> client.messages.forward(+ "s", ForwardMessageRequest.builder().fromChatId("[email protected]").toChatId("[email protected]").messageId("m").build(), key));++ tx.respond(201, MSG);+ for (var entry : sends.entrySet()) {+ entry.getValue().accept(null);+ String originalBody = tx.lastRequest().body();+ assertFalse(tx.lastRequest().headers().containsKey("Idempotency-Key"), entry.getKey());+ for (String key : List.of("first-key", "second-key")) {+ entry.getValue().accept(key);+ assertEquals(HttpMethod.POST, tx.lastRequest().method(), entry.getKey());+ assertEquals("http://h/api/sessions/s/messages/" + entry.getKey(), tx.lastRequest().url());+ assertEquals(key, tx.lastRequest().headers().get("Idempotency-Key"), entry.getKey());+ assertEquals(originalBody, tx.lastRequest().body(), entry.getKey());+ }+ entry.getValue().accept(null);+ assertFalse(tx.lastRequest().headers().containsKey("Idempotency-Key"), entry.getKey());+ assertEquals(originalBody, tx.lastRequest().body(), entry.getKey());+ }+ }++ @Test+ void explicitKeyOverridesMixedCaseDefaultsWithoutChangingLaterCalls() {+ var transport = new MockTransport().respond(201, MSG);+ Map<String, String> headers = Map.of("iDeMpOtEnCy-KeY", "default-key", "X-Trace", "trace");+ var configured = new OpenWAClient(ClientConfig.builder().baseUrl("http://h").apiKey("k")+ .defaultHeaders(headers).transport(transport).build());+ var body = SendTextRequest.builder().chatId("[email protected]").text("hi").build();+ configured.messages.sendText("s", body, "explicit-key");+ assertEquals("explicit-key", transport.lastRequest().headers().get("Idempotency-Key"));+ assertEquals(1L, transport.lastRequest().headers().keySet().stream()+ .filter(name -> name.equalsIgnoreCase("Idempotency-Key")).count());+ assertEquals("trace", transport.lastRequest().headers().get("X-Trace"));+ assertEquals("default-key", headers.get("iDeMpOtEnCy-KeY"));+ configured.messages.sendText("s", body);+ assertEquals("default-key", transport.lastRequest().headers().get("iDeMpOtEnCy-KeY"));+ }++ @Test+ void invalidKeysAreRejectedBeforeTransport() {+ tx.respond(201, MSG);+ var body = SendTextRequest.builder().chatId("[email protected]").text("hi").build();+ client.messages.sendText("s", body, "valid-key");+ var previous = tx.lastRequest();+ for (String key : List.of("", "has space", " key", "key ", "key\n", "key\t", "caf\u00e9", "x".repeat(256))) {+ assertThrows(IllegalArgumentException.class, () -> client.messages.sendText("s", body, key));+ assertSame(previous, tx.lastRequest());+ }+ }++ @Test+ void visibleAsciiKeysAtBothLengthLimitsAreAccepted() {+ tx.respond(201, MSG);+ var body = SendTextRequest.builder().chatId("[email protected]").text("hi").build();+ for (String key : List.of("!", "x".repeat(255))) {+ client.messages.sendText("s", body, key);+ assertEquals(key, tx.lastRequest().headers().get("Idempotency-Key"));+ }+ }+@Testvoid listHitsMessagesPathWithQuery() {tx.respond(200, "{\"messages\":[],\"total\":0}");diff --git a/sdk/javascript/README.md b/sdk/javascript/README.mdindex e652bad18..5e44431e4 100644--- a/sdk/javascript/README.md+++ b/sdk/javascript/README.md@@ -125,3 +125,13 @@ Cutting a release:## LicenseMIT++## Send idempotency++Supply a unique caller-owned key for one logical send and reuse it when retrying that same call. Keys contain 1-255 visible ASCII characters; unrelated calls must use different keys. The SDK forwards the key without changing its retry policy or generating one automatically.++```javascript+await client.messages.sendText(sessionId, { chatId: '[email protected]', text: 'Hello' }, 'order-123');+```++The gateway supports text, image, video, audio, document, sticker, location, contact, template, poll, reply and forward sends. Completed calls replay their response; pending or uncertain outcomes return 409, and a changed request with the same key returns 422. The gateway retains keys for 24 hours. Bulk, product and button operations have no such guarantee. Omit the key to preserve existing behavior.diff --git a/sdk/javascript/src/client.ts b/sdk/javascript/src/client.tsindex 7aa9194ae..ecf4f1589 100644--- a/sdk/javascript/src/client.ts+++ b/sdk/javascript/src/client.ts@@ -108,7 +108,23 @@ export class OpenWAClient {// ── Internal API ─────────────────────────────────────────────────/** Issue a raw request against the API. (Public for advanced use.) */- request<T>(options: RequestOptions): Promise<T> {+ request<T>(options: RequestOptions, idempotencyKey?: string): Promise<T> {+ if (idempotencyKey !== undefined) {+ if (+ typeof idempotencyKey !== 'string' ||+ idempotencyKey.length < 1 ||+ idempotencyKey.length > 255 ||+ /[^\x21-\x7E]/.test(idempotencyKey)+ ) {+ return Promise.reject(new TypeError('OpenWA: idempotencyKey must be 1-255 visible ASCII characters'));+ }+ const headers = { ...options.headers };+ for (const name of Object.keys(headers)) {+ if (name.toLowerCase() === 'idempotency-key') delete headers[name];+ }+ headers['Idempotency-Key'] = idempotencyKey;+ options = { ...options, headers };+ }return request<T>(this.config, options);}@@ -121,12 +137,12 @@ export class OpenWAClient {* Shared transport helper for image/video/audio/document/sticker sends. Public resource methods* expose the narrower per-route request types (including audio-only `ptt`).*/- sendMedia(sessionId: string, segment: string, body: SendMediaRequest): Promise<MessageResponse> {+ sendMedia(sessionId: string, segment: string, body: SendMediaRequest, idempotencyKey?: string): Promise<MessageResponse> {return this.request<MessageResponse>({method: 'POST',path: `/api/sessions/${encodeSegment(sessionId)}/messages/${segment}`,body,- });+ }, idempotencyKey);}}diff --git a/sdk/javascript/src/resources/messages.ts b/sdk/javascript/src/resources/messages.tsindex faefb0b6c..64cc91153 100644--- a/sdk/javascript/src/resources/messages.ts+++ b/sdk/javascript/src/resources/messages.ts@@ -53,85 +53,85 @@ export class MessagesResource {}/** Send a text message. */- sendText(sessionId: string, body: SendTextRequest): Promise<MessageResponse> {+ sendText(sessionId: string, body: SendTextRequest, idempotencyKey?: string): Promise<MessageResponse> {return this.client.request<MessageResponse>({method: 'POST',path: `/api/sessions/${encodeSegment(sessionId)}/messages/send-text`,body,- });+ }, idempotencyKey);}/** Send an image (url or base64). */- sendImage(sessionId: string, body: SendMediaRequest): Promise<MessageResponse> {- return this.client.sendMedia(sessionId, 'send-image', body);+ sendImage(sessionId: string, body: SendMediaRequest, idempotencyKey?: string): Promise<MessageResponse> {+ return this.client.sendMedia(sessionId, 'send-image', body, idempotencyKey);}/** Send a video (url or base64). */- sendVideo(sessionId: string, body: SendMediaRequest): Promise<MessageResponse> {- return this.client.sendMedia(sessionId, 'send-video', body);+ sendVideo(sessionId: string, body: SendMediaRequest, idempotencyKey?: string): Promise<MessageResponse> {+ return this.client.sendMedia(sessionId, 'send-video', body, idempotencyKey);}/** Send an audio file (url or base64). */- sendAudio(sessionId: string, body: SendAudioRequest): Promise<MessageResponse> {- return this.client.sendMedia(sessionId, 'send-audio', body);+ sendAudio(sessionId: string, body: SendAudioRequest, idempotencyKey?: string): Promise<MessageResponse> {+ return this.client.sendMedia(sessionId, 'send-audio', body, idempotencyKey);}/*** Send a document (url or base64). `filename` is optional and is the name the recipient sees;* without it the gateway uses `"file"`, or the URL basename for a URL send on whatsapp-web.js.*/- sendDocument(sessionId: string, body: SendMediaRequest): Promise<MessageResponse> {- return this.client.sendMedia(sessionId, 'send-document', body);+ sendDocument(sessionId: string, body: SendMediaRequest, idempotencyKey?: string): Promise<MessageResponse> {+ return this.client.sendMedia(sessionId, 'send-document', body, idempotencyKey);}/** Send a sticker (url or base64). */- sendSticker(sessionId: string, body: SendMediaRequest): Promise<MessageResponse> {- return this.client.sendMedia(sessionId, 'send-sticker', body);+ sendSticker(sessionId: string, body: SendMediaRequest, idempotencyKey?: string): Promise<MessageResponse> {+ return this.client.sendMedia(sessionId, 'send-sticker', body, idempotencyKey);}/** Send a location. */- sendLocation(sessionId: string, body: SendLocationRequest): Promise<MessageResponse> {+ sendLocation(sessionId: string, body: SendLocationRequest, idempotencyKey?: string): Promise<MessageResponse> {return this.client.request<MessageResponse>({method: 'POST',path: `/api/sessions/${encodeSegment(sessionId)}/messages/send-location`,body,- });+ }, idempotencyKey);}/** Send a contact card. */- sendContact(sessionId: string, body: SendContactRequest): Promise<MessageResponse> {+ sendContact(sessionId: string, body: SendContactRequest, idempotencyKey?: string): Promise<MessageResponse> {return this.client.request<MessageResponse>({method: 'POST',path: `/api/sessions/${encodeSegment(sessionId)}/messages/send-contact`,body,- });+ }, idempotencyKey);}/** Render and send a stored message template. */- sendTemplate(sessionId: string, body: SendTemplateRequest): Promise<MessageResponse> {+ sendTemplate(sessionId: string, body: SendTemplateRequest, idempotencyKey?: string): Promise<MessageResponse> {return this.client.request<MessageResponse>({method: 'POST',path: `/api/sessions/${encodeSegment(sessionId)}/messages/send-template`,body,- });+ }, idempotencyKey);}/** Send a native WhatsApp poll (2–12 options). */- sendPoll(sessionId: string, body: SendPollRequest): Promise<MessageResponse> {+ sendPoll(sessionId: string, body: SendPollRequest, idempotencyKey?: string): Promise<MessageResponse> {return this.client.request<MessageResponse>({method: 'POST',path: `/api/sessions/${encodeSegment(sessionId)}/messages/send-poll`,body,- });+ }, idempotencyKey);}/** Reply to a specific message. */- reply(sessionId: string, body: ReplyMessageRequest): Promise<MessageResponse> {+ reply(sessionId: string, body: ReplyMessageRequest, idempotencyKey?: string): Promise<MessageResponse> {return this.client.request<MessageResponse>({method: 'POST',path: `/api/sessions/${encodeSegment(sessionId)}/messages/reply`,body,- });+ }, idempotencyKey);}/**@@ -147,12 +147,12 @@ export class MessagesResource {}/** Forward a message to another chat. */- forward(sessionId: string, body: ForwardMessageRequest): Promise<MessageResponse> {+ forward(sessionId: string, body: ForwardMessageRequest, idempotencyKey?: string): Promise<MessageResponse> {return this.client.request<MessageResponse>({method: 'POST',path: `/api/sessions/${encodeSegment(sessionId)}/messages/forward`,body,- });+ }, idempotencyKey);}/** React to a message (empty `emoji` removes the reaction). */diff --git a/sdk/javascript/test/messages.test.ts b/sdk/javascript/test/messages.test.tsindex 3679fe629..8afd03b06 100644--- a/sdk/javascript/test/messages.test.ts+++ b/sdk/javascript/test/messages.test.ts@@ -6,6 +6,73 @@ function client(t: MockTransport): OpenWAClient {return new OpenWAClient({ baseUrl: 'http://x', apiKey: 'k', fetch: t.asFetch() });}+describe('MessagesResource idempotency keys', () => {+ const sends: Array<[string, (c: OpenWAClient, key?: string) => Promise<unknown>]> = [+ ['send-text', (c, key) => c.messages.sendText('s', { chatId: '[email protected]', text: 'hi', mentions: ['[email protected]'] }, key)],+ ['send-image', (c, key) => c.messages.sendImage('s', { chatId: '[email protected]', url: 'http://image', caption: 'image' }, key)],+ ['send-video', (c, key) => c.messages.sendVideo('s', { chatId: '[email protected]', url: 'http://video', caption: 'video' }, key)],+ ['send-audio', (c, key) => c.messages.sendAudio('s', { chatId: '[email protected]', url: 'http://audio', ptt: true }, key)],+ ['send-document', (c, key) => c.messages.sendDocument('s', { chatId: '[email protected]', base64: 'YQ==', mimetype: 'application/pdf', filename: 'a.pdf' }, key)],+ ['send-sticker', (c, key) => c.messages.sendSticker('s', { chatId: '[email protected]', url: 'http://sticker', mimetype: 'image/webp' }, key)],+ ['send-location', (c, key) => c.messages.sendLocation('s', { chatId: '[email protected]', latitude: 1, longitude: 2 }, key)],+ ['send-contact', (c, key) => c.messages.sendContact('s', { chatId: '[email protected]', contactName: 'A', contactNumber: '628' }, key)],+ ['send-template', (c, key) => c.messages.sendTemplate('s', { chatId: '[email protected]', templateName: 'welcome', vars: { name: 'A' } }, key)],+ ['send-poll', (c, key) => c.messages.sendPoll('s', { chatId: '[email protected]', name: 'Question', options: ['A', 'B'] }, key)],+ ['reply', (c, key) => c.messages.reply('s', { chatId: '[email protected]', quotedMessageId: 'q', text: 'reply' }, key)],+ ['forward', (c, key) => c.messages.forward('s', { fromChatId: '[email protected]', toChatId: '[email protected]', messageId: 'm' }, key)],+ ];++ it.each(sends)('%s keeps keys local to each call and preserves JSON', async (route, send) => {+ const t = new MockTransport().on('POST', new RegExp(`/messages/${route}$`), { body: { messageId: 'm', timestamp: 1 } });+ const c = new OpenWAClient({ baseUrl: 'http://localhost', apiKey: 'k', fetch: t.asFetch() });+ await send(c);+ const originalBody = t.lastCall!.body;+ expect(t.lastCall!.headers['idempotency-key']).toBeUndefined();++ for (const key of ['first-key', 'second-key']) {+ await send(c, key);+ expect(t.lastCall!.method).toBe('POST');+ expect(t.lastCall!.url).toBe(`http://localhost/api/sessions/s/messages/${route}`);+ expect(t.lastCall!.headers['idempotency-key']).toBe(key);+ expect(t.lastCall!.body).toEqual(originalBody);+ }++ await send(c);+ expect(t.lastCall!.headers['idempotency-key']).toBeUndefined();+ expect(t.lastCall!.body).toEqual(originalBody);+ });++ it('overrides a mixed-case default without changing later calls', async () => {+ const t = new MockTransport().on('POST', /send-text$/, { body: { messageId: 'm', timestamp: 1 } });+ const headers = { 'iDeMpOtEnCy-KeY': 'default-key', 'X-Trace': 'trace' };+ const c = new OpenWAClient({ baseUrl: 'http://localhost', apiKey: 'k', defaultHeaders: headers, fetch: t.asFetch() });+ const body = { chatId: '[email protected]', text: 'hi' };+ await c.messages.sendText('s', body, 'explicit-key');+ expect(t.lastCall!.headers['idempotency-key']).toBe('explicit-key');+ expect(t.lastCall!.headers['x-trace']).toBe('trace');+ expect(headers['iDeMpOtEnCy-KeY']).toBe('default-key');+ await c.messages.sendText('s', body);+ expect(t.lastCall!.headers['idempotency-key']).toBe('default-key');+ });++ it.each(['', 'has space', ' key', 'key ', 'key\n', 'key\t', 'caf\u00e9', 'x'.repeat(256)])(+ 'rejects invalid key %j before transport',+ async key => {+ const t = new MockTransport().on('POST', /send-text$/, { body: { messageId: 'm', timestamp: 1 } });+ const c = new OpenWAClient({ baseUrl: 'http://localhost', apiKey: 'k', fetch: t.asFetch() });+ await expect(c.messages.sendText('s', { chatId: '[email protected]', text: 'hi' }, key)).rejects.toThrow(TypeError);+ expect(t.calls).toHaveLength(0);+ },+ );++ it.each(['!', 'x'.repeat(255)])('accepts visible ASCII key %j', async key => {+ const t = new MockTransport().on('POST', /send-text$/, { body: { messageId: 'm', timestamp: 1 } });+ const c = new OpenWAClient({ baseUrl: 'http://localhost', apiKey: 'k', fetch: t.asFetch() });+ await c.messages.sendText('s', { chatId: '[email protected]', text: 'hi' }, key);+ expect(t.lastCall!.headers['idempotency-key']).toBe(key);+ });+});+describe('MessagesResource — exact paths', () => {it('sendText posts to /messages/send-text (NOT /messages/text)', async () => {const t = new MockTransport().on('POST', /send-text$/, { body: { messageId: 'm1', timestamp: 1 } });diff --git a/sdk/php/README.md b/sdk/php/README.mdindex a79ada66b..3179069f8 100644--- a/sdk/php/README.md+++ b/sdk/php/README.md@@ -157,3 +157,13 @@ exactly like one that worked.## LicenseMIT++## Send idempotency++Supply a unique caller-owned key for one logical send and reuse it when retrying that same call. Keys contain 1-255 visible ASCII characters; unrelated calls must use different keys. The SDK forwards the key without changing its retry policy or generating one automatically.++```php+$client->messages->sendText($sessionId, ['chatId' => '[email protected]', 'text' => 'Hello'], 'order-123');+```++The gateway supports text, image, video, audio, document, sticker, location, contact, template, poll, reply and forward sends. Completed calls replay their response; pending or uncertain outcomes return 409, and a changed request with the same key returns 422. The gateway retains keys for 24 hours. Bulk, product and button operations have no such guarantee. Omit the key to preserve existing behavior.diff --git a/sdk/php/src/Http/HttpExecutor.php b/sdk/php/src/Http/HttpExecutor.phpindex 0dcf12615..00b8c5307 100644--- a/sdk/php/src/Http/HttpExecutor.php+++ b/sdk/php/src/Http/HttpExecutor.php@@ -83,9 +83,9 @@ class HttpExecutor* @throws OpenWAApiException On any non-2xx response (typed subclass).* @throws OpenWATimeoutException On timeout.*/- public function request(string $method, string $path, array $query = [], $body = null)+ public function request(string $method, string $path, array $query = [], $body = null, ?string $idempotencyKey = null){- $response = $this->send($method, $path, $query, $body);+ $response = $this->send($method, $path, $query, $body, $idempotencyKey);$text = (string) $response->getBody();if ($response->getStatusCode() === 204 || $text === '') {@@ -128,8 +128,11 @@ class HttpExecutor* @param array<string,mixed> $query* @param mixed|null $body*/- private function send(string $method, string $path, array $query, $body): ResponseInterface+ private function send(string $method, string $path, array $query, $body, ?string $idempotencyKey = null): ResponseInterface{+ if ($idempotencyKey !== null && preg_match('/\A[\x21-\x7E]{1,255}\z/', $idempotencyKey) !== 1) {+ throw new \InvalidArgumentException('Idempotency-Key must contain 1-255 visible ASCII characters');+ }// The path is appended to the base URL, so one without a leading "/" could move the host// (".example.net/x", "@example.net/x") and send the API key there.if (!str_starts_with($path, '/')) {@@ -150,7 +153,8 @@ class HttpExecutor// case-insensitive and PSR-7 keeps every value, so a caller's copy in another case is dropped.'headers' => array_merge(array_filter($this->defaultHeaders,- fn ($name) => !in_array(strtolower((string) $name), ['x-api-key', 'content-type', 'accept'], true),+ fn ($name) => !in_array(strtolower((string) $name), ['x-api-key', 'content-type', 'accept'], true)+ && ($idempotencyKey === null || strtolower((string) $name) !== 'idempotency-key'),ARRAY_FILTER_USE_KEY), ['X-API-Key' => $this->apiKey,@@ -158,6 +162,9 @@ class HttpExecutor'Accept' => 'application/json',]),];+ if ($idempotencyKey !== null) {+ $options['headers']['Idempotency-Key'] = $idempotencyKey;+ }// Build query string, skipping null values (so absent optionals aren't sent). Guzzle's// 'query' option would replace a query already in a raw path, so extend the URL instead.$url = $this->baseUrl . $path;diff --git a/sdk/php/src/Resources/MessagesResource.php b/sdk/php/src/Resources/MessagesResource.phpindex 9a9ca5d7c..a38e9704b 100644--- a/sdk/php/src/Resources/MessagesResource.php+++ b/sdk/php/src/Resources/MessagesResource.php@@ -39,71 +39,71 @@ class MessagesResource* @param array<string,mixed> $body* @return array<string,mixed>*/- public function sendText(string $sessionId, array $body): array+ public function sendText(string $sessionId, array $body, ?string $idempotencyKey = null): array{- return $this->http->request('POST', "/api/sessions/{$this->http->encodeSegment($sessionId)}/messages/send-text", [], $body);+ return $this->http->request('POST', "/api/sessions/{$this->http->encodeSegment($sessionId)}/messages/send-text", [], $body, $idempotencyKey);}/*** @param array<string,mixed> $body* @return array<string,mixed>*/- public function sendImage(string $sessionId, array $body): array+ public function sendImage(string $sessionId, array $body, ?string $idempotencyKey = null): array{- return $this->sendMedia($sessionId, 'send-image', $body);+ return $this->sendMedia($sessionId, 'send-image', $body, $idempotencyKey);}/** @return array<string,mixed> */- public function sendVideo(string $sessionId, array $body): array+ public function sendVideo(string $sessionId, array $body, ?string $idempotencyKey = null): array{- return $this->sendMedia($sessionId, 'send-video', $body);+ return $this->sendMedia($sessionId, 'send-video', $body, $idempotencyKey);}/** @return array<string,mixed> */- public function sendAudio(string $sessionId, array $body): array+ public function sendAudio(string $sessionId, array $body, ?string $idempotencyKey = null): array{- return $this->sendMedia($sessionId, 'send-audio', $body);+ return $this->sendMedia($sessionId, 'send-audio', $body, $idempotencyKey);}/** @return array<string,mixed> */- public function sendDocument(string $sessionId, array $body): array+ public function sendDocument(string $sessionId, array $body, ?string $idempotencyKey = null): array{- return $this->sendMedia($sessionId, 'send-document', $body);+ return $this->sendMedia($sessionId, 'send-document', $body, $idempotencyKey);}/** @return array<string,mixed> */- public function sendSticker(string $sessionId, array $body): array+ public function sendSticker(string $sessionId, array $body, ?string $idempotencyKey = null): array{- return $this->sendMedia($sessionId, 'send-sticker', $body);+ return $this->sendMedia($sessionId, 'send-sticker', $body, $idempotencyKey);}/** @return array<string,mixed> */- private function sendMedia(string $sessionId, string $segment, array $body): array+ private function sendMedia(string $sessionId, string $segment, array $body, ?string $idempotencyKey = null): array{- return $this->http->request('POST', "/api/sessions/{$this->http->encodeSegment($sessionId)}/messages/{$this->http->encodeSegment($segment)}", [], $body);+ return $this->http->request('POST', "/api/sessions/{$this->http->encodeSegment($sessionId)}/messages/{$this->http->encodeSegment($segment)}", [], $body, $idempotencyKey);}/** @return array<string,mixed> */- public function sendLocation(string $sessionId, array $body): array+ public function sendLocation(string $sessionId, array $body, ?string $idempotencyKey = null): array{- return $this->http->request('POST', "/api/sessions/{$this->http->encodeSegment($sessionId)}/messages/send-location", [], $body);+ return $this->http->request('POST', "/api/sessions/{$this->http->encodeSegment($sessionId)}/messages/send-location", [], $body, $idempotencyKey);}/** @return array<string,mixed> */- public function sendContact(string $sessionId, array $body): array+ public function sendContact(string $sessionId, array $body, ?string $idempotencyKey = null): array{- return $this->http->request('POST', "/api/sessions/{$this->http->encodeSegment($sessionId)}/messages/send-contact", [], $body);+ return $this->http->request('POST', "/api/sessions/{$this->http->encodeSegment($sessionId)}/messages/send-contact", [], $body, $idempotencyKey);}/** @return array<string,mixed> */- public function sendTemplate(string $sessionId, array $body): array+ public function sendTemplate(string $sessionId, array $body, ?string $idempotencyKey = null): array{// vars is a map: an empty PHP array would serialize as a JSON list [] and be rejected by the// gateway's object validation. Cast the empty map to stdClass so it encodes as {}.if (isset($body['vars']) && $body['vars'] === []) {$body['vars'] = new \stdClass();}- return $this->http->request('POST', "/api/sessions/{$this->http->encodeSegment($sessionId)}/messages/send-template", [], $body);+ return $this->http->request('POST', "/api/sessions/{$this->http->encodeSegment($sessionId)}/messages/send-template", [], $body, $idempotencyKey);}/**@@ -112,15 +112,15 @@ class MessagesResource* @param array<string,mixed> $body {chatId, name, options, allowMultipleAnswers?}* @return array<string,mixed>*/- public function sendPoll(string $sessionId, array $body): array+ public function sendPoll(string $sessionId, array $body, ?string $idempotencyKey = null): array{- return $this->http->request('POST', "/api/sessions/{$this->http->encodeSegment($sessionId)}/messages/send-poll", [], $body);+ return $this->http->request('POST', "/api/sessions/{$this->http->encodeSegment($sessionId)}/messages/send-poll", [], $body, $idempotencyKey);}/** @return array<string,mixed> */- public function reply(string $sessionId, array $body): array+ public function reply(string $sessionId, array $body, ?string $idempotencyKey = null): array{- return $this->http->request('POST', "/api/sessions/{$this->http->encodeSegment($sessionId)}/messages/reply", [], $body);+ return $this->http->request('POST', "/api/sessions/{$this->http->encodeSegment($sessionId)}/messages/reply", [], $body, $idempotencyKey);}/**@@ -135,9 +135,9 @@ class MessagesResource}/** @return array<string,mixed> */- public function forward(string $sessionId, array $body): array+ public function forward(string $sessionId, array $body, ?string $idempotencyKey = null): array{- return $this->http->request('POST', "/api/sessions/{$this->http->encodeSegment($sessionId)}/messages/forward", [], $body);+ return $this->http->request('POST', "/api/sessions/{$this->http->encodeSegment($sessionId)}/messages/forward", [], $body, $idempotencyKey);}/** @return array<string,mixed> */diff --git a/sdk/php/tests/ResourcesTest.php b/sdk/php/tests/ResourcesTest.phpindex 7c4c7944f..3201a6f49 100644--- a/sdk/php/tests/ResourcesTest.php+++ b/sdk/php/tests/ResourcesTest.php@@ -4,6 +4,7 @@ declare(strict_types=1);namespace OpenWA\Tests;+use OpenWA\Client;use OpenWA\Exceptions\OpenWANotFoundException;use PHPUnit\Framework\TestCase;@@ -579,6 +580,104 @@ class ResourcesTest extends TestCase$this->assertSame('{}', $backend->rawBody(1));}+ public function testSendMethodsForwardIdempotencyKeysWithoutChangingJson(): void+ {+ $cases = [+ ['sendText', 'send-text', ['chatId' => '[email protected]', 'text' => 'hello', 'quotedMessageId' => 'q']],+ ['sendImage', 'send-image', ['chatId' => '[email protected]', 'url' => 'https://media/image', 'caption' => 'image']],+ ['sendVideo', 'send-video', ['chatId' => '[email protected]', 'url' => 'https://media/video']],+ ['sendAudio', 'send-audio', ['chatId' => '[email protected]', 'url' => 'https://media/audio', 'ptt' => true]],+ ['sendDocument', 'send-document', ['chatId' => '[email protected]', 'url' => 'https://media/doc', 'filename' => 'doc.pdf']],+ ['sendSticker', 'send-sticker', ['chatId' => '[email protected]', 'url' => 'https://media/sticker']],+ ['sendLocation', 'send-location', ['chatId' => '[email protected]', 'latitude' => -6.2, 'longitude' => 106.8]],+ ['sendContact', 'send-contact', ['chatId' => '[email protected]', 'contactName' => 'A', 'contactNumber' => '628']],+ ['sendTemplate', 'send-template', ['chatId' => '[email protected]', 'templateId' => 't', 'vars' => []]],+ ['sendPoll', 'send-poll', ['chatId' => '[email protected]', 'name' => 'Q', 'options' => ['A', 'B']]],+ ['reply', 'reply', ['chatId' => '[email protected]', 'quotedMessageId' => 'q', 'text' => 'reply']],+ ['forward', 'forward', ['fromChatId' => '[email protected]', 'toChatId' => '[email protected]', 'messageId' => 'm']],+ ];+ foreach ([null, '!', str_repeat('a', 255)] as $key) {+ $backend = new MockBackend();+ $client = $backend->makeClient();+ foreach ($cases as $index => [$method, $segment, $body]) {+ $backend->on(200, ['messageId' => 'm', 'timestamp' => 1]);+ if ($key === null) {+ $client->messages->{$method}('s', $body);+ } else {+ $client->messages->{$method}('s', $body, $key);+ }+ $call = $backend->lastCall();+ $this->assertSame('POST', $call['method'], $method);+ $this->assertSame('/api/sessions/s/messages/' . $segment, $call['path'], $method);+ $this->assertSame($body, $call['body'], $method);+ $expected = $body;+ if ($method === 'sendTemplate') {+ $expected['vars'] = new \stdClass();+ }+ $this->assertSame(json_encode($expected), $backend->rawBody($index), $method);+ if ($key === null) {+ $this->assertArrayNotHasKey('idempotency-key', $call['headers'], $method);+ } else {+ $this->assertSame($key, $call['headers']['idempotency-key'], $method);+ }+ }+ }+ }++ public function testSendKeysStayLocalToEachRequest(): void+ {+ $backend = new MockBackend();+ $client = $backend->makeClient();+ $body = ['chatId' => '[email protected]', 'text' => 'hello'];+ foreach (['first-key', 'second-key', null] as $key) {+ $backend->on(200, ['messageId' => 'm', 'timestamp' => 1]);+ if ($key === null) {+ $client->messages->sendText('s', $body);+ $this->assertArrayNotHasKey('idempotency-key', $backend->lastCall()['headers']);+ } else {+ $client->messages->sendText('s', $body, $key);+ $this->assertSame($key, $backend->lastCall()['headers']['idempotency-key']);+ }+ $this->assertSame($body, $backend->lastCall()['body']);+ }+ }++ public function testSendKeyOverridesDefaultHeaderWithoutChangingDefaults(): void+ {+ $backend = new MockBackend();+ $defaults = ['iDeMpOtEnCy-KeY' => 'default-key', 'X-Trace' => 'trace'];+ $client = new Client([+ 'baseUrl' => 'http://localhost:2785',+ 'apiKey' => 'owa_k1_test',+ 'httpClient' => $backend->httpClient(),+ 'defaultHeaders' => $defaults,+ ]);+ $body = ['chatId' => '[email protected]', 'text' => 'hello'];+ $backend->on(200, ['messageId' => 'm', 'timestamp' => 1]);+ $client->messages->sendText('s', $body, 'request-key');+ $this->assertSame('request-key', $backend->lastCall()['headers']['idempotency-key']);+ $this->assertSame('trace', $backend->lastCall()['headers']['x-trace']);+ $backend->on(200, ['messageId' => 'm', 'timestamp' => 1]);+ $client->messages->sendText('s', $body);+ $this->assertSame('default-key', $backend->lastCall()['headers']['idempotency-key']);+ $this->assertSame(['iDeMpOtEnCy-KeY' => 'default-key', 'X-Trace' => 'trace'], $defaults);+ }++ public function testInvalidSendKeysAreRefusedBeforeTransport(): void+ {+ $backend = new MockBackend();+ $client = $backend->makeClient();+ foreach (['', ' ', 'contains space', "key\n", "\xC3\xA9", str_repeat('a', 256)] as $key) {+ try {+ $client->messages->sendText('s', ['chatId' => '[email protected]', 'text' => 'hello'], $key);+ $this->fail('Expected invalid key to be refused');+ } catch (\InvalidArgumentException $error) {+ $this->assertStringContainsString('1-255 visible ASCII', $error->getMessage());+ $this->assertSame([], $backend->calls());+ }+ }+ }+private function assertRequest(MockBackend $backend, string $method, string $path): void{$this->assertSame($method, $backend->lastCall()['method']);diff --git a/sdk/python/README.md b/sdk/python/README.mdindex 8ed824212..82f7fd90e 100644--- a/sdk/python/README.md+++ b/sdk/python/README.md@@ -165,3 +165,13 @@ Cutting a release:## LicenseMIT++## Send idempotency++Supply a unique caller-owned key for one logical send and reuse it when retrying that same call. Keys contain 1-255 visible ASCII characters; unrelated calls must use different keys. The SDK forwards the key without changing its retry policy or generating one automatically.++```python+client.messages.send_text(session_id, {"chatId": "[email protected]", "text": "Hello"}, idempotency_key="order-123")+```++The gateway supports text, image, video, audio, document, sticker, location, contact, template, poll, reply and forward sends. Completed calls replay their response; pending or uncertain outcomes return 409, and a changed request with the same key returns 422. The gateway retains keys for 24 hours. Bulk, product and button operations have no such guarantee. Omit the key to preserve existing behavior.diff --git a/sdk/python/openwa/_http.py b/sdk/python/openwa/_http.pyindex 317ff4c88..497882b8e 100644--- a/sdk/python/openwa/_http.py+++ b/sdk/python/openwa/_http.py@@ -109,9 +109,12 @@ class HttpExecutor:def __exit__(self, *exc: Any) -> None:self.close()- def request(self, method: HttpMethod, path: str, *, query: Mapping[str, Any] | None = None, body: Any = None) -> Any:+ def request(+ self, method: HttpMethod, path: str, *, query: Mapping[str, Any] | None = None,+ body: Any = None, idempotency_key: str | None = None+ ) -> Any:"""Perform one request and return the parsed JSON (or ``None`` for 204)."""- res = self._send(method, path, query=query, body=body)+ res = self._send(method, path, query=query, body=body, idempotency_key=idempotency_key)if res.status_code == 204 or not res.content:return Nonetry:@@ -133,12 +136,24 @@ class HttpExecutor:return b"", Nonereturn res.content, res.headers.get("content-type")- def _send(self, method: HttpMethod, path: str, *, query: Mapping[str, Any] | None, body: Any) -> httpx.Response:+ def _send(+ self, method: HttpMethod, path: str, *, query: Mapping[str, Any] | None,+ body: Any, idempotency_key: str | None = None+ ) -> httpx.Response:"""Shared transport for :meth:`request` and :meth:`request_bytes`: buildsthe URL, performs the request, and translates a non-2xx into a typed error."""+ headers = None+ if idempotency_key is not None:+ if (+ not isinstance(idempotency_key, str)+ or not 1 <= len(idempotency_key) <= 255+ or any(not "!" <= char <= "~" for char in idempotency_key)+ ):+ raise ValueError("Idempotency-Key must contain 1-255 visible ASCII characters")+ headers = {"Idempotency-Key": idempotency_key}url = build_url("", path, query)try:- res = self._client.request(method, url, json=body if body is not None else None)+ res = self._client.request(method, url, json=body if body is not None else None, headers=headers)except httpx.TimeoutException as e:raise OpenWATimeoutError(self._timeout) from e# Treat any non-2xx as an error, including 3xx: redirects are deliberately not followeddiff --git a/sdk/python/openwa/resources/messages.py b/sdk/python/openwa/resources/messages.pyindex 0f7a2c519..65e03bb61 100644--- a/sdk/python/openwa/resources/messages.py+++ b/sdk/python/openwa/resources/messages.py@@ -52,42 +52,42 @@ class MessagesResource:def list(self, session_id: str, query: ListMessagesQuery | None = None) -> MessageListResponse:return self._http.request("GET", f"/api/sessions/{quote_segment(session_id)}/messages", query=query)- def send_text(self, session_id: str, body: SendTextRequest) -> MessageResponse:- return self._http.request("POST", f"/api/sessions/{quote_segment(session_id)}/messages/send-text", body=body)+ def send_text(self, session_id: str, body: SendTextRequest, *, idempotency_key: str | None = None) -> MessageResponse:+ return self._http.request("POST", f"/api/sessions/{quote_segment(session_id)}/messages/send-text", body=body, idempotency_key=idempotency_key)- def send_image(self, session_id: str, body: SendMediaRequest) -> MessageResponse:- return self._send_media(session_id, "send-image", body)+ def send_image(self, session_id: str, body: SendMediaRequest, *, idempotency_key: str | None = None) -> MessageResponse:+ return self._send_media(session_id, "send-image", body, idempotency_key=idempotency_key)- def send_video(self, session_id: str, body: SendMediaRequest) -> MessageResponse:- return self._send_media(session_id, "send-video", body)+ def send_video(self, session_id: str, body: SendMediaRequest, *, idempotency_key: str | None = None) -> MessageResponse:+ return self._send_media(session_id, "send-video", body, idempotency_key=idempotency_key)- def send_audio(self, session_id: str, body: SendAudioRequest) -> MessageResponse:- return self._send_media(session_id, "send-audio", body)+ def send_audio(self, session_id: str, body: SendAudioRequest, *, idempotency_key: str | None = None) -> MessageResponse:+ return self._send_media(session_id, "send-audio", body, idempotency_key=idempotency_key)- def send_document(self, session_id: str, body: SendMediaRequest) -> MessageResponse:- return self._send_media(session_id, "send-document", body)+ def send_document(self, session_id: str, body: SendMediaRequest, *, idempotency_key: str | None = None) -> MessageResponse:+ return self._send_media(session_id, "send-document", body, idempotency_key=idempotency_key)- def send_sticker(self, session_id: str, body: SendMediaRequest) -> MessageResponse:- return self._send_media(session_id, "send-sticker", body)+ def send_sticker(self, session_id: str, body: SendMediaRequest, *, idempotency_key: str | None = None) -> MessageResponse:+ return self._send_media(session_id, "send-sticker", body, idempotency_key=idempotency_key)- def _send_media(self, session_id: str, segment: str, body: SendMediaRequest) -> MessageResponse:- return self._http.request("POST", f"/api/sessions/{quote_segment(session_id)}/messages/{quote_segment(segment)}", body=body)+ def _send_media(self, session_id: str, segment: str, body: SendMediaRequest, *, idempotency_key: str | None = None) -> MessageResponse:+ return self._http.request("POST", f"/api/sessions/{quote_segment(session_id)}/messages/{quote_segment(segment)}", body=body, idempotency_key=idempotency_key)- def send_location(self, session_id: str, body: SendLocationRequest) -> MessageResponse:- return self._http.request("POST", f"/api/sessions/{quote_segment(session_id)}/messages/send-location", body=body)+ def send_location(self, session_id: str, body: SendLocationRequest, *, idempotency_key: str | None = None) -> MessageResponse:+ return self._http.request("POST", f"/api/sessions/{quote_segment(session_id)}/messages/send-location", body=body, idempotency_key=idempotency_key)- def send_contact(self, session_id: str, body: SendContactRequest) -> MessageResponse:- return self._http.request("POST", f"/api/sessions/{quote_segment(session_id)}/messages/send-contact", body=body)+ def send_contact(self, session_id: str, body: SendContactRequest, *, idempotency_key: str | None = None) -> MessageResponse:+ return self._http.request("POST", f"/api/sessions/{quote_segment(session_id)}/messages/send-contact", body=body, idempotency_key=idempotency_key)- def send_template(self, session_id: str, body: SendTemplateRequest) -> MessageResponse:- return self._http.request("POST", f"/api/sessions/{quote_segment(session_id)}/messages/send-template", body=body)+ def send_template(self, session_id: str, body: SendTemplateRequest, *, idempotency_key: str | None = None) -> MessageResponse:+ return self._http.request("POST", f"/api/sessions/{quote_segment(session_id)}/messages/send-template", body=body, idempotency_key=idempotency_key)- def send_poll(self, session_id: str, body: SendPollRequest) -> MessageResponse:+ def send_poll(self, session_id: str, body: SendPollRequest, *, idempotency_key: str | None = None) -> MessageResponse:"""Send a native WhatsApp poll (2–12 options)."""- return self._http.request("POST", f"/api/sessions/{quote_segment(session_id)}/messages/send-poll", body=body)+ return self._http.request("POST", f"/api/sessions/{quote_segment(session_id)}/messages/send-poll", body=body, idempotency_key=idempotency_key)- def reply(self, session_id: str, body: ReplyMessageRequest) -> MessageResponse:- return self._http.request("POST", f"/api/sessions/{quote_segment(session_id)}/messages/reply", body=body)+ def reply(self, session_id: str, body: ReplyMessageRequest, *, idempotency_key: str | None = None) -> MessageResponse:+ return self._http.request("POST", f"/api/sessions/{quote_segment(session_id)}/messages/reply", body=body, idempotency_key=idempotency_key)def click_button(self, session_id: str, body: ClickButtonRequest) -> MessageResponse:"""Click a button on a WhatsApp Business prompt. Baileys only (whatsapp-web.js returns 501)."""@@ -95,8 +95,8 @@ class MessagesResource:"POST", f"/api/sessions/{quote_segment(session_id)}/messages/click-button", body=body)- def forward(self, session_id: str, body: ForwardMessageRequest) -> MessageResponse:- return self._http.request("POST", f"/api/sessions/{quote_segment(session_id)}/messages/forward", body=body)+ def forward(self, session_id: str, body: ForwardMessageRequest, *, idempotency_key: str | None = None) -> MessageResponse:+ return self._http.request("POST", f"/api/sessions/{quote_segment(session_id)}/messages/forward", body=body, idempotency_key=idempotency_key)def react(self, session_id: str, body: ReactMessageRequest) -> SuccessResult:return self._http.request("POST", f"/api/sessions/{quote_segment(session_id)}/messages/react", body=body)diff --git a/sdk/python/tests/test_sdk.py b/sdk/python/tests/test_sdk.pyindex a4ffcb8d0..ac4e22dfe 100644--- a/sdk/python/tests/test_sdk.py+++ b/sdk/python/tests/test_sdk.py@@ -18,6 +18,15 @@ from openwa.types import (AuthValidateResponse,BatchCancelResponse,HealthReadyResponse,+ ForwardMessageRequest,+ ReplyMessageRequest,+ SendAudioRequest,+ SendContactRequest,+ SendLocationRequest,+ SendMediaRequest,+ SendPollRequest,+ SendTemplateRequest,+ SendTextRequest,WebhookDelivery,WebhookDeliveryEvent,WebhookEvent,@@ -260,6 +269,82 @@ class TestClientCore:class TestMessages:+ @pytest.mark.parametrize("key", [None, "!", "a" * 255])+ def test_send_methods_forward_keys_without_changing_json(self, key: str | None) -> None:+ backend = MockBackend().on("POST", "/messages/", body={"messageId": "m", "timestamp": 1})+ client = make_client(backend)+ text: SendTextRequest = {"chatId": "[email protected]", "text": "hello", "quotedMessageId": "q"}+ media: SendMediaRequest = {"chatId": "[email protected]", "url": "https://media/image", "caption": "image"}+ audio: SendAudioRequest = {"chatId": "[email protected]", "url": "https://media/audio", "ptt": True}+ location: SendLocationRequest = {"chatId": "[email protected]", "latitude": -6.2, "longitude": 106.8}+ contact: SendContactRequest = {"chatId": "[email protected]", "contactName": "A", "contactNumber": "628"}+ template: SendTemplateRequest = {"chatId": "[email protected]", "templateId": "t", "vars": {}}+ poll: SendPollRequest = {"chatId": "[email protected]", "name": "Q", "options": ["A", "B"]}+ reply: ReplyMessageRequest = {"chatId": "[email protected]", "quotedMessageId": "q", "text": "reply"}+ forward: ForwardMessageRequest = {"fromChatId": "[email protected]", "toChatId": "[email protected]", "messageId": "m"}++ client.messages.send_text("s", text, idempotency_key=key)+ client.messages.send_image("s", media, idempotency_key=key)+ client.messages.send_video("s", media, idempotency_key=key)+ client.messages.send_audio("s", audio, idempotency_key=key)+ client.messages.send_document("s", media, idempotency_key=key)+ client.messages.send_sticker("s", media, idempotency_key=key)+ client.messages.send_location("s", location, idempotency_key=key)+ client.messages.send_contact("s", contact, idempotency_key=key)+ client.messages.send_template("s", template, idempotency_key=key)+ client.messages.send_poll("s", poll, idempotency_key=key)+ client.messages.reply("s", reply, idempotency_key=key)+ client.messages.forward("s", forward, idempotency_key=key)++ expected = [+ ("send-text", text), ("send-image", media), ("send-video", media), ("send-audio", audio),+ ("send-document", media), ("send-sticker", media), ("send-location", location),+ ("send-contact", contact), ("send-template", template), ("send-poll", poll),+ ("reply", reply), ("forward", forward),+ ]+ assert len(backend.calls) == len(expected)+ for call, (segment, body) in zip(backend.calls, expected):+ assert call.method == "POST"+ assert call.url == f"http://localhost:2785/api/sessions/s/messages/{segment}"+ assert call.body == body+ if key is None:+ assert "idempotency-key" not in call.headers+ else:+ assert call.headers["idempotency-key"] == key++ def test_send_keys_stay_local_to_each_request(self) -> None:+ backend = MockBackend().on("POST", "/send-text", body={"messageId": "m", "timestamp": 1})+ client = make_client(backend)+ body: SendTextRequest = {"chatId": "[email protected]", "text": "hello"}+ client.messages.send_text("s", body, idempotency_key="first-key")+ client.messages.send_text("s", body, idempotency_key="second-key")+ client.messages.send_text("s", body)+ assert [call.headers.get("idempotency-key") for call in backend.calls] == ["first-key", "second-key", None]+ assert all(call.body == body for call in backend.calls)++ def test_send_key_overrides_default_header_without_changing_defaults(self) -> None:+ backend = MockBackend().on("POST", "/send-text", body={"messageId": "m", "timestamp": 1})+ defaults = {"iDeMpOtEnCy-KeY": "default-key", "X-Trace": "trace"}+ client = OpenWAClient(+ base_url="http://localhost:2785", api_key="owa_k1_test",+ default_headers=defaults, transport=backend.as_transport(),+ )+ body: SendTextRequest = {"chatId": "[email protected]", "text": "hello"}+ client.messages.send_text("s", body, idempotency_key="request-key")+ assert backend.last_call.headers["idempotency-key"] == "request-key"+ assert backend.last_call.headers["x-trace"] == "trace"+ client.messages.send_text("s", body)+ assert backend.last_call.headers["idempotency-key"] == "default-key"+ assert defaults == {"iDeMpOtEnCy-KeY": "default-key", "X-Trace": "trace"}++ @pytest.mark.parametrize("key", ["", " ", "contains space", "key\n", "\u00e9", "a" * 256])+ def test_invalid_send_keys_are_refused_before_transport(self, key: str) -> None:+ backend = MockBackend()+ client = make_client(backend)+ with pytest.raises(ValueError, match="1-255 visible ASCII"):+ client.messages.send_text("s", {"chatId": "[email protected]", "text": "hello"}, idempotency_key=key)+ assert backend.calls == []+def test_send_text_uses_send_text_path(self):backend = MockBackend().on("POST", "/send-text", body={"messageId": "m1", "timestamp": 1})make_client(backend).messages.send_text("s1", {"chatId": "[email protected]", "text": "hi"})