uniCloud 生成小程序码
'use strict';
// 从环境变量中获取小程序的 AppID 和 AppSecret
const appid = "";
const secret = "";
/**
* 获取微信 access_token
* @returns {Promise<string>} - access_token
*/
async function getAccessToken() {
try {
const res = await uniCloud.httpclient.request('https://api.weixin.qq.com/cgi-bin/token', {
method: 'GET',
data: {
appid: appid,
secret: secret,
grant_type: 'client_credential',
},
dataType: 'json',
timeout: 10000, // 设置超时时间为10秒
});
if (res.status === 200 && res.data && res.data.access_token) {
return res.data.access_token;
} else {
throw new Error(`获取 access_token 失败: ${res.data.errmsg || '未知错误'}`);
}
} catch (error) {
console.error('获取 access_token 失败:', error);
throw new Error('获取 access_token 失败');
}
}
// 二维码获取
async function getQrCode() {
// 获取access_token
const access_token = await getAccessToken();
const res = await uniCloud.httpclient.request('https://api.weixin.qq.com/wxa/getwxacode?access_token=' +
access_token, {
method: 'POST',
data: JSON.stringify({
path: '/pages/index/index'
}),
header: {
'content-type': 'application/json'
}
});
return res.data;
}
/**
* 将 Buffer 上传到云存储
* @param {Buffer} buffer - 小程序码的 Buffer 数据
* @param {string} fileName - 保存的文件名
* @returns {Promise<string>} - 文件的访问链接
*/
async function uploadBufferToCloudStorage(buffer, fileName) {
try {
const uploadRes = await uniCloud.uploadFile({
cloudPath: `wxacode/${fileName}`,
fileContent: buffer,
});
const tempRes = await uniCloud.getTempFileURL({
fileList: [uploadRes.fileID],
});
return tempRes.fileList[0].tempFileURL;
} catch (error) {
console.error('上传文件失败:', error);
throw new Error('上传文件失败');
}
}
exports.main = async (event, context) => {
try {
let get_code = await getQrCode();
// 3. 将小程序码保存到云存储
const fileName = `wxacode_${Date.now()}.png`; // 动态生成文件名
const fileURL = await uploadBufferToCloudStorage(get_code, fileName);
// 4. 返回成功响应
return {
code: 200,
msg: '小程序码生成成功',
qr_code: fileURL
};
} catch (error) {
console.error('小程序码保存失败:', error);
return {
code: 500,
msg: '小程序码生成失败',
error: error.message,
};
}
};