SandPayService.java 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652
  1. package com.izouma.nineth.service;
  2. import cn.com.sandpay.cashier.sdk.*;
  3. import com.alibaba.fastjson.JSONObject;
  4. import com.izouma.nineth.config.GeneralProperties;
  5. import com.izouma.nineth.config.SandPayProperties;
  6. import com.izouma.nineth.domain.GiftOrder;
  7. import com.izouma.nineth.domain.MintOrder;
  8. import com.izouma.nineth.domain.Order;
  9. import com.izouma.nineth.enums.MintOrderStatus;
  10. import com.izouma.nineth.enums.OrderStatus;
  11. import com.izouma.nineth.exception.BusinessException;
  12. import com.izouma.nineth.repo.GiftOrderRepo;
  13. import com.izouma.nineth.repo.MintOrderRepo;
  14. import com.izouma.nineth.repo.OrderRepo;
  15. import com.izouma.nineth.utils.DateTimeUtils;
  16. import com.izouma.nineth.utils.SnowflakeIdWorker;
  17. import lombok.AllArgsConstructor;
  18. import lombok.extern.slf4j.Slf4j;
  19. import org.apache.commons.codec.binary.Base64;
  20. import org.springframework.cache.annotation.Cacheable;
  21. import org.springframework.stereotype.Service;
  22. import java.io.IOException;
  23. import java.math.BigDecimal;
  24. import java.net.URLDecoder;
  25. import java.nio.charset.StandardCharsets;
  26. import java.text.DecimalFormat;
  27. import java.text.DecimalFormatSymbols;
  28. import java.time.LocalDateTime;
  29. import java.util.HashMap;
  30. import java.util.Locale;
  31. import java.util.Map;
  32. import java.util.Optional;
  33. @Service
  34. @AllArgsConstructor
  35. @Slf4j
  36. public class SandPayService {
  37. private final OrderRepo orderRepo;
  38. private final GiftOrderRepo giftOrderRepo;
  39. private final SandPayProperties sandPayProperties;
  40. private final MintOrderRepo mintOrderRepo;
  41. private final SnowflakeIdWorker snowflakeIdWorker;
  42. private final GeneralProperties generalProperties;
  43. public String paddingOrderId(String orderId) {
  44. if (orderId != null && orderId.length() < 12) {
  45. StringBuilder orderIdBuilder = new StringBuilder(orderId);
  46. for (int i = orderIdBuilder.length(); i < 12; i++) {
  47. orderIdBuilder.insert(0, "0");
  48. }
  49. orderId = orderIdBuilder.toString();
  50. }
  51. return orderId;
  52. }
  53. public String getReqTime() {
  54. return DateTimeUtils.format(LocalDateTime.now(), "yyyyMMddHHmmss");
  55. }
  56. public static String getTimeout(int seconds) {
  57. return DateTimeUtils.format(LocalDateTime.now().plusSeconds(seconds), "yyyyMMddHHmmss");
  58. }
  59. public static String getTimeout(LocalDateTime createTime, int seconds) {
  60. return DateTimeUtils.format(Optional.ofNullable(createTime).orElse(LocalDateTime.now())
  61. .plusSeconds(seconds), "yyyyMMddHHmmss");
  62. }
  63. public String convertAmount(BigDecimal amount) {
  64. DecimalFormat df = new DecimalFormat("000000000000", DecimalFormatSymbols.getInstance(Locale.US));
  65. return df.format(amount.multiply(new BigDecimal("100")));
  66. }
  67. public JSONObject requestServer(JSONObject header, JSONObject body, String reqAddr) {
  68. Map<String, String> reqMap = new HashMap<String, String>();
  69. JSONObject reqJson = new JSONObject();
  70. reqJson.put("head", header);
  71. reqJson.put("body", body);
  72. String reqStr = reqJson.toJSONString();
  73. String reqSign;
  74. // 签名
  75. try {
  76. reqSign = new String(Base64.encodeBase64(CryptoUtil.digitalSign(reqStr.getBytes(StandardCharsets.UTF_8),
  77. CertUtil.getPrivateKey(), "SHA1WithRSA")));
  78. } catch (Exception e) {
  79. log.error(e.getMessage());
  80. return null;
  81. }
  82. //整体报文格式
  83. reqMap.put("charset", "UTF-8");
  84. reqMap.put("data", reqStr);
  85. reqMap.put("signType", "01");
  86. reqMap.put("sign", reqSign);
  87. reqMap.put("extend", "");
  88. String result;
  89. try {
  90. log.info("请求报文:\n{}", JSONObject.toJSONString(reqJson, true));
  91. result = HttpClient.doPost(reqAddr, reqMap, 30000, 30000);
  92. result = URLDecoder.decode(result, StandardCharsets.UTF_8);
  93. } catch (IOException e) {
  94. log.error(e.getMessage());
  95. return null;
  96. }
  97. Map<String, String> respMap = SDKUtil.convertResultStringToMap(result);
  98. String respData = respMap.get("data");
  99. String respSign = respMap.get("sign");
  100. // 验证签名
  101. boolean valid;
  102. try {
  103. valid = CryptoUtil.verifyDigitalSign(respData.getBytes(StandardCharsets.UTF_8),
  104. Base64.decodeBase64(respSign), CertUtil.getPublicKey(), "SHA1WithRSA");
  105. if (!valid) {
  106. log.error("verify sign fail.");
  107. return null;
  108. }
  109. log.info("verify sign success");
  110. JSONObject respJson = JSONObject.parseObject(respData);
  111. if (respJson != null) {
  112. log.info("响应码:[{}]", respJson.getJSONObject("head").getString("respCode"));
  113. log.info("响应描述:[{}]", respJson.getJSONObject("head").getString("respMsg"));
  114. log.info("响应报文:\n{}", JSONObject.toJSONString(respJson, true));
  115. } else {
  116. log.error("服务器请求异常!!!");
  117. }
  118. return respJson;
  119. } catch (Exception e) {
  120. log.error(e.getMessage());
  121. return null;
  122. }
  123. }
  124. public String requestAlipay(String orderId, BigDecimal amount, String subject, String desc,
  125. String timeout, String extend) {
  126. JSONObject res = requestAlipayRaw(orderId, amount, subject, desc, timeout, extend);
  127. if ("000000".equals(res.getJSONObject("head").getString("respCode"))) {
  128. return "alipays://platformapi/startapp?saId=10000007&qrcode=" + res.getJSONObject("body")
  129. .getString("qrCode");
  130. }
  131. throw new BusinessException("斑马冷却系统已启动,请稍后支付");
  132. }
  133. public JSONObject requestAlipayRaw(String orderId, BigDecimal amount, String subject, String desc,
  134. String timeout, String extend) {
  135. if (orderId.length() < 12) {
  136. for (int i = orderId.length(); i < 12; i++) {
  137. orderId = "0" + orderId;
  138. }
  139. }
  140. JSONObject header = new JSONObject();
  141. header.put("version", "1.0"); //版本号
  142. header.put("method", "sandpay.trade.precreate"); //接口名称:统一下单并支付
  143. header.put("productId", "00000006"); //产品编码
  144. header.put("mid", sandPayProperties.getMid()); //商户号
  145. header.put("accessType", "1"); //接入类型设置为普通商户接入
  146. header.put("channelType", "07"); //渠道类型:07-互联网 08-移动端
  147. header.put("reqTime", getReqTime()); //请求时间
  148. JSONObject body = new JSONObject();
  149. body.put("payTool", "0401"); //支付工具: 固定填写0401
  150. body.put("orderCode", orderId); //商户订单号
  151. body.put("totalAmount", convertAmount(amount)); //订单金额 12位长度,精确到分
  152. //body.put("limitPay", "5"); //限定支付方式 送1-限定不能使用贷记卡 送4-限定不能使用花呗 送5-限定不能使用贷记卡+花呗
  153. body.put("subject", subject); //订单标题
  154. body.put("body", desc); //订单描述
  155. body.put("txnTimeOut", timeout); //订单超时时间
  156. body.put("notifyUrl", sandPayProperties.getNotifyUrl()); //异步通知地址
  157. body.put("bizExtendParams", ""); //业务扩展参数
  158. body.put("merchExtendParams", ""); //商户扩展参数
  159. body.put("extend", extend); //扩展域
  160. return requestServer(header, body, "https://cashier.sandpay.com.cn/qr/api/order/create");
  161. }
  162. public JSONObject requestQuick(String orderId, BigDecimal amount, String subject, String desc,
  163. int timeout, String extend, String frontUrl) {
  164. if (orderId.length() < 12) {
  165. for (int i = orderId.length(); i < 12; i++) {
  166. orderId = "0" + orderId;
  167. }
  168. }
  169. JSONObject header = new JSONObject();
  170. header.put("version", "1.0"); //版本号
  171. header.put("method", "sandpay.trade.pay"); //接口名称:统一下单
  172. header.put("mid", sandPayProperties.getMid()); //商户号
  173. header.put("accessType", "1"); //接入类型设置为平台商户接入 //接入类型设置为普通商户接入
  174. header.put("channelType", "07"); //渠道类型:07-互联网 08-移动端
  175. header.put("reqTime", getReqTime()); //请求时间
  176. header.put("productId", "00000008"); //产品编码
  177. JSONObject body = new JSONObject();
  178. body.put("orderCode", orderId); //商户订单号
  179. body.put("totalAmount", convertAmount(amount)); //订单金额
  180. body.put("subject", subject); //订单标题
  181. body.put("body", desc); //订单描述
  182. body.put("txnTimeOut", getTimeout(timeout)); //订单超时时间
  183. body.put("clientIp", "192.168.22.55"); //客户端IP
  184. body.put("limitPay", ""); //限定支付方式 送1-限定不能使用贷记卡送 4-限定不能使用花呗 送5-限定不能使用贷记卡+花呗
  185. body.put("notifyUrl", sandPayProperties.getNotifyUrl()); //异步通知地址
  186. body.put("frontUrl", frontUrl); //前台通知地址
  187. body.put("storeId", ""); //商户门店编号
  188. body.put("terminalId", ""); //商户终端编号
  189. body.put("operatorId", ""); //操作员编号
  190. body.put("clearCycle", ""); //清算模式
  191. body.put("royaltyInfo", ""); //分账信息
  192. body.put("riskRateInfo", ""); //风控信息域
  193. body.put("bizExtendParams", ""); //业务扩展参数
  194. body.put("merchExtendParams", ""); //商户扩展参数
  195. body.put("extend", extend); //扩展域
  196. body.put("payMode", "sand_h5"); //支付模式
  197. return requestServer(header, body, "https://cashier.sandpay.com.cn/gateway/api/order/pay");
  198. }
  199. public JSONObject query(String orderId) {
  200. JSONObject header = new JSONObject();
  201. header.put("version", "1.0"); //版本号
  202. header.put("method", "sandpay.trade.query"); //接口名称:订单查询
  203. header.put("productId", "00000006"); //产品编码
  204. header.put("mid", sandPayProperties.getMid()); //商户号
  205. header.put("accessType", "1"); //接入类型设置为普通商户接入
  206. header.put("channelType", "07"); //渠道类型:07-互联网 08-移动端
  207. header.put("reqTime", getReqTime()); //请求时间
  208. JSONObject body = new JSONObject();
  209. body.put("orderCode", orderId);
  210. body.put("extend", ""); //扩展域
  211. return requestServer(header, body, "https://cashier.sandpay.com.cn/qr/api/order/query");
  212. }
  213. public JSONObject refund(String orderId, BigDecimal amount) {
  214. JSONObject header = new JSONObject();
  215. header.put("version", "1.0"); //版本号
  216. header.put("method", "sandpay.trade.refund"); //接口名称:退货
  217. header.put("productId", "00000006"); //产品编码
  218. header.put("mid", sandPayProperties.getMid()); //商户号
  219. header.put("accessType", "1"); //接入类型设置为普通商户接入
  220. header.put("channelType", "07"); //渠道类型:07-互联网 08-移动端
  221. header.put("reqTime", getReqTime()); //请求时间
  222. JSONObject body = new JSONObject();
  223. body.put("orderCode", snowflakeIdWorker.nextId()); //商户订单号
  224. body.put("oriOrderCode", paddingOrderId(orderId)); //原交易订单号
  225. body.put("refundAmount", convertAmount(amount)); //退货金额
  226. body.put("refundReason", "退款"); //退货原因
  227. body.put("notifyUrl", sandPayProperties.getNotifyUrl()); //异步通知地址
  228. body.put("extend", "");
  229. return requestServer(header, body, "https://cashier.sandpay.com.cn/qr/api/order/refund");
  230. }
  231. @Cacheable(value = "sandPay", key = "#orderId")
  232. public String payOrder(Long orderId) {
  233. Order order = orderRepo.findById(orderId).orElseThrow(new BusinessException("订单不存在"));
  234. if (order.getStatus() != OrderStatus.NOT_PAID) {
  235. throw new BusinessException("订单状态错误");
  236. }
  237. JSONObject extend = new JSONObject();
  238. extend.put("type", "order");
  239. extend.put("id", orderId);
  240. JSONObject res = requestAlipayRaw(orderId.toString(), order.getTotalPrice(), order.getName(), order.getName(),
  241. getTimeout(order.getCreatedAt(), 180), extend.toJSONString());
  242. if (res == null)
  243. throw new BusinessException("下单失败,请稍后再试");
  244. if (!"000000".equals(res.getJSONObject("head").getString("respCode"))) {
  245. String msg = res.getJSONObject("head").getString("respMsg");
  246. if (msg.contains("超限")) {
  247. throw new BusinessException("超过商户单日额度");
  248. }
  249. if (msg.contains("商户状态")) {
  250. throw new BusinessException("超过商户单日额度");
  251. }
  252. throw new BusinessException(msg);
  253. }
  254. return res.getJSONObject("body").getString("qrCode");
  255. }
  256. @Cacheable(value = "sandPayQuick", key = "#orderId")
  257. public String payOrderQuick(Long orderId) {
  258. Order order = orderRepo.findById(orderId).orElseThrow(new BusinessException("订单不存在"));
  259. if (order.getStatus() != OrderStatus.NOT_PAID) {
  260. throw new BusinessException("订单状态错误");
  261. }
  262. JSONObject extend = new JSONObject();
  263. extend.put("type", "order");
  264. extend.put("id", orderId);
  265. JSONObject res = requestQuick(orderId.toString(), order.getTotalPrice(), order.getName(), order.getName(),
  266. 180, extend.toJSONString(), generalProperties.getHost() + "/9th/orderDetail?id=" + orderId);
  267. if (res == null)
  268. throw new BusinessException("下单失败,请稍后再试");
  269. if (!"000000".equals(res.getJSONObject("head").getString("respCode"))) {
  270. String msg = res.getJSONObject("head").getString("respMsg");
  271. if (msg.contains("超限")) {
  272. throw new BusinessException("超过商户单日额度");
  273. }
  274. if (msg.contains("商户状态")) {
  275. throw new BusinessException("超过商户单日额度");
  276. }
  277. throw new BusinessException(msg);
  278. }
  279. return res.getJSONObject("body").getString("credential");
  280. }
  281. @Cacheable(value = "sandPayQuick", key = "#orderId")
  282. public String payGiftQuick(Long orderId) {
  283. GiftOrder order = giftOrderRepo.findById(orderId).orElseThrow(new BusinessException("订单不存在"));
  284. if (order.getStatus() != OrderStatus.NOT_PAID) {
  285. throw new BusinessException("订单状态错误");
  286. }
  287. JSONObject extend = new JSONObject();
  288. extend.put("type", "gift");
  289. extend.put("id", orderId);
  290. JSONObject res = requestQuick(orderId.toString(), order.getGasPrice(), "转增" + order.getAssetId(),
  291. "转增" + order.getAssetId(), 180, extend.toJSONString(),
  292. generalProperties.getHost() + "/9th/");
  293. if (res == null)
  294. throw new BusinessException("下单失败,请稍后再试");
  295. if (!"000000".equals(res.getJSONObject("head").getString("respCode"))) {
  296. String msg = res.getJSONObject("head").getString("respMsg");
  297. if (msg.contains("超限")) {
  298. throw new BusinessException("超过商户单日额度");
  299. }
  300. if (msg.contains("商户状态")) {
  301. throw new BusinessException("超过商户单日额度");
  302. }
  303. throw new BusinessException(msg);
  304. }
  305. return res.getJSONObject("body").getString("credential");
  306. }
  307. @Cacheable(value = "sandPayQuick", key = "#orderId")
  308. public String payMintQuick(Long orderId) {
  309. MintOrder order = mintOrderRepo.findById(orderId).orElseThrow(new BusinessException("订单不存在"));
  310. if (order.getStatus() != MintOrderStatus.NOT_PAID) {
  311. throw new BusinessException("订单状态错误");
  312. }
  313. JSONObject extend = new JSONObject();
  314. extend.put("type", "mintOrder");
  315. extend.put("id", orderId);
  316. JSONObject res = requestQuick(orderId.toString(), order.getGasPrice(),
  317. "铸造活动:" + order.getMintActivityId(), "铸造活动:" + order.getMintActivityId(),
  318. 180, extend.toJSONString(), generalProperties.getHost() + "/9th/");
  319. if (res == null)
  320. throw new BusinessException("下单失败,请稍后再试");
  321. if (!"000000".equals(res.getJSONObject("head").getString("respCode"))) {
  322. String msg = res.getJSONObject("head").getString("respMsg");
  323. if (msg.contains("超限")) {
  324. throw new BusinessException("超过商户单日额度");
  325. }
  326. if (msg.contains("商户状态")) {
  327. throw new BusinessException("超过商户单日额度");
  328. }
  329. throw new BusinessException(msg);
  330. }
  331. return res.getJSONObject("body").getString("credential");
  332. }
  333. @Cacheable(value = "sandPay", key = "#orderId")
  334. public String payGiftOrder(Long orderId) {
  335. GiftOrder order = giftOrderRepo.findById(orderId).orElseThrow(new BusinessException("订单不存在"));
  336. if (order.getStatus() != OrderStatus.NOT_PAID) {
  337. throw new BusinessException("订单状态错误");
  338. }
  339. JSONObject extend = new JSONObject();
  340. extend.put("type", "gift");
  341. extend.put("id", orderId);
  342. JSONObject res = requestAlipayRaw(orderId.toString(), order.getGasPrice(), "转增" + order.getAssetId(),
  343. "转增" + order.getAssetId(),
  344. getTimeout(order.getCreatedAt(), 180), extend.toJSONString());
  345. if (res == null)
  346. throw new BusinessException("下单失败,请稍后再试");
  347. if (!"000000".equals(res.getJSONObject("head").getString("respCode"))) {
  348. String msg = res.getJSONObject("head").getString("respMsg");
  349. if (msg.contains("超限")) {
  350. throw new BusinessException("超过商户单日额度");
  351. }
  352. if (msg.contains("商户状态")) {
  353. throw new BusinessException("超过商户单日额度");
  354. }
  355. throw new BusinessException(msg);
  356. }
  357. return res.getJSONObject("body").getString("qrCode");
  358. }
  359. @Cacheable(value = "sandPay", key = "#orderId")
  360. public String payMintOrder(Long orderId) {
  361. MintOrder order = mintOrderRepo.findById(orderId).orElseThrow(new BusinessException("订单不存在"));
  362. if (order.getStatus() != MintOrderStatus.NOT_PAID) {
  363. throw new BusinessException("订单状态错误");
  364. }
  365. JSONObject extend = new JSONObject();
  366. extend.put("type", "mintOrder");
  367. extend.put("id", orderId);
  368. JSONObject res = requestAlipayRaw(orderId.toString(), order.getGasPrice(), "铸造活动:" + order.getMintActivityId(),
  369. "铸造活动:" + order.getMintActivityId(), getTimeout(order.getCreatedAt(), 180), extend.toJSONString());
  370. if (res == null)
  371. throw new BusinessException("下单失败,请稍后再试");
  372. if (!"000000".equals(res.getJSONObject("head").getString("respCode"))) {
  373. String msg = res.getJSONObject("head").getString("respMsg");
  374. if (msg.contains("超限")) {
  375. throw new BusinessException("超过商户单日额度");
  376. }
  377. if (msg.contains("商户状态")) {
  378. throw new BusinessException("超过商户单日额度");
  379. }
  380. throw new BusinessException(msg);
  381. }
  382. return res.getJSONObject("body").getString("qrCode");
  383. }
  384. public JSONObject transfer(String id, String name, String bank, BigDecimal amount) {
  385. JSONObject request = new JSONObject();
  386. DecimalFormat df = new DecimalFormat("000000000000", DecimalFormatSymbols.getInstance(Locale.US));
  387. request.put("version", "01"); //版本号
  388. request.put("productId", "00000004"); //产品ID
  389. request.put("tranTime", getReqTime()); //交易时间
  390. request.put("orderCode", id); //订单号
  391. request.put("timeOut", getTimeout(180)); //订单超时时间
  392. request.put("tranAmt", df.format(amount.multiply(new BigDecimal("100")))); //金额
  393. request.put("currencyCode", "156"); //币种
  394. request.put("accAttr", "0"); //账户属性 0-对私 1-对公
  395. request.put("accType", "4"); //账号类型 3-公司账户 4-银行卡
  396. request.put("accNo", bank); //收款人账户号
  397. request.put("accName", name); //收款人账户名
  398. request.put("provNo", ""); //收款人开户省份编码
  399. request.put("cityNo", ""); //收款人开会城市编码
  400. request.put("bankName", ""); //收款账户开户行名称
  401. request.put("bankType", ""); //收款人账户联行号
  402. request.put("remark", "消费"); //摘要
  403. request.put("payMode", ""); //付款模式
  404. request.put("channelType", ""); //渠道类型
  405. request.put("extendParams", ""); //业务扩展参数
  406. request.put("reqReserved", ""); //请求方保留域
  407. request.put("extend", ""); //扩展域
  408. request.put("phone", ""); //手机号
  409. String reqData = request.toJSONString();
  410. log.info("请求数据:{}", reqData);
  411. try {
  412. String aesKey = RandomStringGenerator.getRandomStringByLength(16);
  413. byte[] aesKeyBytes = aesKey.getBytes(StandardCharsets.UTF_8);
  414. byte[] plainBytes = reqData.getBytes(StandardCharsets.UTF_8);
  415. String encryptData = new String(Base64.encodeBase64(
  416. CryptoUtil.AESEncrypt(plainBytes, aesKeyBytes, "AES",
  417. "AES/ECB/PKCS5Padding", null)), StandardCharsets.UTF_8);
  418. String sign = new String(Base64.encodeBase64(
  419. CryptoUtil.digitalSign(plainBytes, CertUtil.getPrivateKey(),
  420. "SHA1WithRSA")), StandardCharsets.UTF_8);
  421. String encryptKey = new String(Base64.encodeBase64(
  422. CryptoUtil.RSAEncrypt(aesKeyBytes, CertUtil.getPublicKey(), 2048, 11,
  423. "RSA/ECB/PKCS1Padding")), StandardCharsets.UTF_8);
  424. Map<String, String> reqMap = new HashMap<String, String>();
  425. //整体报文格式
  426. reqMap.put("transCode", "RTPM"); // 交易码
  427. reqMap.put("accessType", "0"); // 接入类型
  428. reqMap.put("merId", sandPayProperties.getMid()); // 合作商户ID 杉德系统分配,唯一标识
  429. reqMap.put("encryptKey", encryptKey); // 加密后的AES秘钥
  430. reqMap.put("encryptData", encryptData); // 加密后的请求/应答报文
  431. reqMap.put("sign", sign); // 签名
  432. reqMap.put("extend", ""); // 扩展域
  433. String result;
  434. try {
  435. log.info("请求报文:{}", reqMap);
  436. result = HttpClient.doPost("https://caspay.sandpay.com.cn/agent-main/openapi/agentpay",
  437. reqMap, 300000, 300000);
  438. result = URLDecoder.decode(result, StandardCharsets.UTF_8);
  439. } catch (IOException e) {
  440. log.error(e.getMessage());
  441. return null;
  442. }
  443. log.info("响应报文:{}", result);
  444. Map<String, String> responseMap = SDKUtil.convertResultStringToMap(result);
  445. String retEncryptKey = responseMap.get("encryptKey");
  446. String retEncryptData = responseMap.get("encryptData");
  447. String retSign = responseMap.get("sign");
  448. log.debug("retEncryptKey:[{}]", retEncryptKey);
  449. log.debug("retEncryptData:[{}]", retEncryptData);
  450. log.debug("retSign:[{}]", retSign);
  451. byte[] decodeBase64KeyBytes = Base64.decodeBase64(retEncryptKey
  452. .getBytes(StandardCharsets.UTF_8));
  453. byte[] merchantAESKeyBytes = CryptoUtil.RSADecrypt(
  454. decodeBase64KeyBytes, CertUtil.getPrivateKey(), 2048, 11,
  455. "RSA/ECB/PKCS1Padding");
  456. byte[] decodeBase64DataBytes = Base64.decodeBase64(retEncryptData.getBytes(StandardCharsets.UTF_8));
  457. byte[] respDataBytes = CryptoUtil.AESDecrypt(decodeBase64DataBytes,
  458. merchantAESKeyBytes, "AES", "AES/ECB/PKCS5Padding", null);
  459. String respData = new String(respDataBytes, StandardCharsets.UTF_8);
  460. log.info("retData:[" + respData + "]");
  461. System.out.println("响应data数据:" + respData);
  462. byte[] signBytes = Base64.decodeBase64(retSign.getBytes(StandardCharsets.UTF_8));
  463. boolean isValid = CryptoUtil.verifyDigitalSign(respDataBytes, signBytes,
  464. CertUtil.getPublicKey(), "SHA1WithRSA");
  465. if (!isValid) {
  466. log.error("verify sign fail.");
  467. return null;
  468. }
  469. log.info("verify sign success");
  470. System.out.println("verify sign success");
  471. JSONObject respJson = JSONObject.parseObject(respData);
  472. return respJson;
  473. } catch (Exception e) {
  474. log.error(e.getMessage());
  475. return null;
  476. }
  477. }
  478. public JSONObject queryTransfer(String tranTime, String orderId) {
  479. JSONObject request = new JSONObject();
  480. request.put("version", "01"); // 版本号
  481. request.put("productId", "00000004"); // 产品ID
  482. request.put("tranTime", tranTime); // 查询订单的交易时间
  483. request.put("orderCode", orderId); // 要查询的订单号
  484. String reqData = request.toJSONString();
  485. log.info("请求数据:{}", reqData);
  486. try {
  487. String aesKey = RandomStringGenerator.getRandomStringByLength(16);
  488. byte[] aesKeyBytes = aesKey.getBytes(StandardCharsets.UTF_8);
  489. byte[] plainBytes = reqData.getBytes(StandardCharsets.UTF_8);
  490. String encryptData = new String(Base64.encodeBase64(
  491. CryptoUtil.AESEncrypt(plainBytes, aesKeyBytes, "AES",
  492. "AES/ECB/PKCS5Padding", null)), StandardCharsets.UTF_8);
  493. String sign = new String(Base64.encodeBase64(
  494. CryptoUtil.digitalSign(plainBytes, CertUtil.getPrivateKey(),
  495. "SHA1WithRSA")), StandardCharsets.UTF_8);
  496. String encryptKey = new String(Base64.encodeBase64(
  497. CryptoUtil.RSAEncrypt(aesKeyBytes, CertUtil.getPublicKey(), 2048, 11,
  498. "RSA/ECB/PKCS1Padding")), StandardCharsets.UTF_8);
  499. Map<String, String> reqMap = new HashMap<String, String>();
  500. //整体报文格式
  501. reqMap.put("transCode", "ODQU"); // 交易码
  502. reqMap.put("accessType", "0"); // 接入类型
  503. reqMap.put("merId", sandPayProperties.getMid()); // 合作商户ID 杉德系统分配,唯一标识
  504. reqMap.put("plId", null);
  505. reqMap.put("encryptKey", encryptKey); // 加密后的AES秘钥
  506. reqMap.put("encryptData", encryptData); // 加密后的请求/应答报文
  507. reqMap.put("sign", sign); // 签名
  508. reqMap.put("extend", ""); // 扩展域
  509. String result;
  510. try {
  511. log.info("请求报文:{}", reqMap);
  512. result = HttpClient.doPost("https://caspay.sandpay.com.cn/agent-main/openapi/queryOrder",
  513. reqMap, 300000, 300000);
  514. result = URLDecoder.decode(result, StandardCharsets.UTF_8);
  515. } catch (IOException e) {
  516. log.error(e.getMessage());
  517. return null;
  518. }
  519. log.info("响应报文:{}", result);
  520. Map<String, String> responseMap = SDKUtil.convertResultStringToMap(result);
  521. String retEncryptKey = responseMap.get("encryptKey");
  522. String retEncryptData = responseMap.get("encryptData");
  523. String retSign = responseMap.get("sign");
  524. log.debug("retEncryptKey:[{}]", retEncryptKey);
  525. log.debug("retEncryptData:[{}]", retEncryptData);
  526. log.debug("retSign:[{}]", retSign);
  527. byte[] decodeBase64KeyBytes = Base64.decodeBase64(retEncryptKey
  528. .getBytes(StandardCharsets.UTF_8));
  529. byte[] merchantAESKeyBytes = CryptoUtil.RSADecrypt(
  530. decodeBase64KeyBytes, CertUtil.getPrivateKey(), 2048, 11,
  531. "RSA/ECB/PKCS1Padding");
  532. byte[] decodeBase64DataBytes = Base64.decodeBase64(retEncryptData.getBytes(StandardCharsets.UTF_8));
  533. byte[] respDataBytes = CryptoUtil.AESDecrypt(decodeBase64DataBytes,
  534. merchantAESKeyBytes, "AES", "AES/ECB/PKCS5Padding", null);
  535. String respData = new String(respDataBytes, StandardCharsets.UTF_8);
  536. log.info("retData:[" + respData + "]");
  537. System.out.println("响应data数据:" + respData);
  538. byte[] signBytes = Base64.decodeBase64(retSign.getBytes(StandardCharsets.UTF_8));
  539. boolean isValid = CryptoUtil.verifyDigitalSign(respDataBytes, signBytes,
  540. CertUtil.getPublicKey(), "SHA1WithRSA");
  541. if (!isValid) {
  542. log.error("verify sign fail.");
  543. return null;
  544. }
  545. log.info("verify sign success");
  546. System.out.println("verify sign success");
  547. JSONObject respJson = JSONObject.parseObject(respData);
  548. return respJson;
  549. } catch (Exception e) {
  550. log.error(e.getMessage());
  551. return null;
  552. }
  553. }
  554. }