Java 支付宝对账功能(查询+文件下载+解压+遍历文件+读文件)

2024-02-13 01:32

本文主要是介绍Java 支付宝对账功能(查询+文件下载+解压+遍历文件+读文件),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

Java 支付宝对账功能(查询+文件下载+解压+遍历文件+读文件)

  • **需求**
  • **流程**
          • 1 、调用支付宝接口, 获取zip 下载地址
          • 2、工具类代码
          • 3、目录
          • 4、开发环境
          • 5、更新实际收益到本地数据库查询
          • C#实现支付宝对账

需求

定时任务:每天统计昨天的公司支付宝账户实际收益(扣除手续费)。

流程

1 、调用支付宝接口, 获取zip 下载地址
package com.ycmedia.task;import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayDataDataserviceBillDownloadurlQueryRequest;
import com.alipay.api.response.AlipayDataDataserviceBillDownloadurlQueryResponse;
import com.google.common.base.Splitter;
import com.ycmedia.constants.Constants;
import com.ycmedia.dao.TaskDao;
import com.ycmedia.entity.RealIncom;
import com.ycmedia.utils.FileUtil;
import com.ycmedia.utils.ReadCsv;import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;@Component
public class AliBillTask {@Autowiredprivate Environment env;SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");@Autowiredprivate TaskDao taskDao;@Scheduled(cron = "0 14 14 ? * *")public void runAlitask() throws Exception {downloadBill();}/*** 获取指定日期的账单*/public void downloadBill() throws Exception {// 将订单提交至支付宝AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do", Constants.ALI_APP_ID,Constants.ALI_PRIVATE_KEY, "json", "utf-8",Constants.ALI_DEV_PLAT_PUBLIC_KEY);AlipayDataDataserviceBillDownloadurlQueryRequest request = new AlipayDataDataserviceBillDownloadurlQueryRequest();JSONObject json = new JSONObject();json.put("bill_type", "trade");//昨天的数据json.put("bill_date", new DateTime().minusDays(1).toString("yyyy-MM-dd"));request.setBizContent(json.toString());AlipayDataDataserviceBillDownloadurlQueryResponse response = alipayClient.execute(request);if(response.isSuccess()){// 获取下载地址urlString url = response.getBillDownloadUrl();// 设置下载后生成Zip目录String filePath = env.getProperty("file.path");String newZip = filePath + new Date().getTime() + ".zip";// 开始下载FileUtil.downloadNet(url, newZip);// 解压到指定目录FileUtil.unZip(newZip, env.getProperty("file.zip.path"));// 遍历文件 获取需要的汇整csvFile[] fs = new File(env.getProperty("file.zip.path")).listFiles();RealIncom income = null;for (File file : fs) {if (file.getAbsolutePath().contains("汇总")) {Double money = ReadCsv.getMoney("", file.getAbsolutePath());income = new RealIncom();income.setDate(new Date());income.setMoney(money);taskDao.insertTodayMoney(income);}}// 插入成功, 删除csv 文件for (File file : fs) {file.delete();}}else{//如果账单不存在, 插入一条空数据到数据库RealIncom income= new RealIncom();income.setDate(new Date());income.setMoney(0.00);taskDao.insertTodayMoney(income);}if (response.isSuccess()) {System.out.println("调用成功");} else {System.out.println("调用失败");}System.out.println(JSON.toJSONString(response));}}
2、工具类代码
package com.ycmedia.utils;import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Enumeration;import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipFile;public class FileUtil {/*** 使用GBK编码可以避免压缩中文文件名乱码*/private static final String CHINESE_CHARSET = "GBK";/*** 文件读取缓冲区大小*/private static final int CACHE_SIZE = 1024;/*** 第一步: 把 支付宝生成的账单 下载到本地目录* * @param path*            支付宝资源url* @param filePath*            生成的zip 包目录* @throws MalformedURLException*/public static void downloadNet(String path, String filePath)throws MalformedURLException {// 下载网络文件int bytesum = 0;int byteread = 0;URL url = new URL(path);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();}}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(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();}}
3、目录

在这里插入图片描述

4、开发环境

在这里插入图片描述

5、更新实际收益到本地数据库查询
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.HashMap;public class ReadCsv {// public static void main(String[] args) {// try {//// BufferedReader reader=new BufferedReader(new InputStreamReader(new// FileInputStream("D:\\down\\1476771240197\\20884217298464250156_20160914_业务明细.csv"),"gbk"));// reader.read();//第一行信息,为标题信息,不用,如果需要,注释掉// String line = null;////// while((line=reader.readLine())!=null){// String item[] = line.split("\r\n");//CSV格式文件为逗号分隔符文件,这里根据逗号切分//// String last = item[item.length-1];//这就是你要的数据了//// if(last.contains(")")){// System.out.println(Double.valueOf(last.split(",")[12])-Double.valueOf(last.split(",")[22]));// }// }// } catch (Exception e) {// e.printStackTrace();// }// }public static HashMap<String, Double> getDetailOrder(String filePath) {HashMap<String, Double> map = new HashMap<String, Double>();try {BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(filePath), "gbk"));reader.read();// 第一行信息,为标题信息,不用,如果需要,注释掉String line = null;while ((line = reader.readLine()) != null) {String item[] = line.split("\r\n");// CSV格式文件为逗号分隔符文件,这里根据逗号切分String last = item[item.length - 1];// 这就是你要的数据了if (last.contains(")")) {map.put(last.split(",")[0],Double.valueOf(last.split(",")[12])- Double.valueOf(last.split(",")[22]));}}} catch (Exception e) {e.printStackTrace();}return map;}/*** 根绝类型获取指定行的数据* * @param type* @return*/public static Double getMoney(String type, String filePath) {Double money = null;try {BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(filePath), "gbk"));reader.read();//String line = null;while ((line = reader.readLine()) != null) {String item[] = line.split("\r\n");String last = item[item.length - 1];if (last.contains("合计")) {String[] strs = last.split(",");money = Double.valueOf(strs[strs.length - 1]);}}} catch (Exception e) {e.printStackTrace();}return money;}}
C#实现支付宝对账

C# 支付宝对账功能(查询+文件下载+解压+遍历文件+读文件)

这篇关于Java 支付宝对账功能(查询+文件下载+解压+遍历文件+读文件)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/704125

相关文章

Java图片压缩三种高效压缩方案详细解析

《Java图片压缩三种高效压缩方案详细解析》图片压缩通常涉及减少图片的尺寸缩放、调整图片的质量(针对JPEG、PNG等)、使用特定的算法来减少图片的数据量等,:本文主要介绍Java图片压缩三种高效... 目录一、基于OpenCV的智能尺寸压缩技术亮点:适用场景:二、JPEG质量参数压缩关键技术:压缩效果对比

Java调用C++动态库超详细步骤讲解(附源码)

《Java调用C++动态库超详细步骤讲解(附源码)》C语言因其高效和接近硬件的特性,时常会被用在性能要求较高或者需要直接操作硬件的场合,:本文主要介绍Java调用C++动态库的相关资料,文中通过代... 目录一、直接调用C++库第一步:动态库生成(vs2017+qt5.12.10)第二步:Java调用C++

springboot+dubbo实现时间轮算法

《springboot+dubbo实现时间轮算法》时间轮是一种高效利用线程资源进行批量化调度的算法,本文主要介绍了springboot+dubbo实现时间轮算法,文中通过示例代码介绍的非常详细,对大家... 目录前言一、参数说明二、具体实现1、HashedwheelTimer2、createWheel3、n

Mybatis 传参与排序模糊查询功能实现

《Mybatis传参与排序模糊查询功能实现》:本文主要介绍Mybatis传参与排序模糊查询功能实现,本文通过实例代码给大家介绍的非常详细,感兴趣的朋友跟随小编一起看看吧... 目录一、#{ }和${ }传参的区别二、排序三、like查询四、数据库连接池五、mysql 开发企业规范一、#{ }和${ }传参的

Java利用docx4j+Freemarker生成word文档

《Java利用docx4j+Freemarker生成word文档》这篇文章主要为大家详细介绍了Java如何利用docx4j+Freemarker生成word文档,文中的示例代码讲解详细,感兴趣的小伙伴... 目录技术方案maven依赖创建模板文件实现代码技术方案Java 1.8 + docx4j + Fr

SpringBoot首笔交易慢问题排查与优化方案

《SpringBoot首笔交易慢问题排查与优化方案》在我们的微服务项目中,遇到这样的问题:应用启动后,第一笔交易响应耗时高达4、5秒,而后续请求均能在毫秒级完成,这不仅触发监控告警,也极大影响了用户体... 目录问题背景排查步骤1. 日志分析2. 性能工具定位优化方案:提前预热各种资源1. Flowable

基于SpringBoot+Mybatis实现Mysql分表

《基于SpringBoot+Mybatis实现Mysql分表》这篇文章主要为大家详细介绍了基于SpringBoot+Mybatis实现Mysql分表的相关知识,文中的示例代码讲解详细,感兴趣的小伙伴可... 目录基本思路定义注解创建ThreadLocal创建拦截器业务处理基本思路1.根据创建时间字段按年进

Java编译生成多个.class文件的原理和作用

《Java编译生成多个.class文件的原理和作用》作为一名经验丰富的开发者,在Java项目中执行编译后,可能会发现一个.java源文件有时会产生多个.class文件,从技术实现层面详细剖析这一现象... 目录一、内部类机制与.class文件生成成员内部类(常规内部类)局部内部类(方法内部类)匿名内部类二、

SpringBoot实现数据库读写分离的3种方法小结

《SpringBoot实现数据库读写分离的3种方法小结》为了提高系统的读写性能和可用性,读写分离是一种经典的数据库架构模式,在SpringBoot应用中,有多种方式可以实现数据库读写分离,本文将介绍三... 目录一、数据库读写分离概述二、方案一:基于AbstractRoutingDataSource实现动态

Springboot @Autowired和@Resource的区别解析

《Springboot@Autowired和@Resource的区别解析》@Resource是JDK提供的注解,只是Spring在实现上提供了这个注解的功能支持,本文给大家介绍Springboot@... 目录【一】定义【1】@Autowired【2】@Resource【二】区别【1】包含的属性不同【2】@