244 lines
9.8 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { CDP, evaluate, goto, launchEdge, openPage, sleep } from '../erp-daily-bills/cdp.mjs';
const BASE = path.dirname(fileURLToPath(import.meta.url));
const PROFILE = path.resolve(BASE, '../../runtime/private/alipay-profile');
const SECRET_FILE = process.env.ALIPAY_SECRET_FILE
|| path.resolve(BASE, '../../runtime/private/敏感信息.md');
const PORT = 9335;
const arg = (name, fallback = null) => {
const hit = process.argv.find((item) => item.startsWith(`--${name}=`));
return hit ? hit.slice(name.length + 3) : fallback;
};
const fmt = (date) => [
date.getFullYear(),
String(date.getMonth() + 1).padStart(2, '0'),
String(date.getDate()).padStart(2, '0'),
].join('-');
const yesterday = new Date(Date.now() - 86400000);
const targetDate = arg('date', fmt(yesterday));
if (!/^\d{4}-\d{2}-\d{2}$/.test(targetDate)) throw new Error('日期必须使用 YYYY-MM-DD 格式');
const outputDir = path.resolve(arg('out', path.join(BASE, '../../runtime/private/alipay-exports', targetDate)));
fs.mkdirSync(outputDir, { recursive: true });
const outputFile = path.join(outputDir, `alipay-company-${targetDate}.csv`);
const stateFile = path.join(outputDir, 'last-export.json');
let secret = '';
let account = process.env.ALIPAY_ACCOUNT?.trim() || '';
let password = process.env.ALIPAY_PASSWORD?.trim() || '';
let accountShort = process.env.ALIPAY_ACCOUNT_SHORT?.trim() || '';
if (!account || !password || !accountShort) {
secret = fs.readFileSync(SECRET_FILE, 'utf8');
account ||= /账号:([^\r\n]+)/.exec(secret)?.[1]?.trim();
password ||= /密码:([^\r\n]+)/.exec(secret)?.[1]?.trim();
accountShort ||= /支付宝账户简称:([^\r\n]+)/.exec(secret)?.[1]?.trim();
}
if (!account || !password || !accountShort) throw new Error('私有文件缺少支付宝账号、密码或账户简称');
const dotDate = targetDate.replaceAll('-', '.');
const query = new URLSearchParams({
dateRange: 'customDate',
beginDate: dotDate,
endDate: dotDate,
beginTime: '00:00',
endTime: '24:00',
dateType: 'createDate',
fundFlow: 'all',
tradeType: 'ALL',
status: 'all',
});
const targetUrl = `https://consumeprod.alipay.com/record/advanced.htm?${query}`;
const { child, version } = await launchEdge({
port: PORT,
profileDir: PROFILE,
headless: !process.argv.includes('--interactive'),
});
const cdp = await CDP.connect(version.webSocketDebuggerUrl);
const { sessionId } = await openPage(cdp, 'about:blank');
async function pageInfo() {
return evaluate(cdp, sessionId, `({
url: location.href,
title: document.title,
text: document.body?.innerText || '',
hasUser: !!document.querySelector('#J-input-user')
&& !!(document.querySelector('#J-input-user').offsetWidth || document.querySelector('#J-input-user').offsetHeight),
hasPassword: [...document.querySelectorAll('input[type="password"]')].some((input) => !!(input.offsetWidth || input.offsetHeight))
})`);
}
async function maybeLogin() {
await goto(cdp, sessionId, targetUrl);
await sleep(1600);
let state = await pageInfo();
if (!/auth\.alipay\.com\/login/.test(state.url) && !state.hasUser && !state.hasPassword) return state;
await evaluate(cdp, sessionId, `(() => {
const el = [...document.querySelectorAll('*')].find((node) => (node.innerText || '').trim() === '账密登录');
el && el.click();
return true;
})()`);
await sleep(900);
const focused = await evaluate(cdp, sessionId, `(() => {
const setValue = (el, value) => {
const setter = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value')?.set;
setter ? setter.call(el, value) : (el.value = value);
el.dispatchEvent(new Event('input', { bubbles: true }));
el.dispatchEvent(new Event('change', { bubbles: true }));
};
const user = document.querySelector('#J-input-user');
const pass = document.querySelector('#password_rsainput')
|| [...document.querySelectorAll('input[type="password"]')].find((input) => !!(input.offsetWidth || input.offsetHeight));
if (!user || !pass) return false;
setValue(user, ${JSON.stringify(account)});
setValue(pass, '');
pass.focus();
pass.click();
return true;
})()`);
if (!focused) throw new Error('未找到支付宝账号或密码输入框');
for (const character of password) {
await cdp.send('Input.dispatchKeyEvent', {
type: 'keyDown',
key: character,
text: character,
unmodifiedText: character,
}, sessionId);
await cdp.send('Input.dispatchKeyEvent', {
type: 'keyUp',
key: character,
}, sessionId);
await sleep(35);
}
await sleep(250);
await evaluate(cdp, sessionId, `(() => {
const pass = document.querySelector('#password_rsainput')
|| [...document.querySelectorAll('input[type="password"]')].find((input) => !!(input.offsetWidth || input.offsetHeight));
pass && pass.blur();
const button = document.querySelector('#J-login-simulate-btn')
|| [...document.querySelectorAll('button')].find((node) => !!(node.offsetWidth || node.offsetHeight)
&& (node.innerText || '').replace(/\\s+/g, '') === '登录');
button && button.click();
return true;
})()`);
await sleep(3500);
state = await pageInfo();
if (/请在下图依次点击|验证码|短信验证|扫码验证/.test(state.text)) {
throw new Error('支付宝登录或账单下载需要人工验证,请先运行 open-login.mjs 完成验证');
}
if (state.hasUser && state.hasPassword) throw new Error('支付宝登录失败,请先运行 open-login.mjs 检查登录状态');
return state;
}
async function waitForRecords() {
for (let attempt = 0; attempt < 20; attempt++) {
const ready = await evaluate(cdp, sessionId, `({
rows: document.querySelectorAll('#tradeRecordsIndex tr.J-item').length,
noData: /暂无数据|没有找到符合条件的记录/.test(document.body?.innerText || ''),
begin: document.querySelector('#beginDate')?.value || '',
end: document.querySelector('#endDate')?.value || ''
})`);
if (ready.begin === dotDate && ready.end === dotDate && (ready.rows > 0 || ready.noData)) return ready;
await sleep(800);
}
throw new Error('支付宝交易记录加载超时');
}
function parseRows(rows) {
return rows.map((row) => {
const cells = row.cells.map((cell) => (cell.innerText || '').replace(/\s+/g, ' ').trim());
const timeMatch = /^(\d{4})[./-](\d{1,2})[./-](\d{1,2})\s+(\d{1,2}):(\d{2})/.exec(cells[0] || '');
const ids = /订单号[::]\s*([^|]+)\|\s*交易号[::]\s*(\d+)/.exec(cells[3] || '') || [];
const amountText = cells[5] || '';
const numeric = Number(amountText.replace(/[^\d.-]/g, ''));
return {
time: timeMatch
? `${timeMatch[1]}-${timeMatch[2].padStart(2, '0')}-${timeMatch[3].padStart(2, '0')} ${timeMatch[4].padStart(2, '0')}:${timeMatch[5]}`
: '',
name: cells[2] || '',
merchantOrderNo: (ids[1] || '').trim(),
recordCode: (ids[2] || '').trim(),
counterparty: cells[4] || '',
direction: amountText.trim().startsWith('-') ? '支出' : '收入',
amount: Math.abs(numeric).toFixed(2),
status: cells[7] || '',
};
}).filter((row) => row.time && row.recordCode && Number(row.amount) > 0);
}
try {
await maybeLogin();
await goto(cdp, sessionId, targetUrl);
await waitForRecords();
const collected = [];
const seenPages = new Set();
for (let page = 1; page <= 200; page++) {
const rows = await evaluate(cdp, sessionId, `[...document.querySelectorAll('#tradeRecordsIndex tr.J-item')].map((row) => ({
cells: [...row.cells].map((cell) => ({ innerText: cell.innerText || '' }))
}))`);
const pageRows = parseRows(rows);
const fingerprint = pageRows.map((row) => row.recordCode).join(',') + '|' + pageRows.length;
if (seenPages.has(fingerprint)) break;
seenPages.add(fingerprint);
collected.push(...pageRows);
const next = await evaluate(cdp, sessionId, `(() => {
const visible = (el) => !!(el.offsetWidth || el.offsetHeight);
const link = [...document.querySelectorAll('a')].find((el) => visible(el)
&& (el.innerText || '').replace(/\\s+/g, '').includes('下一页')
&& !/(disabled|fn-hide)/.test(el.className || ''));
if (!link) return false;
link.click();
return true;
})()`);
if (!next) break;
await sleep(1500);
}
const unique = [...new Map(collected.map((row) => [row.recordCode, row])).values()];
if (unique.length === 0) throw new Error(`支付宝 ${targetDate} 没有可导入交易`);
const header = ['交易时间', '交易对方', '商品说明', '收/支', '金额(元)', '交易状态', '交易号', '商家订单号', '备注'];
const csv = [header, ...unique.map((row) => [
row.time,
row.counterparty,
row.name,
row.direction,
row.amount,
row.status,
row.recordCode,
row.merchantOrderNo,
'',
])].map((line) => line.map((value) => `"${String(value).replaceAll('"', '""')}"`).join(',')).join('\r\n');
fs.writeFileSync(outputFile, `\uFEFF${csv}\r\n`, 'utf8');
const income = unique.filter((row) => row.direction === '收入').reduce((sum, row) => sum + Number(row.amount), 0);
const expense = unique.filter((row) => row.direction === '支出').reduce((sum, row) => sum + Number(row.amount), 0);
const state = {
ok: true,
date: targetDate,
rows: unique.length,
income: Number(income.toFixed(2)),
expense: Number(expense.toFixed(2)),
file: outputFile,
cutoffTime: new Date().toISOString(),
};
fs.writeFileSync(stateFile, JSON.stringify(state, null, 2), 'utf8');
console.log(JSON.stringify({ ...state, accountShort }));
} catch (error) {
fs.writeFileSync(stateFile, JSON.stringify({
ok: false,
date: targetDate,
error: String(error?.message || error),
cutoffTime: new Date().toISOString(),
}, null, 2), 'utf8');
throw error;
} finally {
cdp.close();
child.kill();
}