Files
wx_service/docs/README.md
T

86 lines
2.3 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# 微信小程序登录服务
记录小程序端 `wx.login` 换取 `openid` 并写入数据库的后端服务说明。
## 配置
1. 复制 `.env.example``.env`
2. 按实际环境填写以下变量:
- `SERVER_PORT`HTTP 服务端口,例如 `8080`
- `DB_HOST/DB_PORT/DB_USER/DB_PASSWORD/DB_NAME`MySQL 连接信息。
- `WECHAT_APP_ID``WECHAT_APP_SECRET`:小程序后台 `appId``secret`(例如用户提供的 `wx67444119b166caa0` / `eb57cd73ff48a10b14df484e1d20facf`)。
3. 如果需要,替换 `GIN_MODE``JWT_SECRET` 等其他变量。
## 启动
```bash
go run ./cmd/api
```
启动流程:
1. 加载 `.env`
2. 初始化数据库连接(参见 `internal/database/database.go`)。
3. 自动迁移 `internal/model/user.go` 中的 `users` 表。
4. 注册路由并启动 Gin HTTP 服务。
## 数据表 `users`
| 字段 | 类型 | 说明 |
| --- | --- | --- |
| `id` | bigint unsigned (auto increment) | 主键 |
| `open_id` | varchar(100), unique | 微信 `openid`,登录唯一标识 |
| `union_id` | varchar(100), nullable | 微信 `unionid`(若有) |
| `nick_name` | varchar(100) | 用户昵称 |
| `avatar_url` | varchar(500) | 头像地址 |
| `gender` | tinyint, default 0 | 性别(与小程序一致) |
| `phone` | varchar(20) | 手机号 |
| `session_key` | varchar(100) | 微信会话密钥 |
| `created_at/updated_at/deleted_at` | timestamp | GORM 默认时间戳 |
## 接口
### `POST /api/v1/auth/login`
- **说明**:接收小程序端 `wx.login` 返回的 `code`,向微信 `jscode2session` 请求 `openid` / `session_key`。若 `open_id` 不存在则创建用户,存在则更新资料并返回用户信息。
- **请求体**
```json
{
"code": "wx.login返回的code",
"nickname": "可选",
"avatar_url": "可选",
"gender": 1,
"phone": "110"
}
```
- **响应体**
```json
{
"code": 200,
"message": "success",
"data": {
"user": {
"id": 1,
"open_id": "oXXX",
"union_id": "可选",
"nickname": "昵称",
"avatar_url": "链接",
"gender": 1,
"phone": "110"
},
"session_key": "wx-session-key"
}
}
```
- **错误**
- `400``code` 缺失或请求体非法。
- `502`:微信 API 返回错误。
- `500`:数据库或其他内部异常。
## 健康检查
`GET /healthz` 返回 `{"status": "ok"}`,用于部署探活。