wechat-api-rs 0.1.0

A Rust SDK for WeChat Official Account and Mini Program APIs
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
# 配置指南

本指南详细介绍WeChat SDK的各种配置方式和最佳实践。

## 📋 目录

- [基础配置]#基础配置
- [环境变量配置]#环境变量配置
- [配置文件]#配置文件
- [环境特定配置]#环境特定配置
- [高级配置选项]#高级配置选项
- [安全配置]#安全配置

## 🔧 基础配置

### 必需配置项

```rust
use wechat_sdk::WeChat;

let client = WeChat::builder()
    .app_id("wx1234567890123456")           // 微信AppID (必需)
    .app_secret("your_32_char_app_secret")  // 微信AppSecret (必需)
    .build()?;
```

### 可选配置项

```rust
let client = WeChat::builder()
    .app_id("wx1234567890123456")
    .app_secret("your_app_secret")
    .timeout(std::time::Duration::from_secs(30))    // HTTP超时时间
    .user_agent("MyApp/1.0")                        // 自定义User-Agent
    .build()?;
```

## 🌍 环境变量配置

### 标准环境变量

创建 `.env` 文件:

```env
# 微信基础配置
WECHAT_APP_ID=wx1234567890123456
WECHAT_APP_SECRET=your_32_char_app_secret_here
WECHAT_TOKEN=your_token_here
WECHAT_ENCODING_AES_KEY=your_43_char_encoding_aes_key_here

# 可选配置
WECHAT_TIMEOUT_SECONDS=30
WECHAT_USER_AGENT=MyApp/1.0

# 缓存配置 (可选)
REDIS_URL=redis://localhost:6379
REDIS_KEY_PREFIX=wechat:

# 数据库配置 (可选)
DATABASE_URL=postgresql://user:pass@localhost/wechat_db
DB_MAX_CONNECTIONS=10

# 运行环境
ENVIRONMENT=development
```

### 从环境变量加载

```rust
use wechat_sdk::config::WeChatConfig;

// 自动从环境变量加载
let config = WeChatConfig::from_env()?;
let client = config.build_client()?;

// 手动指定环境变量
use std::env;

let client = WeChat::builder()
    .app_id(env::var("WECHAT_APP_ID")?)
    .app_secret(env::var("WECHAT_APP_SECRET")?)
    .build()?;
```

## 📄 配置文件

### TOML 配置

创建 `wechat.toml`:

```toml
# 基础配置
app_id = "wx1234567890123456"
app_secret = "your_app_secret_here"
token = "your_token"
encoding_aes_key = "your_43_char_encoding_aes_key"
timeout_seconds = 30

# 缓存配置
[cache]
redis_url = "redis://localhost:6379"
key_prefix = "wechat:"
ttl_seconds = 3600

# 数据库配置
[database]
url = "postgresql://user:pass@localhost/wechat_db"
max_connections = 10
min_connections = 5

# 日志配置
[logging]
level = "info"
format = "json"
```

### JSON 配置

创建 `wechat.json`:

```json
{
  "app_id": "wx1234567890123456",
  "app_secret": "your_app_secret_here",
  "token": "your_token",
  "encoding_aes_key": "your_encoding_aes_key",
  "timeout_seconds": 30,
  "cache": {
    "redis_url": "redis://localhost:6379",
    "key_prefix": "wechat:",
    "ttl_seconds": 3600
  },
  "database": {
    "url": "postgresql://user:pass@localhost/wechat_db",
    "max_connections": 10
  }
}
```

### 从配置文件加载

```rust
use wechat_sdk::config::WeChatConfig;

// TOML格式
let config = WeChatConfig::from_file("wechat.toml")?;
let client = config.build_client()?;

// JSON格式
let config = WeChatConfig::from_file("wechat.json")?;
let client = config.build_client()?;

// 自动检测格式
let config = if std::path::Path::new("wechat.toml").exists() {
    WeChatConfig::from_file("wechat.toml")?
} else {
    WeChatConfig::from_file("wechat.json")?
};
```

## 🏗️ 环境特定配置

### 配置结构

```
config/
├── development.toml    # 开发环境
├── testing.toml        # 测试环境
├── staging.toml        # 预发布环境
└── production.toml     # 生产环境
```

### 开发环境配置

`config/development.toml`:

```toml
app_id = "wx_dev_app_id"
app_secret = "dev_app_secret"
token = "dev_token"
timeout_seconds = 60  # 开发环境超时时间长一些

[cache]
redis_url = "redis://localhost:6379"
key_prefix = "wechat:dev:"

[logging]
level = "debug"
format = "pretty"
```

