Java微信支付对帐,微信账单下载并读取到实体Bean,并保存至数据库

2023-12-22 14:59

本文主要是介绍Java微信支付对帐,微信账单下载并读取到实体Bean,并保存至数据库,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

最近公司的项目需要微信对帐功能,这里展示了简单的微信账单下载并读取到数据库方法,有问题或者更好的想法的可以在评论区交流哟。

一、依赖

<!-- 微信支付 -->
<dependency><groupId>com.github.wechatpay-apiv3</groupId><artifactId>wechatpay-java</artifactId><version>0.2.12</version>
</dependency><!-- csv处理 -->
<dependency><groupId>com.opencsv</groupId><artifactId>opencsv</artifactId><version>5.9</version>
</dependency>

二、参考链接

https://pay.weixin.qq.com/docs/merchant/products/bill-download/development.html

https://opencsv.sourceforge.net/

三、详解

  1. 下载微信账单
    public boolean downloadTradeBill(String time, String filePath) {// time = "2023-11-16"; 事例// 获取交易账单RSAAutoCertificateConfig config = this.configManager.getConfig("payOrder");BillDownloadServiceExtension service = new BillDownloadServiceExtension.Builder().config(config).build();GetTradeBillRequest request = new GetTradeBillRequest();request.setBillDate(time);request.setBillType(BillType.ALL);request.setTarType(TarType.GZIP);DigestBillEntity bill = service.getTradeBill(request);try (InputStream inputStream = bill.getInputStream()) {// 使用有缓存的 BufferedOutputStreamtry (BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(filePath))) {// 处理大文件时,常用的缓冲区大小为 8192 或 16384。// 不过,最佳缓冲区大小可能取决于具体的硬件和系统配置。byte[] buffer = new byte[16384];int bytesRead;while ((bytesRead = inputStream.read(buffer)) != -1) {outputStream.write(buffer, 0, bytesRead);}}} catch (IOException e) {throw new RuntimeException(e);}// 验证数据流中已读取数据的摘要if (bill.verifyHash()) {// 账单是完整准确,可以开启后续操作,例如完成每日对账。log.info("微信账单下载验证成功!");return true;} else {// 账单不完整或者被篡改,应清理之前保存的文件try {Path path = Paths.get(filePath);Files.delete(path);} catch (IOException e) {log.error(e.toString());}return false;}}

注意:RSAAutoCertificateConfig config = this.configManager.getConfig(“payOrder”);

请根据自身项目按照实际获取微信支付的RSAAutoCertificateConfig 。

注意:下载的文件格式为UTF-8 BOM 这里有坑,请一定小心

  1. 过滤微信账单的无用部分(完整详细账单格式请见:https://pay.weixin.qq.com/docs/merchant/products/bill-download/format-trade.html)
    在这里插入图片描述
	// 微信账单去除最后无用部分(最后两行汇总信息)private void removeUselessParts(String inputFilePath, String outputFilePath) {try (BufferedReader reader = new BufferedReader(new FileReader(inputFilePath, StandardCharsets.UTF_8));FileWriter writer = new FileWriter(outputFilePath, StandardCharsets.UTF_8)) {String line = null, line1 = null, line2 = null, line3 = null;int count = 0;while ((line = reader.readLine()) != null) {line3 = line2;line2 = line1;line1 = line;if (count < 2) {count++;} else {writer.write(line3 + "\n");}}} catch (IOException e) {logger.error(e.toString());}}
  1. 读取微信账单

微信支付账单实体Bean(可以按需获取,本例只引用了部分)

public class Bill extends BaseEntity {// 交易时间@CsvBindByPosition(position = 0, capture = "`(.*)")@CsvDate("yyyy-MM-dd HH:mm:ss")private Date tradingHours;// 微信订单号@CsvBindByPosition(position = 5, capture = "`(.*)")private String weChatOrderNumber;// 商户订单号@CsvBindByPosition(position = 6, capture = "`(.*)")private String merchantOrderNumber;// 交易状态@CsvBindByPosition(position = 9, capture = "`(.*)")private String transactionStatus;// 应结订单金额@CsvBindByPosition(position = 12, capture = "`(.*)")private String payableOrderAmount;// 微信退款单号@CsvBindByPosition(position = 14, capture = "`(.*)")private String weChatRefundNumber;// 商户退款单号@CsvBindByPosition(position = 15, capture = "`(.*)")private String merchantRefundNumber;// 退款金额@CsvBindByPosition(position = 16, capture = "`(.*)")private BigDecimal refundAmount;// 订单金额@CsvBindByPosition(position = 24, capture = "`(.*)")private BigDecimal amount;// 申请退款金额@CsvBindByPosition(position = 25, capture = "`(.*)")private BigDecimal requestRefundAmount;
}

读取微信账单csv文件

	public void readAndSaveWeChatTradeBill(String filePath) {InputStreamReader reader = null;try {reader = new InputStreamReader(new FileInputStream(filePath), StandardCharsets.UTF_8);CsvToBean<WeChatTradeBill> csvToBean = new CsvToBeanBuilder<WeChatTradeBill>(reader).withType(WeChatTradeBill.class).withSkipLines(1).build();// 使用迭代器读取并分步保存int count = 0;List<WeChatTradeBill> list = new ArrayList<>();for (WeChatTradeBill next : csvToBean) {count++;if (count % 100 == 0) {weChatTradeBillDao.saveAll(list);list = new ArrayList<>();} else {list.add(next);}}if (!CollectionUtils.isEmpty(list)) {weChatTradeBillDao.saveAll(list);}} catch (FileNotFoundException e) {throw new RuntimeException(e);} finally {try {assert reader != null;reader.close();} catch (IOException e) {logger.error(e.toString());}}}

四、完整参考

public void autoImportWeChatTradeBill(String date) {String time;if (date == null) {LocalDate threeDayAgo = LocalDate.now().minusDays(3L);time = threeDayAgo.format(DateTimeFormatter.ISO_LOCAL_DATE);} else {time = LocalDate.parse(date, DateTimeFormatter.ISO_DATE).format(DateTimeFormatter.ISO_DATE);}String downloadFilePath = System.getProperty("user.dir") + "\\" + time + "-wechat.csv";String updateFilePath = System.getProperty("user.dir") + "\\" + time + "-wechat-update.csv";// 尝试下载账单文件,并且去除最后无用部分int count = 0;while (count < 10) {count++;boolean b = wechatUtils.downloadTradeBill(time, downloadFilePath);if (b) {break;} else if (count >= 10) {logger.error("多次尝试,账单仍下载失败!!!");}}this.removeUselessParts(downloadFilePath, updateFilePath);// 解决this自调用事务失效问题WeChatTradeBillServiceImpl bean = applicationContext.getBean(WeChatTradeBillServiceImpl.class);bean.readAndSaveWeChatTradeBill(updateFilePath);// 删除之前下载的账单文件。removeOldDownloadFile(downloadFilePath);removeOldDownloadFile(updateFilePath);}// 删除下载的微信账单文件
private void removeOldDownloadFile(String filePath) {try {Path path = Paths.get(filePath);Files.delete(path);} catch (IOException e) {logger.error(e.toString());}
}

这篇关于Java微信支付对帐,微信账单下载并读取到实体Bean,并保存至数据库的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



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

相关文章

Spring Boot整合消息队列RabbitMQ的实现示例

《SpringBoot整合消息队列RabbitMQ的实现示例》本文主要介绍了SpringBoot整合消息队列RabbitMQ的实现示例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的... 目录RabbitMQ 简介与安装1. RabbitMQ 简介2. RabbitMQ 安装Spring

springMVC返回Http响应的实现

《springMVC返回Http响应的实现》本文主要介绍了在SpringBoot中使用@Controller、@ResponseBody和@RestController注解进行HTTP响应返回的方法,... 目录一、返回页面二、@Controller和@ResponseBody与RestController

JAVA集成本地部署的DeepSeek的图文教程

《JAVA集成本地部署的DeepSeek的图文教程》本文主要介绍了JAVA集成本地部署的DeepSeek的图文教程,包含配置环境变量及下载DeepSeek-R1模型并启动,具有一定的参考价值,感兴趣的... 目录一、下载部署DeepSeek1.下载ollama2.下载DeepSeek-R1模型并启动 二、J

springboot rocketmq配置生产者和消息者的步骤

《springbootrocketmq配置生产者和消息者的步骤》本文介绍了如何在SpringBoot中集成RocketMQ,包括添加依赖、配置application.yml、创建生产者和消费者,并展... 目录1. 添加依赖2. 配置application.yml3. 创建生产者4. 创建消费者5. 使用在

Spring Retry 实现乐观锁重试实践记录

《SpringRetry实现乐观锁重试实践记录》本文介绍了在秒杀商品SKU表中使用乐观锁和MybatisPlus配置乐观锁的方法,并分析了测试环境和生产环境的隔离级别对乐观锁的影响,通过简单验证,... 目录一、场景分析 二、简单验证 2.1、可重复读 2.2、读已提交 三、最佳实践 3.1、配置重试模板

Spring中@Lazy注解的使用技巧与实例解析

《Spring中@Lazy注解的使用技巧与实例解析》@Lazy注解在Spring框架中用于延迟Bean的初始化,优化应用启动性能,它不仅适用于@Bean和@Component,还可以用于注入点,通过将... 目录一、@Lazy注解的作用(一)延迟Bean的初始化(二)与@Autowired结合使用二、实例解

SpringBoot使用Jasypt对YML文件配置内容加密的方法(数据库密码加密)

《SpringBoot使用Jasypt对YML文件配置内容加密的方法(数据库密码加密)》本文介绍了如何在SpringBoot项目中使用Jasypt对application.yml文件中的敏感信息(如数... 目录SpringBoot使用Jasypt对YML文件配置内容进行加密(例:数据库密码加密)前言一、J

Java中有什么工具可以进行代码反编译详解

《Java中有什么工具可以进行代码反编译详解》:本文主要介绍Java中有什么工具可以进行代码反编译的相关资,料,包括JD-GUI、CFR、Procyon、Fernflower、Javap、Byte... 目录1.JD-GUI2.CFR3.Procyon Decompiler4.Fernflower5.Jav

Spring Boot 中正确地在异步线程中使用 HttpServletRequest的方法

《SpringBoot中正确地在异步线程中使用HttpServletRequest的方法》文章讨论了在SpringBoot中如何在异步线程中正确使用HttpServletRequest的问题,... 目录前言一、问题的来源:为什么异步线程中无法访问 HttpServletRequest?1. 请求上下文与线

在 Spring Boot 中使用异步线程时的 HttpServletRequest 复用问题记录

《在SpringBoot中使用异步线程时的HttpServletRequest复用问题记录》文章讨论了在SpringBoot中使用异步线程时,由于HttpServletRequest复用导致... 目录一、问题描述:异步线程操作导致请求复用时 Cookie 解析失败1. 场景背景2. 问题根源二、问题详细分