Twilioapp/server/index.js
2025-06-29 01:33:41 +08:00

99 lines
2.6 KiB
JavaScript

const express = require('express');
const cors = require('cors');
const jwt = require('jsonwebtoken');
const { AccessToken } = require('twilio').jwt;
const { VideoGrant } = AccessToken;
const app = express();
const PORT = 3001;
// 中间件
app.use(cors());
app.use(express.json());
// Twilio 配置 - 请替换为您的实际凭证
const TWILIO_CONFIG = {
accountSid: process.env.TWILIO_ACCOUNT_SID || 'AC_YOUR_ACCOUNT_SID',
apiKey: process.env.TWILIO_API_KEY || 'SK3b25e00e6914162a7cf829cffc415cb3',
apiSecret: process.env.TWILIO_API_SECRET || 'PpGH298dlRgMSeGrexUjw1flczTVIw9H',
};
// 生成 Twilio Access Token
app.post('/api/twilio/token', (req, res) => {
try {
const { identity, roomName } = req.body;
if (!identity || !roomName) {
return res.status(400).json({
error: 'Identity and roomName are required'
});
}
// 创建 Access Token
const token = new AccessToken(
TWILIO_CONFIG.accountSid,
TWILIO_CONFIG.apiKey,
TWILIO_CONFIG.apiSecret,
{ identity: identity }
);
// 创建 Video Grant
const videoGrant = new VideoGrant({
room: roomName
});
// 将 grant 添加到 token
token.addGrant(videoGrant);
// 生成 JWT token
const jwtToken = token.toJwt();
console.log(`Generated token for identity: ${identity}, room: ${roomName}`);
res.json({
token: jwtToken,
identity: identity,
roomName: roomName
});
} catch (error) {
console.error('Token generation error:', error);
res.status(500).json({
error: 'Failed to generate token',
details: error.message
});
}
});
// 健康检查端点
app.get('/health', (req, res) => {
res.json({
status: 'ok',
timestamp: new Date().toISOString(),
service: 'Twilio Token Server'
});
});
// 获取房间信息(模拟)
app.get('/api/twilio/rooms', (req, res) => {
res.json({
rooms: [
{ name: 'test-room', participants: 0 },
{ name: 'demo-room', participants: 2 },
]
});
});
// 启动服务器
app.listen(PORT, () => {
console.log(`🚀 Twilio Token Server running on http://localhost:${PORT}`);
console.log(`📋 Health check: http://localhost:${PORT}/health`);
console.log(`🎥 Token endpoint: http://localhost:${PORT}/api/twilio/token`);
console.log('');
console.log('⚠️ 请确保已设置正确的 Twilio 凭证:');
console.log(` TWILIO_ACCOUNT_SID: ${TWILIO_CONFIG.accountSid}`);
console.log(` TWILIO_API_KEY: ${TWILIO_CONFIG.apiKey}`);
console.log(` TWILIO_API_SECRET: ${TWILIO_CONFIG.apiSecret.substring(0, 4)}...`);
});
module.exports = app;