Java 实现微信和支付宝支付功能

时间:2021-10-26 05:52:13

一、前期准备

1、申请好微信商户号appid,拿到商户id和商户秘钥,退款的话需要商户证书
2、申请好支付宝商户号appid,商户公钥和秘钥(需要用支付宝工具自己生成),支付宝退款不需要证书

二、数据库表设计

1、微信支付配置表

  1. CREATE TABLE `py_wx_config` (
  2. `wx_config_id` varchar(18) NOT NULL COMMENT '微信支付配置ID',
  3. `appid` varchar(128) DEFAULT NULL COMMENT '微信公众号ID',
  4. `mch_id` varchar(128) DEFAULT NULL COMMENT '商户号ID',
  5. `mch_key_secret` varchar(2200) DEFAULT NULL COMMENT '商户安全密钥',
  6. `crt_path` varchar(200) DEFAULT NULL COMMENT '商户证书存放路径',
  7. `app_secret` varchar(2200) DEFAULT NULL COMMENT '公众号安全密钥',
  8. `create_id` varchar(18) DEFAULT NULL COMMENT '创建人',
  9. `create_time` datetime DEFAULT NULL COMMENT '创建时间',
  10. `upd_id` varchar(18) DEFAULT NULL COMMENT '修改人',
  11. `upd_time` datetime DEFAULT NULL COMMENT '修改时间',
  12. `delete_flag` tinyint(1) NOT NULL DEFAULT '0' COMMENT '删除标志',
  13. `app_code` varchar(18) NOT NULL COMMENT '商家编码',
  14. `bm_code` varchar(20) DEFAULT NULL COMMENT '部门编码',
  15. PRIMARY KEY (`wx_config_id`) USING BTREE
  16. ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 ROW_FORMAT=COMPACT COMMENT='微信支付配置';

2、微信小程序支付配置表

  1. CREATE TABLE `py_wx_min_config` (
  2. `wx_min_config_id` varchar(18) NOT NULL COMMENT '微信支付配置ID',
  3. `appid` varchar(128) DEFAULT NULL COMMENT '微信公众号ID',
  4. `mch_id` varchar(128) DEFAULT NULL COMMENT '商户号ID',
  5. `mch_key_secret` varchar(2200) DEFAULT NULL COMMENT '商户安全密钥',
  6. `crt_path` varchar(200) DEFAULT NULL COMMENT '商户证书存放路径',
  7. `app_secret` varchar(2200) DEFAULT NULL COMMENT '公众号安全密钥',
  8. `create_id` varchar(18) DEFAULT NULL COMMENT '创建人',
  9. `create_time` datetime DEFAULT NULL COMMENT '创建时间',
  10. `upd_id` varchar(18) DEFAULT NULL COMMENT '修改人',
  11. `upd_time` datetime DEFAULT NULL COMMENT '修改时间',
  12. `delete_flag` tinyint(1) NOT NULL DEFAULT '0' COMMENT '删除标志',
  13. `app_code` varchar(18) NOT NULL COMMENT '商家编码',
  14. `sys_software_code` varchar(18) DEFAULT NULL COMMENT '系统编码',
  15. PRIMARY KEY (`wx_min_config_id`) USING BTREE
  16. ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 ROW_FORMAT=COMPACT COMMENT='微信支付配置';

3、支付宝支付配置表

  1. CREATE TABLE `py_alipay_config` (
  2. `alipay_config_id` varchar(18) NOT NULL COMMENT '支付宝支付配置ID',
  3. `ali_private_key` varchar(2200) DEFAULT NULL COMMENT '支付宝密钥',
  4. `ali_public_key` varchar(2200) DEFAULT NULL COMMENT '支付宝公钥',
  5. `ali_appid` varchar(128) DEFAULT NULL COMMENT '支付宝appid',
  6. `create_id` varchar(18) DEFAULT NULL COMMENT '创建人',
  7. `create_time` datetime DEFAULT NULL COMMENT '创建时间',
  8. `upd_id` varchar(18) DEFAULT NULL COMMENT '修改人',
  9. `upd_time` datetime DEFAULT NULL COMMENT '修改时间',
  10. `delete_flag` tinyint(1) NOT NULL DEFAULT '0' COMMENT '删除标志',
  11. `app_code` varchar(18) NOT NULL COMMENT '商家编码',
  12. PRIMARY KEY (`alipay_config_id`) USING BTREE
  13. ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 ROW_FORMAT=COMPACT COMMENT='支付宝支付配置';

4、支付流水记录表

  1. CREATE TABLE `py_pay_log` (
  2. `pay_log_id` varchar(18) NOT NULL COMMENT '支付流水ID',
  3. `pay_no` varchar(20) DEFAULT NULL COMMENT '支付订单号',
  4. `third_id` varchar(64) DEFAULT NULL COMMENT '微信支付宝订单ID',
  5. `money_type` varchar(20) DEFAULT NULL COMMENT '支付类型 0-微信 1-支付宝 2-会员卡 3-银联',
  6. `mq_topic` varchar(100) DEFAULT NULL COMMENT 'MQ主题',
  7. `mq_status` tinyint(3) DEFAULT NULL COMMENT 'MQ发送状态 0-待发送 1-已发送 2-发送失败',
  8. `mq_remark` varchar(100) DEFAULT NULL COMMENT 'MQ发送备注',
  9. `request` text COMMENT '发送数据',
  10. `response` text COMMENT '返回数据',
  11. `fee` decimal(14,2) DEFAULT NULL COMMENT '订单金额',
  12. `create_id` varchar(18) DEFAULT NULL COMMENT '创建人',
  13. `create_time` datetime DEFAULT NULL COMMENT '创建时间',
  14. `upd_id` varchar(18) DEFAULT NULL COMMENT '修改人',
  15. `upd_time` datetime DEFAULT NULL COMMENT '修改时间',
  16. `delete_flag` tinyint(1) NOT NULL DEFAULT '0' COMMENT '删除标志',
  17. `app_code` varchar(18) NOT NULL COMMENT '商家编码',
  18. `pay_config_json_str` longtext COMMENT '支付配置',
  19. PRIMARY KEY (`pay_log_id`) USING BTREE
  20. ) ENGINE=MyISAM DEFAULT CHARSET=utf8mb4 ROW_FORMAT=DYNAMIC COMMENT='支付流水';

5、支付失败记录表

  1. CREATE TABLE `pay_fail_log` (
  2. `pay_id` varchar(18) NOT NULL,
  3. `json_date` varchar(500) DEFAULT NULL,
  4. `create_id` varchar(18) DEFAULT NULL,
  5. `create_time` datetime DEFAULT NULL,
  6. `update_id` varchar(18) DEFAULT NULL,
  7. `update_time` datetime DEFAULT NULL,
  8. `app_code` varchar(18) NOT NULL,
  9. `delete_flag` tinyint(1) DEFAULT '0' COMMENT '是否删除:0-否;1-是',
  10. PRIMARY KEY (`pay_id`) USING BTREE
  11. ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 ROW_FORMAT=COMPACT;

三、依赖引入

  1. <?xml version="1.0" encoding="UTF-8"?>
  2.  
  3. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  5.  
  6. <parent>
  7. <groupId>org.springframework.boot</groupId>
  8. <artifactId>spring-boot-starter-parent</artifactId>
  9. <version>2.1.3.RELEASE</version>
  10. <relativePath/> <!-- lookup parent from repository -->
  11. </parent>
  12.  
  13. <modelVersion>4.0.0</modelVersion>
  14. <groupId>com.pay</groupId>
  15. <artifactId>qc-payment</artifactId>
  16. <version>2.3</version>
  17. <name>qc-payment</name>
  18. <!-- FIXME change it to the project's website -->
  19. <url>http://www.example.com</url>
  20.  
  21. <properties>
  22. <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  23. <maven.compiler.source>1.7</maven.compiler.source>
  24. <maven.compiler.target>1.7</maven.compiler.target>
  25. <spring-cloud.version>Greenwich.SR1</spring-cloud.version>
  26. </properties>
  27.  
  28. <dependencies>
  29. <dependency>
  30. <groupId>org.springframework.boot</groupId>
  31. <artifactId>spring-boot-starter-data-redis</artifactId>
  32. </dependency>
  33. <dependency>
  34. <groupId>org.springframework.boot</groupId>
  35. <artifactId>spring-boot-starter-web</artifactId>
  36. </dependency>
  37. <dependency>
  38. <groupId>org.springframework.cloud</groupId>
  39. <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
  40. </dependency>
  41. <dependency>
  42. <groupId>org.springframework.cloud</groupId>
  43. <artifactId>spring-cloud-starter-netflix-zuul</artifactId>
  44. </dependency>
  45.  
  46. <!--z支付宝-->
  47. <dependency>
  48. <groupId>com.alipay.sdk</groupId>
  49. <artifactId>alipay-sdk-java</artifactId>
  50. <version>3.3.4.ALL</version>
  51. </dependency>
  52.  
  53. <dependency>
  54. <groupId>org.springframework.boot</groupId>
  55. <artifactId>spring-boot-starter-test</artifactId>
  56. <scope>test</scope>
  57. </dependency>
  58.  
  59. <!--导入重试机制的坐标-->
  60. <dependency>
  61. <groupId>org.springframework.retry</groupId>
  62. <artifactId>spring-retry</artifactId>
  63. </dependency>
  64.  
  65. <!--引入Hystrix依赖-->
  66. <dependency>
  67. <groupId>org.springframework.cloud</groupId>
  68. <artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
  69. </dependency>
  70.  
  71. <!--导入jwt相关依赖-->
  72. <dependency>
  73. <groupId>com.auth0</groupId>
  74. <artifactId>java-jwt</artifactId>
  75. <version>3.4.1</version>
  76. </dependency>
  77.  
  78. <!-- StringUtil 类-->
  79. <dependency>
  80. <groupId>org.apache.commons</groupId>
  81. <artifactId>commons-lang3</artifactId>
  82. <version>3.3.2</version>
  83. </dependency>
  84.  
  85. <!-- ali 连接池 -->
  86. <dependency>
  87. <groupId>com.alibaba</groupId>
  88. <artifactId>druid</artifactId>
  89. <version>1.1.12</version>
  90. </dependency>
  91.  
  92. <!-- mybatis -->
  93. <dependency>
  94. <groupId>org.mybatis.spring.boot</groupId>
  95. <artifactId>mybatis-spring-boot-starter</artifactId>
  96. <version>2.0.0</version>
  97. </dependency>
  98.  
  99. <!-- mysql -->
  100. <dependency>
  101. <groupId>mysql</groupId>
  102. <artifactId>mysql-connector-java</artifactId>
  103. </dependency>
  104. <dependency>
  105. <groupId>javax.persistence</groupId>
  106. <artifactId>persistence-api</artifactId>
  107. <version>1.0.2</version>
  108. </dependency>
  109. <!-- https://mvnrepository.com/artifact/tk.mybatis/mapper -->
  110. <dependency>
  111. <groupId>tk.mybatis</groupId>
  112. <artifactId>mapper</artifactId>
  113. <version>4.0.3</version>
  114. </dependency>
  115.  
  116. <!-- import lombok 可以省去getter setter toString等方法 -->
  117. <dependency>
  118. <groupId>org.projectlombok</groupId>
  119. <artifactId>lombok</artifactId>
  120. <scope>provided</scope>
  121. </dependency>
  122.  
  123. <!-- commons-io -->
  124. <dependency>
  125. <groupId>commons-io</groupId>
  126. <artifactId>commons-io</artifactId>
  127. <version>2.4</version>
  128. </dependency>
  129.  
  130. <!-- 引入easyqinyu-tools项目 -->
  131. <dependency>
  132. <groupId>com.pay</groupId>
  133. <artifactId>easyqinyu-tools</artifactId>
  134. <version>0.0.1-SNAPSHOT</version>
  135. </dependency>
  136.  
  137. <!-- pagehelper分页插件 -->
  138. <dependency>
  139. <groupId>com.github.pagehelper</groupId>
  140. <artifactId>pagehelper</artifactId>
  141. <version>5.1.2</version>
  142. </dependency>
  143.  
  144. <dependency>
  145. <groupId>com.github.pagehelper</groupId>
  146. <artifactId>pagehelper-spring-boot-autoconfigure</artifactId>
  147. <version>1.2.3</version>
  148. </dependency>
  149. <dependency>
  150. <groupId>com.github.pagehelper</groupId>
  151. <artifactId>pagehelper-spring-boot-starter</artifactId>
  152. <version>1.2.3</version>
  153. </dependency>
  154. <dependency>
  155. <groupId>com.qcsoft</groupId>
  156. <artifactId>qc-swagger-ui</artifactId>
  157. <version>0.0.1-SNAPSHOT</version>
  158. <scope>compile</scope>
  159. </dependency>
  160. <dependency>
  161. <groupId>com.google.zxing</groupId>
  162. <artifactId>core</artifactId>
  163. <version>3.3.0</version>
  164. </dependency>
  165.  
  166. <dependency>
  167. <groupId>com.alibaba</groupId>
  168. <artifactId>fastjson</artifactId>
  169. <version>RELEASE</version>
  170. <scope>compile</scope>
  171. </dependency>
  172.  
  173. <dependency>
  174. <groupId>org.apache.httpcomponents</groupId>
  175. <artifactId>httpclient</artifactId>
  176. <version>${httpclient.version}</version>
  177. </dependency>
  178.  
  179. <dependency>
  180. <groupId>com.google.code.gson</groupId>
  181. <artifactId>gson</artifactId>
  182. <version>2.8.2</version>
  183. </dependency>
  184.  
  185. <!--阿里云信息发送-->
  186. <dependency>
  187. <groupId>com.aliyun</groupId>
  188. <artifactId>aliyun-java-sdk-core</artifactId>
  189. <version>3.3.1</version>
  190. </dependency>
  191. <dependency>
  192. <groupId>com.github.1991wangliang</groupId>
  193. <artifactId>aliyun-java-sdk-dysmsapi</artifactId>
  194. <version>1.0.0</version>
  195. </dependency>
  196.  
  197. <dependency>
  198. <groupId>org.springframework.kafka</groupId>
  199. <artifactId>spring-kafka</artifactId>
  200. </dependency>
  201.  
  202. <!-- xml解析-->
  203. <dependency>
  204. <groupId>com.thoughtworks.xstream</groupId>
  205. <artifactId>xstream</artifactId>
  206. <version>1.4.10</version>
  207. </dependency>
  208.  
  209. <!-- dom4j -->
  210. <dependency>
  211. <groupId>org.dom4j</groupId>
  212. <artifactId>dom4j</artifactId>
  213. <version>2.1.1</version>
  214. </dependency>
  215.  
  216. <dependency>
  217. <groupId>com.github.binarywang</groupId>
  218. <artifactId>weixin-java-common</artifactId>
  219. <version>3.3.4.B</version>
  220. </dependency>
  221.  
  222. <dependency>
  223. <groupId>org.jodd</groupId>
  224. <artifactId>jodd-http</artifactId>
  225. <scope>compile</scope>
  226. </dependency>
  227.  
  228. <dependency>
  229. <groupId>org.apache.commons</groupId>
  230. <artifactId>commons-lang3</artifactId>
  231. </dependency>
  232.  
  233. <!-- xml解析-->
  234. <dependency>
  235. <groupId>commons-beanutils</groupId>
  236. <artifactId>commons-beanutils</artifactId>
  237. <version>1.9.3</version>
  238. </dependency>
  239.  
  240. <dependency>
  241. <groupId>jdom</groupId>
  242. <artifactId>jdom</artifactId>
  243. <version>1.0</version>
  244. </dependency>
  245.  
  246. <dependency>
  247. <groupId>org.bouncycastle</groupId>
  248. <artifactId>bcpkix-jdk15on</artifactId>
  249. <version>1.59</version>
  250. </dependency>
  251. <dependency>
  252. <groupId>org.jodd</groupId>
  253. <artifactId>jodd-http</artifactId>
  254. <version>3.7.1</version>
  255. </dependency>
  256. <!--二维码工具-->
  257. <dependency>
  258. <groupId>com.google.zxing</groupId>
  259. <artifactId>core</artifactId>
  260. <version>3.2.1</version>
  261. </dependency>
  262.  
  263. <dependency>
  264. <groupId>com.qcsoft</groupId>
  265. <artifactId>qc-commonbean</artifactId>
  266. <version>0.0.1-SNAPSHOT</version>
  267. </dependency>
  268.  
  269. <dependency>
  270. <groupId>org.springframework.cloud</groupId>
  271. <artifactId>spring-cloud-starter-openfeign</artifactId>
  272. </dependency>
  273. <!-- xxl-job-core -->
  274. <dependency>
  275. <groupId>com.xuxueli</groupId>
  276. <artifactId>xxl-job-core</artifactId>
  277. <version>2.0.1</version>
  278. </dependency>
  279. <!--线路跟踪-->
  280. <dependency>
  281. <groupId>org.springframework.cloud</groupId>
  282. <artifactId>spring-cloud-starter-netflix-hystrix-dashboard</artifactId>
  283. </dependency>
  284.  
  285. <dependency>
  286. <groupId>org.springframework.boot</groupId>
  287. <artifactId>spring-boot-starter-actuator</artifactId>
  288. </dependency>
  289. </dependencies>
  290.  
  291. <dependencyManagement>
  292. <dependencies>
  293. <dependency>
  294. <groupId>org.springframework.cloud</groupId>
  295. <artifactId>spring-cloud-dependencies</artifactId>
  296. <version>${spring-cloud.version}</version>
  297. <type>pom</type>
  298. <scope>import</scope>
  299. </dependency>
  300. </dependencies>
  301. </dependencyManagement>
  302. <build>
  303. <finalName>qc-payment</finalName>
  304. <plugins>
  305. <plugin>
  306. <groupId>org.springframework.boot</groupId>
  307. <artifactId>spring-boot-maven-plugin</artifactId>
  308. </plugin>
  309. <plugin>
  310. <groupId>org.apache.maven.plugins</groupId>
  311. <artifactId>maven-compiler-plugin</artifactId>
  312. <configuration>
  313. <source>8</source>
  314. <target>8</target>
  315. </configuration>
  316. </plugin>
  317. </plugins>
  318. </build>
  319. </project>

四、程序实现

1、Controller

  1. package com.qcsoft.payment.controller;
  2.  
  3. import com.alibaba.fastjson.JSON;
  4. import com.qcsoft.commonbean.bean.common.SwaggerConstant;
  5. import com.qcsoft.commonbean.bean.payment.common.PrePayResult;
  6. import com.qcsoft.commonbean.bean.payment.wx.bean.PreOrderParam;
  7. import com.qcsoft.commonbean.bean.payment.wx.exception.WxPayException;
  8. import com.qcsoft.commonbean.bean.payment.wx.util.QrcodeUtils;
  9. import com.qcsoft.easyqinyutools.message.ReturnMsg;
  10. import com.qcsoft.payment.controller.commom.BaseController;
  11. import com.qcsoft.payment.service.PayService;
  12. import com.qcsoft.swaggerui.anno.ApiTag;
  13. import org.slf4j.Logger;
  14. import org.slf4j.LoggerFactory;
  15. import org.springframework.beans.factory.annotation.Autowired;
  16. import org.springframework.web.bind.annotation.*;
  17.  
  18. import javax.imageio.ImageIO;
  19. import javax.servlet.http.HttpServletRequest;
  20. import javax.servlet.http.HttpServletResponse;
  21. import java.awt.image.BufferedImage;
  22. import java.io.IOException;
  23.  
  24. /**
  25. * @Description: 支付控制中心
  26. * @Author:
  27. * @Date:
  28. */
  29. @RestController
  30. @RequestMapping("/v2")
  31. public class PayController extends BaseController {
  32. private static final Logger logger = LoggerFactory.getLogger(PayController.class);
  33.  
  34. @Autowired
  35. private PayService payService;
  36.  
  37. //private final AtomicInteger tick = new AtomicInteger();
  38.  
  39. /**
  40. * 统一预支付接口(统一下单)
  41. *
  42. * @param orderParam {dh:订单号,payType:支付方式(WXPAY、ALIPAY、MEMBER_CARD、ACCOUNT),appCode:商家编码,
  43. * tradeType:支付方式类型(NATIVE、JSAPI、APP、MWEB),openId:支付方式为JSAPI必传,reqId:请求的真实IP地址
  44. * ,redirectUrl:支付成功返回地址,appCode:商家编码,outTradeNo:商务订单号,timeExpire,订单到期时间
  45. * ,totalAmount:订单金额,body:商品简单描述,subject:订单标题,quitUrl:中途退出}
  46. * @param token token
  47. * @return (微信公众号 / 小程序返回一串json字符串 : { appId :, timeStamp :, nonceStr : , info_package :, paySign :, signType : }, 前端使用微信sdk调用微信支付)
  48. * (微信扫码支付返回一个连接,前端需要把连接生成一个二维码使用,连接如:weixin://123.123.com/***)
  49. * (微信H5--返回一个连接,前端需要把连接生成一个连接前端直接跳转该连接使用,使用如:location.href='weixin://123.123.com/***')
  50. * (支付宝扫码支付--返回一个连接,前端直接跳转到该连接使用,使用如:location.href='weixin://123.123.com/***')
  51. * (支付宝扫码H5--返回一个页面form表单,前端需要把这个form表单渲染到h5页面上,使用如:$("#view).html(alipayForm)')
  52. * (支付宝app支付--返回一个参数包,如sdk-version=**&service=**&&service=**&&body=**&&out_trade_no=**&,前端使用支付宝sdk调用app支付')
  53. * {
  54. * wxNativeUrl:微信扫码地址
  55. * wxAppPackage:app支付sdk参数包
  56. * wxJsapiPackage:公众号支付包
  57. * wxH5Url:h5支付url
  58. * wxScanUrl:wxScanUrl
  59. * alipayScanUrl:支付宝扫码支付url
  60. * alipayH5Form:支付宝h5支付表单
  61. * alipayAppParamStr:支付宝app支付参数支付串
  62. * }
  63. * @throws WxPayException
  64. */
  65. @RequestMapping(value = "/prePayOrder")
  66. @ApiTag(SwaggerConstant.PAYMENT_001)
  67. public ReturnMsg prePayOrder(@RequestBody PreOrderParam orderParam) {
  68. String metadata = JSON.toJSONString(orderParam);
  69. logger.info("PayController.prePayOrder----\n正在请求支付....,参数为>>>>{}", metadata);
  70. ReturnMsg ret = new ReturnMsg();
  71. //预下单
  72. PrePayResult prePayResult = this.payService.payPreOrder(orderParam);
  73. ret.setData(prePayResult);
  74. return ret.success("下单成功,订单有效期为" + orderParam.getTimeExpire());
  75. }
  76.  
  77. /**
  78. * 生成支付二维码
  79. *
  80. * @param url 二维码地址
  81. * @throws IOException
  82. */
  83. @RequestMapping(value = "/createQrCode/url")
  84. @ApiTag(SwaggerConstant.PAYMENT_001)
  85. public void createQrCode(@PathVariable String url, HttpServletRequest request, HttpServletResponse response) throws IOException {
  86. String queryString = request.getQueryString();
  87. BufferedImage bufferedImage = QrcodeUtils.encode(url+queryString, 500, 500, null, null);
  88. BufferedImage grayImage = QrcodeUtils.grayImage(bufferedImage);
  89. ImageIO.write(grayImage, "png", response.getOutputStream());
  90. }
  91.  
  92. }

2、PayService

  1. package com.qcsoft.payment.service.impl;
  2.  
  3. import com.alibaba.fastjson.JSON;
  4. import com.alipay.api.AlipayClient;
  5. import com.qcsoft.commonbean.bean.common.KafkaConstant;
  6. import com.qcsoft.commonbean.bean.payment.ChinaumsConfig;
  7. import com.qcsoft.commonbean.bean.payment.PayLog;
  8. import com.qcsoft.commonbean.bean.payment.common.PayConstant;
  9. import com.qcsoft.commonbean.bean.payment.common.PrePayResult;
  10. import com.qcsoft.commonbean.bean.payment.common.WxPrePayResultPackage;
  11. import com.qcsoft.commonbean.bean.payment.wx.bean.PreOrderParam;
  12. import com.qcsoft.commonbean.bean.payment.wx.bean.request.WxPayUnifiedOrderRequest;
  13. import com.qcsoft.commonbean.bean.payment.wx.bean.result.WxPayUnifiedOrderResult;
  14. import com.qcsoft.commonbean.bean.payment.wx.config.WxPayConfig;
  15. import com.qcsoft.easyqinyutools.utils.JsonUtil;
  16. import com.qcsoft.payment.commns.exception.BaseException;
  17. import com.qcsoft.payment.commns.exception.QYError;
  18. import com.qcsoft.payment.commns.utils.UserUtil;
  19. import com.qcsoft.payment.commns.utils.weixin.PackageUtil;
  20. import com.qcsoft.payment.service.*;
  21. import org.apache.commons.lang3.StringUtils;
  22. import org.slf4j.Logger;
  23. import org.slf4j.LoggerFactory;
  24. import org.springframework.beans.factory.annotation.Autowired;
  25. import org.springframework.stereotype.Service;
  26.  
  27. import java.util.SortedMap;
  28. import java.util.TreeMap;
  29.  
  30. @Service
  31. public class PayServiceImpl implements PayService {
  32. public Logger logger = LoggerFactory.getLogger(getClass());
  33. @Autowired
  34. private AliPayService aliPayService;
  35. @Autowired
  36. private WxPayService wxPayService;
  37. @Autowired
  38. private ChinaumsPayService chinaumsPayService;
  39.  
  40. @Autowired
  41. private UserUtil userUtil;
  42. @Autowired
  43. private PayLogService payLogService;
  44.  
  45. @Override
  46. public PrePayResult payPreOrder(PreOrderParam orderParam) throws BaseException {
  47. logger.info("PayServiceImpl.payPreOrder---->>>>\n准备下单.....,当前用户订单号[{}]", orderParam.getDh());
  48. String temp = "";
  49. PrePayResult payResult = new PrePayResult();
  50. //校验支付方式
  51. String payType = orderParam.getPayType();
  52. if (!StringUtils.isNotBlank(payType))
  53. throw new BaseException(QYError.msg("请选择支付方式!"));
  54. if (PayConstant.WXPAY.toString().equals(payType)) {
  55. //查询商家配置信息
  56. WxPayConfig config;
  57. if (orderParam.getTradeType().equals(PayConstant.WECHATAPP.toString())) {
  58. config = wxPayService.getWxMinPayConfigByAppCode(orderParam.getAppCode(), orderParam.getSysSoftwareCode());
  59. } else {
  60. config = wxPayService.getWxPayConfigByAppCode(orderParam.getAppCode(), orderParam.getBmCode());
  61. }
  62. //设置预支付请求参数
  63. if (orderParam.getTradeType().equals(PayConstant.WECHATAPP.toString())) {
  64. orderParam.setTradeType(PayConstant.JSAPI.toString());
  65. }
  66. WxPayUnifiedOrderRequest requestParam = wxPayService.packRequestParam(orderParam);
  67. //开始请求预支付接口
  68. WxPayUnifiedOrderResult result = wxPayService.wxPrePay(config, requestParam);
  69. //根据支付类型设置值
  70. WxPrePayResultPackage resultPackage = null;
  71. if (orderParam.getTradeType().equals(PayConstant.APP.toString()) || orderParam.getTradeType().equals(PayConstant.JSAPI.toString()) || orderParam.getTradeType().equals(PayConstant.WECHATAPP.toString())) {
  72. resultPackage = new WxPrePayResultPackage();
  73. String timeMillis = PackageUtil.getTimeStamp();
  74. String nonceString = PackageUtil.getNonceStr();
  75. resultPackage.setAppId(result.getAppid());
  76. resultPackage.setNonceStr(nonceString);
  77. resultPackage.setTimeStamp(timeMillis);
  78. resultPackage.setPrePayId(result.getPrepayId());
  79. resultPackage.setInfoPackage("prepay_id=" + result.getPrepayId());
  80. resultPackage.setSignType(requestParam.getSignType());
  81. if (orderParam.getTradeType().equals(PayConstant.APP.toString())) {
  82. SortedMap<String, String> returnData = PackageUtil.getReturnData(resultPackage, config.getMchId());
  83. String paysign = PackageUtil.createSign(returnData, config.getMchKey());
  84. resultPackage.setPaySign(paysign);
  85. resultPackage.setInfoPackage(returnData.get("package"));
  86. payResult.setWxAppPackage(resultPackage);
  87. } else {
  88. SortedMap<String, String> paypackageParams = new TreeMap<String, String>();
  89. paypackageParams.put("appId", result.getAppid()); // appid
  90. paypackageParams.put("timeStamp", timeMillis); //
  91. paypackageParams.put("nonceStr", nonceString); //
  92. paypackageParams.put("package", resultPackage.getInfoPackage()); //
  93. paypackageParams.put("signType", resultPackage.getSignType());
  94. String paysign = PackageUtil.createSign(paypackageParams, config.getMchKey());
  95. resultPackage.setPaySign(paysign);
  96. payResult.setWxJsapiPackage(resultPackage);
  97. }
  98. } else if (orderParam.getTradeType().equals(PayConstant.MWEB.toString())) {
  99. payResult.setWxH5Url(result.getMwebUrl() + " &redirect_url=" + orderParam.getRedirectUrl());
  100. } else if (orderParam.getTradeType().equals(PayConstant.NATIVE.toString())) {
  101. payResult.setWxNativeUrl(result.getCodeURL());
  102. }
  103. //添加支付日志
  104. insertPayLog(orderParam, KafkaConstant.PAYMENT_NOTIFY_001.getTopic(), "0", resultPackage, JSON.toJSONString(config));
  105. return payResult;
  106. } else if (PayConstant.ALIPAY.toString().equals(payType)) {
  107. AlipayClient client = aliPayService.getAlipayClientByAppCode(orderParam.getAppCode());
  108. if (orderParam.getTradeType().equals(PayConstant.APP.toString())) {
  109. temp = aliPayService.aliAppPay(client, orderParam);
  110. payResult.setAlipayAppParamStr(temp);
  111. } else if (orderParam.getTradeType().equals(PayConstant.MWEB.toString())) {
  112. temp = aliPayService.aliH5Pay(client, orderParam);
  113. payResult.setAlipayH5Form(temp);
  114. } else if (orderParam.getTradeType().equals(PayConstant.NATIVE.toString())) {
  115. temp = aliPayService.aliScanPay(client, orderParam);
  116. payResult.setAlipayScanUrl(temp);
  117. }
  118. //添加支付日志
  119. insertPayLog(orderParam, KafkaConstant.PAYMENT_NOTIFY_001.getTopic(), "1", orderParam, JSON.toJSONString(aliPayService.getConfigByAppCode(orderParam.getAppCode())));
  120. return payResult;
  121. } else if (PayConstant.WECHATAPP.toString().equals(payType)) {
  122.  
  123. } else if (PayConstant.CHINAUMS.toString().equals(payType)) { //银联pos支付
  124. //查询商家配置信息
  125. ChinaumsConfig config;
  126. config = chinaumsPayService.getPayConfigByAppCode(orderParam.getAppCode(), orderParam.getBmCode());
  127. if (orderParam.getTradeType().equals(PayConstant.CODE_SCAN.toString())) {
  128. chinaumsPayService.codeScanPay(config, orderParam);
  129. }
  130. //添加支付日志
  131. insertPayLog(orderParam, KafkaConstant.PAYMENT_NOTIFY_001.getTopic(), "3", orderParam, JSON.toJSONString(config));
  132. return payResult;
  133. }
  134. logger.warn("用户未选择正确的支付方式");
  135. throw new BaseException(QYError.msg("请选择正确的支付方式!"));
  136.  
  137. }
  138.  
  139. public void insertPayLog(PreOrderParam orderParam, String topic, String moneyType, Object obj, String payConfigJsonStr) {
  140. PayLog payLog = new PayLog();
  141. payLog.setAppCode(orderParam.getAppCode());
  142. payLog.setPayLogId(orderParam.getDh());
  143. payLog.setMoneyType(moneyType);
  144. payLog.setMqTopic(topic);
  145. payLog.setMqStatus(0);
  146. payLog.setPayNo(orderParam.getDh());
  147. payLog.setRequest(JsonUtil.toJSon(obj));
  148. payLog.setFee(orderParam.getTotalAmount());
  149. payLog.setPayConfigJsonStr(payConfigJsonStr);
  150. payLogService.saveOrUpdate(payLog);
  151. }
  152. }

3、AliPayService

  1. package com.qcsoft.payment.service;
  2.  
  3. import com.alipay.api.AlipayClient;
  4. import com.alipay.api.request.AlipayTradeRefundRequest;
  5. import com.alipay.api.response.AlipayTradeQueryResponse;
  6. import com.alipay.api.response.AlipayTradeRefundResponse;
  7. import com.qcsoft.commonbean.bean.payment.AlipayConfig;
  8. import com.qcsoft.commonbean.bean.payment.alipay.AliPayRefundParam;
  9. import com.qcsoft.commonbean.bean.payment.common.PayNotify;
  10. import com.qcsoft.commonbean.bean.payment.wx.bean.PreOrderParam;
  11. import com.qcsoft.easyqinyutools.message.ReturnMsg;
  12.  
  13. import javax.servlet.http.HttpServletRequest;
  14. import java.util.Map;
  15.  
  16. public interface AliPayService {
  17. /**
  18. *
  19. * @param alipayClient
  20. * @param orderParam
  21. * @param
  22. * @return
  23. */
  24. String aliAppPay(AlipayClient alipayClient,PreOrderParam orderParam);
  25.  
  26. String aliScanPay(AlipayClient alipayClient, PreOrderParam orderParam);
  27.  
  28. String aliH5Pay(AlipayClient alipayClient, PreOrderParam orderParam);
  29.  
  30. void aliPayNotify(PayNotify params);
  31.  
  32. boolean rsaCheckV1(HttpServletRequest request,String appCode);
  33.  
  34. AlipayTradeQueryResponse aliPayOrderQuery(AlipayClient alipayClient, String out_trade_no);
  35.  
  36. AlipayClient getAlipayClientByAppCode(String appCode);
  37.  
  38. AlipayConfig getConfigByAppCode(String appCode);
  39.  
  40. /**
  41. * 支付宝退款接口
  42. * @param aliPayRefundParam
  43. * @return
  44. */
  45. ReturnMsg aliPayRefund(AliPayRefundParam aliPayRefundParam);
  46.  
  47. }

AliPayServiceImpl

  1. package com.qcsoft.payment.service.impl;
  2.  
  3. import com.alibaba.fastjson.JSON;
  4. import com.alipay.api.AlipayApiException;
  5. import com.alipay.api.AlipayClient;
  6. import com.alipay.api.DefaultAlipayClient;
  7. import com.alipay.api.domain.AlipayTradeAppPayModel;
  8. import com.alipay.api.domain.AlipayTradePrecreateModel;
  9. import com.alipay.api.domain.AlipayTradeRefundModel;
  10. import com.alipay.api.domain.AlipayTradeWapPayModel;
  11. import com.alipay.api.internal.util.AlipaySignature;
  12. import com.alipay.api.request.*;
  13. import com.alipay.api.response.*;
  14. import com.qcsoft.commonbean.bean.payment.AlipayConfig;
  15. import com.qcsoft.commonbean.bean.payment.alipay.AliPayRefundParam;
  16. import com.qcsoft.commonbean.bean.payment.common.PayConstant;
  17. import com.qcsoft.commonbean.bean.payment.common.PayNotify;
  18. import com.qcsoft.commonbean.bean.payment.wx.bean.PreOrderParam;
  19. import com.qcsoft.easyqinyutools.message.ReturnMsg;
  20. import com.qcsoft.payment.commns.exception.BaseException;
  21. import com.qcsoft.payment.commns.exception.QYError;
  22. import com.qcsoft.payment.commns.utils.DateUtils;
  23. import com.qcsoft.payment.commns.utils.RedisUtil;
  24. import com.qcsoft.payment.service.AliPayService;
  25. import com.qcsoft.payment.service.AlipayConfigService;
  26. import org.slf4j.Logger;
  27. import org.slf4j.LoggerFactory;
  28. import org.springframework.beans.factory.annotation.Autowired;
  29. import org.springframework.beans.factory.annotation.Value;
  30. import org.springframework.stereotype.Service;
  31.  
  32. import javax.servlet.http.HttpServletRequest;
  33. import java.net.URLEncoder;
  34. import java.util.Date;
  35. import java.util.HashMap;
  36. import java.util.Iterator;
  37. import java.util.Map;
  38.  
  39. /**
  40. * 支付宝相关业务实现类
  41. */
  42. @Service
  43. public class AliPayServiceImpl implements AliPayService {
  44. private static final Logger logger = LoggerFactory.getLogger(AliPayServiceImpl.class);
  45. @Autowired
  46. private AlipayConfigService alipayConfigService;
  47. @Autowired
  48. private RedisUtil redisUtil;
  49. @Value("${payNotifyUrl}")
  50. private String notifyUrl;
  51.  
  52. /**
  53. * APP支付
  54. * 参数加签
  55. */
  56. @Override
  57. public String aliAppPay(AlipayClient alipayClient, PreOrderParam orderParam) {
  58. logger.info("AliPayServiceImpl.aliAppPay--->>>\n支付宝预支付开始,\n支付类型为:APP支付,\n订单号为:{}", orderParam.getDh());
  59. Date date = new Date();
  60. AlipayTradeAppPayResponse response = null;
  61. // 发起App支付请求
  62. AlipayTradeAppPayModel model = new AlipayTradeAppPayModel();
  63. // 订单描述
  64. model.setBody(orderParam.getBody());
  65. // 订单标题
  66. model.setSubject(orderParam.getSubject());
  67. // 商户订单号 就是商户后台生成的订单号
  68. model.setOutTradeNo(orderParam.getOutTradeNo());
  69. // 该笔订单允许的最晚付款时间,逾期将关闭交易。取值范围:1m~15d。m-分钟,h-小时,d-天,1c-当天 (屁股后面的字母一定要带,不然报错)
  70. model.setTimeoutExpress(DateUtils.toString(date, orderParam.getTimeExpire()));
  71. // 订单总金额 ,默认单位为元,精确到小数点后两位,取值范围[0.01,100000000]
  72. model.setTotalAmount(orderParam.getTotalAmount().toString());
  73. // 销售产品码
  74. model.setProductCode(PayConstant.ALIPAY_QUICK_WAP_WAY.getKey());
  75. AlipayTradeAppPayRequest request = new AlipayTradeAppPayRequest();
  76. request.setBizModel(model);
  77. // request.setNotifyUrl("商户外网可以访问的异步地址,不写就是不回调");
  78. request.setNotifyUrl(notifyUrl + PayConstant.ALIPAY_05.getKey() + "/" + orderParam.getAppCode() + "/" + orderParam.getDh());
  79. //支付成功返回地址
  80. request.setReturnUrl(orderParam.getRedirectUrl());
  81. // 通过api的方法请求阿里接口获得反馈
  82. logger.info("AliPayServiceImpl.aliAppPay----->\n支付宝预支付接口请求信息:{}", JSON.toJSONString(request));
  83. try {
  84. response = alipayClient.sdkExecute(request);
  85. } catch (AlipayApiException e) {
  86. logger.info("AliPayServiceImpl.aliAppPay----->\n支付宝预下单失败,\n本次下单的订单号为:{},\n相关报错信息为:{}", orderParam.getDh(), response, e);
  87. throw new BaseException(QYError.msg("调用支付宝预下单接口失败![" + e.getMessage() + "]"));
  88. }
  89.  
  90. logger.info("AliPayServiceImpl.aliAppPay----->\n支付宝预支付接口返回信息:{}", JSON.toJSONString(response));
  91. if (response.isSuccess()) {
  92. logger.info("AliPayServiceImpl.aliAppPay----->\n支付宝预下单成功,\n本次下单的订单号为:{},商户订单号为:{}", orderParam.getDh(), orderParam.getOutTradeNo());
  93. } else {
  94. logger.error("AliPayServiceImpl.aliAppPay----->\n调用支付宝预下单接口失败!\n具体信息为:\n{}", response.getBody());
  95. throw new BaseException(QYError.msg("调用支付宝预下单接口失败![" + response.getMsg() + "]"));
  96. }
  97. return response.getBody();
  98. }
  99.  
  100. /**
  101. * 扫码支付
  102. * 参数加签
  103. */
  104. @Override
  105. public String aliScanPay(AlipayClient alipayClient, PreOrderParam orderParam) {
  106. logger.info("AliPayServiceImpl.aliScanPay--->>>\n支付宝预支付开始,\n支付类型为:扫码支付,\n订单号:{}", orderParam.getDh());
  107. /* AlipayTradePagePayResponse response = null;*/
  108. AlipayTradePrecreateResponse response = null;
  109. Date date = new Date();
  110. /**
  111. * 设置请求model参数(body、subject、outTradeNo、totalAmount、timeoutExpress;必传)
  112. */
  113. AlipayTradePrecreateModel model = new AlipayTradePrecreateModel();
  114. // 订单描述
  115. model.setBody(orderParam.getBody());
  116. // 订单标题
  117. model.setSubject(orderParam.getBody());
  118. // 商户订单号 就是商户后台生成的订单号
  119. model.setOutTradeNo(orderParam.getOutTradeNo());
  120. // 该笔订单允许的最晚付款时间,逾期将关闭交易。取值范围:1m~15d。m-分钟,h-小时,d-天,1c-当天 (屁股后面的字母一定要带,不然报错)
  121. model.setTimeoutExpress(orderParam.getTimeExpire());
  122. //model.setSellerId(DateUtils.toString(date, "yyyyMMddHHmmssSSS"));
  123. // 订单总金额 ,默认单位为元,精确到小数点后两位,取值范围[0.01,100000000]
  124. model.setTotalAmount(orderParam.getTotalAmount().toString());
  125. //model.setProductCode(PayConstant.ALIPAY_FAST_INSTANT_TRADE_PAY.getKey());
  126. // 选填
  127. /**
  128. * 创建支付宝扫码支付请求接口类,设置相关请求处理信息,准备请求下单
  129. */
  130. AlipayTradePrecreateRequest request = new AlipayTradePrecreateRequest();
  131. request.setBizModel(model);
  132. // request.setNotifyUrl("商户外网可以访问的异步地址,不写就是不回调");
  133. request.setNotifyUrl(notifyUrl + PayConstant.ALIPAY_05.getKey() + "/" + orderParam.getAppCode() + "/" + orderParam.getDh());
  134.  
  135. //支付成功返回地址
  136. request.setReturnUrl(orderParam.getRedirectUrl());
  137. // 通过api的方法请求阿里接口获得反馈 alipayClient.pageExecute(request)
  138. try {
  139. logger.info("支付宝扫码付请求报文:{}",JSON.toJSONString(request));
  140. response = alipayClient.execute(request)/**/;
  141. } catch (AlipayApiException e) {
  142. logger.info("AliPayServiceImpl.aliScanPay----->\n支付宝预下单失败,\n本次下单的订单号:{},\n相关报错信息为:{}", orderParam.getDh(), response, e);
  143. throw new BaseException(QYError.msg("调用支付宝预下单接口失败![" + e.getMessage() + "]"));
  144. }catch (Exception e){
  145. e.printStackTrace();
  146. throw new BaseException(QYError.msg("调用支付宝预下单接口失败![" + e.getMessage() + "]"));
  147. }
  148.  
  149. //打印返回信息
  150. logger.info("AliPayServiceImpl.aliScanPay----->\n支付宝预支付接口返回信息:{}", JSON.toJSONString(response));
  151. //判断预下单返回状态
  152. if (response.isSuccess()) {
  153. logger.info("AliPayServiceImpl.aliScanPay----->\n支付宝预下单成功,\n本次下单的订单号:{},商务订单号为", orderParam.getDh(), orderParam.getOutTradeNo());
  154. } else {
  155. logger.error("AliPayServiceImpl.aliScanPay----->\n调用支付宝预下单接口失败!\n具体信息:\n{}", response.getBody());
  156. throw new BaseException(QYError.msg("调用支付宝预下单接口失败![" + response.getMsg() + "]"));
  157. }
  158.  
  159. return response.getQrCode();
  160. }
  161.  
  162. /**
  163. * H5支付
  164. * 参数加签
  165. */
  166. @Override
  167. public String aliH5Pay(AlipayClient alipayClient, PreOrderParam orderParam) {
  168. logger.info("AliPayServiceImpl.aliH5Pay--->>>\n支付宝预支付开始,\n支付类型为:H5支付,\n订单号:{}", orderParam.getDh());
  169. String form = "";
  170. AlipayTradeWapPayResponse response = null;
  171. /**
  172. * 封装请求支付信息
  173. */
  174. AlipayTradeWapPayModel payModel = new AlipayTradeWapPayModel();
  175. payModel.setOutTradeNo(orderParam.getOutTradeNo());
  176. payModel.setSubject(orderParam.getBody());
  177. payModel.setTotalAmount(orderParam.getTotalAmount().toString());
  178. payModel.setBody(orderParam.getBody());
  179. payModel.setTimeoutExpress(orderParam.getTimeExpire());
  180. payModel.setProductCode(PayConstant.ALIPAY_QUICK_WAP_WAY.getKey());
  181. payModel.setQuitUrl(URLEncoder.encode(orderParam.getQuitUrl()));
  182. /**
  183. * 创建支付宝H5支付请求接口类,设置相关请求处理信息,准备请求下单
  184. */
  185. AlipayTradeWapPayRequest alipay_request = new AlipayTradeWapPayRequest();
  186. alipay_request.setBizModel(payModel);
  187. // 设置异步通知地址
  188. logger.info("通知地址{}", notifyUrl + PayConstant.ALIPAY_05.getKey() + "/" + orderParam.getAppCode() + "/" + orderParam.getDh());
  189. alipay_request.setNotifyUrl(notifyUrl + PayConstant.ALIPAY_05.getKey() + "/" + orderParam.getAppCode() + "/" + orderParam.getDh());
  190. // 设置同步地址
  191. alipay_request.setReturnUrl(URLEncoder.encode(orderParam.getRedirectUrl()));
  192. // 调用SDK生成表单
  193. try {
  194. response = alipayClient.pageExecute(alipay_request);
  195. if (response.isSuccess()) {
  196. form = response.getBody();
  197. logger.info("AliPayServiceImpl.aliH5Pay----->>>>\n支付宝预支付接口返回信息:{}", JSON.toJSONString(response));
  198. } else {
  199. logger.info("AliPayServiceImpl.aliH5Pay----->>>>\n支付宝预支付接口返回信息:{}", JSON.toJSONString(response));
  200. throw new BaseException(QYError.msg("支付宝"));
  201. }
  202.  
  203. } catch (AlipayApiException e) {
  204. logger.info("AliPayServiceImpl.aliH5Pay----->>>>\n支付宝预支付接口返回信息:{}", JSON.toJSONString(response));
  205. throw new BaseException(QYError.msg("调用支付宝预下单接口失败![" + e.getMessage() + "]"));
  206. }
  207. logger.info("AliPayServiceImpl.aliH5Pay----->>>>\n支付宝预支付接口返回信息:{}", JSON.toJSONString(response));
  208. /**
  209. * 打印日志,并返回链接
  210. */
  211. return form;
  212. }
  213.  
  214. /**
  215. * 支付宝通知
  216. *
  217. * @param params
  218. */
  219. @Override
  220. public void aliPayNotify(PayNotify params) {
  221. logger.info("AliPayServiceImpl.appAliPayNotify-\n阿里服务器消费手机回调参数获取和参数判断-------》》》");
  222. /**
  223. * 打印信息
  224. */
  225. //校验支付金额
  226. /*ReturnMsg returnMsg = restTemplate.postForEntity(params.getNoOrderAmountUrl(), params, ReturnMsg.class).getBody();
  227. if (!returnMsg.isSuccess()) {
  228. logger.info("WxPayController.wxPayNotify-->\n校验订单金额失败,请核实商务订单号:{}", params);
  229. throw new BaseException(QYError.msg("校验订单金额失败!商务订单号[" + params.getOutTradeNo() + "]"));
  230. }*/
  231. /**
  232. * 判断支付状态
  233. */
  234. if (params.getTradeStatus().equals("TRADE_SUCCESS")) {
  235. logger.info("AliPayServiceImpl.appAliPayNotify----\n支付宝支付成功!商务订单号[{}]----->>", params.getOutTradeNo(), JSON.toJSONString(params));
  236. } else {
  237. logger.error("AliPayServiceImpl.appAliPayNotify---\n支付宝支付失败!商务订单号[{}]---->>", params.getOutTradeNo());
  238. throw new BaseException(QYError.msg("支付宝支付失败!商务订单号[" + params.getOutTradeNo() + "]"));
  239. }
  240. }
  241.  
  242. @Override
  243. public boolean rsaCheckV1(HttpServletRequest request, String appCode) {
  244. //获取支付宝GET过来反馈信息
  245. Map<String, String> params = new HashMap<String, String>();
  246. // 签名验证(对支付宝返回的数据验证,确定是支付宝返回的)
  247. boolean result = false;
  248. try {
  249. // 从支付宝回调的request域中取值
  250. Map<String, String[]> requestParams = request.getParameterMap();
  251. for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
  252. String name = iter.next();
  253. String[] values = (String[]) requestParams.get(name);
  254. String valueStr = "";
  255. for (int i = 0; i < values.length; i++) {
  256. valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
  257. }
  258. params.put(name, valueStr);
  259. }
  260. logger.info("AliPayServiceImpl.appAliPayNotify--\n支付宝通知数据包----->>>>>>>>>>>>>>>{}", JSON.toJSONString(params));
  261. // 商家编码
  262.  
  263. AlipayConfig alipayConfig = getConfigByAppCode(appCode);
  264. result = AlipaySignature.rsaCheckV1(params, alipayConfig.getAliPublicKey(),
  265. PayConstant.ALIPAY_CHARSET.getKey(), PayConstant.ALIPAY_SIGN_TYPE_RSA2.getKey());
  266. } catch (Exception e) {
  267. logger.error("AliPayServiceImpl.appAliPayNotify---\n校验签名失败!商务订单号[{}]---->>", JSON.toJSONString(request), e);
  268. throw new BaseException(QYError.msg("支付宝支付校验签名失败!"));
  269. }
  270. return result;
  271. }
  272.  
  273. /**
  274. * 根据商务订单号查询查询支付信息
  275. *
  276. * @param alipayClient
  277. * @param out_trade_no
  278. * @return
  279. */
  280. @Override
  281. public AlipayTradeQueryResponse aliPayOrderQuery(AlipayClient alipayClient, String out_trade_no) {
  282. logger.info("AliPayServiceImpl.aliPayOrderQuery----\n根据商务订单号查询支付宝订单信息,\n商务订单号:[{}]----》》》", out_trade_no);
  283. AlipayTradeQueryResponse response = null;
  284. AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();
  285. //设置查询参数
  286. Map<String, String> bizModel = new HashMap<>();
  287. bizModel.put("out_trade_no", out_trade_no);
  288. request.setBizContent(JSON.toJSONString(bizModel));
  289. //开始查询
  290. try {
  291. response = alipayClient.execute(request);
  292. } catch (AlipayApiException e) {
  293. logger.error("AliPayServiceImpl.aliPayOrderQuery--->>\n支付宝订单查询失败,\n商务订单号:[{}]", out_trade_no);
  294. throw new BaseException(QYError.msg("订单号[" + out_trade_no + "],订单支付失败,状态码为[" + response.getTradeStatus() + "]"));
  295. }
  296.  
  297. logger.info("AliPayServiceImpl.aliPayOrderQuery---->>\n查询支付宝订单信息,\n商务订单号:[{}],\n返回信息:{}", out_trade_no, JSON.toJSONString(response));
  298. //查询状态处理
  299. if (response.isSuccess()) {
  300. logger.info("AliPayServiceImpl.aliPayOrderQuery--->>\n支付宝订单查询成功,\n商务订单号:[{}]", out_trade_no);
  301. } else {
  302. logger.error("AliPayServiceImpl.aliPayOrderQuery--->>\n支付宝订单查询失败,\n商务订单号:[{}]", out_trade_no);
  303. throw new BaseException(QYError.msg("订单号[" + out_trade_no + "],订单支付失败,状态码为[" + response.getTradeStatus() + "]"));
  304. }
  305.  
  306. return response;
  307. }
  308.  
  309. /**
  310. * 根据商家编码设置alipay配置信息
  311. *
  312. * @param appCode 商家编码
  313. * @return
  314. */
  315. @Override
  316. public AlipayClient getAlipayClientByAppCode(String appCode) {
  317. logger.info("AliPayServiceImpl.getAlipayClientByAppCode--->>\n获取支付宝配置信息:[{}]", appCode);
  318. AlipayConfig alipayConfig = null;
  319. /**
  320. * 获取商家支付宝配置信息(优先级:1-redis,2-mysql,3-用户系统)
  321. */
  322. try {
  323. alipayConfig = getConfigByAppCode(appCode);
  324. if (alipayConfig == null) {
  325. logger.info("AliPayServiceImpl.getAlipayClientByAppCode--->>\n获取支付宝支付配置信息失败:[{}]", appCode);
  326. logger.info("AliPayServiceImpl.getAlipayClientByAppCode--->>\n获取支付宝支付配置信息失败:[{}{}]", appCode,alipayConfig);
  327. throw new BaseException(QYError.msg("获取支付宝支付配置信息失败!"));
  328. }
  329. } catch (Exception e) {
  330. logger.error("AliPayServiceImpl.getAlipayClientByAppCode--->>\n获取支付宝配置信息失败:[{}]", e);
  331. throw new BaseException(QYError.msg("获取支付宝配置信息失败!"));
  332. }
  333. AlipayClient alipayClient = new DefaultAlipayClient(
  334. PayConstant.ALIPAY_01.getKey(),
  335. alipayConfig.getAliAppid(),
  336. alipayConfig.getAliPrivateKey(),
  337. PayConstant.ALIPAY_FORMAT.getKey(),
  338. PayConstant.ALIPAY_CHARSET.getKey(),
  339. alipayConfig.getAliPublicKey(),
  340. PayConstant.ALIPAY_SIGN_TYPE_RSA2.getKey());
  341. return alipayClient;
  342. }
  343.  
  344. //获取商家支付宝的配置信息
  345. public AlipayConfig getConfigByAppCode(String appCode) {
  346. AlipayConfig alipayConfig = alipayConfigService.selectByAppCode(appCode);
  347. return alipayConfig;
  348. }
  349.  
  350. /**
  351. * 支付宝退款接口
  352. * @param aliPayRefundParam
  353. * @return
  354. */
  355. public ReturnMsg aliPayRefund(AliPayRefundParam aliPayRefundParam){
  356. ReturnMsg returnMsg=new ReturnMsg();
  357.  
  358. String appCode=aliPayRefundParam.getAppCode();
  359. AlipayClient alipayClient = getAlipayClientByAppCode(appCode);
  360.  
  361. AlipayTradeRefundResponse response = null;
  362. AlipayTradeRefundModel model = new AlipayTradeRefundModel();
  363. //订单支付时传入的商户订单号,不能和 trade_no同时为空。
  364. model.setOutTradeNo(aliPayRefundParam.getOutTradeNo());
  365. //支付宝交易号,和商户订单号不能同时为空
  366. //model.setTradeNo(aliPayRefundParam.getTradeNo());
  367. //标识一次退款请求,同一笔交易多次退款需要保证唯一,如需部分退款,则此参数必传。
  368. model.setOutRequestNo(aliPayRefundParam.getOutRequestNo());
  369. // 需要退款的金额,该金额不能大于订单金额,单位为元,支持两位小数
  370. model.setRefundAmount(aliPayRefundParam.getRefundAmount());
  371. //退款的原因说明
  372. model.setRefundReason(aliPayRefundParam.getRefundReason());
  373.  
  374. /**
  375. * 创建支付宝扫码支付请求接口类,设置相关请求处理信息,准备请求下单
  376. */
  377. AlipayTradeRefundRequest request = new AlipayTradeRefundRequest();
  378. request.setBizModel(model);
  379. //商户外网可以访问的异步地址,不写就是不回调
  380. request.setNotifyUrl(notifyUrl + PayConstant.ALIPAY_05.getKey() + "/" + aliPayRefundParam.getAppCode() + "/" + aliPayRefundParam.getDh());
  381. //支付成功返回地址
  382. request.setReturnUrl(aliPayRefundParam.getRedirectUrl());
  383.  
  384. // 通过api的方法请求阿里接口获得反馈 alipayClient.pageExecute(request)
  385. try {
  386. logger.info("支付宝退款请求完整报文:{}",JSON.toJSONString(request));
  387. response = alipayClient.execute(request)/**/;
  388. } catch (AlipayApiException e) {
  389. logger.info("支付宝退款失败,\n本次下单的订单号:{},\n相关报错信息为:{}", aliPayRefundParam.getDh(), response, e);
  390. throw new BaseException(QYError.msg("调用支付宝预退款失败![" + e.getMessage() + "]"));
  391. }catch (Exception e){
  392. e.printStackTrace();
  393. throw new BaseException(QYError.msg("支付宝预退款失败![" + e.getMessage() + "]"));
  394. }
  395.  
  396. //打印返回信息
  397. logger.info("支付宝退款失败:{}", JSON.toJSONString(response));
  398. //判断预下单返回状态
  399. if (response.isSuccess()&&"Y".equals(response.getFundChange())) {
  400. logger.info("AliPayServiceImpl.aliScanPay----->\n支付宝退款成功,\n本次下单的订单号:{},商务订单号为,{}", aliPayRefundParam.getDh(), aliPayRefundParam.getOutTradeNo());
  401. return returnMsg.setData("退款成功");
  402.  
  403. } else {
  404. logger.error("AliPayServiceImpl.aliScanPay----->\n调用支付宝退款接口失败!\n具体信息:\n{}", response.getBody());
  405. throw new BaseException(QYError.msg("调用支付宝退款接口失败![" + response.getBody() + "]"));
  406. }
  407. }
  408.  
  409. }

4、WxPayService

  1. package com.qcsoft.payment.service;
  2.  
  3. import com.qcsoft.commonbean.bean.payment.WxMinConfig;
  4. import com.qcsoft.commonbean.bean.payment.wx.bean.PreOrderParam;
  5. import com.qcsoft.commonbean.bean.payment.wx.bean.WxRefund;
  6. import com.qcsoft.commonbean.bean.payment.wx.bean.entpay.EntPayParam;
  7. import com.qcsoft.commonbean.bean.payment.wx.bean.entpay.EntPayResult;
  8. import com.qcsoft.commonbean.bean.payment.wx.bean.request.WxPayUnifiedOrderRequest;
  9. import com.qcsoft.commonbean.bean.payment.wx.bean.result.BaseWxPayResult;
  10. import com.qcsoft.commonbean.bean.payment.wx.bean.result.WxPayOrderQueryResult;
  11. import com.qcsoft.commonbean.bean.payment.wx.bean.result.WxPayUnifiedOrderResult;
  12. import com.qcsoft.commonbean.bean.payment.wx.config.WxPayConfig;
  13. import com.qcsoft.commonbean.bean.payment.wx.exception.WxPayException;
  14.  
  15. /**
  16. * 微信预支付
  17. * @param appId 应用ID(微信公众号)
  18. * @param mchId 商务号ID
  19. * @param mchKey 商务号密钥
  20. * @param notifyUrl 异步通知地址
  21. * @param signType 签名类型
  22. * @param body 描述
  23. * @param totalFee 金额
  24. * @param spbillCreateIp app和h5支付需要用户的真实请求地址
  25. * @param tradeType
  26. * @param outTradeNo
  27. * @return
  28. */
  29. public interface WxPayService {
  30. /**
  31. *
  32. * @param config {appId:应用ID,mchId:商务号ID,mchKey:商务号密钥,notifyUrl:异步通知地址,signType:签名类型}
  33. * @param request {body:订单描述,totalFee:金额,
  34. * spbillCreateIp:app和h5支付需要用户的真实请求地址Native支付填调用微信支付API的机器IP,
  35. * tradeType:SAPI--公众号支付、NATIVE--原生扫码支付、APP--app支付,统一下单接口trade_type的传参可参考这里,
  36. * outTradeNo:商户订单号,productId:商品Id(扫码支付必传,其他选填),openid:公众号openId}
  37. * @return
  38. */
  39. WxPayUnifiedOrderResult wxPrePay(WxPayConfig config, WxPayUnifiedOrderRequest request);
  40.  
  41. /**
  42. * 根据appCode获取商家微信支付配置
  43. * @param appCode
  44. * @return
  45. */
  46. WxPayConfig getWxPayConfigByAppCode(String appCode,String bmCode);
  47.  
  48. WxPayConfig getWxMinPayConfigByAppCode(String appCode,String sysSoftwareCode);
  49.  
  50. /**
  51. * 封装预下单参数实体
  52. * @param orderParam 预支付接口参数实体
  53. * @param order 点单
  54. * @return
  55. */
  56. WxPayUnifiedOrderRequest packRequestParam(PreOrderParam orderParam);
  57.  
  58. /**
  59. * 查询订单
  60. * @param appCode 商家编码
  61. * @param dh 订单号
  62. * @param sysSoftwareCode
  63. */
  64. WxPayOrderQueryResult wxPayOrderQuery(String appCode, String bmCode, String dh, Integer type, String sysSoftwareCode);
  65.  
  66. /**
  67. * 企业支付
  68. * @param params
  69. * @return:
  70. * @Author:
  71. * @date:
  72. */
  73. BaseWxPayResult entPay(EntPayParam params) throws WxPayException;
  74. }

WxPayServiceImpl

  1. package com.qcsoft.payment.service.impl;
  2.  
  3. import com.alibaba.fastjson.JSON;
  4. import com.qcsoft.commonbean.bean.payment.PayLog;
  5. import com.qcsoft.commonbean.bean.payment.WxConfig;
  6. import com.qcsoft.commonbean.bean.payment.WxMinConfig;
  7. import com.qcsoft.commonbean.bean.payment.common.PayConstant;
  8. import com.qcsoft.commonbean.bean.payment.common.PayNotify;
  9. import com.qcsoft.commonbean.bean.payment.wx.bean.PreOrderParam;
  10. import com.qcsoft.commonbean.bean.payment.wx.bean.entpay.*;
  11. import com.qcsoft.commonbean.bean.payment.wx.bean.request.WxPayOrderQueryRequest;
  12. import com.qcsoft.commonbean.bean.payment.wx.bean.request.WxPayUnifiedOrderRequest;
  13. import com.qcsoft.commonbean.bean.payment.wx.bean.result.BaseWxPayResult;
  14. import com.qcsoft.commonbean.bean.payment.wx.bean.result.WxPayOrderQueryResult;
  15. import com.qcsoft.commonbean.bean.payment.wx.bean.result.WxPayUnifiedOrderResult;
  16. import com.qcsoft.commonbean.bean.payment.wx.config.WxPayConfig;
  17. import com.qcsoft.commonbean.bean.payment.wx.exception.WxPayException;
  18. import com.qcsoft.commonbean.bean.payment.wx.handler.EntPayHandler;
  19. import com.qcsoft.commonbean.bean.payment.wx.handler.WxPayHandler;
  20. import com.qcsoft.commonbean.bean.payment.wx.handler.impl.EntPayHandlerImpl;
  21. import com.qcsoft.commonbean.bean.payment.wx.handler.impl.WxPayHandlerApacheHttpImpl;
  22. import com.qcsoft.payment.commns.exception.BaseException;
  23. import com.qcsoft.payment.commns.exception.QYError;
  24. import com.qcsoft.payment.commns.utils.DateUtils;
  25. import com.qcsoft.payment.commns.utils.RedisUtil;
  26. import com.qcsoft.payment.service.PayLogService;
  27. import com.qcsoft.payment.service.WxConfigService;
  28. import com.qcsoft.payment.service.WxMinConfigService;
  29. import com.qcsoft.payment.service.WxPayService;
  30. import lombok.extern.slf4j.Slf4j;
  31. import org.apache.commons.lang3.StringUtils;
  32. import org.slf4j.Logger;
  33. import org.slf4j.LoggerFactory;
  34. import org.springframework.beans.factory.annotation.Autowired;
  35. import org.springframework.beans.factory.annotation.Value;
  36. import org.springframework.stereotype.Service;
  37.  
  38. import java.math.BigDecimal;
  39. import java.util.Date;
  40.  
  41. @Service
  42. @Slf4j
  43. public class WxPayServiceImpl implements WxPayService {
  44. private static final Logger logger = LoggerFactory.getLogger(WxPayServiceImpl.class);
  45.  
  46. @Value("${payNotifyUrl}")
  47. private String notifyUrl;
  48. @Autowired
  49. private RedisUtil redisUtil;
  50. @Autowired
  51. private WxConfigService wxConfigService;
  52. @Autowired
  53. private WxMinConfigService wxMinConfigService;
  54. @Autowired
  55. private PayLogService payLogService;
  56.  
  57. /**
  58. * @param config {appId:应用ID,mchId:商务号ID,mchKey:商务号密钥,notifyUrl:异步通知地址,signType:签名类型}
  59. * @param request {body:订单描述,totalFee:金额,
  60. * spbillCreateIp:app和h5支付需要用户的真实请求地址Native支付填调用微信支付API的机器IP,
  61. * tradeType:SAPI--公众号支付、NATIVE--原生扫码支付、APP--app支付,统一下单接口trade_type的传参可参考这里,
  62. * outTradeNo:商户订单号,productId:商品Id(扫码支付必传,其他选填),openid:公众号openId} 还有很多参数选填
  63. * @return
  64. * @throws WxPayException
  65. */
  66. @Override
  67. public WxPayUnifiedOrderResult wxPrePay(WxPayConfig config, WxPayUnifiedOrderRequest request) {
  68. logger.info("WxPayServiceImpl.wxPrePay--->>\n微信预支付,\n商务订单号:[{}]", request.getOutTradeNo());
  69. WxPayHandler wx = new WxPayHandlerApacheHttpImpl();
  70. WxPayUnifiedOrderResult orderResult = null;
  71. wx.setConfig(config);
  72. log.info("WxPayUnifiedOrderResult ={}", config.getNotifyUrl());
  73. try {
  74. orderResult = wx.unifiedOrder(request);
  75. } catch (WxPayException e) {
  76. logger.error("WxPayServiceImpl.wxPrePay--->>\n微信预支付失败,\n商务订单号:[{}]", request.getOutTradeNo(), orderResult);
  77. logger.error("异常信息{}", e.getMessage());
  78. throw new BaseException(QYError.msg("订单号[" + request.getOutTradeNo() + "]预支付失败!"));
  79. }
  80. return orderResult;
  81. }
  82.  
  83. /**
  84. * 根据商家编码获取微信商户配置信息
  85. *
  86. * @param appCode
  87. * @return
  88. */
  89. @Override
  90. public WxPayConfig getWxPayConfigByAppCode(String appCode, String bmCode) {
  91. logger.info("WxPayServiceImpl.getWxPayConfigByAppCode--->>\n获取微信支付配置信息:appCode[{}],bmCode[{}]", appCode, bmCode);
  92. WxConfig config = null;
  93. WxPayConfig wxPayConfig = new WxPayConfig();
  94. /**
  95. * 获取商家支付宝配置信息(优先级:1-redis,2-mysql,3-用户系统)
  96. */
  97. try {
  98. //2、mysql
  99. if (config == null) {
  100. if (StringUtils.isNotBlank(bmCode)) {
  101. config = wxConfigService.selectByBmCode(bmCode, appCode);
  102. //如果部门取不到,则去商家的配置
  103. if (config == null)
  104. config = wxConfigService.selectByAppCode(appCode);
  105. } else {
  106. config = wxConfigService.selectByAppCode(appCode);
  107. }
  108. }
  109. if (config == null) {
  110. logger.warn("WxPayServiceImpl.getWxPayConfigByAppCode--->>\n获取微信支付配置信息失败:[{}]", appCode);
  111. throw new BaseException(QYError.msg("获取微信支付配置信息失败!"));
  112. }
  113. } catch (Exception e) {
  114. logger.error("WxPayServiceImpl.getWxPayConfigByAppCode--->>\n获取微信支付配置信息失败:[{}]", e);
  115. throw new BaseException(QYError.msg("获取微信支付配置信息失败!"));
  116. }
  117. //根据appCode查询商家微信配置信息
  118. wxPayConfig.setAppId(config.getAppid());
  119. wxPayConfig.setMchId(config.getMchId());
  120. wxPayConfig.setMchKey(config.getMchKeySecret());
  121. wxPayConfig.setSignType(PayConstant.WXPAY_SIGNTYPE_MD5.getKey());
  122. wxPayConfig.setKeyUrl(config.getCrtPath());
  123. wxPayConfig.setKeyPath(config.getCrtPath());
  124. log.info("获取微信公众号配置为 [{}],转为微信支付实体为 [{}]",config,wxPayConfig);
  125. return wxPayConfig;
  126. }
  127.  
  128. @Override
  129. public WxPayConfig getWxMinPayConfigByAppCode(String appCode, String sysSoftwareCode) {
  130. logger.error("WxPayServiceImpl.getWxMinPayConfigByAppCode--->>\n获取微信小程序支付配置信息:[{}]", appCode);
  131. if (StringUtils.isBlank(sysSoftwareCode)) {
  132. sysSoftwareCode = "store-service";
  133. }
  134. WxMinConfig config = null;
  135. WxPayConfig wxPayConfig = new WxPayConfig();
  136. /**
  137. * 获取商家支付宝配置信息(优先级:1-redis,2-mysql,3-用户系统)
  138. */
  139. try {
  140. if (config == null) {
  141. //config = wxMinConfigService.selectByAppCode(appCode);
  142. config = wxMinConfigService.selectBySysSoftwareCode(appCode,sysSoftwareCode);
  143. }
  144. if (config == null) {
  145. logger.warn("WxPayServiceImpl.getWxMinPayConfigByAppCode--->>\n获取微信小程序支付配置信息失败:[{}]", appCode);
  146. throw new BaseException(QYError.msg("获取微信支付配置信息失败!"));
  147. }
  148. } catch (Exception e) {
  149. logger.error("WxPayServiceImpl.getWxMinPayConfigByAppCode--->>\n获取微信小程序支付配置信息失败:[{}]", e);
  150. throw new BaseException(QYError.msg("获取微信小程序支付配置信息失败!"));
  151. }
  152. //根据appCode查询商家微信配置信息
  153. wxPayConfig.setAppId(config.getAppid());
  154. wxPayConfig.setMchId(config.getMchId());
  155. wxPayConfig.setMchKey(config.getMchKeySecret());
  156. wxPayConfig.setSignType(PayConstant.WXPAY_SIGNTYPE_MD5.getKey());
  157. wxPayConfig.setKeyUrl(config.getCrtPath());
  158. wxPayConfig.setKeyPath(config.getCrtPath());
  159. log.info("获取微信小程序退款配置为 [{}],转为微信支付实体为 [{}]",config,wxPayConfig);
  160. return wxPayConfig;
  161. }
  162.  
  163. /**
  164. * 封装预下单参数实体
  165. *
  166. * @param orderParam 预支付接口参数实体
  167. * @param order 点单
  168. * @return
  169. */
  170. @Override
  171. public WxPayUnifiedOrderRequest packRequestParam(PreOrderParam orderParam) {
  172. Date date = new Date();
  173. BigDecimal paramAmount = new BigDecimal(orderParam.getTotalAmount().toString());
  174. BigDecimal multiplyNum = new BigDecimal("100");
  175. WxPayUnifiedOrderRequest request = WxPayUnifiedOrderRequest.newBuilder()
  176. .body(orderParam.getBody())
  177. .totalFee(paramAmount.multiply(multiplyNum).intValue())
  178. .spbillCreateIp(orderParam.getReqId())
  179. .notifyUrl(notifyUrl + PayConstant.WXPAY_09.getKey())
  180. .tradeType(orderParam.getTradeType())
  181. .outTradeNo(orderParam.getOutTradeNo())
  182. .build();
  183. log.info("WxPayUnifiedOrderRequest = {}", PayConstant.WXPAY_09.getKey());
  184.  
  185. request.setProductId(orderParam.getDh());
  186. request.setDetail(orderParam.getSubject());
  187. PayNotify payNotify = new PayNotify();
  188. payNotify.setAppCode(orderParam.getAppCode());
  189. payNotify.setCode(orderParam.getBmCode());
  190. payNotify.setDh(orderParam.getDh());
  191. request.setAttach(JSON.toJSONString(payNotify));
  192. if (orderParam.getTradeType().equals(PayConstant.JSAPI.toString())) {
  193. request.setOpenid(orderParam.getOpenId());
  194. }
  195. //开始时间
  196. request.setTimeStart(DateUtils.getLastMinute(date, 0));
  197. //有效期
  198. request.setTimeExpire(orderParam.getTimeExpire());
  199. return request;
  200. }
  201.  
  202. /**
  203. * 订单查询
  204. *
  205. * @param appCode 商家编码
  206. * @param dh 订单号
  207. * @param sysSoftwareCode
  208. * @return
  209. */
  210. @Override
  211. public WxPayOrderQueryResult wxPayOrderQuery(String appCode, String bmCode, String dh, Integer type, String sysSoftwareCode) {
  212. logger.info("WxPayServiceImpl.wxPayOrderQuery--->>\n微信订单查询,\n本次查询的商家编码为:[{}],商务订单号:[{}]", appCode, dh);
  213. WxPayHandler handler = new WxPayHandlerApacheHttpImpl();
  214. WxPayOrderQueryRequest request = new WxPayOrderQueryRequest();
  215. WxPayOrderQueryResult queryResult = null;
  216. WxPayConfig config = null;
  217.  
  218. try {
  219. PayLog payLog = payLogService.selectByDh(dh);
  220. if (payLog==null) {
  221. //商家的微信支付
  222. if (type == null || type == 1) {
  223. bmCode = null;
  224. config = this.getWxPayConfigByAppCode(appCode, bmCode);
  225. //部门的微信支付支付
  226. } else if (type == 2) {
  227. config = this.getWxPayConfigByAppCode(appCode, bmCode);
  228. //商家小程序支付
  229. } else if (type == 3) {
  230. config = this.getWxMinPayConfigByAppCode(appCode,sysSoftwareCode);
  231. }
  232. }else{
  233. config = JSON.parseObject(payLog.getPayConfigJsonStr(), WxPayConfig.class);
  234. }
  235. request.setOutTradeNo(dh);
  236. handler.setConfig(config);
  237. queryResult = handler.queryOrder(request);
  238. logger.info("WxPayServiceImpl.wxPayOrderQuery--->>\n微信订单查询成功,\n返回包信息:[{}]", JSON.toJSONString(queryResult));
  239. } catch (WxPayException e) {
  240. logger.error("WxPayServiceImpl.wxPayOrderQuery--->>\n微信订单查询失败,\n商务订单号:[{}]", dh);
  241. throw new BaseException(QYError.msg("微信订单查询失败,商务订单号:[{}]" + dh + ""));
  242. }
  243. return queryResult;
  244. }
  245. /**
  246. * 企业支付
  247. * @param params
  248. * @return: com.qcsoft.commonbean.bean.payment.wx.bean.result.BaseWxPayResult
  249. * @Author:
  250. * @date:
  251. */
  252. @Override
  253. public BaseWxPayResult entPay(EntPayParam params) throws WxPayException {
  254. WxPayHandler wxPayHandler = new WxPayHandlerApacheHttpImpl();
  255. WxPayConfig config = null;
  256. EntPayResult result = null;
  257. EntPayBankResult bankResult = null;
  258. if (params.getTradeType() != null && params.getTradeType() == 3) {
  259. config = this.getWxMinPayConfigByAppCode(params.getAppCode(),params.getSysSoftwareCode());
  260. } else {
  261. config = this.getWxPayConfigByAppCode(params.getAppCode(), params.getBmCode());
  262. }
  263. config.setUseKey(true);
  264. wxPayHandler.setConfig(config);
  265. if (params.getTradeType()==1) {
  266. EntPayRequest request = packEntPayRequest(params,config);
  267. EntPayHandler entPayHandler = new EntPayHandlerImpl(wxPayHandler);
  268.  
  269. result = entPayHandler.entPay(request);
  270. return result;
  271. }else{
  272. EntPayBankRequest request = packEntPayBankRequest(params);
  273. EntPayHandler entPayHandler = new EntPayHandlerImpl(wxPayHandler);
  274. bankResult = entPayHandler.payBank(request);
  275. return bankResult;
  276. }
  277. }
  278. /**
  279. * 封装微信企业支付请求参数
  280. * @param params
  281. * @return: com.qcsoft.commonbean.bean.payment.wx.bean.entpay.EntPayRequest
  282. * @Author:
  283. * @date:
  284. */
  285. public EntPayRequest packEntPayRequest(EntPayParam params,WxPayConfig config) {
  286. EntPayRequest request = new EntPayRequest();
  287. request.setAmount(params.getAmount().multiply(new BigDecimal("10")).intValue());
  288. request.setCheckName("NO_CHECK");
  289. request.setOpenid(params.getOpenid());
  290. request.setSpbillCreateIp(params.getSpbillCreateIp());
  291. request.setPartnerTradeNo(params.getPartnerTradeNo());
  292. request.setMchAppid(config.getAppId());
  293. request.setMchId(config.getMchId());
  294. request.setDescription(params.getDesc());
  295. return request;
  296. }
  297.  
  298. /**
  299. * 封装银行卡企业支付参数
  300. * @param params
  301. * @return: com.qcsoft.commonbean.bean.payment.wx.bean.entpay.EntPayBankRequest
  302. * @Author:
  303. * @date:
  304. */
  305. public EntPayBankRequest packEntPayBankRequest(EntPayParam params) {
  306. EntPayBankRequest request = new EntPayBankRequest();
  307. request.setAmount(params.getAmount().multiply(new BigDecimal("10")).intValue());
  308. request.setBankCode(params.getBankCode());
  309. request.setEncTrueName(params.getEncTrueName());
  310. request.setPartnerTradeNo(params.getPartnerTradeNo());
  311. request.setDescription(params.getDesc());
  312. return request;
  313. }
  314. }

5、这些类是和数据库交互的增删查该类

  1. @Autowired
  2. private WxConfigService wxConfigService;
  3. @Autowired
  4. private WxMinConfigService wxMinConfigService;
  5. @Autowired
  6. private PayLogService payLogService;
  7. @Autowired
  8. private AlipayConfigService alipayConfigService;
  9. ```

到此这篇关于Java 实现微信和支付宝支付功能的文章就介绍到这了,更多相关Java 微信和支付宝支付内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!