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整合dubbo+zookeeper的详细过程

《Springboot整合dubbo+zookeeper的详细过程》本文讲解SpringBoot整合Dubbo与Zookeeper实现API、Provider、Consumer模式,包含依赖配置、... 目录Spring boot整合dubbo+zookeeper1.创建父工程2.父工程引入依赖3.创建ap

SQL server数据库如何下载和安装

《SQLserver数据库如何下载和安装》本文指导如何下载安装SQLServer2022评估版及SSMS工具,涵盖安装配置、连接字符串设置、C#连接数据库方法和安全注意事项,如混合验证、参数化查... 目录第一步:打开官网下载对应文件第二步:程序安装配置第三部:安装工具SQL Server Manageme

C#连接SQL server数据库命令的基本步骤

《C#连接SQLserver数据库命令的基本步骤》文章讲解了连接SQLServer数据库的步骤,包括引入命名空间、构建连接字符串、使用SqlConnection和SqlCommand执行SQL操作,... 目录建议配合使用:如何下载和安装SQL server数据库-CSDN博客1. 引入必要的命名空间2.

SpringBoot结合Docker进行容器化处理指南

《SpringBoot结合Docker进行容器化处理指南》在当今快速发展的软件工程领域,SpringBoot和Docker已经成为现代Java开发者的必备工具,本文将深入讲解如何将一个SpringBo... 目录前言一、为什么选择 Spring Bootjavascript + docker1. 快速部署与

Spring Boot spring-boot-maven-plugin 参数配置详解(最新推荐)

《SpringBootspring-boot-maven-plugin参数配置详解(最新推荐)》文章介绍了SpringBootMaven插件的5个核心目标(repackage、run、start... 目录一 spring-boot-maven-plugin 插件的5个Goals二 应用场景1 重新打包应用

SpringBoot+EasyExcel实现自定义复杂样式导入导出

《SpringBoot+EasyExcel实现自定义复杂样式导入导出》这篇文章主要为大家详细介绍了SpringBoot如何结果EasyExcel实现自定义复杂样式导入导出功能,文中的示例代码讲解详细,... 目录安装处理自定义导出复杂场景1、列不固定,动态列2、动态下拉3、自定义锁定行/列,添加密码4、合并

Spring Boot集成Druid实现数据源管理与监控的详细步骤

《SpringBoot集成Druid实现数据源管理与监控的详细步骤》本文介绍如何在SpringBoot项目中集成Druid数据库连接池,包括环境搭建、Maven依赖配置、SpringBoot配置文件... 目录1. 引言1.1 环境准备1.2 Druid介绍2. 配置Druid连接池3. 查看Druid监控

Java中读取YAML文件配置信息常见问题及解决方法

《Java中读取YAML文件配置信息常见问题及解决方法》:本文主要介绍Java中读取YAML文件配置信息常见问题及解决方法,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要... 目录1 使用Spring Boot的@ConfigurationProperties2. 使用@Valu

创建Java keystore文件的完整指南及详细步骤

《创建Javakeystore文件的完整指南及详细步骤》本文详解Java中keystore的创建与配置,涵盖私钥管理、自签名与CA证书生成、SSL/TLS应用,强调安全存储及验证机制,确保通信加密和... 目录1. 秘密键(私钥)的理解与管理私钥的定义与重要性私钥的管理策略私钥的生成与存储2. 证书的创建与

浅析Spring如何控制Bean的加载顺序

《浅析Spring如何控制Bean的加载顺序》在大多数情况下,我们不需要手动控制Bean的加载顺序,因为Spring的IoC容器足够智能,但在某些特殊场景下,这种隐式的依赖关系可能不存在,下面我们就来... 目录核心原则:依赖驱动加载手动控制 Bean 加载顺序的方法方法 1:使用@DependsOn(最直