
方案 | 是否需要安装 | 适用场景 |
axios(本文示例默认) | npm install axios | 已有项目在用 axios,或偏好其 API 风格。 |
Node.js 原生 fetch | 无需安装(Node.js ≥ 18 内置) | 零依赖、现代项目推荐。 |
Node.js 原生 https | 无需安装 | 兼容老版本 Node.js(< 18)。 |
npm install axios
// 替换 axios.post 调用// 原: const resp = await axios.post(`https://${MPS_HOST}`, payload, { headers });// return resp.data;// 改为:const resp = await fetch(`https://${MPS_HOST}`, {method: 'POST',headers: headers,body: JSON.stringify(payload)});return await resp.json();
crypto 模块即可完成签名,无需额外安装。签名部分无外部依赖。{"tencentCloud": {"secretId": "您的 SecretId","secretKey": "您的 SecretKey","region": "ap-guangzhou"}}
.gitignore)。功能 | 接口 | Action | 功能说明 | 请求频率限制 |
360°全景图 | CreateAigcImageTask | 根据 prompt 或 参考图 生成全景图,二选一输入,不可同时输入。 | 20 次/秒 | |
| DescribeAigcImageTask | 轮询全景图生成进度和结果。 | 20 次/秒 | |
3D 场景生成 | CreateAigcVideoTask | 根据 prompt 或 参考图 生成3D 场景,二选一输入,不可同时输入。 | 10 次/秒 | |
| DescribeAigcVideoTask | 轮询3D 场景生成进度和结果。 | 50 次/秒 | |
/*** 腾讯云 API 签名工具 (TC3-HMAC-SHA256)*/const crypto = require('crypto');function sha256(message) {return crypto.createHash('sha256').update(message).digest('hex');}function hmac256(key, message) {return crypto.createHmac('sha256', key).update(message).digest();}/*** 生成腾讯云 API V3 签名* @param {string} secretId - 腾讯云 SecretId* @param {string} secretKey - 腾讯云 SecretKey* @param {string} service - 服务名,如 'mps'* @param {string} action - 接口名,如 'CreateAigcVideoTask'* @param {string} payload - 请求体 JSON 字符串* @param {string} region - 地域,如 'ap-guangzhou'* @param {string} [version] - API 版本号,默认 '2019-06-12'* @returns {{ headers: object }} - 包含完整签名的请求头*/function signRequest(secretId, secretKey, service, action, payload, region, version) {const timestamp = Math.floor(Date.now() / 1000);const date = new Date(timestamp * 1000).toISOString().split('T')[0];// ===== 步骤1: 拼接规范请求串 =====const httpRequestMethod = 'POST';const canonicalUri = '/';const canonicalQueryString = '';const contentType = 'application/json';const canonicalHeaders =`content-type:${contentType}\\n` +`host:${service}.tencentcloudapi.com\\n` +`x-tc-action:${action.toLowerCase()}\\n`;const signedHeaders = 'content-type;host;x-tc-action';const hashedRequestPayload = sha256(payload);const canonicalRequest =`${httpRequestMethod}\\n${canonicalUri}\\n${canonicalQueryString}\\n` +`${canonicalHeaders}\\n${signedHeaders}\\n${hashedRequestPayload}`;// ===== 步骤2: 拼接待签名字符串 =====const algorithm = 'TC3-HMAC-SHA256';const credentialScope = `${date}/${service}/tc3_request`;const hashedCanonicalRequest = sha256(canonicalRequest);const stringToSign =`${algorithm}\\n${timestamp}\\n${credentialScope}\\n${hashedCanonicalRequest}`;// ===== 步骤3: 计算签名 =====const secretDate = hmac256(`TC3${secretKey}`, date);const secretService = hmac256(secretDate, service);const secretSigning = hmac256(secretService, 'tc3_request');const signature = crypto.createHmac('sha256', secretSigning).update(stringToSign).digest('hex');// ===== 步骤4: 拼接 Authorization =====const authorization =`${algorithm} Credential=${secretId}/${credentialScope}, ` +`SignedHeaders=${signedHeaders}, Signature=${signature}`;return {headers: {'Authorization': authorization,'Content-Type': contentType,'Host': `${service}.tencentcloudapi.com`,'X-TC-Action': action,'X-TC-Timestamp': String(timestamp),'X-TC-Version': version || '2019-06-12','X-TC-Region': region || ''}};}module.exports = { signRequest };
const axios = require('axios');const { signRequest } = require('./tencent-sign');const MPS_HOST = 'mps.tencentcloudapi.com';const SERVICE = 'mps';/*** 通用 MPS API 调用函数*/async function callMpsApi(action, params, config) {const payload = JSON.stringify(params);const { headers } = signRequest(config.tencentCloud.secretId,config.tencentCloud.secretKey,SERVICE,action,payload,config.tencentCloud.region);const resp = await axios.post(`https://${MPS_HOST}`, payload, { headers });return resp.data;}// =============================================// 混元全景图(360°,ModelVersion=3d-world-panorama-2.0)// =============================================/*** 创建混元全景图任务* @param {string} prompt - 全景描述(不超过 600 字符)* @param {string} imageUrl - 参考图 URL(可选,用于图生全景)* @param {object} options - 额外选项* @param {string} options.modelName - 模型名称,默认 'Hunyuan'* @param {string} options.modelVersion - 模型版本号,默认 '3d-world-panorama-2.0'* @param {object} options.storeCos - COS 存储参数* @returns {{ Response: { TaskId: string, RequestId: string } }}*/async function createPanoramaTask(prompt, imageUrl, options = {}) {const config = options._config; // 传入配置对象const params = {ModelName: options.modelName || 'Hunyuan',ModelVersion: options.modelVersion || '3d-world-panorama-2.0',Prompt: prompt,Operator: options.operator || 'admin'};// 参考图(图生全景)if (imageUrl) {params.ImageUrl = imageUrl;}// COS 存储if (options.storeCos) {params.StoreCosParam = options.storeCos;}return await callMpsApi('CreateAigcImageTask', params, config);}// =============================================// 混元 3D 世界(ModelVersion=3d-world-scene-2.0)// =============================================/*** 创建混元 3D 世界任务(文生 / 图生 3D、实景 3D 复刻)* @param {string} prompt - 场景描述(不超过 600 字符)* @param {string} imageUrl - 参考图 URL(可选,用于图生 3D)* @param {object} options - 额外选项* @param {string} options.modelName - 模型名称,默认 'Hunyuan'* @param {string} options.modelVersion - 模型版本号,默认 '3d-world-scene-2.0'* @param {object} options.storeCos - COS 存储参数* @returns {{ Response: { TaskId: string, RequestId: string } }}*/async function createWorldTask(prompt, imageUrl, options = {}) {const config = options._config; // 传入配置对象const params = {ModelName: options.modelName || 'Hunyuan',ModelVersion: options.modelVersion || '3d-world-scene-2.0',Prompt: prompt,Operator: options.operator || 'admin'};// 参考图(图生 3D / 实景复刻)if (imageUrl) {params.ImageUrl = imageUrl;}// COS 存储if (options.storeCos) {params.StoreCosParam = options.storeCos;}return await callMpsApi('CreateAigcVideoTask', params, config);}/*** 查询混元全景图任务* @param {string} taskId - 创建任务时返回的 TaskId,形如 '4-AigcImage-xxx'* @param {object} config - 配置对象* @returns {{ Response: { Status: string, ImageUrl: string[], Message: string, RequestId: string } }}* Status: 'WAIT' | 'RUN' | 'DONE' | 'FAIL'* ImageUrl: 任务完成时返回全景图 URL 列表(⚠️ 仅存储 12 小时)*/async function describeImageTask(taskId, config) {return await callMpsApi('DescribeAigcImageTask', { TaskId: taskId }, config);}/*** 查询混元 3D 世界任务* @param {string} taskId - 创建任务时返回的 TaskId,形如 '4-AigcImage-xxx'* @param {object} config - 配置对象* @returns {{ Response: { Status: string, Message: string, RequestId: string,* image_url: string, scene_url: string, point_url: string,* mesh_url: string, mesh_simplified_url: string, position_info: string } }}* Status: 'WAIT' | 'RUN' | 'DONE' | 'FAIL'* 任务完成(DONE)时返回:* scene_url - 3DGS 场景文件 URL* mesh_url - Mesh 网格文件 URL(GLB/FBX/OBJ)* mesh_simplified_url - 简化 Mesh URL* point_url - 点云文件 URL(PLY)* image_url - 预览图 URL* position_info - 位置/包围盒信息 JSON 字符串(up_direction、facing_direction、center_point、scale、x/y/z_min/max)* ⚠️ 以上结果 URL 仅存储 12 小时*/async function describeSceneTask(taskId, config) {return await callMpsApi('DescribeAigcImageTask', { TaskId: taskId }, config);}module.exports = {callMpsApi,createPanoramaTask,createWorldTask,describeImageTask,describeSceneTask};
async function generatePanorama() {// 第1步: 创建全景图生成任务console.log('🌏 正在创建全景图生成任务...');const createResult = await callMpsApi('CreateAigcImageTask', {ModelName: 'Hunyuan',ModelVersion: '3d-world-panorama-2.0',Prompt: 'a 360 panorama of a fantasy castle on a cliff',Operator: 'admin'});const taskId = createResult.Response.TaskId;console.log(`✅ 任务创建成功, TaskId: ${taskId}`);// 第2步: 轮询查询任务状态let status = 'WAIT';let imageUrls = [];while (status === 'WAIT' || status === 'RUN') {await new Promise(resolve => setTimeout(resolve, 5000));const queryResult = await callMpsApi('DescribeAigcImageTask', {TaskId: taskId});status = queryResult.Response.Status;console.log(`⏳ 任务状态: ${status}`);if (status === 'DONE') {imageUrls = queryResult.Response.ImageUrls;console.log('🎉 全景图生成成功!');console.log(`🖼️ 全景图URL: ${imageUrls}`);} else if (status === 'FAIL') {console.error('❌ 生成失败:');}}return imageUrls;}generatePanorama().catch(console.error);
async function generateWorld() {// 第1步: 创建 3D 场景生成任务(使用图片作为参考,图生 3D场景)console.log('🌍 正在创建 3D 世界生成任务...');const createResult = await callMpsApi('CreateAigcVideoTask', {ModelName: 'Hunyuan',ModelVersion: '3d-world-scene-2.0',Prompt: 'generate a walkable 3D world from this image',ImageUrl: 'https://example.com/scene.png', // 参考图(图生 3D)Operator: 'admin'});const taskId = createResult.Response.TaskId;console.log(`✅ 任务创建成功, TaskId: ${taskId}`);// 第2步: 轮询查询任务状态let status = 'WAIT';let videoUrls = [];while (status === 'WAIT' || status === 'RUN') {await new Promise(resolve => setTimeout(resolve, 5000));const queryResult = await callMpsApi('DescribeAigcVideoTask', {TaskId: taskId});status = queryResult.Response.Status;console.log(`⏳ 任务状态: ${status}`);if (status === 'DONE') {videoUrls = queryResult.Response.VideoUrls;const resolution = queryResult.Response.Resolution;console.log('🎉 3D 场景生成成功!');console.log(`📹 结果URL: ${videoUrls}`);console.log(`📐 分辨率: ${resolution}`);} else if (status === 'FAIL') {console.error('❌ 生成失败:');}}return videoUrls;}generateWorld().catch(console.error);
/*** 带重试和超时的轮询函数(全景图与 3D 场景任务均通过 DescribeAigcImageTask 查询)* @param {string} taskId - 任务 ID* @param {number} timeout - 超时时间(毫秒),默认 30 分钟* @param {number} interval - 轮询间隔(毫秒),默认 5000*/async function pollTaskResult(taskId, timeout = 1800000, interval = 5000) {const startTime = Date.now();while (Date.now() - startTime < timeout) {const result = await callMpsApi('DescribeAigcImageTask', { TaskId: taskId });const resp = result.Response;if (resp.Status === 'DONE') {// 全景图: resp.ImageUrl;3D 场景: resp.scene_url / mesh_url / point_url 等return { success: true, response: resp };}if (resp.Status === 'FAIL') {return {success: false,error: resp.Message || '任务失败'};}// WAIT 或 RUN,继续等待await new Promise(resolve => setTimeout(resolve, interval));}return { success: false, error: '轮询超时' };}// 使用示例async function main() {// 创建全景图任务(360°)const panoTask = await callMpsApi('CreateAigcImageTask', {ModelName: 'Hunyuan',ModelVersion: '3d-world-panorama-2.0',Prompt: 'a 360 panorama of a fantasy castle on a cliff',Operator: 'admin'});const panoResult = await pollTaskResult(panoTask.Response.TaskId);if (panoResult.success) {console.log('全景图:', panoResult.response.ImageUrl[0]);// 用全景图作为参考图,继续生成可漫游的 3D 场景const worldTask = await callMpsApi('CreateAigcVideoTask', {ModelName: 'Hunyuan',ModelVersion: '3d-world-scene-2.0',Prompt: 'generate a walkable 3D world from this image',ImageUrl: panoResult.response.ImageUrl[0],Operator: 'admin'});const worldResult = await pollTaskResult(worldTask.Response.TaskId);if (worldResult.success) {const resp = worldResult.response;console.log('3DGS 场景:', resp.scene_url);console.log('Mesh 网格:', resp.mesh_url);console.log('简化 Mesh:', resp.mesh_simplified_url);console.log('点云 PLY:', resp.point_url);}}}main().catch(console.error);
{"tencentCloud": {"secretId": "您的 SecretId","secretKey": "您的 SecretKey","region": "ap-guangzhou"},"cosOutput": {"bucket": "your-bucket-name-1234567890","region": "ap-guangzhou","outputDir": "/aigc-output/"},"mps": {"panorama": {"enabled": true,"modelName": "Hunyuan","modelVersion": "3d-world-panorama-2.0"},"world3d": {"enabled": true,"modelName": "Hunyuan","modelVersion": "3d-world-scene-2.0"}},"concurrency": {"maxPanoramaTasks": 2,"maxWorldTasks": 1,"pollIntervalMs": 5000}}
curl -X POST https://mps.tencentcloudapi.com \\-H "Content-Type: application/json" \\-H "X-TC-Action: CreateAigcImageTask" \\-H "X-TC-Version: 2019-06-12" \\-H "X-TC-Region: ap-guangzhou" \\-H "Authorization: TC3-HMAC-SHA256 Credential=AKIDxxx/2026-07-22/mps/tc3_request, SignedHeaders=content-type;host, Signature=xxx" \\-d '{"ModelName": "Hunyuan","ModelVersion": "3d-world-panorama-2.0","Prompt": "a 360 panorama of a fantasy castle on a cliff","Operator": "admin"}'
{"Response": {"RequestId": "1047d0dc-6dc8-4898-a7f3-03726a822b0e","TaskId": "4-AigcImage-c3b145ec76****94ac55b9e63be17d"}}
POST / HTTP/1.1Host: mps.tencentcloudapi.comContent-Type: application/jsonX-TC-Action: DescribeAigcImageTaskX-TC-Version: 2019-06-12{"TaskId": "4-AigcImage-c3b145ec76xxxx94ac55b9e63be17d"}
{"Response": {"ImageUrls": ["https://1a168d6xxxx-100xxxx3.cos.ap-chongqing.myqcloud.com/1a168d62vodcq2510xxxx0/89e6a7645001834816711593827/aigcImageGenFile.png"],"Message": "ok","ModelVersion": "3d-world-panorama-2.0","RequestId": "1562526381312631916","Status": "DONE"}}
curl -X POST https://mps.tencentcloudapi.com \\-H "Content-Type: application/json" \\-H "X-TC-Action: CreateAigcVideoTask" \\-H "X-TC-Version: 2019-06-12" \\-H "X-TC-Region: ap-guangzhou" \\-H "Authorization: TC3-HMAC-SHA256 Credential=AKIDxxx/2026-07-22/mps/tc3_request, SignedHeaders=content-type;host, Signature=xxx" \\-d '{"ModelName": "Hunyuan","ModelVersion": "3d-world-scene-2.0","Prompt": "generate a walkable 3D world from this image","ImageUrl": "https://example.com/scene.png","Operator": "admin"}'
{"Response": {"RequestId": "1047d0dc-6dc8-4898-a7f3-03726a822b0e","TaskId": "4-AigcVideo-c3b145ec76****94ac55b9e63be17d"}}
POST / HTTP/1.1Host: mps.tencentcloudapi.comContent-Type: application/jsonX-TC-Action: DescribeAigcVideoTaskX-TC-Version: 2019-06-12{"TaskId": "4-AigcVideo-c3b145ec76xxxx94ac55b9e63be17d"}
{"Response": {"ErrCode": "","InfoList": [{"Info": "https://xxx-100xxxx3.cos.ap-chongqing.myqcloud.com/1a168d62vodcq2510xxxx0/7a5646c35001834816721727529/aigcVideoGenFile.spz","Type": "scene_url"},{"Info": "https://xx-100xxxx3.cos.ap-chongqing.myqcloud.com/1a168d62vodcq2510xxxx0/7a5646c35001834816721727529/aigcVideoGenFile_1.ply","Type": "point_url"},{"Info": "https://xxx-100xxxx3.cos.ap-chongqing.myqcloud.com/1a168d62vodcq2510xxxx0/7a5646c35001834816721727529/aigcVideoGenFile_2.ply","Type": "mesh_url"},{"Info": "https://xxx-100xxxx3.cos.ap-chongqing.myqcloud.com/1a168d62vodcq2510xxxx0/7a5646c35001834816721727529/aigcVideoGenFile_3.ply","Type": "mesh_simplified_url"},{"Info": "{\\"up_direction\\": [-0.02079851923949021, 0.2613014462384399, 0.9650331475090088], \\"facing_direction\\": [-0.626063846931178, 0.7491595220706289, -0.21634248324506605], \\"center_point\\": [1.782250738281545, -1.9750670645362651, 1.0067128278740172], \\"scale\\": 11.956174528691873, \\"x_min\\": -13.44873332977295, \\"x_max\\": 16.499736785888672, \\"y_min\\": -10.109375953674316, \\"y_max\\": 10.426920890808105, \\"z_min\\": -7.725327491760254, \\"z_max\\": 9.579703330993652, \\"scene_type\\": \\"indoor\\", \\"bbox\\": [], \\"human_scale\\": 1.0, \\"kwargs\\": {\\"camera_obb\\": [1.6270229082336667, -1.8028265092799098, 1.6301805654329842, 7.386863719037379, 4.968907858993009, 1.6818647610009452]}, \\"air_wall\\": {\\"scene_type\\": \\"indoor\\", \\"bbox\\": [-13.44873332977295, 16.499736785888672, -10.109375953674316, 10.426920890808105, -7.725327491760254, 9.579703330993652, 1.6270229082336667, -1.8028265092799098, 1.6301805654329842, 7.386863719037379, 4.968907858993009, 1.6818647610009452]}}","Type": "position_info"},{"Info": "https://xxx-100xxxx3.cos.ap-chongqing.myqcloud.com/1a168d62vodcq2510xxxx0/7a5646c35001834816721727529/aigcVideoGenFile_5.png","Type": "image_url"}],"Message": "ok","RequestId": "1561810987380319545","Resolution": "","Status": "DONE","VideoUrls": []}}
文档反馈