wx-server-sdk 调用
在微信小程序云函数中通过内置的 wx-server-sdk 调用混元生图模型。wx-server-sdk 已预装在微信云函数环境中,无需额外安装。
说明
图片生成功能仅支持在云函数中调用,小程序端不支持直接调用。
前置条件
- 已开通微信云开发环境
- wx-server-sdk 3.0.5-beta.1 或更高版本(支持
cloud.ai()) - 生图资源:小程序成长计划赠送的生图资源
版本说明
cloud.ai() 接口需要 wx-server-sdk 3.0.5-beta.1 或更高版本。可在云函数的 package.json 中指定版本:
{
"dependencies": {
"wx-server-sdk": "3.0.5-beta.1"
}
}
创建生图云函数
新建云函数,在 index.js 中填入以下代码:
const cloud = require('wx-server-sdk')
cloud.init({
env: cloud.DYNAMIC_CURRENT_ENV,
timeout: 150000, // 单次 HTTP 请求超时 150s,覆盖默认的 ~15s
})
const ALLOWED_SIZES = ['1024x1024', '1280x720', '720x1280', '1280x1280']
exports.main = async (event, context) => {
const prompt = (event.prompt || '').trim()
if (!prompt) {
return { error: '请输入提示词' }
}
if (prompt.length > 500) {
return { error: '提示词最多 500 字' }
}
const size = ALLOWED_SIZES.includes(event.size) ? event.size : '1024x1024'
const imageModel = cloud.ai().createImageModel('hunyuan-image')
const res = await imageModel.generateImage({
model: 'hunyuan-image-v3.0-v1.0.4',
prompt,
size,
revise: { value: true },
enable_thinking: { value: false },
})
return {
url: res.data[0].url, // 图片 URL,24 小时有效
revisedPrompt: res.data[0].revised_prompt, // 优化后的提示词
}
}
超时时间
图片生成耗时较长(开启 revise 改写约增加 10 秒,开启 thinking 模式最长增加 60 秒),建议将云函数超时时间设置为 900 秒。
在小程序中调用
云函数部署后,在小程序代码中调用:
const res = await wx.cloud.callFunction({
name: 'generateImage',
data: {
prompt: '一只胖胖的橘猫坐在窗台上打盹,水彩风格,温暖色调',
size: '1024x1024',
},
})
console.log(res.result.url) // 图片 URL
console.log(res.result.revisedPrompt) // 改写后的 prompt
保存图片到云存储
生成的图片 URL 24 小时后失效。如需永久保存,可在云函数中直接下载并上传到云存储:
const https = require('https')
const cloud = require('wx-server-sdk')
cloud.init({
env: cloud.DYNAMIC_CURRENT_ENV,
timeout: 150000,
})
exports.main = async (event, context) => {
const prompt = (event.prompt || '').trim()
const imageModel = cloud.ai().createImageModel('hunyuan-image')
const res = await imageModel.generateImage({
model: 'hunyuan-image-v3.0-v1.0.4',
prompt,
revise: { value: true },
enable_thinking: { value: false },
})
// 下载图片并上传到云存储
const imageBuffer = await downloadImage(res.data[0].url)
const uploadRes = await cloud.uploadFile({
cloudPath: `ai-images/${Date.now()}.jpg`,
fileContent: imageBuffer,
})
return {
fileID: uploadRes.fileID,
revisedPrompt: res.data[0].revised_prompt,
}
}
function downloadImage(url) {
return new Promise((resolve, reject) => {
https.get(url, (response) => {
const chunks = []
response.on('data', (chunk) => chunks.push(chunk))
response.on('end', () => resolve(Buffer.concat(chunks)))
response.on('error', reject)
})
})
}