微信V3账单下载-文件流转excel

问题描述

       1、从接口 微信支付-开发者文档 拿到download_url 后应如何操作,如何下载.gzip压缩包,或者导出为excel文件,折腾了很久,微信文档写的不够详尽,将今天的踩的坑记录一下,以备后期取用。

{
	"download_url": "https://api.mch.weixin.qq.com/v3/billdownload/file?token=6XIv5TUPto7pByrTQKhd6kwvyKLG2uY2wMMR8cNXqaA_Cv_isgaUtBzp4QtiozLO",
	"hash_type": "SHA1",
	"hash_value": "8823044c286bea726f149bfcfce0b0318122d755"
}

解决方法

 function downloadBills($download_url)
    {
        //https://api.mch.weixin.qq.com/v3/billdownload/file?token=I57jwoqQ0Doq-HEH4_FnrsjXmU8h0OsZAXh9xQa9bf2ojSwhVOym2kw0zWPoM3Nm&tartype=gzip
        $urlArr = explode('?token=', $download_url);
        $urlArr2 = explode('&tartype=', $urlArr[1]);
        $token =  $urlArr2[0];

        $filename = '账单';
        try {
            $resp = $this->payInstance->chain('v3/billdownload/file')->get([
                'query' => [
                    'token' => $token,
                ],
                'headers' => [
                    'Accept' => 'application/json',
                ],
            ]);
         
            header("Content-type:application/vnd.ms-excel");
            header("Content-Disposition: attachment; filename={$filename}-". date('Y-m-d')  .".csv");
            echo $resp->getBody()."\n";

        } catch (\Exception $e) {
            echo $e->getMessage() . "\n
";
            if ($e->hasResponse()) {
                echo $e->getResponse()->getStatusCode() . ' ' . $e->getResponse()->getReasonPhrase() . "\n";
                echo $e->getResponse()->getBody();
            }

        }

    }

        2、在 问题1 中调用微信“申请分账账单”接口拿到下载地址 download_url 后,直接调用 downloadBills 方法,可导出excel账单。

        注意:$this->payInstance 更换成自己的构造实例即可。如下图所示。

// 加载商户私钥
$this->merchantPrivateKeyInstance = Rsa::from($this->service_config['private_key_file_path'],Rsa::KEY_TYPE_PRIVATE);//private_key_file_path:商户API私钥
// 加载平台证书
$this->platformPublicKeyInstance = PemUtil::loadCertificate($this->service_config['certificate_file_path']);//certificate_file_path:微信支付平台证书
// 解析平台证书序列号
$this->platformCertificateSerial = PemUtil::parseCertificateSerialNo($this->platformPublicKeyInstance);

// 工厂方法构造一个实例
$this->payInstance = Builder::factory([
     'mchid'      => '53357899',
     'serial'     => '772B030C7585D333FAFF9F0DDA482E06C20233',//商户证书序列号
     'privateKey' => $this->merchantPrivateKeyInstance,
     'certs'      => [
         $this->platformCertificateSerial => $this->platformPublicKeyInstance,
     ],
]);

你可能感兴趣的:(php,excel,微信支付v3,微信分账账单下载)