天天看點

java下載下傳支付寶對賬單,實作與支付寶實收對賬和日清日結對賬

java實作與支付寶實收對賬和日清日結對賬,主要三步驟:

一、擷取支付寶參數

String  appid= "您的APP ID";
String alipayPrivateKey="您的支付寶私鑰";//注意:不是應用私鑰
String alipayPublicKey="您的支付寶公鑰";//注意:不是應用共鑰
String signType ="RSA";//不是MD5,也不是RSA2
           

二、擷取支付寶賬單下載下傳位址

public static String getBillDownloadUrl() {
String appid= "您的APP ID"; 
String alipayPrivateKey="您的支付寶私鑰";//注意:不是應用私鑰 
String alipayPublicKey="您的支付寶公鑰";//注意:不是應用共鑰 
String signType ="RSA";//不是MD5,也不是RSA2
    AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do", appid, alipayPrivateKey, "json", "UTF-8", alipayPublicKey, signType);//獲得初始化的AlipayClient
    AlipayDataDataserviceBillDownloadurlQueryRequest request = new AlipayDataDataserviceBillDownloadurlQueryRequest();//建立API對應的request類
    request.setBizContent("{" +
            "    \"bill_type\":\"trade\"," +
            "    \"bill_date\":\"2019-04\"}"); //設定業務參數
    AlipayDataDataserviceBillDownloadurlQueryResponse response = null;//通過alipayClient調用API,獲得對應的response類
    try {
        response = alipayClient.execute(request);
    } catch (AlipayApiException e) {
        e.printStackTrace();
    }
    System.out.println(response.getBillDownloadUrl());
    return  response.getBillDownloadUrl();
}
           

運作後,會傳回如下位址:

 http://dwbillcenter.alipay.com/downloadBillFile.resource?bizType=trade&userId=2088***&fileType=csv.zip&bizDates=201904&downloadFileName=2088221672***_201904.csv.zip&fileId=%2Ftrade%2F2088221***%2F201904.csv.zip&timestamp=1557848347&token=6e06b4***42dcd3b1

三、下載下傳賬單并解析下載下傳檔案,實作實收對賬

實收對賬,指支付寶賬單與系統中記錄的賬單進行對比,這個跟具體業務有關,這裡就不說明。

重點事項下載下傳并解析下載下傳檔案,為字元串。

public  void downConentBill() throws Exception {
        String alipay_url =this.getBillDownloadUrl();
        String filename=getDownloadFileName(alipay_url);

        String down_url = "f:\\alipaybill\\"+filename+".zip";
        /*
         * 通過調用支付寶接口傳回的url下載下傳zip檔案
         */
        boolean down_success = downLoadZip(alipay_url,down_url);
        String connetall = "";

        //true or  false 下載下傳成功,調用解壓方法
        if(down_success){
            File save_down_url = new File(down_url);
            /*
             * 解壓下載下傳的zip檔案
             */
//            String unzipFilePath = comZipCvsFile(save_down_url);

            /*
             * 讀取下載下傳的zip檔案,傳回一個string字元串
             */
            connetall = readZipToString(save_down_url);
        }
        /* 傳回結果
         * 1.false,下載下傳失敗
         * 2.空字元串||"false"。解壓或者讀取轉string失敗
         */
        //return connetall;
    }
           
/**
 * 通過支付寶查詢對賬單接口傳回的url,下載下傳zip檔案
 * @param alipay_url
 * @param down_url
 * @return
 */
public static boolean downLoadZip(String alipay_url,String down_url) {
    boolean down_success = false;
    int bytesum = 0;
    int byteread = 0;
    Date date = new Date();
    SimpleDateFormat sf = new SimpleDateFormat("yyyy/MM/dd");
    String dateFloder = sf.format(date);

    InputStream inStream = null;
    FileOutputStream fs = null;

    try {

        URL url = new URL(alipay_url);
        URLConnection conn = url.openConnection();
        inStream = conn.getInputStream();

        //自定義檔案儲存位址
        String unzipFilePath =  down_url.substring(0, down_url.lastIndexOf("\\"));//判斷下載下傳儲存路徑檔案夾

        File unzipFileDir = new File(unzipFilePath);//下載下傳檔案存放位址
        if (!unzipFileDir.exists() || !unzipFileDir.isDirectory()) {
            unzipFileDir.mkdirs();
        }
        //解壓檔案是否已存在
        File entryFile = new File(down_url);
        if (entryFile.exists()) {
            //删除已存在的目标檔案
            entryFile.delete();
        }

        fs = new FileOutputStream(down_url);

        byte[] buffer = new byte[4028];

        while ((byteread = inStream.read(buffer)) != -1) {
            bytesum += byteread;
            fs.write(buffer, 0, byteread);
        }
        down_success = true;
        System.out.println(dateFloder+"檔案下載下傳成功.....");
    } catch (Exception e) {
        System.out.println(dateFloder+"檔案下載下傳失敗" + e);

        return false;
    } finally {
        try {
            if (inStream != null) {
                inStream.close();
            }
        } catch (IOException e) {
            inStream = null;
        }

        try {
            if (fs != null) {
                fs.close();
            }
        } catch (IOException e) {
            fs = null;
        }
    }
    return down_success;
}
           
/**
 * 讀取zip檔案,不解壓縮直接解析,支援檔案名中文,解決内容亂碼
 * @param file
 * @return   讀取zip檔案,傳回字元串
 * @throws Exception
 */
@SuppressWarnings("unchecked")
public static  String readZipToString(File file) throws Exception {
    String connet = "";
    try {

        //獲得輸入流,檔案為zip格式,
        //支付寶提供
        //20886126836996110156_20160906.csv.zip内包含
        //20886126836996110156_20160906_業務明細.csv
        //20886126836996110156_20160906_業務明細(彙總).csv
        ZipInputStream in = new ZipInputStream(new FileInputStream(file));
        //不解壓直接讀取,加上gbk解決亂碼問題
        BufferedReader br = new BufferedReader(new InputStreamReader(in,"gbk"));
        ZipEntry zipFile;
        //傳回的字元串---每個檔案内容相加
        BufferedWriter bw = null;
        //循環讀取zip中的cvs檔案,無法使用jdk自帶,因為檔案名中有中文
        while ((zipFile=in.getNextEntry())!=null) {
            if (zipFile.isDirectory()){
                //如果是目錄,不處理
            }
            String file_connet = "";
            //獲得cvs名字
            String fileName = zipFile.getName();
            System.out.println("-----"+fileName);
            //檢測檔案是否存在
            if (fileName != null && fileName.indexOf(".") != -1) {
                String line;
                /*
                 * 1.每一行用 | 隔開
                 * 2.每一個檔案用 ; 隔開
                 */
                //  bw = new BufferedWriter(new FileWriter("d:\\test\\test.txt")); //測試讀取内容
                while ((line = br.readLine()) != null) {

                    file_connet = file_connet + "|" + line;
                    // System.out.println(line);

                }
            }

            connet = connet + file_connet + ";";
        }
        //  bw.write(connet);
        //關閉流
        //  bw.close();
        br.close();
        in.close();


    } catch (Exception e) {
        System.out.println("zip檔案讀取失敗" + e);

        return "false";
    }

    return connet;
}
           

源碼下載下傳

繼續閱讀