百度360必应搜狗淘宝本站头条
当前位置:网站首页 > 编程字典 > 正文

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

toyiye 2024-06-21 12:18 8 浏览 0 评论

需求

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

流程

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 {
@Autowired
private Environment env;
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
@Autowired
private 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()){
// 获取下载地址url
String 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"));
// 遍历文件 获取需要的汇整csv
File[] 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();
}
}

更新实际收益到本地数据库查询

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;
}
}

相关推荐

为何越来越多的编程语言使用JSON(为什么编程)

JSON是JavascriptObjectNotation的缩写,意思是Javascript对象表示法,是一种易于人类阅读和对编程友好的文本数据传递方法,是JavaScript语言规范定义的一个子...

何时在数据库中使用 JSON(数据库用json格式存储)

在本文中,您将了解何时应考虑将JSON数据类型添加到表中以及何时应避免使用它们。每天?分享?最新?软件?开发?,Devops,敏捷?,测试?以及?项目?管理?最新?,最热门?的?文章?,每天?花?...

MySQL 从零开始:05 数据类型(mysql数据类型有哪些,并举例)

前面的讲解中已经接触到了表的创建,表的创建是对字段的声明,比如:上述语句声明了字段的名称、类型、所占空间、默认值和是否可以为空等信息。其中的int、varchar、char和decimal都...

JSON对象花样进阶(json格式对象)

一、引言在现代Web开发中,JSON(JavaScriptObjectNotation)已经成为数据交换的标准格式。无论是从前端向后端发送数据,还是从后端接收数据,JSON都是不可或缺的一部分。...

深入理解 JSON 和 Form-data(json和formdata提交区别)

在讨论现代网络开发与API设计的语境下,理解客户端和服务器间如何有效且可靠地交换数据变得尤为关键。这里,特别值得关注的是两种主流数据格式:...

JSON 语法(json 语法 priority)

JSON语法是JavaScript语法的子集。JSON语法规则JSON语法是JavaScript对象表示法语法的子集。数据在名称/值对中数据由逗号分隔花括号保存对象方括号保存数组JS...

JSON语法详解(json的语法规则)

JSON语法规则JSON语法是JavaScript对象表示法语法的子集。数据在名称/值对中数据由逗号分隔大括号保存对象中括号保存数组注意:json的key是字符串,且必须是双引号,不能是单引号...

MySQL JSON数据类型操作(mysql的json)

概述mysql自5.7.8版本开始,就支持了json结构的数据存储和查询,这表明了mysql也在不断的学习和增加nosql数据库的有点。但mysql毕竟是关系型数据库,在处理json这种非结构化的数据...

JSON的数据模式(json数据格式示例)

像XML模式一样,JSON数据格式也有Schema,这是一个基于JSON格式的规范。JSON模式也以JSON格式编写。它用于验证JSON数据。JSON模式示例以下代码显示了基本的JSON模式。{"...

前端学习——JSON格式详解(后端json格式)

JSON(JavaScriptObjectNotation)是一种轻量级的数据交换格式。易于人阅读和编写。同时也易于机器解析和生成。它基于JavaScriptProgrammingLa...

什么是 JSON:详解 JSON 及其优势(什么叫json)

现在程序员还有谁不知道JSON吗?无论对于前端还是后端,JSON都是一种常见的数据格式。那么JSON到底是什么呢?JSON的定义...

PostgreSQL JSON 类型:处理结构化数据

PostgreSQL提供JSON类型,以存储结构化数据。JSON是一种开放的数据格式,可用于存储各种类型的值。什么是JSON类型?JSON类型表示JSON(JavaScriptO...

JavaScript:JSON、三种包装类(javascript 包)

JOSN:我们希望可以将一个对象在不同的语言中进行传递,以达到通信的目的,最佳方式就是将一个对象转换为字符串的形式JSON(JavaScriptObjectNotation)-JS的对象表示法...

Python数据分析 只要1分钟 教你玩转JSON 全程干货

Json简介:Json,全名JavaScriptObjectNotation,JSON(JavaScriptObjectNotation(记号、标记))是一种轻量级的数据交换格式。它基于J...

比较一下JSON与XML两种数据格式?(json和xml哪个好)

JSON(JavaScriptObjectNotation)和XML(eXtensibleMarkupLanguage)是在日常开发中比较常用的两种数据格式,它们主要的作用就是用来进行数据的传...

取消回复欢迎 发表评论:

请填写验证码