Files
gofly-platform-services/zlt-doc/WECHAT_MINIAPP_LOGIN.md
T
2026-03-07 19:31:53 +08:00

261 lines
6.0 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.
# 微信小程序登录接口文档
## 接口概述
本接口用于微信小程序用户登录,支持通过微信小程序 code 获取用户 openId 并完成登录认证。
## 接口信息
- **接口地址**: `/oauth/token`
- **请求方式**: `POST`
- **Content-Type**: `application/json`
## 请求参数
| 参数名 | 类型 | 必填 | 说明 |
|--------|------|------|------|
| grantType | String | 是 | 固定值:`tencent` |
| clientId | String | 是 | 客户端ID,如:`webApp` |
| code | String | 是 | 微信小程序登录凭证 code |
| encryptedData | String | 建议 | 微信加密数据(用于获取手机号) |
| iv | String | 建议 | 微信加密算法初始向量 |
| appCode | String | 否 | 应用标识,多小程序时使用 |
## 请求示例
```json
{
"grantType": "tencent",
"clientId": "webApp",
"code": "081xYz0w3XXXXX",
"encryptedData": "CiyLU1Aw2KjvrjMdj8YKliAjtP4gsMZMQmRzooG2xrDcvSnxIMXFufNstNGTyaGS9uT5geRa0W4oTOb1WT7fJlAC+oNPdbB+3hVbJSRgv+4lGOETKUQz6OYStslQ41Vo+VruvZhXQoXYITvg6iEvwQ==",
"iv": "r7BXXsfdsfdsKZacZxdsafY5hQ==",
"appCode": "default"
}
```
## 响应参数
### 成功响应
```json
{
"access_token": "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9...",
"token_type": "Bearer",
"refresh_token": "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9...",
"expires_in": 43199,
"scope": "all",
"user_info": {
"id": 1,
"username": "user_wx_xxx",
"nickname": "微信用户",
"mobile": "13800138000",
"enabled": true
}
}
```
### 失败响应
```json
{
"error": "invalid_grant",
"error_description": "Code cannot be null or empty"
}
```
## 小程序端实现步骤
### 1. 获取微信登录凭证
```javascript
// 1. 调用微信登录接口获取 code
wx.login({
success: (res) => {
if (res.code) {
const code = res.code;
// 继续下一步
}
}
});
```
### 2. 获取手机号(可选但建议)
```javascript
// 2. 获取用户手机号
<button open-type="getPhoneNumber" bindgetphonenumber="getPhoneNumber">
授权手机号登录
</button>
getPhoneNumber(e) {
if (e.detail.errMsg === 'getPhoneNumber:ok') {
const encryptedData = e.detail.encryptedData;
const iv = e.detail.iv;
// 继续下一步
}
}
```
### 3. 调用后端登录接口
```javascript
// 3. 调用后端登录接口
wx.request({
url: 'https://your-domain.com/api-uaa/oauth/token',
method: 'POST',
header: {
'Content-Type': 'application/json'
},
data: {
grantType: 'tencent',
clientId: 'webApp',
code: code,
encryptedData: encryptedData, // 可选
iv: iv, // 可选
appCode: 'default' // 可选
},
success: (res) => {
if (res.statusCode === 200) {
const accessToken = res.data.access_token;
const userInfo = res.data.user_info;
// 保存 token
wx.setStorageSync('access_token', accessToken);
wx.setStorageSync('user_info', userInfo);
// 跳转到首页
wx.switchTab({
url: '/pages/index/index'
});
}
}
});
```
### 4. 完整示例代码
```javascript
// pages/login/login.js
Page({
data: {
code: '',
encryptedData: '',
iv: ''
},
onLoad() {
this.getWxCode();
},
// 获取微信 code
getWxCode() {
wx.login({
success: (res) => {
if (res.code) {
this.setData({ code: res.code });
}
}
});
},
// 获取手机号
getPhoneNumber(e) {
if (e.detail.errMsg === 'getPhoneNumber:ok') {
this.setData({
encryptedData: e.detail.encryptedData,
iv: e.detail.iv
});
this.login();
}
},
// 登录
login() {
wx.request({
url: 'https://your-domain.com/api-uaa/oauth/token',
method: 'POST',
header: {
'Content-Type': 'application/json'
},
data: {
grantType: 'tencent',
clientId: 'webApp',
code: this.data.code,
encryptedData: this.data.encryptedData,
iv: this.data.iv
},
success: (res) => {
if (res.statusCode === 200) {
wx.setStorageSync('access_token', res.data.access_token);
wx.setStorageSync('user_info', res.data.user_info);
wx.switchTab({ url: '/pages/index/index' });
} else {
wx.showToast({
title: '登录失败',
icon: 'none'
});
}
}
});
}
});
```
## 后续请求携带 Token
登录成功后,后续请求需要在 Header 中携带 access_token:
```javascript
wx.request({
url: 'https://your-domain.com/api-user/users/current',
method: 'GET',
header: {
'Authorization': 'Bearer ' + wx.getStorageSync('access_token')
},
success: (res) => {
console.log(res.data);
}
});
```
## 配置说明
### 后端配置
需要在数据库中配置微信小程序信息(appId、appSecret):
```sql
-- 微信小程序配置表(需要根据实际表结构调整)
INSERT INTO wechat_config (app_code, app_id, app_secret, type)
VALUES ('default', 'wx1234567890abcdef', 'your_app_secret', 'MINI');
```
### 微信小程序配置
1. 登录微信公众平台
2. 开发 > 开发管理 > 开发设置
3. 配置服务器域名(request 合法域名)
4. 添加你的后端域名:`https://your-domain.com`
## 注意事项
1. **code 有效期**: 微信 code 只能使用一次,5分钟内有效
2. **手机号获取**: encryptedData 和 iv 用于解密手机号,建议获取以完善用户信息
3. **appCode**: 如果有多个小程序,需要传递 appCode 区分
4. **Token 过期**: access_token 默认有效期 12 小时,过期后需要使用 refresh_token 刷新
## 错误码说明
| 错误码 | 说明 | 解决方案 |
|--------|------|----------|
| invalid_grant | code 无效或已使用 | 重新调用 wx.login() 获取新 code |
| 不支持的appid | 未配置该小程序 | 检查数据库中的微信配置 |
| 用户登录信息待处理 | 用户信息异常 | 联系管理员检查用户数据 |
## 测试建议
1. 使用微信开发者工具测试
2. 真机调试验证完整流程
3. 测试 token 过期后的刷新逻辑