JVAV - 对接支付宝- 下载对账单接口

支付宝的对接文档

https://opendocs.alipay.com/apis/02byuu

import com.alipay.api.AlipayClient;

public vid aliPayBills(String billDate, PayAccountConfig accountConfig) throws Exception {

        AlipayClient alipayClient = getInstance();
        AlipayDataDataserviceBillDownloadurlQueryRequest request = new AlipayDataDataserviceBillDownloadurlQueryRequest();
        Map<String, String> params = new HashMap<>();
        params.put("bill_type", "signcustomer");
        params.put("bill_date", billDate);
        request.setBizContent(JSON.toJSONString(params));
        AlipayDataDataserviceBillDownloadurlQueryResponse response = alipayClient.certificateExecute(request);
        if (response.isSuccess()) {
            String payBillsPath = aliPayBillsPath;
            //获取支付宝对账单URL(url有效时间为30秒)
            String url = response.getBillDownloadUrl();
            log.info("***************获取到的支付宝对账单的URL:" + url + "**********************");
            String newZip = payBillsPath + new Date().getTime() + ".zip";
            // 开始下载 (下载文件为zip)
            SaveFile.downloadNet(url, newZip, payBillsPath);
            //解压(解压后有两个文件,明细,明细汇总)
            SaveFile.unZip(newZip, payBillsPath);
            log.info("***************下载,解压完成**********************");
            //获取解压后的两个文件
            File[] fs = new File(payBillsPath).listFiles();
            //用来保存明细的数据
            ArrayList<String[]> csvList = new ArrayList<>();
            String fileName = "";
            //获取对账单明细(只需要处理明细文件)
            for (File file : fs) {
                if (!file.getAbsolutePath().contains("汇总") && !file.getAbsolutePath().contains("zip")) {
                    fileName = file.getAbsolutePath();
                    csvList = getFileCell(fileName);
                }
            }
            File file2 = new File(fileName);
            FileInputStream inputStream = new FileInputStream(file2);
            MultipartFile multipartFile = new MockMultipartFile(file2.getName(), file2.getName(), ContentType.APPLICATION_OCTET_STREAM.toString(), inputStream);
            String originalFilename = multipartFile.getOriginalFilename();
            OssUtil.uploadFile(bucketName, originalFilename, multipartFile, "/paybills");

            for (File file : fs) {
                if (file.isFile()) {
                    SaveFile.delFile(file.getAbsolutePath());
                } else {
                    SaveFile.delFolder(file.getAbsolutePath());
                }
            }
            return csvList;
        } else {
            System.out.println("调用失败");
            return null;
        }
    }

工具类:支护宝API请求初始化

public static AlipayClient getInstance() throws Exception {
        if (Instance == null) {
            synchronized (AlipayClient.class) {
                if (Instance == null) {
                    //构造client
                    CertAlipayRequest certAlipayRequest = new CertAlipayRequest();
                    //设置网关地址
                    certAlipayRequest.setServerUrl("https://openapi.alipay.com/gateway.do");
                    //设置应用Id
                    certAlipayRequest.setAppId(appId);
                    //设置应用私钥
                    certAlipayRequest.setPrivateKey(privateKey);
                    //设置请求格式,固定值json
                    certAlipayRequest.setFormat("json");
                    //设置字符集
                    certAlipayRequest.setCharset(CPayConfig.CHARSET);
                    //设置签名类型
                    certAlipayRequest.setSignType(CPayConfig.ALI_SIGN_TYPE);
                    //设置应用公钥证书路径
                    certAlipayRequest.setCertPath(appCertPath);
                    //设置支付宝公钥证书路径
                    certAlipayRequest.setAlipayPublicCertPath(aliPayCertPath);
                    //设置支付宝根证书路径
                    certAlipayRequest.setRootCertPath(aliPayRootCertPath);
                    //构造client
                    return new DefaultAlipayClient(certAlipayRequest);
                }
            }
        }
        return Instance;
    }

文件工具

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
import org.apache.commons.compress.archivers.zip.ZipFile;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Enumeration;
import java.util.zip.ZipEntry;

/**
 * 根据url下载文件到本地指定目录
 * 然后上传到服务器
 *
 * @Author stone
 * @Date 2020/07/21
 * @return
 */
@Slf4j
public class SaveFile {

    /**
     * 使用GBK编码可以避免压缩中文文件名乱码
     */
    private static final String CHINESE_CHARSET = "GBK";

    /**
     * 文件读取缓冲区大小
     */
    private static final int CACHE_SIZE = 1024;

    /**
     * 根据Url下载文件
     *
     * @param urlStr
     * @param fileName
     * @param savePath
     * @throws IOException
     */
    public static void downLoadFromUrl(String urlStr, String fileName,
                                       String savePath) throws IOException {
        URL url = new URL(urlStr);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        //设置超时间为3秒
        conn.setConnectTimeout(3 * 1000);
        //防止屏蔽程序抓取而返回403错误
        conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");

        //得到输入流
        InputStream inputStream = conn.getInputStream();
        //获取自己数组
        byte[] getData = readInputStream(inputStream);

        //文件保存位置
        File saveDir = new File(savePath);
        if (!saveDir.exists()) {
            saveDir.mkdir();
        }
        File file = new File(saveDir + File.separator + fileName);
        FileOutputStream fos = new FileOutputStream(file);
        fos.write(getData);
        if (fos != null) {
            fos.close();
        }
        if (inputStream != null) {
            inputStream.close();
        }
        log.info("info: {} download success ", url);
    }

    public static void delFile(String path) {
        File file = new File(path);
        if (!file.exists()) return;

        if (file.isFile() || file.list() == null) {
            file.delete();
            log.info("the file:{} has been deleted", file.getName());
        }
    }