### 生产环境配置

`config/production.toml`:

```toml
app_id = "wx_prod_app_id"
app_secret = "prod_app_secret"
token = "prod_token"
timeout_seconds = 30

[cache]
redis_url = "redis://prod-redis:6379"
key_prefix = "wechat:prod:"
ttl_seconds = 7200

[logging]
level = "warn"
format = "json"
```

### 环境配置加载

```rust
use wechat_sdk::config::{ConfigFactory, Environment};

// 根据环境变量自动选择
let env = Environment::from_env();
let config = ConfigFactory::create_for_env(env)?;
let client = config.build_client()?;

// 指定环境
let config = ConfigFactory::production()?;
let client = config.build_client()?;
```

## ⚙️ 高级配置选项

### 完整配置结构

```rust
use wechat_sdk::config::WeChatConfig;

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WeChatConfig {
    // 基础配置
    pub app_id: String,
    pub app_secret: String,
    pub token: Option<String>,
    pub encoding_aes_key: Option<String>,
    
    // HTTP配置
    pub timeout_seconds: Option<u64>,
    pub user_agent: Option<String>,
    pub max_retries: Option<u32>,
    
    // 缓存配置
    pub cache: Option<CacheConfig>,
    
    // 数据库配置
    pub database: Option<DatabaseConfig>,
    
    // 日志配置
    pub logging: Option<LoggingConfig>,
    
    // 安全配置
    pub security: Option<SecurityConfig>,
}
```

### 缓存配置

```rust
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CacheConfig {
    pub redis_url: String,
    pub key_prefix: String,
    pub ttl_seconds: Option<u64>,
    pub max_connections: Option<u32>,
    pub timeout_seconds: Option<u64>,
}
```

### 数据库配置

```rust
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DatabaseConfig {
    pub url: String,
    pub max_connections: Option<u32>,
    pub min_connections: Option<u32>,
    pub acquire_timeout_seconds: Option<u64>,
    pub idle_timeout_seconds: Option<u64>,
}
```

### 日志配置

```rust
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LoggingConfig {
    pub level: String,        // trace, debug, info, warn, error
    pub format: String,       // json, pretty, compact
    pub output: String,       // stdout, stderr, file
    pub file_path: Option<String>,
}
```

## 🛡️ 安全配置

### 密钥管理

```toml
[security]
# 是否验证SSL证书
verify_ssl = true

# API调用频率限制 (每分钟)
rate_limit_per_minute = 2000

# 是否启用请求签名验证
enable_signature_verification = true

# 允许的IP白名单
allowed_ips = ["192.168.1.0/24", "10.0.0.0/8"]
```

### 环境变量安全

```bash
# 使用外部密钥管理系统
export WECHAT_APP_SECRET_FILE=/run/secrets/wechat_app_secret
export WECHAT_TOKEN_FILE=/run/secrets/wechat_token

# 或使用加密的环境变量
export WECHAT_APP_SECRET_ENCRYPTED="encrypted_value_here"
export ENCRYPTION_KEY="your_encryption_key"
```

### 安全配置加载

```rust
use wechat_sdk::config::SecureConfigLoader;

let config = SecureConfigLoader::new()
    .load_from_file_if_exists("WECHAT_APP_SECRET_FILE")?
    .load_encrypted_env("WECHAT_APP_SECRET_ENCRYPTED", "ENCRYPTION_KEY")?
    .build()?;
```

## 🔧 配置管理器

### 统一配置管理

```rust
use wechat_sdk::config::ConfigManager;

// 创建配置管理器
let mut config_manager = ConfigManager::new().await?;

// 获取客户端
let client = config_manager.client();

// 热重载配置
config_manager.reload().await?;

// 配置验证
config_manager.validate()?;
```

### 配置监听器

```rust
use wechat_sdk::config::ConfigWatcher;

let watcher = ConfigWatcher::new("wechat.toml")
    .on_change(|new_config| {
        println!("配置已更新: {:?}", new_config);
        // 重新初始化客户端
    })
    .watch().await?;
```

## 📊 配置验证

### 基础验证

```rust
impl WeChatConfig {
    pub fn validate(&self) -> Result<(), ConfigError> {
        // 验证AppID格式
        if !self.app_id.starts_with("wx") || self.app_id.len() != 18 {
            return Err(ConfigError::InvalidAppId);
        }
        
        // 验证AppSecret长度
        if self.app_secret.len() != 32 {
            return Err(ConfigError::InvalidAppSecret);
        }
        
        // 验证超时时间
        if let Some(timeout) = self.timeout_seconds {
            if timeout == 0 || timeout > 300 {
                return Err(ConfigError::InvalidTimeout);
            }
        }
        
        Ok(())
    }
}
```

