← Back to Plugins
Integration

Plugin Http Inbound

zayme429 By zayme429 👁 760 views ▲ 0 votes

HTTP REST API plugin for OpenClaw - enables any application to communicate with OpenClaw AI through standard HTTP requests

GitHub

Install

npm install

#

Configuration Example

{
  "channels": {
    "http-inbound": {
      "enabled": true,
      "port": 3000,
      "host": "0.0.0.0",
      "apiKeys": {
        "your-secret-api-key-here": {
          "name": "My App",
          "created": "2026-03-10"
        }
      }
    }
  }
}

README

# OpenClaw HTTP Inbound Channel Plugin

一个为 OpenClaw 提供 HTTP REST API 接入能力的插件,允许任何应用通过标准 HTTP 请求与 OpenClaw AI 进行对话。

![License](https://img.shields.io/badge/license-MIT-blue)
![OpenClaw](https://img.shields.io/badge/OpenClaw-Plugin-green)
![Node](https://img.shields.io/badge/node-%3E%3D16.0.0-brightgreen)

---

## 🎯 功能特性

- ✅ **HTTP REST API** - 标准的 POST 请求接口
- ✅ **API Key 认证** - 支持多个 API Key,安全可靠
- ✅ **会话管理** - 自动维护对话上下文
- ✅ **健康检查** - 内置健康检查端点
- ✅ **跨平台支持** - 支持任何能发送 HTTP 请求的客户端
- ✅ **易于集成** - 简单的 JSON 请求/响应格式

---

## 📋 前置要求

- OpenClaw 已安装并运行
- Node.js >= 16.0.0
- npm 或 yarn

---

## 🚀 快速开始

### 步骤 1: 安装插件

```bash
# 克隆仓库
git clone https://github.com/zayme429/openclaw-plugin-http-inbound.git
cd openclaw-plugin-http-inbound

# 安装依赖
npm install

# 构建插件
npm run build

# 安装到 OpenClaw
openclaw plugins install .
```

### 步骤 2: 配置 API Key

编辑 OpenClaw 配置文件:

```bash
nano ~/.openclaw/openclaw.json
```


添加以下配置:

```json
{
  "channels": {
    "http-inbound": {
      "enabled": true,
      "port": 3000,
      "host": "0.0.0.0",
      "apiKeys": {
        "your-secret-api-key-here": {
          "name": "My App",
          "created": "2026-03-10"
        }
      }
    }
  }
}
```

### 步骤 3: 重启 OpenClaw

```bash
openclaw restart
```

### 步骤 4: 测试连接

```bash
curl -X POST http://localhost:3000/api/chat \
  -H "Authorization: Bearer your-secret-api-key-here" \
  -H "Content-Type: application/json" \
  -d '{
    "message": "Hello, OpenClaw!",
    "userId": "test-user"
  }'
```

预期响应:

```json
{
  "ok": true,
  "reply": "Hello! How can I help you today?",
  "sessionId": "http-inbound:test-user"
}
```

---

## 📡 API 文档

### POST /api/chat

发送消息到 OpenClaw AI。

**请求头**:
```
Authorization: Bearer YOUR_API_KEY
Content-Type: application/json
```

**请求体**:
```json
{
  "message": "你好",
  "userId": "user-123",
  "sessionId": "optional-session-id"
}
```


**参数说明**:
- `message` (必需): 用户消息内容
- `userId` (必需): 用户唯一标识符
- `sessionId` (可选): 会话 ID,用于维护对话上下文。如果不提供,将自动生成

**响应**:
```json
{
  "ok": true,
  "reply": "你好!有什么我可以帮助你的吗?",
  "sessionId": "http-inbound:user-123"
}
```

**错误响应**:
```json
{
  "ok": false,
  "error": "Invalid API key"
}
```

### GET /health

健康检查端点。

**响应**:
```json
{
  "status": "ok",
  "channel": "http-inbound",
  "timestamp": 1234567890
}
```

---

## 🔧 使用示例

### cURL

```bash
curl -X POST http://your-server:3000/api/chat \
  -H "Authorization: Bearer your-api-key" \
  -H "Content-Type: application/json" \
  -d '{
    "message": "What is the weather today?",
    "userId": "user-001"
  }'
```

### Python

```python
import requests

url = "http://your-server:3000/api/chat"
headers = {
    "Authorization": "Bearer your-api-key",
    "Content-Type": "application/json"
}
data = {
    "message": "Hello!",
    "userId": "user-001"
}

response = requests.post(url, json=data, headers=headers)
result = response.json()

print(f"AI Reply: {result['reply']}")
print(f"Session ID: {result['sessionId']}")
```


### JavaScript/Node.js

```javascript
const axios = require('axios');

async function chat(message, userId) {
  const response = await axios.post(
    'http://your-server:3000/api/chat',
    {
      message: message,
      userId: userId
    },
    {
      headers: {
        'Authorization': 'Bearer your-api-key',
        'Content-Type': 'application/json'
      }
    }
  );

  return response.data;
}

chat('Hello!', 'user-001').then(result => {
  console.log('AI Reply:', result.reply);
  console.log('Session ID:', result.sessionId);
});
```

### Swift (iOS)

```swift
func sendMessage(message: String, userId: String) async throws -> [String: Any] {
    let url = URL(string: "http://your-server:3000/api/chat")!
    var request = URLRequest(url: url)
    request.httpMethod = "POST"
    request.setValue("Bearer your-api-key", forHTTPHeaderField: "Authorization")
    request.setValue("application/json", forHTTPHeaderField: "Content-Type")

    let body: [String: Any] = [
        "message": message,
        "userId": userId
    ]
    request.httpBody = try JSONSerialization.data(withJSONObject: body)

    let (data, _) = try await URLSession.shared.data(for: request)
    let result = try JSONSerialization.jsonObject(with: data) as! [String: Any]

    return result
}
```

### Java

```java
import okhttp3.*;
import org.json.JSONObject;

public class OpenClawClient {
    private static final String URL = "http://your-server:3000/api/chat";
    private static final String API_KEY = "your-api-key";

    public static JSONObject sendMessage(String message, String userId) throws Exception {
        OkHttpClient client = new OkHttpClient();

        JSONObject json = new JSONObject();
        json.put("message", message);
        json.put("userId", userId);

        RequestBody body = RequestBody.create(
            json.toString(),
            MediaType.parse("application/json")
        );

        Request request = new Request.Builder()
            .url(URL)
            .addHeader("Authorization", "Bearer " + API_KEY)
            .post(body)
            .build();

        Response response = client.newCall(request).execute();
        return new JSONObject(response.body().string());
    }
}
```


---

## 🧪 本地测试

### 使用 Mock Server

如果你还没有 OpenClaw 服务器,可以使用 Mock Server 进行本地测试:

```bash
# 启动 Mock Server
python3 mock-server.py
```

Mock Server 会在 `http://localhost:3000` 启动,使用预设的 API Key: `test-api-key-12345`

测试:

```bash
curl -X POST http://localhost:3000/api/chat \
  -H "Authorization: Bearer test-api-key-12345" \
  -H "Content-Type: application/json" \
  -d '{
    "message": "Hello",
    "userId": "test-user"
  }'
```

---

## 🔐 安全建议

### 1. 保护 API Key

❌ **不要**在客户端代码中硬编码 API Key:

```javascript
// 错误示例 - API Key 暴露在客户端
const apiKey = "your-secret-key"; // 不要这样做!
```

✅ **应该**通过后端服务器转发请求:

```
客户端 → 你的后端服务器 → OpenClaw 服务器
```

### 2. 使用 HTTPS

生产环境建议使用反向代理(如 Nginx)配置 HTTPS:

```nginx
server {
    listen 443 ssl;
    server_name your-domain.com;

    ssl_certificate /path/to/cert.pem;
    ssl_certificate_key /path/to/key.pem;

    location /api/chat {
        proxy_pass http://localhost:3000;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
    }
}
```

### 3. 限制访问

使用防火墙限制只允许特定 IP 访问:

```bash
# 只允许特定 IP 访问 3000 端口
sudo ufw allow from YOUR_BACKEND_IP to any port 3000
```

### 4. 定期轮换 API Key

建议定期更换 API Key,并撤销旧的 Key。


---

## 🏗️ 架构建议

### 推荐架构

```
┌─────────────┐      HTTPS      ┌──────────────┐      HTTP       ┌─────────────┐
│   客户端     │ ──────────────> │  你的后端     │ ─────────────> │  OpenClaw   │
│ (iOS/Web/   │                 │  服务器       │                │  服务器     │
│  Android)   │ <────────────── │ (添加API Key) │ <───────────── │ (本插件)    │
└─────────────┘                 └──────────────┘                └─────────────┘
```

**优点**:
- ✅ API Key 不暴露给客户端
- ✅ 可以添加额外的认证和授权
- ✅ 可以记录和监控请求
- ✅ 可以实现请求限流

### 不推荐的架构

```
┌─────────────┐      HTTP       ┌─────────────┐
│   客户端     │ ─────────────> │  OpenClaw   │
│ (iOS/Web/   │                │  服务器     │
│  Android)   │ <───────────── │ (本插件)    │
└─────────────┘                └─────────────┘
```

**缺点**:
- ❌ API Key 暴露在客户端代码中
- ❌ 任何人都可以反编译获取 API Key
- ❌ 无法控制访问权限

---

## 📚 完整文档

- [安装指南](INSTALL.md) - 详细的安装步骤
- [部署指南](DEPLOY.md) - 生产环境部署建议
- [Mock Server 使用](MOCK-SERVER.md) - 本地测试指南
- [安全审计](SECURITY_AUDIT.md) - 安全最佳实践
- [项目总结](SUMMARY.md) - 技术细节和设计决策

---

## 🔄 会话管理

### 自动会话管理

如果不提供 `sessionId`,插件会自动生成:

```bash
# 第一次请求
curl -X POST http://localhost:3000/api/chat \
  -H "Authorization: Bearer your-api-key" \
  -H "Content-Type: application/json" \
  -d '{
    "message": "我叫张三",
    "userId": "user-001"
  }'

# 响应包含 sessionId
{
  "ok": true,
  "reply": "你好,张三!",
  "sessionId": "http-inbound:user-001"
}
```

### 手动会话管理

使用返回的 `sessionId` 继续对话:

```bash
# 第二次请求 - 使用相同的 sessionId
curl -X POST http://localhost:3000/api/chat \
  -H "Authorization: Bearer your-api-key" \
  -H "Content-Type: application/json" \
  -d '{
    "message": "我叫什么名字?",
    "userId": "user-001",
    "sessionId": "http-inbound:user-001"
  }'

# AI 会记住之前的对话
{
  "ok": true,
  "reply": "你叫张三。",
  "sessionId": "http-inbound:user-001"
}
```


---

## 🐛 故障排查

### 问题 1: 连接被拒绝

**症状**: `Connection refused` 或 `ECONNREFUSED`

**解决方案**:
1. 检查 OpenClaw 是否运行: `openclaw status`
2. 检查端口是否正确: `netstat -tulpn | grep 3000`
3. 检查防火墙设置: `sudo ufw status`

### 问题 2: 401 Unauthorized

**症状**: `{"ok": false, "error": "Invalid API key"}`

**解决方案**:
1. 检查 API Key 是否正确
2. 检查 `~/.openclaw/openclaw.json` 配置
3. 确认 OpenClaw 已重启: `openclaw restart`

### 问题 3: 超时

**症状**: 请求超时,没有响应

**解决方案**:
1. 检查 OpenClaw 日志: `openclaw logs`
2. 增加客户端超时时间(建议 30 秒以上)
3. 检查服务器负载

### 问题 4: 插件未加载

**症状**: 健康检查失败,端口未监听

**解决方案**:
```bash
# 检查插件是否已安装
openclaw plugins list

# 重新安装插件
cd openclaw-plugin-http-inbound
npm run build
openclaw plugins install .

# 重启 OpenClaw
openclaw restart
```

---

## 🤝 贡献

欢迎提交 Issue 和 Pull Request!

---

## 📄 License

MIT License

---

## 🙏 致谢

本插件为 [AgentDigitalTwin](https://github.com/zayme429/agent-digital-twin) 项目的一部分,现独立发布以便其他项目使用。

---

## 📞 支持

- 提交 Issue: https://github.com/zayme429/openclaw-plugin-http-inbound/issues
- 参考项目: https://github.com/zayme429/agent-digital-twin

integration

Comments

Sign in to leave a comment

Loading comments...