技术 · 思考 · 实践 · 成长

首页/支付/正文

微信支付 V3 系列(八):下载账单——交易账单、资金账单与对账实战

支付5 次阅读

钱付得对不对,要靠账单说话。微信支付 V3 提供交易账单(每笔交易明细)和资金账单(账户资金流水)两类下载接口:先申请拿到 download_url,再下载 CSV 校验入库,最后和本地订单表对账。本文写透全流程(基础封装见系列一)。

一、账单类型与生成时间

账单接口内容
交易账单GET /v3/bill/tradebill每笔订单/退款的交易明细
资金账单GET /v3/bill/fundbill账户资金流水(收入/支出/手续费)
  • 账单 T+1 生成:今天的账单明天才能下载;bill_date 传账单日期(YYYY-MM-DD)
  • 一般只能查最近 3 个月,重要账单下载后自行归档
  • 下载文件为 CSV(tar_type=GZIP 时为 .zip 压缩包)

二、申请交易账单

GET https://api.mch.weixin.qq.com/v3/bill/tradebill?bill_date=2026-12-01&bill_type=ALL&tar_type=GZIP
参数必填说明
bill_date是账单日期 YYYY-MM-DD
bill_type否ALL 全部(默认)/ SUCCESS 成功 / REFUND 退款
tar_type否GZIP 压缩包(默认)/ NONE 原始 CSV
compress_type否数据压缩格式,一般不传

应答:

{
  "download_bill_count": "2",
  "trade_bill": {
    "hash_type": "SHA256",
    "hash_value": "3706613c...",
    "download_url": "https://api.mch.weixin.qq.com/v3/billdownload/file?..."
  }
}

三、申请资金账单

GET https://api.mch.weixin.qq.com/v3/bill/fundbill?bill_date=2026-12-01&account_type=ALL&tar_type=GZIP

多一个 account_type:BASIC 基本账户 / OPERATION 运营账户 / ALL 全部;应答里的 fund_bill 同样含 hash_type/hash_value/download_url。

四、下载账单文件

  • 对 download_url 发起 GET 即可(微信侧已签名的临时链接,无需再带 Authorization 头)
  • tar_type=GZIP 时先解压得到 CSV;CSV 首行是账单说明,第二行起是表头+数据
  • 交易账单关键列:交易时间、微信订单号、商户订单号、交易类型、交易状态、应结订单金额、退款单号、申请退款金额、手续费
文件结构(GZIP):
bill_20261201_ALL.zip
└── bill_20261201_ALL.csv      # 标题行 + 表头行 + 明细行

五、账单完整性校验(别跳过)

下载后对账单文件本体算哈希,与申请接口返回的 hash_value 比对,防止下载被篡改:

// hash_type 为 SHA256 或 SM3
$hash = hash('sha256', file_get_contents($billFile));   // 与 hash_value 比对
if (! hash_equals($expectedHash, $hash)) {
    throw new RuntimeException('账单校验失败,文件可能损坏');
}

六、ThinkPHP 8 服务封装

<?php
namespace appservice;

use thinkfacadeDb;

class BillService extends WxPayService
{
    // 申请交易账单,返回下载信息
    public function tradeBill(string $billDate, string $type = 'ALL'): array
    {
        $url = 'https://api.mch.weixin.qq.com/v3/bill/tradebill?' . http_build_query([
            'bill_date' => $billDate,
            'bill_type' => $type,          // ALL / SUCCESS / REFUND
            'tar_type'  => 'GZIP',
        ]);
        $resp = $this->request('GET', $url);
        return $resp['trade_bill'] ?? [];    // hash_type / hash_value / download_url
    }

    // 下载 + 校验 + 归档
    public function download(string $downloadUrl, string $hash, string $saveTo): string
    {
        $raw = file_get_contents($downloadUrl);          // 无需签名头
        if (! hash_equals($hash, hash('sha256', $raw))) {
            throw new RuntimeException('账单哈希校验失败');
        }
        file_put_contents($saveTo, $raw, LOCK_EX);
        return $saveTo;                                  // .zip 需再解压
    }

    // 账单登记(MySQL 8)
    public function record(string $billDate, string $billType, string $hash, string $file): void
    {
        Db::name('pay_bill')->replace([
            'bill_date'  => $billDate,
            'bill_type'  => $billType,
            'hash_value' => $hash,
            'file_path'  => $file,
            'status'     => 1,
            'download_time' => date('Y-m-d H:i:s'),
        ]);
    }
}
CREATE TABLE pay_bill (
  id            BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
  bill_date     DATE        NOT NULL,
  bill_type     VARCHAR(10) NOT NULL COMMENT 'ALL/SUCCESS/REFUND',
  hash_value    VARCHAR(128) NOT NULL,
  file_path     VARCHAR(255) NOT NULL,
  status        TINYINT NOT NULL DEFAULT 1 COMMENT '1已下载 2已对账',
  download_time DATETIME NOT NULL,
  UNIQUE KEY uk_bill (bill_date, bill_type)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='账单归档';

七、小案例:每日自动下载与对账命令

<?php
namespace appcommand;

use appserviceBillService;
use thinkconsoleCommand;
use thinkconsoleInput;
use thinkconsoleOutput;
use thinkconsoleinputArgument;

class BillDownload extends Command
{
    protected function configure()
    {
        $this->setName('bill:download')
             ->addArgument('date', Argument::OPTIONAL, '账单日期 Y-m-d(默认昨天)');
    }

    protected function execute(Input $input, Output $output)
    {
        $date = $input->getArgument('date') ?: date('Y-m-d', strtotime('-1 day'));
        $svc  = new BillService();

        $bill = $svc->tradeBill($date, 'ALL');
        if (empty($bill['download_url'])) {
            $output->writeln("<comment>{$date} 账单未生成(T+1),稍后重试</comment>");
            return;
        }

        $file = ROOT_PATH . 'runtime/bill/bill_' . $date . '.zip';
        $svc->download($bill['download_url'], $bill['hash_value'], $file);
        $svc->record($date, 'ALL', $bill['hash_value'], $file);

        $output->writeln("<info>{$date} 账单已下载并通过哈希校验</info>");
    }
}
# 注册到 config/console.php 后,挂 crontab 每天上午拉前一天账单
30 9 * * * cd /www/wwwroot/shop && php think bill:download

对账要点:解压 CSV 后按商户订单号与 pay_order 核对——金额(应结订单金额 vs total_fee)、状态(SUCCESS/REFUND vs status)、手续费入账;差异记录到对账差异表人工复核。

八、总结

下载账单三步:申请(tradebill/fundbill,T+1)→ 下载(download_url 免签名)→ 校验(hash_type/hash_value);bill_date 查历史、bill_type 分全量/成功/退款;TP8 里封装 BillService + bill:download 命令挂 crontab;账单入库后与 pay_order 对账是财务闭环的最后一步。

梦想在远方闪烁,脚步则需踏实前行。

评论交流

0 条评论 · 支持多级回复
验证码
暂无评论,来说说你的想法吧

相关文章

继续阅读