### 连接测试

```rust
impl WeChatConfig {
    pub async fn test_connection(&self) -> Result<(), ConfigError> {
        let client = self.build_client()?;
        
        // 测试获取access_token
        let token = client.core().get_access_token().await
            .map_err(ConfigError::ConnectionFailed)?;
            
        println!("✅ 连接测试成功,Access Token: {}...", &token[..10]);
        Ok(())
    }
}
```

## 🐳 容器化配置

### Docker配置

`Dockerfile`:

```dockerfile
FROM rust:1.70 as builder

WORKDIR /app
COPY . .
RUN cargo build --release

FROM debian:bookworm-slim
RUN apt-get update && apt-get install -y \
    ca-certificates \
    && rm -rf /var/lib/apt/lists/*

WORKDIR /app
COPY --from=builder /app/target/release/my-wechat-app .
COPY config/ ./config/

# 创建非root用户
RUN useradd -m appuser
USER appuser

CMD ["./my-wechat-app"]
```

`docker-compose.yml`:

```yaml
version: '3.8'

services:
  app:
    build: .
    environment:
      - ENVIRONMENT=production
      - WECHAT_CONFIG_PATH=/app/config/production.toml
      - REDIS_URL=redis://redis:6379
      - DATABASE_URL=postgresql://user:pass@postgres:5432/wechat
    secrets:
      - wechat_app_secret
      - wechat_token
    depends_on:
      - redis
      - postgres

  redis:
    image: redis:7-alpine
    volumes:
      - redis_data:/data

  postgres:
    image: postgres:15
    environment:
      POSTGRES_DB: wechat
      POSTGRES_USER: user
      POSTGRES_PASSWORD: pass
    volumes:
      - postgres_data:/var/lib/postgresql/data

secrets:
  wechat_app_secret:
    external: true
  wechat_token:
    external: true

volumes:
  redis_data:
  postgres_data:
```

## 📝 配置示例

### 完整的生产环境配置

`config/production.toml`:

```toml
# WeChat基础配置
app_id = "wx1234567890123456"
app_secret = "your_production_app_secret"
token = "your_production_token"
encoding_aes_key = "your_production_encoding_aes_key"

# HTTP配置
timeout_seconds = 30
user_agent = "MyWeChatApp/1.0"
max_retries = 3

# 缓存配置
[cache]
redis_url = "redis://prod-redis-cluster:6379"
key_prefix = "wechat:prod:"
ttl_seconds = 7200
max_connections = 20
timeout_seconds = 5

# 数据库配置
[database]
url = "postgresql://wechat_user:secure_password@prod-db:5432/wechat_prod"
max_connections = 20
min_connections = 5
acquire_timeout_seconds = 30
idle_timeout_seconds = 600

# 日志配置
[logging]
level = "info"
format = "json"
output = "stdout"

# 安全配置
[security]
verify_ssl = true
rate_limit_per_minute = 1800
enable_signature_verification = true
allowed_ips = ["10.0.0.0/8", "172.16.0.0/12"]

# 监控配置
[monitoring]
enable_metrics = true
metrics_port = 9090
health_check_path = "/health"
```

## 🔍 调试配置

### 配置诊断工具

```rust
use wechat_sdk::config::ConfigDiagnostic;

let diagnostic = ConfigDiagnostic::new();

// 检查配置文件
diagnostic.check_config_file("wechat.toml")?;

// 检查环境变量
diagnostic.check_environment_variables()?;

// 检查网络连接
diagnostic.check_network_connectivity().await?;

// 检查依赖服务
diagnostic.check_redis_connection().await?;
diagnostic.check_database_connection().await?;

// 生成诊断报告
let report = diagnostic.generate_report();
println!("{}", report);
```

---

## 📚 相关链接

- [快速开始指南]./quickstart.md
- [API使用文档]./api-reference.md
- [最佳实践]./best-practices.md
- [示例代码]../examples/

## 💡 小贴士

1. **安全第一**:不要在代码中硬编码敏感信息
2. **环境隔离**:为不同环境使用不同的配置文件
3. **配置验证**:启动时验证所有配置项
4. **热重载**:生产环境支持配置热重载
5. **监控配置**:记录配置变更和异常
6. **备份配置**:定期备份重要配置文件