    public static void delFolder(String folderPath) {
        try {
            delAllFile(folderPath); // 删除完里面所有内容
            String filePath = folderPath;
            filePath = filePath.toString();
            java.io.File myFilePath = new java.io.File(filePath);
            myFilePath.delete(); // 删除空文件夹
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public static boolean delAllFile(String path) {
        boolean flag = false;
        File file = new File(path);
        if (!file.exists()) {
            return flag;
        }
        if (!file.isDirectory()) {
            return flag;
        }
        String[] tempList = file.list();
        File temp = null;
        for (int i = 0; i < tempList.length; i++) {
            if (path.endsWith(File.separator)) {
                temp = new File(path + tempList[i]);
            } else {
                temp = new File(path + File.separator + tempList[i]);
            }
            if (temp.isFile()) {
                temp.delete();
            }
            if (temp.isDirectory()) {
                delAllFile(path + "/" + tempList[i]);// 先删除文件夹里面的文件
                delFolder(path + "/" + tempList[i]);// 再删除空文件夹
                flag = true;
            }
        }
        return flag;
    }

    /**
     * 从输入流中获取字节数组
     *
     * @param inputStream
     * @return
     * @throws IOException
     */
    public static byte[] readInputStream(InputStream inputStream) throws IOException {
        byte[] buffer = new byte[1024];
        int len = 0;
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        while ((len = inputStream.read(buffer)) != -1) {
            bos.write(buffer, 0, len);
        }
        bos.close();
        return bos.toByteArray();
    }

    public static void downloadNet(String path, String filePath,String filePath1)
            throws MalformedURLException {
        // 下载网络文件
        int bytesum = 0;
        int byteread = 0;

        URL url = new URL(path);

        //文件保存位置
        File saveDir = new File(filePath1);
        if (!saveDir.exists()) {
            saveDir.mkdir();
        }
        try {
            URLConnection conn = url.openConnection();
            InputStream inStream = conn.getInputStream();
            FileOutputStream fs = new FileOutputStream(filePath);

            byte[] buffer = new byte[1204];
            while ((byteread = inStream.read(buffer)) != -1) {
                bytesum += byteread;
                fs.write(buffer, 0, byteread);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    /**
     * 解压到指定目录
     *
     * @param zipFilePath
     * @param destDir
     * @throws Exception
     */
    public static void unZip(String zipFilePath, String destDir)
            throws Exception {

        ZipFile zipFile = new ZipFile(zipFilePath, CHINESE_CHARSET);
        Enumeration<?> emu = zipFile.getEntries();
        BufferedInputStream bis;
        FileOutputStream fos;
        BufferedOutputStream bos;
        File file, parentFile;
        ZipEntry entry;
        byte[] cache = new byte[CACHE_SIZE];
        while (emu.hasMoreElements()) {
            entry = (ZipEntry) emu.nextElement();
            if (entry.isDirectory()) {
                new File(destDir + entry.getName()).mkdirs();
                continue;
            }
            bis = new BufferedInputStream(zipFile.getInputStream((ZipArchiveEntry) entry));
            file = new File(destDir + entry.getName());
            parentFile = file.getParentFile();
            if (parentFile != null && (!parentFile.exists())) {
                parentFile.mkdirs();
            }
            fos = new FileOutputStream(file);
            bos = new BufferedOutputStream(fos, CACHE_SIZE);
            int nRead = 0;
            while ((nRead = bis.read(cache, 0, CACHE_SIZE)) != -1) {
                fos.write(cache, 0, nRead);
            }
            bos.flush();
            bos.close();
            fos.close();
            bis.close();
        }
        zipFile.close();
    }
}
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
只要是通过认证的支付帐户均可实现在线支付。方便快捷,设置好自己的帐户,就可以在线实时收款了。 内附ASP,PHP,NET示例 使用方法: 在获得到对应的接口代码后 1、打开Config.asp 配置文件好您的支付帐号,注意!!!必须是要通过身份认证的方能使用,收款手续费百分之三。 2、把ASP代码发布到IIS 服务器中,直接访问index.asp文件为网银行直连,访问alipay.asp是直接到就可以到支付的收银台 3、对支付成功的订单信息,进行数据库的操作。 返回的机制有两种: 一种 return_url 即时返回,此返回是get方式。 二种 notify_url 通知返回,此返回时post方式,进行服务器点对点的通知机制。 注意:返回的地址中不能自定义携带参数。例如 http://www.alipay.com/return_Alipay_Notify.asp?xx=test 更多有关返回机制及区别请查看文档。 4、如果获得返回信息 在指定的两种返回接收的文件中 get或post获得 例如:return_url:返回设置文件中的return_Alipay_Notify.asp, 商户网站中传递给支付的订单号码-------request("out_trade_no") , 价格-------request("price") notify_url:返回设置文件中的Alipay_Notify.asp, 商户网站中传递给支付的订单号码-------request("out_trade_no") , 价格-------request("price") 5、用这个你们开发的支付接口资金安全吗? 我们是正规合法注册的公司,是我们自己和支付签约后,为了方便更多的网友能便捷使用支付在线支付接口而开发的,并非赢利产品。付款是直接到达的您所设置的支付帐户的。 6、如果两种方式都设置,就要判断交易的订单是否有更新过,因为两种返回机制不同。可能同时返回、或者有先后,注意订单更新时候要判断订单不能个重复更新。 买家付完款(trade_status=TRADE_FINISHED)在此状 态下进行数据库的更新。并返回给支付success。若没有得到success。 如有疑问,请联系QQ:399051063.

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值