uniapp 对接企业微信直播 已经得到了接口返回的living_code , 接下来怎么做 查看直播详情呢
时间: 2025-07-21 12:57:08 浏览: 1
<think>我们已经在UniApp中获取了企业微信直播的living_code,现在需要查看直播详情。
根据企业微信API文档,获取直播详情需要调用`/cgi-bin/living/get_living_info`接口,该接口需要传递livingid(即living_code)和access_token。
由于企业微信API要求从服务端调用(出于安全考虑,需要access_token,且access_token的获取需要corpid和secret),因此我们不能直接在UniApp前端调用,而是通过自有服务端中转。
步骤:
1. UniApp前端将living_code发送给自有服务端。
2. 服务端使用企业微信API获取直播详情(需要用到企业微信的access_token)。
3. 服务端将直播详情返回给UniApp前端。
企业微信获取直播详情API文档:https://work.weixin.qq.com/api/doc/90000/90135/93634
具体实现:
一、UniApp前端代码(发送请求到服务端):
```javascript
// 假设我们已经存储了living_code
const living_code = uni.getStorageSync('living_code');
// 调用服务端接口获取直播详情
async function getLiveDetail() {
try {
const res = await uni.request({
url: 'https://your-server.com/api/get-live-detail', // 服务端接口
method: 'POST',
data: {
living_code: living_code
}
});
// 注意:uni.request返回的是一个数组 [error, response]
if (res[0]) {
throw res[0]; // 网络错误等
}
const response = res[1].data;
if (response.errcode === 0) {
// 这里response.data就是直播详情
console.log('直播详情:', response.data);
// 处理直播详情数据,例如展示在页面上
} else {
uni.showToast({
title: '获取直播详情失败: ' + response.errmsg,
icon: 'none'
});
}
} catch (e) {
uni.showToast({
title: '请求失败: ' + (e.errMsg || e.message),
icon: 'none'
});
}
}
```
二、服务端代码(Node.js示例):
```javascript
// 服务端接口:/api/get-live-detail
app.post('/api/get-live-detail', async (req, res) => {
const { living_code } = req.body;
// 1. 获取access_token(需要缓存,避免频繁请求)
const tokenRes = await axios.get(`https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=${corpid}&corpsecret=${secret}`);
const access_token = tokenRes.data.access_token;
// 2. 调用企业微信获取直播详情接口
try {
const detailRes = await axios.post(
`https://qyapi.weixin.qq.com/cgi-bin/living/get_living_info?access_token=${access_token}`,
{
livingid: living_code
}
);
// 3. 返回给前端
res.json({
errcode: 0,
data: detailRes.data
});
} catch (e) {
// 企业微信接口返回的错误
res.status(500).json({
errcode: e.response.data.errcode,
errmsg: e.response.data.errmsg
});
}
});
```
三、直播详情返回示例(企业微信API返回):
```json
{
"errcode": 0,
"errmsg": "ok",
"living_info": {
"theme": "直播主题",
"anchor_userid": "主播UserID",
"living_start": 1586390400,
"living_duration": 3600,
"status": 1, // 直播状态:1=直播中,2=未开始,3=已结束,4=已过期
"reserve_living_start": 1586390400, // 预约开始时间
"description": "直播描述",
"type": 4, // 直播类型:4=通用直播
"livingid": "living_code", // 直播id
"viewer_num": 100, // 观看人数
"comment_num": 200, // 评论数
"open_replay": 1, // 是否开启回放:0否,1是
"push_stream_url": "推流地址" // 仅当主播在直播中返回
}
}
```
四、注意事项:
1. 服务端需要缓存access_token(有效期7200秒),避免频繁请求。
2. 直播状态(status)非常重要,可以根据状态来显示不同的界面(例如:直播中、未开始、已结束)。
3. 如果开启了回放(open_replay=1),直播结束后可以获取回放地址(需要调用另一个接口获取回放地址)。
五、相关问题:
1. 如何获取企业微信直播的回放地址?
2. 直播状态有哪些?分别代表什么含义?
3. 如何判断当前用户是否有权限观看直播?
4. UniApp中如何展示直播详情页面?
注意:以上代码仅为示例,实际开发中请根据项目需求进行调整,并做好错误处理。</think>在 UniApp 中对接企业微信直播并获取 `living_code` 后,查看直播详情的完整实现步骤如下:
### 一、核心实现流程
```mermaid
graph TD
A[UniApp前端] -->|发送 living_code| B[自有服务端]
B -->|请求企业微信API| C[企业微信服务器]
C -->|返回直播详情| B
B -->|返回数据| A
A -->|渲染详情| D[用户界面]
```
### 二、UniApp 前端实现
```javascript
// 获取直播详情方法
async getLiveDetail(living_code) {
try {
const res = await uni.request({
url: 'https://your-server.com/api/get-live-detail',
method: 'POST',
header: { 'Content-Type': 'application/json' },
data: { living_code }
});
if (res[1].data.errcode === 0) {
const detail = res[1].data.living_info;
// 处理直播详情数据
this.processLiveDetail(detail);
} else {
uni.showToast({ title: '获取失败: ' + res[1].data.errmsg, icon: 'none' });
}
} catch (e) {
uni.showToast({ title: '网络请求异常', icon: 'none' });
}
},
// 处理直播详情数据
processLiveDetail(detail) {
// 状态映射:1=直播中,2=未开始,3=已结束,4=已过期
const statusMap = {
1: { text: '直播中', color: '#07c160' },
2: { text: '未开始', color: '#ff976a' },
3: { text: '已结束', color: '#909399' },
4: { text: '已过期', color: '#909399' }
};
this.liveInfo = {
theme: detail.theme || '无标题',
anchor: detail.anchor_userid,
status: statusMap[detail.status] || { text: '未知状态', color: '#ff0000' },
startTime: this.formatTime(detail.living_start),
duration: `${Math.floor(detail.living_duration/60)}分钟`,
viewers: detail.viewer_num || 0,
comments: detail.comment_num || 0,
replay: detail.open_replay === 1 // 是否开启回放
};
},
// 时间格式化方法
formatTime(timestamp) {
const date = new Date(timestamp * 1000);
return `${date.getFullYear()}-${(date.getMonth()+1).toString().padStart(2,'0')}-${date.getDate().toString().padStart(2,'0')} ${date.getHours().toString().padStart(2,'0')}:${date.getMinutes().toString().padStart(2,'0')}`;
}
```
### 三、服务端实现(Node.js 示例)
```javascript
// 获取直播详情接口 /api/get-live-detail
router.post('/api/get-live-detail', async (req, res) => {
const { living_code } = req.body;
try {
// 1. 获取企业微信access_token(需缓存)
const tokenRes = await axios.get(
`https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=${CORP_ID}&corpsecret=${SECRET}`
);
// 2. 调用企业微信直播详情接口
const detailRes = await axios.post(
`https://qyapi.weixin.qq.com/cgi-bin/living/get_living_info?access_token=${tokenRes.data.access_token}`,
{ livingid: living_code }
);
// 3. 返回直播详情
res.json({
errcode: 0,
living_info: detailRes.data.living_info
});
} catch (e) {
console.error('获取直播详情失败:', e.response.data);
res.status(500).json({
errcode: e.response.data.errcode || -1,
errmsg: e.response.data.errmsg || '服务端异常'
});
}
});
```
### 四、直播详情数据结构
企业微信返回的直播详情包含以下关键字段:
```json
{
"errcode": 0,
"errmsg": "ok",
"living_info": {
"theme": "季度产品发布会",
"anchor_userid": "zhangsan",
"living_start": 1600000000,
"living_duration": 7200,
"status": 1, // 直播状态:1=直播中,2=未开始,3=已结束,4=已过期
"reserve_living_start": 1600000000,
"description": "2023年Q4新品发布",
"type": 4, // 直播类型:4=通用直播
"livingid": "living_code_value",
"viewer_num": 152, // 观看人数
"comment_num": 86, // 评论数
"open_replay": 1, // 是否开启回放:0否,1是
"push_stream_url": "rtmp://xxx" // 推流地址(仅主播可见)
}
}
```
### 五、关键注意事项
1. **状态处理逻辑**:
```javascript
// 根据状态显示不同UI
get statusBadge() {
switch(this.liveInfo.status) {
case 1: return { text: '直播中', color: 'error' };
case 2: return { text: '未开始', color: 'warning' };
case 3: return { text: '已结束', color: 'success' };
default: return { text: '已过期', color: 'info' };
}
}
```
2. **安全限制**:
- 企业微信API调用必须通过服务端中转[^1]
- 服务端IP需加入企业微信白名单(后台 > 应用管理)
- 敏感字段(如 `push_stream_url`)建议服务端过滤后再返回前端
3. **性能优化**:
```javascript
// 直播中状态轮询(每60秒更新一次)
startPolling() {
this.pollTimer = setInterval(() => {
if (this.liveInfo.status === 1) {
this.getLiveDetail(this.livingCode);
} else {
clearInterval(this.pollTimer);
}
}, 60000);
}
```
### 六、常见错误处理
| 错误码 | 原因 | 解决方案 |
|--------|-----------------------|------------------------------|
| 41040 | 直播不存在 | 检查living_code是否正确 |
| 41041 | 直播已过期 | 创建新的直播 |
| 60011 | IP不在白名单 | 添加服务端IP到企业微信后台 |
| 40014 | access_token过期 | 服务端重新获取access_token |
### 七、最佳实践建议
1. **详情页UI示例**:
```html
<view class="live-detail">
<view class="status-badge" :style="{background: liveInfo.status.color}">
{{ liveInfo.status.text }}
</view>
<view class="title">{{ liveInfo.theme }}</view>
<view class="info-row">
<text>主播: {{ liveInfo.anchor }}</text>
<text>开始时间: {{ liveInfo.startTime }}</text>
</view>
<view class="stats">
<view>👁 {{ liveInfo.viewers }}人观看</view>
<view>💬 {{ liveInfo.comments }}条评论</view>
</view>
<button v-if="liveInfo.status.value===1" @click="enterLive">进入直播</button>
<button v-if="liveInfo.status.value===3 && liveInfo.replay" @click="watchReplay">观看回放</button>
</view>
```
2. **服务端缓存优化**:
```javascript
// 使用redis缓存access_token
const getAccessToken = async () => {
const cachedToken = await redis.get('qywx_token');
if (cachedToken) return cachedToken;
const res = await axios.get(`https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=${CORP_ID}&corpsecret=${SECRET}`);
await redis.setex('qywx_token', 7000, res.data.access_token); // 提前过期
return res.data.access_token;
};
```
> 企业微信直播API文档参考:[获取直播详情](https://work.weixin.qq.com/api/doc/90000/90135/93634)[^1]
### 相关问题
1. 如何获取企业微信直播的回放地址?
2. 直播结束后如何自动生成回放视频?
3. UniApp中如何实现直播间的实时弹幕功能?
4. 企业微信直播的推流参数如何获取和使用?
5. 如何实现直播开始前的提醒功能?
阅读全文
相关推荐














