const fs = require('fs'); const path = require('path'); const ci = require('miniprogram-ci'); const root = path.resolve(__dirname, '..'); const appid = process.env.MP_APPID || 'wxbb5d4030dd1c431f'; const secret = process.env.MP_APPSECRET || readAppSecret(); const privateKeyPath = process.env.MP_PRIVATE_KEY_PATH ? path.resolve(root, process.env.MP_PRIVATE_KEY_PATH) : path.join(root, 'deploy', `private.${appid}.key`); const version = process.env.MP_VERSION || '1.1.1'; const desc = process.env.MP_DESC || 'jxc'; const auditDesc = process.env.MP_AUDIT_DESC || `${desc} v${version}:新增加工与加工验收、优化移动端业务功能`; function readAppSecret() { const secretFile = path.join(root, 'deploy', '小程序AppSecret.txt'); if (!fs.existsSync(secretFile)) return ''; const text = fs.readFileSync(secretFile, 'utf8'); const match = text.match(/AppSecret\s+([a-f0-9]+)/i); return match ? match[1].trim() : ''; } async function wechatApi(pathname, body) { const token = await getAccessToken(); const url = `https://api.weixin.qq.com${pathname}${pathname.includes('?') ? '&' : '?'}access_token=${token}`; const res = await fetch(url, { method: body ? 'POST' : 'GET', headers: { 'Content-Type': 'application/json' }, body: body ? JSON.stringify(body) : undefined, }); const json = await res.json(); if (json.errcode && json.errcode !== 0) { throw new Error(`${pathname} failed: ${json.errcode} ${json.errmsg || ''}`.trim()); } return json; } async function getAccessToken() { if (!secret) throw new Error('Missing MP_APPSECRET or deploy/小程序AppSecret.txt'); const url = `https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${appid}&secret=${secret}`; const res = await fetch(url); const json = await res.json(); if (!json.access_token) { throw new Error(`getAccessToken failed: ${json.errcode || ''} ${json.errmsg || ''}`.trim()); } return json.access_token; } async function waitForPrivacyCheck(maxAttempts = 24, intervalMs = 5000) { let useFallbackWait = false; for (let i = 1; i <= maxAttempts; i += 1) { try { const result = await wechatApi('/wxa/security/get_code_privacy_info'); if (result.errcode === 0 || result.audit_status === 0) { console.log('Privacy/code check passed'); return; } } catch (err) { const msg = String(err.message || err); if (msg.includes('48001')) { useFallbackWait = true; break; } if (!msg.includes('61039')) throw err; console.log(`Waiting for code check (${i}/${maxAttempts})...`); } await new Promise((resolve) => setTimeout(resolve, intervalMs)); } if (useFallbackWait) { console.log('Privacy check API unavailable, waiting 30s before submit...'); await new Promise((resolve) => setTimeout(resolve, 30000)); return; } throw new Error('Code privacy check did not finish in time'); } async function buildAuditItems() { const category = await wechatApi('/wxa/get_category'); const list = category.category_list || []; if (!list.length) { throw new Error('No configured miniprogram categories found in WeChat admin'); } const first = list[0]; return [{ address: 'pages/home/home', tag: first.second_name ? `${first.first_name} ${first.second_name}` : first.first_name, first_class: first.first_name, second_class: first.second_name || '', third_class: first.third_name || '', first_id: first.first_id, second_id: first.second_id || 0, third_id: first.third_id || 0, title: 'AI生鲜配送', }]; } async function main() { if (!fs.existsSync(privateKeyPath)) { throw new Error(`Missing miniprogram upload private key: ${privateKeyPath}`); } const skipUpload = process.env.MP_SKIP_UPLOAD === '1'; if (!skipUpload) { const project = new ci.Project({ appid, type: 'miniProgram', projectPath: root, privateKeyPath, ignores: ['node_modules/**/*', 'server/**/*', 'src/**/*', 'dist/**/*'], }); console.log(`Uploading miniprogram ${appid} version=${version} desc=${desc}`); await ci.upload({ project, version, desc, setting: { es6: true, minify: true, minifyJS: true, minifyWXML: true, minifyWXSS: true, }, onProgressUpdate: console.log, }); console.log('Upload complete'); } else { console.log('Skipping upload (MP_SKIP_UPLOAD=1)'); } console.log('Waiting for WeChat code check...'); await waitForPrivacyCheck(); const itemList = await buildAuditItems(); console.log('Submitting audit...'); try { const audit = await wechatApi('/wxa/submit_audit', { item_list: itemList, version_desc: auditDesc, privacy_api_not_use: false, }); console.log(`Audit submitted. auditid=${audit.auditid}`); } catch (err) { const msg = String(err.message || err); if (msg.includes('86000')) { console.log(''); console.log('=== 代码已上传,但 Open API 无法代提交审核(86000)==='); console.log('请在微信公众平台手动提交:'); console.log(' 登录 mp.weixin.qq.com → 管理 → 版本管理 → 开发版本'); console.log(` 找到版本 ${version}(备注 jxc)→ 点击「提交审核」`); console.log(` 版本说明可填:${auditDesc}`); return; } throw err; } } main().catch((error) => { console.error(error); process.exit(1); });