need:
Scheduled task: Count the actual income of the company's Alipay account every day (deducting handling fees)
process:
1. Call the Alipay interface to get the zip download address
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));
}
}
Tool class code:
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();
}
}