@chatwise/node 0.0.0-stage → 0.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +19 -0
- package/LICENSE +202 -0
- package/README.md +592 -2
- package/dist/cjs/client.d.ts +20 -0
- package/dist/cjs/client.js +32 -0
- package/dist/cjs/core/errors.d.ts +101 -0
- package/dist/cjs/core/errors.js +143 -0
- package/dist/cjs/core/http.d.ts +87 -0
- package/dist/cjs/core/http.js +360 -0
- package/dist/cjs/core/pagination.d.ts +35 -0
- package/dist/cjs/core/pagination.js +101 -0
- package/dist/cjs/generated/types.d.ts +1017 -0
- package/dist/cjs/generated/types.js +3 -0
- package/dist/cjs/index.d.ts +15 -0
- package/dist/cjs/index.js +26 -0
- package/dist/cjs/package.json +1 -0
- package/dist/cjs/resources/conversations.d.ts +20 -0
- package/dist/cjs/resources/conversations.js +32 -0
- package/dist/cjs/resources/messages.d.ts +104 -0
- package/dist/cjs/resources/messages.js +112 -0
- package/dist/cjs/resources/webhook-deliveries.d.ts +27 -0
- package/dist/cjs/resources/webhook-deliveries.js +42 -0
- package/dist/cjs/resources/webhook-endpoints.d.ts +54 -0
- package/dist/cjs/resources/webhook-endpoints.js +82 -0
- package/dist/cjs/resources/webhook-event-types.d.ts +13 -0
- package/dist/cjs/resources/webhook-event-types.js +22 -0
- package/dist/cjs/resources/whatsapp-templates.d.ts +48 -0
- package/dist/cjs/resources/whatsapp-templates.js +71 -0
- package/dist/cjs/version.d.ts +2 -0
- package/dist/cjs/version.js +5 -0
- package/dist/cjs/webhooks.d.ts +74 -0
- package/dist/cjs/webhooks.js +123 -0
- package/dist/esm/client.d.ts +20 -0
- package/dist/esm/client.js +28 -0
- package/dist/esm/core/errors.d.ts +101 -0
- package/dist/esm/core/errors.js +124 -0
- package/dist/esm/core/http.d.ts +87 -0
- package/dist/esm/core/http.js +356 -0
- package/dist/esm/core/pagination.d.ts +35 -0
- package/dist/esm/core/pagination.js +95 -0
- package/dist/esm/generated/types.d.ts +1017 -0
- package/dist/esm/generated/types.js +2 -0
- package/dist/esm/index.d.ts +15 -0
- package/dist/esm/index.js +4 -0
- package/dist/esm/package.json +1 -0
- package/dist/esm/resources/conversations.d.ts +20 -0
- package/dist/esm/resources/conversations.js +28 -0
- package/dist/esm/resources/messages.d.ts +104 -0
- package/dist/esm/resources/messages.js +108 -0
- package/dist/esm/resources/webhook-deliveries.d.ts +27 -0
- package/dist/esm/resources/webhook-deliveries.js +38 -0
- package/dist/esm/resources/webhook-endpoints.d.ts +54 -0
- package/dist/esm/resources/webhook-endpoints.js +78 -0
- package/dist/esm/resources/webhook-event-types.d.ts +13 -0
- package/dist/esm/resources/webhook-event-types.js +18 -0
- package/dist/esm/resources/whatsapp-templates.d.ts +48 -0
- package/dist/esm/resources/whatsapp-templates.js +67 -0
- package/dist/esm/version.d.ts +2 -0
- package/dist/esm/version.js +2 -0
- package/dist/esm/webhooks.d.ts +74 -0
- package/dist/esm/webhooks.js +118 -0
- package/package.json +79 -4
package/README.md
CHANGED
|
@@ -1,3 +1,593 @@
|
|
|
1
|
-
#
|
|
1
|
+
# Chatwise for Node.js
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
The official Node.js SDK for the [Chatwise API](https://chatwise.so/docs): read your WhatsApp, Instagram, Messenger and Website Chat inbox, reply to customers, send WhatsApp templates, and receive signed webhooks.
|
|
4
|
+
|
|
5
|
+
- **Small.** No dependencies, and ES modules and CommonJS with types for both.
|
|
6
|
+
- **Typed.** Requests, responses and webhook events, generated from the API's own specification.
|
|
7
|
+
- **Careful.** It retries only what is safe to repeat, so a retry never sends a message twice.
|
|
8
|
+
|
|
9
|
+
## Install
|
|
10
|
+
|
|
11
|
+
```bash
|
|
12
|
+
npm install @chatwise/node
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
It needs Node.js 20 or later. Use it on a server only: anyone who has your API key can use it.
|
|
16
|
+
|
|
17
|
+
## Quick start
|
|
18
|
+
|
|
19
|
+
Create an API key in the dashboard under **Settings → Developer → API Keys**, with the **Read conversations** permission, and set it as `CHATWISE_API_KEY`.
|
|
20
|
+
|
|
21
|
+
```ts
|
|
22
|
+
import { Chatwise } from '@chatwise/node';
|
|
23
|
+
|
|
24
|
+
const chatwise = new Chatwise(); // Reads CHATWISE_API_KEY.
|
|
25
|
+
|
|
26
|
+
const { data: conversations } = await chatwise.conversations.list({ status: 'open', limit: 5 });
|
|
27
|
+
|
|
28
|
+
for (const { id, channel, participant } of conversations) {
|
|
29
|
+
console.log(id, channel, participant.name);
|
|
30
|
+
}
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
## Read the inbox
|
|
34
|
+
|
|
35
|
+
A list can be iterated over, and reads its pages as it goes:
|
|
36
|
+
|
|
37
|
+
```ts
|
|
38
|
+
import { Chatwise } from '@chatwise/node';
|
|
39
|
+
|
|
40
|
+
const chatwise = new Chatwise();
|
|
41
|
+
|
|
42
|
+
for await (const message of chatwise.messages.list({ channel: 'WHATSAPP', q: 'refund' })) {
|
|
43
|
+
console.log(message.sentAt, message.direction, message.text);
|
|
44
|
+
}
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
Or read page by page. Keep `nextCursor` to go on later, with the same filters:
|
|
48
|
+
|
|
49
|
+
```ts
|
|
50
|
+
import { Chatwise } from '@chatwise/node';
|
|
51
|
+
|
|
52
|
+
const chatwise = new Chatwise();
|
|
53
|
+
|
|
54
|
+
let page = await chatwise.conversations.list({ channel: 'INSTAGRAM', limit: 100 });
|
|
55
|
+
console.log(page.data.length, page.nextCursor);
|
|
56
|
+
|
|
57
|
+
while (page.hasNextPage()) {
|
|
58
|
+
page = (await page.getNextPage())!;
|
|
59
|
+
console.log(page.data.length);
|
|
60
|
+
}
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
One conversation, its messages of a day, and one message:
|
|
64
|
+
|
|
65
|
+
```ts
|
|
66
|
+
import { Chatwise } from '@chatwise/node';
|
|
67
|
+
|
|
68
|
+
const chatwise = new Chatwise();
|
|
69
|
+
|
|
70
|
+
const conversation = await chatwise.conversations.get('1234');
|
|
71
|
+
|
|
72
|
+
const messages = chatwise.messages.listInConversation(conversation.id, {
|
|
73
|
+
from: new Date('2026-11-12T00:00:00Z'),
|
|
74
|
+
to: new Date('2026-11-13T00:00:00Z'),
|
|
75
|
+
order: 'asc',
|
|
76
|
+
});
|
|
77
|
+
for await (const message of messages) console.log(message.text);
|
|
78
|
+
|
|
79
|
+
const message = await chatwise.messages.get('1234', '5678');
|
|
80
|
+
console.log(message.attachments);
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
Ids are strings. They can be larger than a JavaScript number can hold, so don't convert them.
|
|
84
|
+
|
|
85
|
+
To copy new messages on a schedule, see [examples/copy-messages.ts](https://github.com/vectorscalelabs/chatwise-node/blob/main/examples/copy-messages.ts). To get them as they arrive, use [webhooks](#receive-webhooks).
|
|
86
|
+
|
|
87
|
+
## Reply to a customer
|
|
88
|
+
|
|
89
|
+
With a text, in a WhatsApp, Instagram or Messenger conversation:
|
|
90
|
+
|
|
91
|
+
```ts
|
|
92
|
+
import { Chatwise } from '@chatwise/node';
|
|
93
|
+
|
|
94
|
+
const chatwise = new Chatwise();
|
|
95
|
+
|
|
96
|
+
const { id, channel } = await chatwise.messages.reply(
|
|
97
|
+
'1234',
|
|
98
|
+
{ text: 'Yes, it is available in blue.' },
|
|
99
|
+
{ idempotencyKey: 'reply-evt_01JE2Z3QK4T8M6N2R5S7V9W1X3' },
|
|
100
|
+
);
|
|
101
|
+
console.log(`${channel} accepted message ${id}`);
|
|
102
|
+
```
|
|
103
|
+
|
|
104
|
+
Or with a file, on WhatsApp, Instagram and Messenger. Chatwise downloads it from its address, which must be public and `https`, and [converts it](https://chatwise.so/docs/replies#what-can-be-sent) to what the channel takes:
|
|
105
|
+
|
|
106
|
+
```ts
|
|
107
|
+
import { Chatwise } from '@chatwise/node';
|
|
108
|
+
|
|
109
|
+
const chatwise = new Chatwise();
|
|
110
|
+
|
|
111
|
+
const { type } = await chatwise.messages.reply(
|
|
112
|
+
'1234',
|
|
113
|
+
{
|
|
114
|
+
media: {
|
|
115
|
+
url: 'https://example.com/files/invoice-1042.pdf',
|
|
116
|
+
fileName: 'Invoice 1042.pdf',
|
|
117
|
+
caption: 'Here is your invoice.', // Only on WhatsApp, and not with audio.
|
|
118
|
+
},
|
|
119
|
+
},
|
|
120
|
+
{ idempotencyKey: 'invoice-1042' },
|
|
121
|
+
);
|
|
122
|
+
console.log(`Sent as ${type}`);
|
|
123
|
+
```
|
|
124
|
+
|
|
125
|
+
The answer means the channel accepted the message, not that it was delivered. A customer can be answered for 24 hours after their latest message. Later the code is `REPLY_WINDOW_CLOSED`: on WhatsApp, [send a template](#send-a-whatsapp-template) then.
|
|
126
|
+
|
|
127
|
+
**One `idempotencyKey` stands for one message.** Make it from what you answer, such as the event's id. A call that is repeated with the same key, content and API key doesn't send the message again, for 30 days. With another `idempotencyKey` or another API key it sends another message. What to do when a reply throws:
|
|
128
|
+
|
|
129
|
+
| It throws | What to do |
|
|
130
|
+
| --- | --- |
|
|
131
|
+
| `SEND_OUTCOME_UNKNOWN` | Let a person decide. The message [may have been sent](https://chatwise.so/docs/replies#when-it-isnt-clear), even if the conversation doesn't show it, and a repeat sends nothing. Send it again with a new key only if it is better that the customer gets it twice than not at all. |
|
|
132
|
+
| A `ConnectionError`, a `RequestAbortedError`, any other 5xx, a 429, `SEND_IN_PROGRESS`, `MEDIA_PROCESSING`, or a 401 with the message `Invalid API key` | Call it again later, with the same key, content and API key. It may have been sent, and then the repeat returns that message. |
|
|
133
|
+
| `MEDIA_DOWNLOAD_FAILED` | Call it again after a minute, and the file is downloaded again. For another address, use a new key. |
|
|
134
|
+
| Any other 4xx | Fix what it names first: until then it fails again. Other content, such as another file, needs a new key. |
|
|
135
|
+
|
|
136
|
+
**An error is about the last request of the call.** If an earlier one got no answer, a 401, 403, 404 or 429 doesn't say that nothing was sent, so don't go on with another `idempotencyKey`. With a file no error says so while the earlier request is still running, because that one can send the file later: wait a minute and make the call once more first. The same goes for a new API key, such as after `SEND_NOT_PERMITTED`: first make sure that it wasn't sent.
|
|
137
|
+
|
|
138
|
+
A file can take minutes to prepare. The call waits for it, for ten minutes unless `mediaTimeoutMs` says otherwise: see [retries](#retries-and-timeouts). [examples/reply.ts](https://github.com/vectorscalelabs/chatwise-node/blob/main/examples/reply.ts) answers a message and handles what can go wrong.
|
|
139
|
+
|
|
140
|
+
**When you answer webhooks, answer `message.received` only.** Each reply makes a `message.sent` event, as every message from the workspace does: a program that answers those answers itself.
|
|
141
|
+
|
|
142
|
+
## Download a message's files
|
|
143
|
+
|
|
144
|
+
```ts
|
|
145
|
+
import { Chatwise } from '@chatwise/node';
|
|
146
|
+
|
|
147
|
+
const chatwise = new Chatwise();
|
|
148
|
+
|
|
149
|
+
for (const file of await chatwise.messages.listFiles('1234', '5678')) {
|
|
150
|
+
if (file.url === null) {
|
|
151
|
+
console.log(file.type, file.status); // It is still being copied (pending), or it is gone (unavailable).
|
|
152
|
+
continue;
|
|
153
|
+
}
|
|
154
|
+
// A plain fetch: whoever has the link has the file, so it needs no API key. Don't send yours.
|
|
155
|
+
const response = await fetch(file.url);
|
|
156
|
+
if (!response.ok) throw new Error(`The file answered ${response.status}`);
|
|
157
|
+
console.log(file.name, file.mimeType, (await response.arrayBuffer()).byteLength);
|
|
158
|
+
}
|
|
159
|
+
```
|
|
160
|
+
|
|
161
|
+
A link works for five minutes, until `urlExpiresAt`. Don't store it: list the files again for a new one. `name` is what the sender called the file, so don't use it as a path. [Read the files](https://chatwise.so/docs/replies#4-read-the-files) says which files there are on which channel. [examples/download-files.ts](https://github.com/vectorscalelabs/chatwise-node/blob/main/examples/download-files.ts) waits for those that are still being copied.
|
|
162
|
+
|
|
163
|
+
## Send a WhatsApp template
|
|
164
|
+
|
|
165
|
+
By its name:
|
|
166
|
+
|
|
167
|
+
```ts
|
|
168
|
+
import { Chatwise } from '@chatwise/node';
|
|
169
|
+
|
|
170
|
+
const chatwise = new Chatwise();
|
|
171
|
+
|
|
172
|
+
const { from } = await chatwise.whatsappTemplates.send({
|
|
173
|
+
phoneNumber: '12025550147',
|
|
174
|
+
templateName: 'order_ready',
|
|
175
|
+
templateLanguage: 'en_US',
|
|
176
|
+
templateParams: [{ parameter_name: 'order_number', text: 'A-1042' }],
|
|
177
|
+
});
|
|
178
|
+
console.log(`Sent from ${from}`);
|
|
179
|
+
```
|
|
180
|
+
|
|
181
|
+
Or by its id, which also works for templates that share a name:
|
|
182
|
+
|
|
183
|
+
```ts
|
|
184
|
+
import { Chatwise } from '@chatwise/node';
|
|
185
|
+
|
|
186
|
+
const chatwise = new Chatwise();
|
|
187
|
+
|
|
188
|
+
for await (const template of chatwise.whatsappTemplates.list({ sendable: true, language: 'en_US' })) {
|
|
189
|
+
console.log(template.id, template.name, template.components.body.variables);
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
await chatwise.messages.send({
|
|
193
|
+
to: '12025550147',
|
|
194
|
+
templateId: '123456789012345',
|
|
195
|
+
templateParams: [{ parameter_name: 'order_number', text: 'A-1042' }],
|
|
196
|
+
});
|
|
197
|
+
```
|
|
198
|
+
|
|
199
|
+
The answer means WhatsApp accepted the message, not that it was delivered. Sending twice sends two messages: see [retries](#retries-and-timeouts).
|
|
200
|
+
|
|
201
|
+
## Create a WhatsApp template
|
|
202
|
+
|
|
203
|
+
```ts
|
|
204
|
+
import { Chatwise } from '@chatwise/node';
|
|
205
|
+
|
|
206
|
+
const chatwise = new Chatwise();
|
|
207
|
+
|
|
208
|
+
const created = await chatwise.whatsappTemplates.create(
|
|
209
|
+
{
|
|
210
|
+
name: 'order_ready',
|
|
211
|
+
language: 'en_US',
|
|
212
|
+
category: 'UTILITY',
|
|
213
|
+
components: {
|
|
214
|
+
body: { text: 'Your order {{order_number}} is ready to collect.', examples: { order_number: 'A-1042' } },
|
|
215
|
+
},
|
|
216
|
+
},
|
|
217
|
+
{ idempotencyKey: 'order-ready-en-us-v1' },
|
|
218
|
+
);
|
|
219
|
+
|
|
220
|
+
// Meta reviews it. Once `status` isn't PENDING any more, `sendable` says whether it can be sent.
|
|
221
|
+
const { status, sendable } = await chatwise.whatsappTemplates.get(created.id);
|
|
222
|
+
console.log(status, sendable);
|
|
223
|
+
```
|
|
224
|
+
|
|
225
|
+
Call it again with the same `idempotencyKey` and template, and you get the same template back.
|
|
226
|
+
|
|
227
|
+
## Receive webhooks
|
|
228
|
+
|
|
229
|
+
Chatwise sends events to your server as signed HTTPS requests. Create an endpoint, and store its secret:
|
|
230
|
+
|
|
231
|
+
```ts
|
|
232
|
+
import { Chatwise } from '@chatwise/node';
|
|
233
|
+
|
|
234
|
+
const chatwise = new Chatwise();
|
|
235
|
+
|
|
236
|
+
const endpoint = await chatwise.webhookEndpoints.create({
|
|
237
|
+
name: 'Order support',
|
|
238
|
+
url: 'https://example.com/webhooks/chatwise',
|
|
239
|
+
events: ['message.received'],
|
|
240
|
+
});
|
|
241
|
+
console.log(endpoint.signingSecret); // The only time it is returned.
|
|
242
|
+
```
|
|
243
|
+
|
|
244
|
+
Then check each request with `verifyWebhook`. It needs the body **exactly as received**, so get it before anything parses it. Each of these does:
|
|
245
|
+
|
|
246
|
+
### Express
|
|
247
|
+
|
|
248
|
+
```ts
|
|
249
|
+
import express from 'express';
|
|
250
|
+
import { verifyWebhook, WebhookVerificationError, type WebhookEvent } from '@chatwise/node';
|
|
251
|
+
|
|
252
|
+
const app = express();
|
|
253
|
+
|
|
254
|
+
// express.raw keeps the body as it was received, whatever its type. Put this route before any
|
|
255
|
+
// app.use(express.json()), which would parse it. Chatwise sends up to 256 KB, more than Express's own limit.
|
|
256
|
+
app.post('/webhooks/chatwise', express.raw({ type: () => true, limit: '300kb' }), (request, response) => {
|
|
257
|
+
let event: WebhookEvent;
|
|
258
|
+
try {
|
|
259
|
+
event = verifyWebhook({ payload: request.body ?? '', headers: request.headers, secret: process.env.CHATWISE_WEBHOOK_SECRET });
|
|
260
|
+
} catch (error) {
|
|
261
|
+
if (!(error instanceof WebhookVerificationError)) throw error; // A 500, so Chatwise tries again.
|
|
262
|
+
console.error(error.message); // After a 400 it doesn't, so watch for these.
|
|
263
|
+
response.status(400).send(error.code);
|
|
264
|
+
return;
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
// Answer within 10 seconds. An event that was answered isn't sent again, so first put work that must not
|
|
268
|
+
// be lost in a queue.
|
|
269
|
+
response.sendStatus(204);
|
|
270
|
+
|
|
271
|
+
if (event.type === 'message.received') {
|
|
272
|
+
console.log(`New message in conversation ${event.data.message.conversationId}`);
|
|
273
|
+
}
|
|
274
|
+
});
|
|
275
|
+
|
|
276
|
+
app.listen(3000);
|
|
277
|
+
```
|
|
278
|
+
|
|
279
|
+
### Next.js
|
|
280
|
+
|
|
281
|
+
```ts
|
|
282
|
+
// app/webhooks/chatwise/route.ts
|
|
283
|
+
import { verifyWebhook, WebhookVerificationError, type WebhookEvent } from '@chatwise/node';
|
|
284
|
+
|
|
285
|
+
// verifyWebhook uses Node's crypto, which the Edge runtime doesn't have.
|
|
286
|
+
export const runtime = 'nodejs';
|
|
287
|
+
|
|
288
|
+
export async function POST(request: Request): Promise<Response> {
|
|
289
|
+
// Anyone can send a request, and Next.js has no limit. Chatwise sends up to 256 KB. A request without a
|
|
290
|
+
// Content-Length has to be limited by your host or proxy.
|
|
291
|
+
if (Number(request.headers.get('content-length')) > 300 * 1024) return new Response(null, { status: 413 });
|
|
292
|
+
|
|
293
|
+
let event: WebhookEvent;
|
|
294
|
+
try {
|
|
295
|
+
// text(), not json(): the signature is of the body as it was received.
|
|
296
|
+
event = verifyWebhook({ payload: await request.text(), headers: request.headers, secret: process.env.CHATWISE_WEBHOOK_SECRET });
|
|
297
|
+
} catch (error) {
|
|
298
|
+
if (!(error instanceof WebhookVerificationError)) throw error; // A 500, so Chatwise tries again.
|
|
299
|
+
console.error(error.message); // After a 400 it doesn't, so watch for these.
|
|
300
|
+
return new Response(error.code, { status: 400 });
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
// Answer within 10 seconds. Put longer work in a queue, or in Next.js's after().
|
|
304
|
+
if (event.type === 'message.received') {
|
|
305
|
+
console.log(`New message in conversation ${event.data.message.conversationId}`);
|
|
306
|
+
}
|
|
307
|
+
return new Response(null, { status: 204 });
|
|
308
|
+
}
|
|
309
|
+
```
|
|
310
|
+
|
|
311
|
+
### Hono
|
|
312
|
+
|
|
313
|
+
```ts
|
|
314
|
+
import { serve } from '@hono/node-server';
|
|
315
|
+
import { Hono } from 'hono';
|
|
316
|
+
import { bodyLimit } from 'hono/body-limit';
|
|
317
|
+
import { verifyWebhook, WebhookVerificationError, type WebhookEvent } from '@chatwise/node';
|
|
318
|
+
|
|
319
|
+
const app = new Hono();
|
|
320
|
+
|
|
321
|
+
// Anyone can send a request, so limit what is read. Chatwise sends up to 256 KB. The connection is closed,
|
|
322
|
+
// so that what wasn't read can't get in the way of another request.
|
|
323
|
+
const limit = bodyLimit({ maxSize: 300 * 1024, onError: (c) => c.body(null, 413, { Connection: 'close' }) });
|
|
324
|
+
|
|
325
|
+
app.post('/webhooks/chatwise', limit, async (c) => {
|
|
326
|
+
let event: WebhookEvent;
|
|
327
|
+
try {
|
|
328
|
+
// text(), not json(): the signature is of the body as it was received.
|
|
329
|
+
event = verifyWebhook({ payload: await c.req.text(), headers: c.req.raw.headers, secret: process.env.CHATWISE_WEBHOOK_SECRET });
|
|
330
|
+
} catch (error) {
|
|
331
|
+
if (!(error instanceof WebhookVerificationError)) throw error; // A 500, so Chatwise tries again.
|
|
332
|
+
console.error(error.message); // After a 400 it doesn't, so watch for these.
|
|
333
|
+
return c.text(error.code, 400);
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
// Answer within 10 seconds. Put longer work in a queue.
|
|
337
|
+
if (event.type === 'message.received') {
|
|
338
|
+
console.log(`New message in conversation ${event.data.message.conversationId}`);
|
|
339
|
+
}
|
|
340
|
+
return c.body(null, 204);
|
|
341
|
+
});
|
|
342
|
+
|
|
343
|
+
serve({ fetch: app.fetch, port: 3000 });
|
|
344
|
+
```
|
|
345
|
+
|
|
346
|
+
`verifyWebhook` checks the signature in constant time and that the request is at most five minutes old (`toleranceSeconds` changes that). It throws:
|
|
347
|
+
|
|
348
|
+
- a `WebhookVerificationError` if the request isn't a valid webhook. Answer 400. Its `code` is `missing_header`, `malformed_header`, `timestamp_too_old`, `timestamp_too_new`, `signature_mismatch` or `invalid_payload`;
|
|
349
|
+
- another `ChatwiseError` if your own code has to change: no secret, or a body that was already parsed. Let it become a 500, and Chatwise tries again once you fixed it.
|
|
350
|
+
|
|
351
|
+
**A delivery you answer with a 400 is not sent again.** Chatwise retries after no answer, a 408, 425, 429 or 5xx. Anything else that isn't a 2xx, a 400, 401 or 413 too, fails the delivery at once. So a wrong secret, or a clock that is off by more than five minutes, loses deliveries until you notice: log these errors, and watch `health` of the endpoint. Once it is fixed, send the failed deliveries of the last 30 days again, as [redeliver-failed.ts](https://github.com/vectorscalelabs/chatwise-node/blob/main/examples/redeliver-failed.ts) does.
|
|
352
|
+
|
|
353
|
+
**The same event can arrive more than once**, with the same `event.id`. Remember the ids you handled.
|
|
354
|
+
|
|
355
|
+
### Events
|
|
356
|
+
|
|
357
|
+
`event.type` tells events apart, and TypeScript then knows their `data`:
|
|
358
|
+
|
|
359
|
+
```ts
|
|
360
|
+
import type { WebhookEvent } from '@chatwise/node';
|
|
361
|
+
|
|
362
|
+
export function handle(event: WebhookEvent): string {
|
|
363
|
+
switch (event.type) {
|
|
364
|
+
case 'message.received': {
|
|
365
|
+
const { message, conversation } = event.data;
|
|
366
|
+
return `${conversation.participant.name ?? 'Someone'} on ${message.channel}: ${message.text ?? message.type}`;
|
|
367
|
+
}
|
|
368
|
+
case 'message.failed': {
|
|
369
|
+
const { message, error } = event.data;
|
|
370
|
+
return `${message.id} wasn't delivered: ${error?.title ?? error?.code ?? 'no reason given'}`;
|
|
371
|
+
}
|
|
372
|
+
case 'comment.received': {
|
|
373
|
+
const { comment, post } = event.data;
|
|
374
|
+
return `${comment.author.username ?? 'Someone'} commented on ${post.id}: ${comment.text}`;
|
|
375
|
+
}
|
|
376
|
+
case 'webhook.test':
|
|
377
|
+
return event.data.message;
|
|
378
|
+
default:
|
|
379
|
+
// Always have a default: Chatwise adds events, and they reach you before you update this package.
|
|
380
|
+
return `Ignored ${event.type}`;
|
|
381
|
+
}
|
|
382
|
+
}
|
|
383
|
+
|
|
384
|
+
console.log(handle({
|
|
385
|
+
id: 'evt_01JE2Z3QK4T8M6N2R5S7V9W1X3',
|
|
386
|
+
type: 'webhook.test',
|
|
387
|
+
timestamp: '2026-11-30T10:00:00.000Z',
|
|
388
|
+
apiVersion: '2026-12-01',
|
|
389
|
+
workspaceId: '42',
|
|
390
|
+
data: { endpointId: 'we_01JE2Z3K8Q9V7W5X4Y3Z2A1B0C', message: 'This is a test event from Chatwise.' },
|
|
391
|
+
}));
|
|
392
|
+
```
|
|
393
|
+
|
|
394
|
+
| Event | When it is sent | `data` |
|
|
395
|
+
| --- | --- | --- |
|
|
396
|
+
| `message.received` | A customer sent a message, on any channel. | `message`, `conversation`, `account` |
|
|
397
|
+
| `message.sent` | The workspace sent a message, and the channel accepted it. | `message`, `conversation`, `account` |
|
|
398
|
+
| `message.delivered` | The channel says that a message from the workspace was delivered. | `message`, `conversation`, `account` |
|
|
399
|
+
| `message.read` | The channel says that the customer read it. | `message`, `conversation`, `account` |
|
|
400
|
+
| `message.failed` | The channel says that it couldn't be delivered. | `message`, `conversation`, `account`, `error` |
|
|
401
|
+
| `comment.received` | Someone commented on a post of a connected Instagram account. | `comment`, `post`, `account` |
|
|
402
|
+
| `webhook.test` | You sent a test event. | `endpointId`, `message` |
|
|
403
|
+
|
|
404
|
+
Each [event's page](https://chatwise.so/docs/webhooks/events) says when exactly it is sent, and when not. **Don't rely on the order.** A message's events can arrive in any order, and some never do: `message.read` can come before `message.delivered`, or not at all, when the customer turned read receipts off.
|
|
405
|
+
|
|
406
|
+
### Test, rotate and redeliver
|
|
407
|
+
|
|
408
|
+
```ts
|
|
409
|
+
import { Chatwise } from '@chatwise/node';
|
|
410
|
+
|
|
411
|
+
const chatwise = new Chatwise();
|
|
412
|
+
const endpointId = 'we_01JE2Z3K8Q9V7W5X4Y3Z2A1B0C';
|
|
413
|
+
|
|
414
|
+
// Sends a webhook.test event now, and says what your endpoint answered.
|
|
415
|
+
const { delivered, statusCode, error } = await chatwise.webhookEndpoints.test(endpointId);
|
|
416
|
+
console.log(delivered, statusCode, error);
|
|
417
|
+
|
|
418
|
+
// For 24 hours deliveries are signed with both secrets, so you can switch without missing any.
|
|
419
|
+
const { signingSecret, previousSecretExpiresAt } = await chatwise.webhookEndpoints.rotateSecret(endpointId);
|
|
420
|
+
console.log(signingSecret.length, previousSecretExpiresAt);
|
|
421
|
+
|
|
422
|
+
// What was sent in the last 30 days, and sending it again.
|
|
423
|
+
for await (const delivery of chatwise.webhookDeliveries.list(endpointId, { status: 'FAILED' })) {
|
|
424
|
+
const { attemptLog } = await chatwise.webhookDeliveries.get(delivery.id);
|
|
425
|
+
console.log(delivery.eventType, delivery.lastError, attemptLog.length);
|
|
426
|
+
await chatwise.webhookDeliveries.redeliver(delivery.id);
|
|
427
|
+
}
|
|
428
|
+
|
|
429
|
+
// How its deliveries are going. Chatwise leaves an endpoint that is unavailable alone for a while: until
|
|
430
|
+
// backoffUntil, which is null when it isn't waiting. A test that succeeds ends the wait.
|
|
431
|
+
const { status, health } = await chatwise.webhookEndpoints.get(endpointId);
|
|
432
|
+
console.log(status, health.consecutiveFailures, health.lastSuccessAt, health.backoffUntil);
|
|
433
|
+
|
|
434
|
+
// Pause it, and delete it.
|
|
435
|
+
await chatwise.webhookEndpoints.update(endpointId, { status: 'PAUSED' });
|
|
436
|
+
await chatwise.webhookEndpoints.delete(endpointId);
|
|
437
|
+
```
|
|
438
|
+
|
|
439
|
+
## Errors
|
|
440
|
+
|
|
441
|
+
Everything the SDK throws is a `ChatwiseError`. An answer that isn't a success is an `APIError`, with a class for each status:
|
|
442
|
+
|
|
443
|
+
```ts
|
|
444
|
+
import { APIError, BadRequestError, Chatwise, ConflictError, NotFoundError, RateLimitError } from '@chatwise/node';
|
|
445
|
+
|
|
446
|
+
const chatwise = new Chatwise();
|
|
447
|
+
|
|
448
|
+
try {
|
|
449
|
+
await chatwise.conversations.get('404');
|
|
450
|
+
} catch (error) {
|
|
451
|
+
if (error instanceof NotFoundError) {
|
|
452
|
+
console.log('There is no such conversation.');
|
|
453
|
+
} else if (error instanceof BadRequestError) {
|
|
454
|
+
for (const { path, message } of error.fieldErrors) console.log(path, message);
|
|
455
|
+
} else if (error instanceof ConflictError) {
|
|
456
|
+
console.log(error.code); // Such as TEMPLATE_EXISTS.
|
|
457
|
+
} else if (error instanceof RateLimitError) {
|
|
458
|
+
console.log(`Wait ${error.retryAfterMs} ms.`);
|
|
459
|
+
} else if (error instanceof APIError) {
|
|
460
|
+
console.log(error.status, error.message, error.errorId); // Quote errorId to support.
|
|
461
|
+
} else {
|
|
462
|
+
throw error;
|
|
463
|
+
}
|
|
464
|
+
}
|
|
465
|
+
```
|
|
466
|
+
|
|
467
|
+
| Class | When |
|
|
468
|
+
| --- | --- |
|
|
469
|
+
| `BadRequestError` | 400: something in the request is invalid. `fieldErrors` says what. |
|
|
470
|
+
| `AuthenticationError` | 401: the key is missing, invalid, expired or revoked. With the message `Invalid API key`, Chatwise couldn't check it: try again. |
|
|
471
|
+
| `PaymentRequiredError` | 402: sending is paused for the workspace, or its subscription needs attention. |
|
|
472
|
+
| `PermissionDeniedError` | 403: the key lacks a scope, WhatsApp has to be reconnected, or the key's creator may not send replies any more. |
|
|
473
|
+
| `NotFoundError` | 404: it doesn't exist in the key's workspace. |
|
|
474
|
+
| `ConflictError` | 409: it conflicts with an earlier request, or with how things are now. `code` says how, such as `REPLY_WINDOW_CLOSED` or `TEMPLATE_EXISTS`. |
|
|
475
|
+
| `PayloadTooLargeError` | 413: the request is larger than 100 KB. |
|
|
476
|
+
| `UnprocessableEntityError` | 422: the channel refused a reply, or its file can't be downloaded or sent. `code` says which. |
|
|
477
|
+
| `RateLimitError` | 429: more than 120 requests in a minute with this key, the default limit, or too many [replies or files](https://chatwise.so/docs/rate-limits#replies). |
|
|
478
|
+
| `ServerError` | 5xx: something failed or is busy in Chatwise or at the channel, or WhatsApp refused a template. With the code `SEND_OUTCOME_UNKNOWN`, a reply [may have been sent](#reply-to-a-customer). |
|
|
479
|
+
| `ConnectionError` | There was no complete answer. `RequestTimeoutError` is one, when it took too long. |
|
|
480
|
+
| `RequestAbortedError` | Your `signal` aborted the request. |
|
|
481
|
+
| `WebhookVerificationError` | `verifyWebhook` refused the request. |
|
|
482
|
+
|
|
483
|
+
An answer far larger than the API's isn't read to its end: an error then has an empty `body`, and a success is a `ConnectionError`.
|
|
484
|
+
|
|
485
|
+
Every `APIError` has `status`, `message`, `code`, `fieldErrors`, `errorId`, `retryAfterMs`, `method`, `path` and `body`. No error contains your API key.
|
|
486
|
+
|
|
487
|
+
## Retries and timeouts
|
|
488
|
+
|
|
489
|
+
A failed call is retried up to twice, if that is safe. A 401 never is, also for a reply:
|
|
490
|
+
|
|
491
|
+
| | After a 429 | After a 5xx, a network error or a timeout |
|
|
492
|
+
| --- | --- | --- |
|
|
493
|
+
| Reads | Retried | Retried |
|
|
494
|
+
| Replies | Retried | Retried, with the same `idempotencyKey`: the route recognizes a repeat. So is a 409 with the code `SEND_IN_PROGRESS`. Not if the code is `SEND_OUTCOME_UNKNOWN` |
|
|
495
|
+
| Creating a template | Retried | Retried: the route recognizes a repeat. Not if the answer has a `code`, which says what to do. `TEMPLATE_SUBMISSION_IN_PROGRESS` means to call again later |
|
|
496
|
+
| Sending a template, and every other change | Retried: it wasn't carried out | **Not retried**: it may have been carried out |
|
|
497
|
+
|
|
498
|
+
It waits longer each time, and as long as `Retry-After` says: 60 seconds when you are over the rate limit. A wait of more than 90 seconds isn't waited out: the call fails with the error. Where a call can't take that long, pass `maxRetries: 0`. **After sending a template fails with anything but an `APIError` with a 4xx status, it may have been sent,** even if the conversation doesn't show it. Check before you send again.
|
|
499
|
+
|
|
500
|
+
**A reply is different,** because it can be repeated: [call it again](#reply-to-a-customer), with the same key.
|
|
501
|
+
|
|
502
|
+
**A file isn't always ready at once.** `MEDIA_PROCESSING` and `MEDIA_BUSY` say to repeat the request until it is. `messages.reply` does, as `Retry-After` says, as long as the next request begins within `mediaTimeoutMs` of the call. That is ten minutes by default, and 0 with `maxRetries: 0`, which makes one request. These repeats don't count as retries, and the count of retries starts again after each. Leave `timeoutMs` at a minute for a file: a request waits up to 25 seconds for it, and then sends it.
|
|
503
|
+
|
|
504
|
+
**A video on Messenger can take longer to send than the retries last.** Facebook fetches it, and if that takes [more than 30 seconds](https://chatwise.so/docs/replies#when-messenger-takes-long), the request answers `SEND_IN_PROGRESS` and Chatwise goes on sending it. The call throws that when its retries are used up. Make it again within a minute, with the same `idempotencyKey`: if Facebook refused the video, only the repeats of the next minute are told, and a later one sends it again. Or pass a higher `maxRetries`, up to 10.
|
|
505
|
+
|
|
506
|
+
Each attempt may take 60 seconds. Change that for every call, or for one, or pass a signal:
|
|
507
|
+
|
|
508
|
+
```ts
|
|
509
|
+
import { Chatwise } from '@chatwise/node';
|
|
510
|
+
|
|
511
|
+
const chatwise = new Chatwise({ timeoutMs: 20_000, maxRetries: 4 });
|
|
512
|
+
|
|
513
|
+
const controller = new AbortController();
|
|
514
|
+
process.once('SIGTERM', () => controller.abort());
|
|
515
|
+
|
|
516
|
+
const page = await chatwise.messages.list({ limit: 100 }, {
|
|
517
|
+
signal: controller.signal, // Also ends the waits between attempts.
|
|
518
|
+
timeoutMs: 5000,
|
|
519
|
+
maxRetries: 0,
|
|
520
|
+
});
|
|
521
|
+
console.log(page.data.length);
|
|
522
|
+
```
|
|
523
|
+
|
|
524
|
+
## Methods and scopes
|
|
525
|
+
|
|
526
|
+
A key can do only what its scopes allow, and no scope includes another.
|
|
527
|
+
|
|
528
|
+
| Method | Scopes |
|
|
529
|
+
| --- | --- |
|
|
530
|
+
| `conversations.list(params?)` | `conversations:read` |
|
|
531
|
+
| `conversations.get(conversationId)` | `conversations:read` |
|
|
532
|
+
| `messages.list(params?)` | `messages:read` |
|
|
533
|
+
| `messages.listInConversation(conversationId, params?)` | `messages:read` |
|
|
534
|
+
| `messages.get(conversationId, messageId)` | `messages:read` |
|
|
535
|
+
| `messages.listFiles(conversationId, messageId)` | `messages:read` |
|
|
536
|
+
| `messages.reply(conversationId, params, { idempotencyKey })` | `messages:reply` |
|
|
537
|
+
| `messages.send(params)` | `messages:send` |
|
|
538
|
+
| `whatsappTemplates.list(params?)` | `templates:read` |
|
|
539
|
+
| `whatsappTemplates.get(templateId)` | `templates:read` |
|
|
540
|
+
| `whatsappTemplates.create(params, { idempotencyKey }?)` | `templates:write` |
|
|
541
|
+
| `whatsappTemplates.send(params)` | `messages:send` |
|
|
542
|
+
| `webhookEndpoints.list()` | `webhooks:read` |
|
|
543
|
+
| `webhookEndpoints.create(params)` | `webhooks:write`, and `messages:read` to subscribe to `message.*` events |
|
|
544
|
+
| `webhookEndpoints.get(endpointId)` | `webhooks:read` |
|
|
545
|
+
| `webhookEndpoints.update(endpointId, params)` | `webhooks:write`, and `messages:read` if it has `message.*` events before or after the change |
|
|
546
|
+
| `webhookEndpoints.delete(endpointId)` | `webhooks:write` |
|
|
547
|
+
| `webhookEndpoints.test(endpointId)` | `webhooks:write` |
|
|
548
|
+
| `webhookEndpoints.rotateSecret(endpointId)` | `webhooks:write`, and `messages:read` if it has `message.*` events |
|
|
549
|
+
| `webhookDeliveries.list(endpointId, params?)` | `webhooks:read` |
|
|
550
|
+
| `webhookDeliveries.get(deliveryId)` | `webhooks:read`, and `messages:read` if it is for a `message.*` event |
|
|
551
|
+
| `webhookDeliveries.redeliver(deliveryId)` | `webhooks:write`, and `messages:read` if it is for a `message.*` event |
|
|
552
|
+
| `webhookEventTypes.list()` | `webhooks:read` |
|
|
553
|
+
|
|
554
|
+
Every method takes `{ signal, timeoutMs, maxRetries }` as its last argument. Lists with pages return a page when awaited, and their items when iterated over. `webhookEndpoints.list()` and `webhookEventTypes.list()` are short, and return an array.
|
|
555
|
+
|
|
556
|
+
## Options
|
|
557
|
+
|
|
558
|
+
```ts
|
|
559
|
+
import { Chatwise } from '@chatwise/node';
|
|
560
|
+
|
|
561
|
+
const chatwise = new Chatwise({
|
|
562
|
+
apiKey: process.env.CHATWISE_API_KEY, // The default.
|
|
563
|
+
baseUrl: 'https://api.chatwise.so', // The default.
|
|
564
|
+
timeoutMs: 60_000, // The default, for each attempt.
|
|
565
|
+
maxRetries: 2, // The default.
|
|
566
|
+
// Your own fetch, for a proxy or for tests. It receives the key, in the Authorization header.
|
|
567
|
+
fetch: (url, init) => fetch(url, init),
|
|
568
|
+
});
|
|
569
|
+
|
|
570
|
+
console.log(await chatwise.webhookEventTypes.list());
|
|
571
|
+
```
|
|
572
|
+
|
|
573
|
+
The key isn't on the client, so logging a client doesn't show it. Redirects aren't followed, and `baseUrl` must be `https` unless it is this machine, so the key isn't sent anywhere else.
|
|
574
|
+
|
|
575
|
+
## TypeScript and CommonJS
|
|
576
|
+
|
|
577
|
+
The types need TypeScript 5.0 or later, and neither the DOM's nor Node's types. In CommonJS:
|
|
578
|
+
|
|
579
|
+
```js
|
|
580
|
+
const { Chatwise } = require('@chatwise/node');
|
|
581
|
+
|
|
582
|
+
const chatwise = new Chatwise();
|
|
583
|
+
chatwise.webhookEndpoints.list().then((endpoints) => console.log(endpoints.length));
|
|
584
|
+
```
|
|
585
|
+
|
|
586
|
+
Values and fields the API adds later reach you as they are, and the types allow for them: a channel or a status you don't know is a string. New events and fields can arrive in any version of the API, so ignore what you don't know.
|
|
587
|
+
|
|
588
|
+
## Help
|
|
589
|
+
|
|
590
|
+
- [API documentation](https://chatwise.so/docs), [webhooks](https://chatwise.so/docs/webhooks) and the [changelog](https://github.com/vectorscalelabs/chatwise-node/blob/main/CHANGELOG.md).
|
|
591
|
+
- [Report a problem](https://github.com/vectorscalelabs/chatwise-node/issues) with this package. Leave out API keys, signing secrets and customers' messages. To report a security problem, see [SECURITY.md](https://github.com/vectorscalelabs/chatwise-node/blob/main/SECURITY.md).
|
|
592
|
+
|
|
593
|
+
Copyright 2026 VectorScale Labs Private Limited. [Apache License 2.0](https://github.com/vectorscalelabs/chatwise-node/blob/main/LICENSE).
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import { type ChatwiseOptions } from './core/http.js';
|
|
2
|
+
import { Conversations } from './resources/conversations.js';
|
|
3
|
+
import { Messages } from './resources/messages.js';
|
|
4
|
+
import { WebhookDeliveries } from './resources/webhook-deliveries.js';
|
|
5
|
+
import { WebhookEndpoints } from './resources/webhook-endpoints.js';
|
|
6
|
+
import { WebhookEventTypes } from './resources/webhook-event-types.js';
|
|
7
|
+
import { WhatsappTemplates } from './resources/whatsapp-templates.js';
|
|
8
|
+
/**
|
|
9
|
+
* A client of the Chatwise API, for one workspace: the API key's. Use it on a server only, because
|
|
10
|
+
* anyone who has the key can use it.
|
|
11
|
+
*/
|
|
12
|
+
export declare class Chatwise {
|
|
13
|
+
readonly conversations: Conversations;
|
|
14
|
+
readonly messages: Messages;
|
|
15
|
+
readonly whatsappTemplates: WhatsappTemplates;
|
|
16
|
+
readonly webhookEndpoints: WebhookEndpoints;
|
|
17
|
+
readonly webhookDeliveries: WebhookDeliveries;
|
|
18
|
+
readonly webhookEventTypes: WebhookEventTypes;
|
|
19
|
+
constructor(options?: ChatwiseOptions);
|
|
20
|
+
}
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.Chatwise = void 0;
|
|
4
|
+
const http_js_1 = require("./core/http.js");
|
|
5
|
+
const conversations_js_1 = require("./resources/conversations.js");
|
|
6
|
+
const messages_js_1 = require("./resources/messages.js");
|
|
7
|
+
const webhook_deliveries_js_1 = require("./resources/webhook-deliveries.js");
|
|
8
|
+
const webhook_endpoints_js_1 = require("./resources/webhook-endpoints.js");
|
|
9
|
+
const webhook_event_types_js_1 = require("./resources/webhook-event-types.js");
|
|
10
|
+
const whatsapp_templates_js_1 = require("./resources/whatsapp-templates.js");
|
|
11
|
+
/**
|
|
12
|
+
* A client of the Chatwise API, for one workspace: the API key's. Use it on a server only, because
|
|
13
|
+
* anyone who has the key can use it.
|
|
14
|
+
*/
|
|
15
|
+
class Chatwise {
|
|
16
|
+
conversations;
|
|
17
|
+
messages;
|
|
18
|
+
whatsappTemplates;
|
|
19
|
+
webhookEndpoints;
|
|
20
|
+
webhookDeliveries;
|
|
21
|
+
webhookEventTypes;
|
|
22
|
+
constructor(options = {}) {
|
|
23
|
+
const request = (0, http_js_1.createRequester)(options);
|
|
24
|
+
this.conversations = new conversations_js_1.Conversations(request);
|
|
25
|
+
this.messages = new messages_js_1.Messages(request);
|
|
26
|
+
this.whatsappTemplates = new whatsapp_templates_js_1.WhatsappTemplates(request);
|
|
27
|
+
this.webhookEndpoints = new webhook_endpoints_js_1.WebhookEndpoints(request);
|
|
28
|
+
this.webhookDeliveries = new webhook_deliveries_js_1.WebhookDeliveries(request);
|
|
29
|
+
this.webhookEventTypes = new webhook_event_types_js_1.WebhookEventTypes(request);
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
exports.Chatwise = Chatwise;
|