> ## Documentation Index
> Fetch the complete documentation index at: https://gowa-docs.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# 正在接收消息

> 使用 webhooks 处理收到的消息，或者读取存储在 GOWA 的聊天存储中的聊天和消息。

GOWA提供了两种接收信息的方式：

| 方法 | 使用它 |
| - | - |
| **Webhooks** (推荐) | 实时响应事件，GOWA将每个事件推到您的 URL。 |
| **聊天存储 API** | 正在读取历史记录，在下限后赶上，正在生成收件箱视图。 |

## Webhooks

使用 webhook URL 和 secret启动 GOWA：

```bash theme={null}
./whatsapp rest --basic-auth=admin:changeme \
  --webhook=https://example.com/wa-hook \
  --webhook-secret=change-me \
  --webhook-events=message,message.ack
```

收到的文本信息为：

```json theme={null}
{
  "event": "message",
  "device_id": "628123456789@s.whatsapp.net",
  "session_id": "my-device",
  "payload": {
    "id": "3EB0C127D7BACC83D6A1",
    "chat_id": "628987654321@s.whatsapp.net",
    "from": "628987654321@s.whatsapp.net",
    "from_name": "John Doe",
    "sender_display_name": "John Doe",
    "timestamp": "2026-10-15T10:30:00Z",
    "is_from_me": false,
    "body": "Hello, how are you?"
  }
}
```

在群组中，`chat_id` 是群组 JID（`...@g.us`），`from` 则是发送消息的成员。

### 示例：自动回复机器人

使用相同的设备验证签名，确认并通过 API 答复：

```javascript theme={null}
const express = require("express");
const crypto = require("crypto");

const GOWA = "http://localhost:3000";
const AUTH = "Basic " + Buffer.from("admin:changeme").toString("base64");
const SECRET = "change-me";

const app = express();
app.post("/wa-hook", express.raw({ type: "application/json" }), async (req, res) => {
  const sig = crypto.createHmac("sha256", SECRET).update(req.body).digest("hex");
  const received = req.get("X-Hub-Signature-256") || "";
  const expected = `sha256=${sig}`;
  if (!/^sha256=[0-9a-f]{64}$/.test(received) ||
      received.length !== expected.length ||
      !crypto.timingSafeEqual(Buffer.from(received), Buffer.from(expected))) {
    return res.sendStatus(401);
  }
  const evt = JSON.parse(req.body);
  res.sendStatus(200);
  if (evt.event !== "message" || evt.payload.is_from_me) return;
  if (!evt.session_id) return;
  if (!/^hi\b/i.test(evt.payload.body || "")) return;

  const response = await fetch(`${GOWA}/send/message`, {
    method: "POST",
    headers: {
      Authorization: AUTH,
      "Content-Type": "application/json",
      "X-Device-Id": evt.session_id,          // reply from the slot that received it
    },
    body: JSON.stringify({
      phone: evt.payload.chat_id,
      message: "Hello! How can we help?",
      reply_message_id: evt.payload.id,
    }),
  });
  if (!response.ok) console.error("GOWA reply failed", response.status);
});
app.listen(8080);
```

这个最低限度的例子在发出答复之前就予以确认。 对于生产者来说，在确认之前对已验证的事件进行持久排队，通过设备、 聊天和消息ID进行反复，并且在您的工作人员中重新尝试失败发送。 跳过事件没有 `session_id` 或明确解析正确的设备。

如果要对每条消息发送固定回复，设置 `WHATSAPP_AUTO_REPLY="We'll get back to you soon"` 即可，无需编写代码。

每个事件类型、媒体字段、 重试和每个设备的 URL，请参阅 [Webhooks](https://gowa-docs.mintlify.site/zh/concepts/webhooks.md)。

### 处理新事件形状

专辑头是 `payload.album` 的 `message` 事件，没有文字正文。每个图像或视频都会作为一个单独的媒体事件使用 `payload.album_id`。用该ID来分组媒体，而不是将标题视为缺失的消息。

`newsletter.message` 包含频道计数器更新，不能保证一个新的帖子。 在线和离线联系更新使用 `presence` ，需要 `POST /user/presence/subscribe` ，并要求您的客户端继续可用。群组名称更改使用 `group.info` 。

订阅 `device.logged_out`、`device.temporary_ban` 和 `device.reachout_timelock`，以区分账号限制与普通断开连接。这些事件始终通过 `session_id` 标识设备槽位。有关字段和在线状态配置，请参阅 [Webhook](https://gowa-docs.mintlify.site/zh/concepts/webhooks.md)。

## 聊天存储 API

GOWA 在其本地聊天存储中记录每个位置的聊天和消息。每台设备查询：

```bash theme={null}
# list chats (filters: search, has_media, archived; paging: limit, offset)
curl -u admin:changeme -H "X-Device-Id: my-device" \
  "http://localhost:3000/chats?limit=20"

# messages in one chat (filters: start_time, end_time, media_only, is_from_me, search)
curl -u admin:changeme -H "X-Device-Id: my-device" \
  "http://localhost:3000/chat/628987654321@s.whatsapp.net/messages?limit=50"
```

只能获取 GOWA 已见过的消息（连接期间收到的消息，或由 WhatsApp 历史同步传来的消息）。若要请求手机提供某个聊天中更早的历史消息，请调用 `POST /chat/{chat_jid}/history` 并携带 `{"count": 50}`；消息会异步到达。

投票适合于补丁和收件箱视图。对于机器人和自动化，请使用 web 钩子。

## 正在下载媒体

当自动下载（默认）时，webhook 会在`statics/media/`下提供路径，服务于`http://localhost:3000/statics/media/<file>`。否则需要获取媒体：

```bash theme={null}
curl -u admin:changeme -H "X-Device-Id: my-device" \
  "http://localhost:3000/message/3EB0C127D7BACC83D6A3/download?phone=628987654321@s.whatsapp.net"
```

查看 [传入媒体](https://gowa-docs.mintlify.site/zh/examples/media-handling.md#%E4%BC%A0%E5%85%A5%E5%AA%92%E4%BD%93) 的条件，GOWA 可以恢复过期文件。

## 读取收入

使用 `POST /message/{message_id}/read` 和 `{"phone": "<chat_jid>"}` 将消息标记为已读（蓝色双勾），或设置 `WHATSAPP_AUTO_MARK_READ=true`，自动将所有收到的消息标记为已读。


## Related topics

- [快速开始](https://gowa-docs.mintlify.site/zh/quickstart.md)
- [正在发送消息](https://gowa-docs.mintlify.site/zh/examples/sending-messages.md)
- [Webhooks](https://gowa-docs.mintlify.site/zh/concepts/webhooks.md)
- [设置正在消失的消息计时器](https://gowa-docs.mintlify.site/zh/api-reference/chat/设置正在消失的消息计时器.md)
- [GOWA: WhatsApp REST API](https://gowa-docs.mintlify.site/zh/index.md)


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.