feat: 增加朱俊祥支付宝安全自动登录配置 #1244

Merged
shanshi merged 1 commits from feature/shanshi-zhu-junxiang-alipay-daily into main 2026-11-18 17:34:49 +08:00
8 changed files with 318 additions and 41 deletions

View File

@ -1,14 +1,22 @@
# 公司非店铺支付宝每日账单
# 朱俊祥支付宝每日账单
每天 09:45 自动读取公司支付宝账户前一天的交易记录,并导入财务台账“动账明细”。
每天 09:45 自动读取朱俊祥支付宝前一天的交易记录,并导入财务台账“朱俊祥支付宝”独立账单。
## 首次登录
## 首次设置
```powershell
node scripts\company-alipay-direct\open-login.mjs
pwsh -File scripts\company-alipay-direct\setup-account.ps1
```
脚本会打开独立 Edge 登录窗口并预填账号。图形验证码、短信或扫码确认必须由本人完成;登录成功后保留该浏览器配置目录,后续定时任务复用登录会话。
按提示在本机输入支付宝账号、密码和财务台账账户简称。默认简称为“朱俊祥支付宝”。密码使用 Windows 当前用户 DPAPI 加密保存到 `runtime/private/alipay-account.dpapi`,不会进入 Git 或日志。
设置完成后脚本会打开独立 Edge 登录窗口并预填账号。图形验证码、短信或扫码确认必须由本人完成;登录成功后保留该浏览器配置目录,后续定时任务复用登录会话。
以后登录失效时,只需重新运行:
```powershell
pwsh -File scripts\company-alipay-direct\open-login.ps1
```
## 手动运行
@ -25,7 +33,7 @@ pwsh -File scripts\company-alipay-direct\run-alipay-daily.ps1 -Date 2026-10-29 -
pwsh -File scripts\company-alipay-direct\install-daily-task.ps1
```
账号、密码、账户简称和浏览器登录态仅保存在 `runtime/private/`,不会进入 Git。私有文件需包含 `账号:`、`密码:` 和 `支付宝账户简称:` 三项。任一登录失效、验证页面出现、空数据或导入失败都会保留上一版数据并记录日志。
账号、密码、账户简称和浏览器登录态仅保存在 `runtime/private/`,不会进入 Git。任一登录失效、验证页面出现、空数据或导入失败都会保留上一版数据并记录日志。
定时任务通过 `run-alipay-daily.cmd` 启动,并优先使用系统 Node.js;若仅在 Codex 运行时可用,会自动使用当前固定运行时路径。任务宿主错误记录在同目录的 `task-host.log`,业务错误记录在日期日志中。

View File

@ -0,0 +1,149 @@
#Requires -Version 5.1
function Get-AlipayRepositoryRoot {
return Split-Path -Parent (Split-Path -Parent $PSScriptRoot)
}
function Get-AlipayEncryptedConfigPath {
return Join-Path (Get-AlipayRepositoryRoot) 'runtime\private\alipay-account.dpapi'
}
function ConvertFrom-SecureStringForAlipay {
param([Parameter(Mandatory = $true)][Security.SecureString] $Value)
$pointer = [Runtime.InteropServices.Marshal]::SecureStringToBSTR($Value)
try {
return [Runtime.InteropServices.Marshal]::PtrToStringBSTR($pointer)
} finally {
[Runtime.InteropServices.Marshal]::ZeroFreeBSTR($pointer)
}
}
function Assert-AlipayAccountConfig {
param([Parameter(Mandatory = $true)] $Config)
if ($Config.account -notmatch '^[A-Za-z0-9@._+-]{6,100}$') {
throw '支付宝账号格式无效,请使用手机号、邮箱或支付宝登录账号。'
}
if ([string]::IsNullOrWhiteSpace($Config.password)) {
throw '支付宝密码不能为空。'
}
if ([string]::IsNullOrWhiteSpace($Config.accountShort)) {
throw '支付宝账户简称不能为空。'
}
}
function Save-AlipayEncryptedAccountConfig {
param(
[Parameter(Mandatory = $true)][string] $Account,
[Parameter(Mandatory = $true)][Security.SecureString] $Password,
[Parameter(Mandatory = $true)][string] $AccountShort,
[string] $Path = (Get-AlipayEncryptedConfigPath)
)
$passwordText = ConvertFrom-SecureStringForAlipay $Password
try {
$config = [ordered]@{
account = $Account.Trim()
password = $passwordText
accountShort = $AccountShort.Trim()
}
Assert-AlipayAccountConfig ([pscustomobject] $config)
$json = $config | ConvertTo-Json -Compress
$secureJson = ConvertTo-SecureString -String $json -AsPlainText -Force
$cipherText = ConvertFrom-SecureString $secureJson
$directory = Split-Path -Parent $Path
New-Item -ItemType Directory -Force -Path $directory | Out-Null
[IO.File]::WriteAllText($Path, $cipherText, [Text.Encoding]::ASCII)
} finally {
if ($null -ne $passwordText) {
$passwordText = $null
}
}
}
function Read-AlipayEncryptedAccountConfig {
param([string] $Path = (Get-AlipayEncryptedConfigPath))
$path = $Path
if (-not (Test-Path -LiteralPath $path -PathType Leaf)) {
return $null
}
$cipherText = [IO.File]::ReadAllText($path, [Text.Encoding]::ASCII)
$secureJson = ConvertTo-SecureString -String $cipherText
$json = ConvertFrom-SecureStringForAlipay $secureJson
try {
$config = $json | ConvertFrom-Json
Assert-AlipayAccountConfig $config
return [pscustomobject]@{
account = [string] $config.account
password = [string] $config.password
accountShort = [string] $config.accountShort
source = 'dpapi'
}
} finally {
if ($null -ne $json) {
$json = $null
}
}
}
function Read-AlipayLegacyAccountConfig {
$path = Join-Path (Get-AlipayRepositoryRoot) 'runtime\private\敏感信息.md'
if (-not (Test-Path -LiteralPath $path -PathType Leaf)) {
return $null
}
$text = [IO.File]::ReadAllText($path, [Text.UTF8Encoding]::new($false))
$config = [pscustomobject]@{
account = [regex]::Match($text, '账号:([^\r\n]+)').Groups[1].Value.Trim()
password = [regex]::Match($text, '密码:([^\r\n]+)').Groups[1].Value.Trim()
accountShort = [regex]::Match($text, '支付宝账户简称:([^\r\n]+)').Groups[1].Value.Trim()
source = 'legacy'
}
if ([string]::IsNullOrWhiteSpace($config.account) -or
[string]::IsNullOrWhiteSpace($config.password) -or
[string]::IsNullOrWhiteSpace($config.accountShort)) {
return $null
}
Assert-AlipayAccountConfig $config
return $config
}
function Read-AlipayAccountConfig {
$config = Read-AlipayEncryptedAccountConfig
if ($null -ne $config) {
return $config
}
return Read-AlipayLegacyAccountConfig
}
function Find-AlipayNodeExecutable {
$nodeCommand = Get-Command node.exe -ErrorAction SilentlyContinue | Select-Object -First 1
if ($null -ne $nodeCommand) {
return $nodeCommand.Source
}
$candidates = @(
(Join-Path $env:ProgramFiles 'nodejs\node.exe'),
(Join-Path $env:USERPROFILE '.cache\codex-runtimes\codex-primary-runtime\dependencies\node\bin\node.exe')
)
return $candidates | Where-Object { Test-Path -LiteralPath $_ -PathType Leaf } | Select-Object -First 1
}
function Set-AlipayNodeEnvironment {
param([Parameter(Mandatory = $true)] $Config)
$env:ALIPAY_ACCOUNT = [string] $Config.account
$env:ALIPAY_PASSWORD = [string] $Config.password
$env:ALIPAY_ACCOUNT_SHORT = [string] $Config.accountShort
}
function Clear-AlipayNodeEnvironment {
Remove-Item Env:ALIPAY_ACCOUNT -ErrorAction SilentlyContinue
Remove-Item Env:ALIPAY_PASSWORD -ErrorAction SilentlyContinue
Remove-Item Env:ALIPAY_ACCOUNT_SHORT -ErrorAction SilentlyContinue
}

View File

@ -25,10 +25,16 @@ fs.mkdirSync(outputDir, { recursive: true });
const outputFile = path.join(outputDir, `alipay-company-${targetDate}.csv`);
const stateFile = path.join(outputDir, 'last-export.json');
const secret = fs.readFileSync(SECRET_FILE, 'utf8');
const account = /账号:([^\r\n]+)/.exec(secret)?.[1]?.trim();
const password = /密码:([^\r\n]+)/.exec(secret)?.[1]?.trim();
const accountShort = /支付宝账户简称:([^\r\n]+)/.exec(secret)?.[1]?.trim();
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('-', '.');

View File

@ -5,7 +5,7 @@ param(
[ValidatePattern('^([01]\d|2[0-3]):[0-5]\d$')]
[string] $Time = '09:45',
[string] $TaskName = 'CaiWuXiTong-CompanyAlipayDaily'
[string] $TaskName = 'CaiWuXiTong-ZhuJunxiangAlipayDaily'
)
Set-StrictMode -Version Latest
@ -30,7 +30,7 @@ try {
$service.Connect()
$rootFolder = $service.GetFolder('\')
$definition = $service.NewTask(0)
$definition.RegistrationInfo.Description = 'CaiWuXiTong 公司非店铺支付宝前一日账单同步'
$definition.RegistrationInfo.Description = 'CaiWuXiTong 朱俊祥支付宝前一日账单同步'
$definition.Principal.UserId = $currentUser
$definition.Principal.LogonType = 3
$definition.Principal.RunLevel = 0
@ -62,7 +62,7 @@ try {
3,
$null
)
Write-Host "已安装每日支付宝账单任务:$TaskName,执行时间每天 $Time。"
Write-Host "已安装朱俊祥支付宝每日账单任务:$TaskName,执行时间每天 $Time。"
[void] [System.Runtime.InteropServices.Marshal]::FinalReleaseComObject($registered)
} finally {
foreach ($item in @($definition, $rootFolder, $service)) {

View File

@ -9,9 +9,14 @@ const SECRET_FILE = process.env.ALIPAY_SECRET_FILE
|| path.resolve(BASE, '../../runtime/private/敏感信息.md');
const PORT = 9335;
const text = fs.readFileSync(SECRET_FILE, 'utf8');
const account = /账号:([^\r\n]+)/.exec(text)?.[1]?.trim();
const password = /密码:([^\r\n]+)/.exec(text)?.[1]?.trim();
let text = '';
let account = process.env.ALIPAY_ACCOUNT?.trim() || '';
let password = process.env.ALIPAY_PASSWORD?.trim() || '';
if (!account || !password) {
text = fs.readFileSync(SECRET_FILE, 'utf8');
account ||= /账号:([^\r\n]+)/.exec(text)?.[1]?.trim();
password ||= /密码:([^\r\n]+)/.exec(text)?.[1]?.trim();
}
if (!account || !password) throw new Error('私有文件缺少支付宝账号或密码');
const { child, version } = await launchEdge({

View File

@ -0,0 +1,31 @@
#Requires -Version 5.1
[CmdletBinding()]
param()
Set-StrictMode -Version Latest
$ErrorActionPreference = 'Stop'
. (Join-Path $PSScriptRoot 'account-config.ps1')
$config = Read-AlipayAccountConfig
if ($null -eq $config) {
throw '尚未配置支付宝账号,请先运行 setup-account.ps1。'
}
$node = Find-AlipayNodeExecutable
if ([string]::IsNullOrWhiteSpace($node)) {
throw '未找到 Node.js,无法打开支付宝登录窗口。'
}
Set-AlipayNodeEnvironment $config
try {
& $node (Join-Path $PSScriptRoot 'open-login.mjs')
if ($LASTEXITCODE -ne 0) {
throw '支付宝登录窗口启动失败。'
}
Write-Host ''
Write-Host '请完成图形验证码、短信或扫码确认。' -ForegroundColor Yellow
Read-Host '确认已经登录成功并看到支付宝页面后,回到这里按 Enter' | Out-Null
} finally {
Clear-AlipayNodeEnvironment
}

View File

@ -17,11 +17,11 @@ Set-StrictMode -Version Latest
$ErrorActionPreference = 'Stop'
$root = Split-Path -Parent (Split-Path -Parent $PSScriptRoot)
$secretFile = Join-Path $root 'runtime\private\敏感信息.md'
$exportScript = Join-Path $PSScriptRoot 'export-daily.mjs'
$logDir = Join-Path $root 'runtime\private\alipay-exports\logs'
New-Item -ItemType Directory -Force -Path $logDir | Out-Null
$logFile = Join-Path $logDir ((Get-Date -Format 'yyyyMMdd') + '.log')
. (Join-Path $PSScriptRoot 'account-config.ps1')
function Write-Log {
param([string] $Message)
@ -29,21 +29,12 @@ function Write-Log {
Add-Content -LiteralPath $logFile -Value $line -Encoding UTF8
}
if (-not (Test-Path -LiteralPath $secretFile -PathType Leaf)) {
throw '缺少 runtime/private/敏感信息.md'
}
$secret = [System.IO.File]::ReadAllText(
$secretFile,
[System.Text.UTF8Encoding]::new($false)
)
$account = [regex]::Match($secret, '账号:([^\r\n]+)').Groups[1].Value.Trim()
$accountShort = [regex]::Match($secret, '支付宝账户简称:([^\r\n]+)').Groups[1].Value.Trim()
if ($account -notmatch '^\d{6,30}$') {
throw '私有文件中的支付宝账号格式无效'
}
if ([string]::IsNullOrWhiteSpace($accountShort)) {
throw '私有文件中的支付宝账户简称不能为空'
$config = Read-AlipayAccountConfig
if ($null -eq $config) {
throw '尚未配置支付宝账号,请先运行 setup-account.ps1。'
}
$account = [string] $config.account
$accountShort = [string] $config.accountShort
if ([string]::IsNullOrWhiteSpace($Date)) {
$Date = (Get-Date).Date.AddDays(-1).ToString('yyyy-MM-dd')
}
@ -53,21 +44,18 @@ $localFile = Join-Path $outputDir ('alipay-company-' + $Date + '.csv')
if (-not [string]::IsNullOrWhiteSpace($InputFile)) {
$localFile = (Resolve-Path -LiteralPath $InputFile -ErrorAction Stop).Path
} else {
$nodeCommand = Get-Command node.exe -ErrorAction SilentlyContinue | Select-Object -First 1
$node = if ($null -ne $nodeCommand) { $nodeCommand.Source } else { $null }
if ([string]::IsNullOrWhiteSpace($node)) {
$nodeCandidates = @(
(Join-Path $env:ProgramFiles 'nodejs\node.exe'),
(Join-Path $env:USERPROFILE '.cache\codex-runtimes\codex-primary-runtime\dependencies\node\bin\node.exe')
)
$node = $nodeCandidates | Where-Object { Test-Path -LiteralPath $_ -PathType Leaf } | Select-Object -First 1
}
$node = Find-AlipayNodeExecutable
if ([string]::IsNullOrWhiteSpace($node)) {
Write-Log '未找到 node.exe;未写入财务台账'
throw '未找到 Node.js,请安装 Node.js 后重新触发任务'
}
Write-Log ('开始导出支付宝账单:' + $Date)
$exportOutput = (& $node $exportScript ('--date=' + $Date) ('--out=' + $outputDir) 2>&1 | Out-String)
Set-AlipayNodeEnvironment $config
try {
$exportOutput = (& $node $exportScript ('--date=' + $Date) ('--out=' + $outputDir) 2>&1 | Out-String)
} finally {
Clear-AlipayNodeEnvironment
}
if ($LASTEXITCODE -ne 0 -or -not (Test-Path -LiteralPath $localFile -PathType Leaf)) {
Write-Log ('支付宝导出失败:' + ($exportOutput.Trim() -replace "`r?`n", ' | '))
throw '支付宝账单导出失败;未写入财务台账'

View File

@ -0,0 +1,90 @@
#Requires -Version 5.1
[CmdletBinding()]
param(
[string] $AccountShort = '朱俊祥支付宝',
[switch] $SkipLogin
)
Set-StrictMode -Version Latest
$ErrorActionPreference = 'Stop'
. (Join-Path $PSScriptRoot 'account-config.ps1')
$existing = Read-AlipayAccountConfig
$accountPrompt = if ($null -ne $existing) {
'支付宝账号(手机号/邮箱/登录账号,留空沿用 ' + $existing.account + ')'
} else {
'支付宝账号(手机号/邮箱/登录账号)'
}
do {
$account = Read-Host $accountPrompt
if ([string]::IsNullOrWhiteSpace($account) -and $null -ne $existing) {
$account = [string] $existing.account
}
if ($account -notmatch '^[A-Za-z0-9@._+-]{6,100}$') {
Write-Host '账号格式无效,请使用手机号、邮箱或支付宝登录账号。' -ForegroundColor Yellow
}
} while ($account -notmatch '^[A-Za-z0-9@._+-]{6,100}$')
do {
$password = Read-Host '支付宝登录密码(输入时不显示)' -AsSecureString
$confirmPassword = Read-Host '再次输入支付宝登录密码' -AsSecureString
$passwordText = ConvertFrom-SecureStringForAlipay $password
$confirmText = ConvertFrom-SecureStringForAlipay $confirmPassword
try {
if ([string]::IsNullOrEmpty($passwordText)) {
Write-Host '密码不能为空,请重新输入。' -ForegroundColor Yellow
continue
}
if ($passwordText -cne $confirmText) {
Write-Host '两次输入的密码不一致,请重新输入。' -ForegroundColor Yellow
continue
}
break
} finally {
$confirmText = $null
$passwordText = $null
}
} while ($true)
$defaultShort = if ($null -ne $existing -and -not [string]::IsNullOrWhiteSpace($existing.accountShort)) {
[string] $existing.accountShort
} else {
$AccountShort
}
$enteredShort = Read-Host ('财务台账账户简称,直接回车使用“' + $defaultShort + '”')
if (-not [string]::IsNullOrWhiteSpace($enteredShort)) {
$defaultShort = $enteredShort.Trim()
}
Save-AlipayEncryptedAccountConfig -Account $account -Password $password -AccountShort $defaultShort
$configPath = Get-AlipayEncryptedConfigPath
Write-Host ('账号信息已使用 Windows 当前用户加密保存:' + $configPath) -ForegroundColor Green
Write-Host ('导入账户简称:' + $defaultShort) -ForegroundColor Green
if ($SkipLogin) {
return
}
$saved = Read-AlipayEncryptedAccountConfig
$node = Find-AlipayNodeExecutable
if ([string]::IsNullOrWhiteSpace($node)) {
throw '未找到 Node.js,无法打开支付宝登录窗口。'
}
Set-AlipayNodeEnvironment $saved
try {
& $node (Join-Path $PSScriptRoot 'open-login.mjs')
if ($LASTEXITCODE -ne 0) {
throw '支付宝登录窗口启动失败。'
}
Write-Host ''
Write-Host '请在弹出的 Edge 窗口中完成图形验证码、短信或扫码确认。' -ForegroundColor Yellow
Read-Host '确认已经登录成功并看到支付宝页面后,回到这里按 Enter' | Out-Null
} finally {
Clear-AlipayNodeEnvironment
}
Write-Host '登录会话已保存。下一步可以安装或运行每日任务。' -ForegroundColor Green