123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810 |
- package com.szwl.controller;
- import com.alibaba.fastjson.JSON;
- import com.alibaba.fastjson.JSONObject;
- import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
- import com.baomidou.mybatisplus.core.toolkit.Wrappers;
- import com.fasterxml.jackson.core.JsonProcessingException;
- import com.fasterxml.jackson.databind.JsonNode;
- import com.fasterxml.jackson.databind.ObjectMapper;
- import com.fasterxml.jackson.databind.node.ArrayNode;
- import com.fasterxml.jackson.databind.node.JsonNodeFactory;
- import com.fasterxml.jackson.databind.node.ObjectNode;
- import com.szwl.common.AccessTokenCommon;
- import com.szwl.constant.AirwallexConstant;
- import com.szwl.feign.bean.SzwlFeign;
- import com.szwl.model.bean.PaymentIntentRequestBody;
- import com.szwl.model.bean.RefundRequestBody;
- import com.szwl.model.bo.R;
- import com.szwl.model.bo.ResponseModel;
- import com.szwl.model.dto.*;
- import com.szwl.model.entity.*;
- import com.szwl.model.utils.AccessTokenThreadUtil;
- import com.szwl.service.*;
- import io.swagger.annotations.Api;
- import io.swagger.annotations.ApiOperation;
- import lombok.extern.slf4j.Slf4j;
- import org.apache.commons.lang.StringUtils;
- import org.springframework.beans.factory.annotation.Value;
- import org.springframework.scheduling.annotation.Scheduled;
- import org.springframework.web.bind.annotation.*;
- import java.math.BigDecimal;
- import java.math.RoundingMode;
- import java.sql.Timestamp;
- import java.text.ParseException;
- import java.text.SimpleDateFormat;
- import java.time.OffsetDateTime;
- import java.time.format.DateTimeFormatter;
- import java.util.*;
- //@CrossOrigin
- @Api(value = "/api/airwallexPay", tags = {"空中云汇"})
- @RestController
- @RequestMapping("/api/airwallexPay")
- @Slf4j
- public class AirwallexPayController {
- // @Value("${test.value:bbb}")
- // private String testValue;
- TAdminService tAdminService;
- AirwallexService airwallexService;
- TCoinOrderService tCoinOrderService;
- TOrderDetailsService tOrderDetailsService;
- TAirwallexPaymentService tAirwallexPaymentService;
- SzwlFeign szwlFeign;
- TAirwallexMchService airwallexMchService;
- TAirwallexWalletService airwallexWalletService;
- public AirwallexPayController(TAdminService tAdminService, AirwallexService airwallexService, TCoinOrderService tCoinOrderService, TOrderDetailsService tOrderDetailsService, TAirwallexPaymentService tAirwallexPaymentService, SzwlFeign szwlFeign, TAirwallexMchService airwallexMchService, TAirwallexWalletService airwallexWalletService) {
- this.tAdminService = tAdminService;
- this.airwallexService = airwallexService;
- this.tCoinOrderService = tCoinOrderService;
- this.tOrderDetailsService = tOrderDetailsService;
- this.tAirwallexPaymentService = tAirwallexPaymentService;
- this.szwlFeign = szwlFeign;
- this.airwallexMchService = airwallexMchService;
- this.airwallexWalletService = airwallexWalletService;
- }
- @ApiOperation(value = "创建收款人")
- @PostMapping("/caBeneficiary")
- public JsonNode caBeneficiary(@RequestBody CaBeneficiaryRequestDTO requestDTO) {
- BeneficiaryDTO beneficiary = requestDTO.getBeneficiary();
- List<String> paymentMethods = requestDTO.getPaymentMethods();
- String nickname = requestDTO.getNickname();
- String resp = airwallexService.caBeneficiary(beneficiary, nickname, paymentMethods);
- try {
- JsonNode jsonNode = new ObjectMapper().readTree(resp);
- return jsonNode;
- } catch (JsonProcessingException e) {
- e.printStackTrace();
- }
- // JSONObject jsonObject = JSON.parseObject(resp);
- // String beneficiaryId = jsonObject.getString("beneficiary_id");
- return null;
- }
- @ApiOperation(value = "获取authCode")
- @PostMapping("/getAuthCode")
- public JsonNode getAuthCode(@RequestBody GetAuthCodeDTO getAuthCodeDTO) {
- String codeChallenge = getAuthCodeDTO.getCodeChallenge();
- String[] scope = getAuthCodeDTO.getScope();
- String resp = airwallexService.getAuthCode(codeChallenge, scope);
- try {
- JsonNode jsonNode = new ObjectMapper().readTree(resp);
- return jsonNode;
- } catch (JsonProcessingException e) {
- e.printStackTrace();
- }
- return null;
- }
- // @GetMapping("/getAccessToken")
- // public ResponseModel<?> getAccessToken() {
- // String accessToken = airwallexService.getAccessToken();
- // //获取到的accessToken可以放入内存或者存到数据库中,不用每次都获取
- // return R.ok(accessToken);
- // }
- @ApiOperation(value = "获取token")
- @GetMapping("/getAccessToken")
- @Scheduled(cron = "0 0/20 * * * ?")
- public void getAccessToken() {
- AccessTokenCommon.ACCESS_TOKEN = AccessTokenThreadUtil.getAccessToken();
- }
- /**
- * 创建付款意向 - 消费者发起
- *
- * @param paymentIntentRequestBody
- * @return
- */
- @ApiOperation(value = "Create a PaymentIntent")
- @PostMapping("/createAPaymentIntent")
- public R createAPaymentIntent(@RequestBody PaymentIntentRequestBody paymentIntentRequestBody) {
- log.info("发起支付请求");
- // 先获取token
- // String accessToken = airwallexService.getAccessToken();
- // new AccessTokenThreadUtil().run();
- // String accessToken = AccessTokenCommon.ACCESS_TOKEN;
- //
- // if(accessToken == null || "".equals(accessToken)) {
- // accessToken = new AccessTokenThreadUtil().getAccessToken();
- // return R.fail(L0006);
- // }
- // 如果是海外客户,使用的是 Airwallex ,就要判断他有没有设置分销
- // 在 Airwallex 支付之前,要先判断
- String createDate = paymentIntentRequestBody.getCreateDate();
- BigDecimal amount = paymentIntentRequestBody.getAmount();
- String currency = paymentIntentRequestBody.getCurrency();
- String merchantOrderId = paymentIntentRequestBody.getMerchantOrderId();
- // String requestId = paymentIntentRequestBody.getRequestId();
- String requestId = UUID.randomUUID().toString().trim().replaceAll("-", "");
- Long productId = paymentIntentRequestBody.getProductId();
- String productName = paymentIntentRequestBody.getProductName();
- String clientId = paymentIntentRequestBody.getClientId();
- Long equipmentId = paymentIntentRequestBody.getEquipmentId();
- Integer productNumber = paymentIntentRequestBody.getProductNumber();
- // 生成订单编号
- String sn = tCoinOrderService.initSn(equipmentId);
- // 七云还是申泽
- TEquipment equipment = R.getDataIfSuccess(szwlFeign.findEquipmentByClientId(clientId));
- if (equipment == null || equipmentId == null) {
- return R.fail("找不到设备");
- }
- // System.out.println("设备信息:>>> " + equipment);
- String machineType = equipment.getMachineType(); // 设备类型
- Long adminId = equipment.getAdminId();
- if (adminId == null) {
- return R.fail("找不到设备商家");
- }
- String adminIdStr = String.valueOf(adminId);
- // 根据 adminId 获取admin信息中的公司类型
- TAdmin adminById = R.getDataIfSuccess(szwlFeign.getAdmin(adminIdStr));
- // TAdmin byId = tAdminService.getById(adminId);
- String companyType = adminById.getCompanyType(); // 公司类型
- // Airwallex 分账参数
- ArrayNode altInfos = JsonNodeFactory.instance.arrayNode();
- // Airwallex 分账明细
- ObjectNode airDistributionDetails = JsonNodeFactory.instance.objectNode();
- // 查找商品
- ResponseModel<TProduct> product = szwlFeign.getProduct(String.valueOf(equipmentId), productName);
- // 获取关联设备的分销
- TProportion proportion = R.getDataIfSuccess(szwlFeign.getProportion(String.valueOf(equipmentId)));
- airDistributionDetails = getDistributionDetails(proportion, amount);
- // 创建订单
- TCoinOrder tCoinOrder = new TCoinOrder();
- tCoinOrder.setAdminId(adminById.getId());
- if (StringUtils.isNotEmpty(createDate)) {
- SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
- Date parse = null;
- try {
- parse = simpleDateFormat.parse(createDate);
- } catch (ParseException e) {
- throw new RuntimeException(e);
- }
- tCoinOrder.setCreateDate(parse);
- tCoinOrder.setModifyDate(parse);
- } else {
- tCoinOrder.setCreateDate(new Date());
- tCoinOrder.setModifyDate(new Date());
- }
- tCoinOrder.setPayDate(new Date());
- tCoinOrder.setSn(sn);
- tCoinOrder.setAmount(amount);
- tCoinOrder.setCurrency(currency);
- tCoinOrder.setMerchantOrderId(merchantOrderId);
- tCoinOrder.setRequestId(requestId);
- tCoinOrder.setProductId(productId);
- tCoinOrder.setProductName(productName);
- tCoinOrder.setProductNumber(productNumber);
- tCoinOrder.setClientId(clientId);
- tCoinOrder.setEquipmentId(equipmentId);
- // 设置订单支付状态,0未支付,1已支付,3已退款。
- tCoinOrder.setStatus(0);
- tCoinOrder.setIsAir("1");
- tCoinOrder.setAltInfo(altInfos.toString());
- tCoinOrder.setMachineType(machineType);
- tCoinOrder.setCompanyType(companyType);
- tCoinOrder.setType(adminById.getType());
- switch (adminById.getType()) {
- case 0:
- tCoinOrder.setAdminProportion(proportion.getAdminProportion());
- tCoinOrder.setAgencyProportion(proportion.getAgencyProportion());
- tCoinOrder.setAgencyId(proportion.getAgencyId());
- break;
- case 1:
- tCoinOrder.setAdminProportion(proportion.getAdminProportion());
- tCoinOrder.setAgencyProportion(proportion.getAgencyProportion());
- tCoinOrder.setAgencyId(proportion.getAgencyId());
- tCoinOrder.setMerchantProportion(proportion.getMerchantProportion());
- tCoinOrder.setMerchantId(proportion.getMerchantId());
- break;
- case 2:
- tCoinOrder.setAdminProportion(proportion.getAdminProportion());
- tCoinOrder.setAgencyProportion(proportion.getAgencyProportion());
- tCoinOrder.setAgencyId(proportion.getAgencyId());
- tCoinOrder.setMerchantProportion(proportion.getMerchantProportion());
- tCoinOrder.setMerchantId(proportion.getMerchantId());
- tCoinOrder.setPersonageProportion(proportion.getPersonageProportion());
- tCoinOrder.setPersonageId(proportion.getPersonageId());
- break;
- default:
- // 如果类型不匹配任何 case,则执行默认逻辑
- break;
- }
- tCoinOrder.setAltInfo(airDistributionDetails.toString());
- // 订单明细表
- TOrderDetails tOrderDetails = new TOrderDetails();
- tOrderDetails.setId(merchantOrderId);
- tOrderDetails.setAdminId(adminById.getId());
- tOrderDetails.setEquipmentId(equipmentId);
- if (StringUtils.isNotEmpty(createDate)) {
- SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
- Date parse = null;
- try {
- parse = simpleDateFormat.parse(createDate);
- } catch (ParseException e) {
- throw new RuntimeException(e);
- }
- tOrderDetails.setCreateDate(parse);
- } else {
- tOrderDetails.setCreateDate(new Date());
- }
- tOrderDetails.setOrderSn(sn);
- tOrderDetails.setPrice(amount);
- tOrderDetails.setProductName(productName);
- tOrderDetails.setProductNo(product.getData().getNo());
- tOrderDetails.setProductNumber(productNumber);
- tOrderDetails.setAmount(amount);
- tOrderDetails.setRefundStatus("0");
- tOrderDetails.setCompanyType(companyType);
- tOrderDetails.setMachineType(machineType);
- String clientSix = clientId.substring(clientId.length() - 6);
- String productNameMerge = "";
- if (productNumber > 1) {
- if (machineType == null || "0".equals(machineType)) {
- productNameMerge = "棉花糖-" + equipment.getName() + "-" + clientSix;
- } else {
- productNameMerge = "爆米花-" + equipment.getName() + "-" + clientSix;
- }
- } else {
- productNameMerge = productName + "-" + equipment.getName() + "-" + clientSix;
- }
- ObjectMapper mapper = new ObjectMapper();
- ObjectNode order = mapper.createObjectNode();
- ArrayNode products = mapper.createArrayNode();
- ObjectNode airProduct = mapper.createObjectNode();
- // Name of the product. Maximum of 255 characters.
- // airProduct.put("name", productNameMerge);
- // Product description. Maximum of 500 characters.
- airProduct.put("desc", productNameMerge);
- airProduct.put("quantity", productNumber);
- products.add(airProduct);
- order.set("products", products);
- // 返回payment intent id和client secret
- Map<String, Object> responseMap = airwallexService.caPaymentIntent(amount, currency, requestId, merchantOrderId, order);
- String paymentIntentId = (String) responseMap.get("id");
- String clientSecret = (String) responseMap.get("client_secret");
- // 把 paymentIntentId 保存到表中
- tCoinOrder.setPaymentIntentId(paymentIntentId);
- // boolean save = tOrderAbroadService.save(tOrderAbroad);
- // System.out.println("将订单存入数据库:" + save);
- // 拼接二维码链接给前端
- // String env = AirwallexConstant.ENV;
- // String mode = AirwallexConstant.MODE;
- // String locale = "it";
- String qrUrl = AirwallexConstant.QR_URL;
- String QR = qrUrl + "?intent_id=" + paymentIntentId + "&client_secret=" + clientSecret + "¤cy=" + currency;
- // 将订单存入数据库
- tCoinOrderService.save(tCoinOrder);
- tOrderDetailsService.save(tOrderDetails);
- return R.ok().setData(QR);
- }
- @ApiOperation(value = "获取支付订单的信息,订单状态")
- @GetMapping("/retrieveAPaymentIntent")
- public JSON retrieveAPaymentIntent(@RequestParam String id) {
- log.info("查询支付订单信息");
- // 这里的intId指的是paymentIntendId,也是id
- String intentResp = airwallexService.retrieveAPaymentIntent(id);
- JSONObject jsonObject = JSON.parseObject(intentResp);
- // 取消订单的原因
- // String cancellationReason = jsonObject.getString("cancellation_reason");
- // 支付信息
- String amount = jsonObject.getString("amount");
- String currency = jsonObject.getString("currency");
- String createdAt = jsonObject.getString("created_at");
- String updatedAt = jsonObject.getString("updated_at");
- String status = jsonObject.getString("status");
- // String customer = jsonObject.getString("customer");
- // JSONObject customerObj = JSON.parseObject(customer);
- // String address = customerObj.getString("address");
- // TODO: 要改???
- String type = jsonObject.getJSONObject("latest_payment_attempt").getJSONObject("payment_method").getString("type");
- // JSONObject jsonObject4 = Optional.ofNullable(jsonObject)
- // .flatMap(jsonObject3 -> Optional.ofNullable(jsonObject3.getJSONObject("customer")))
- // .flatMap(jsonObject3 -> Optional.ofNullable(jsonObject3.getJSONObject("address")))
- // .flatMap(jsonObject3 -> Optional.ofNullable(jsonObject3.getJSONObject("state")))
- // .orElse(null);
- // String state = JSON.toJSONString(jsonObject4);
- // JSONObject jsonObject3 = Optional.ofNullable(jsonObject)
- // .map(jsonObject1 -> jsonObject1.getJSONObject("latest_payment_attempt"))
- // .map(jsonObject1 -> jsonObject1.getJSONObject("payment_method"))
- // .map(jsonObject1 -> jsonObject1.getJSONObject("type"))
- // .orElse(null);
- // String state = JSON.toJSONString(jsonObject3);
- // JSONObject stateJson = Optional.ofNullable(jsonObject)
- // .flatMap(jsonObject1 -> Optional.ofNullable(jsonObject1.getJSONObject("customer")))
- // .flatMap(jsonObject1 -> Optional.ofNullable(jsonObject1.getJSONObject("address")))
- // .flatMap(jsonObject1 -> Optional.ofNullable(jsonObject1.getJSONObject("state")))
- // .orElse(null);
- // String state = JSON.toJSONString(stateJson);
- // JSONObject cityJson = Optional.ofNullable(jsonObject)
- // .flatMap(jsonObject1 -> Optional.ofNullable(jsonObject1.getJSONObject("latest_payment_attempt")))
- // .flatMap(jsonObject1 -> Optional.ofNullable(jsonObject1.getJSONObject("payment_method")))
- // .flatMap(jsonObject1 -> Optional.ofNullable(jsonObject1.getJSONObject("id")))
- // .orElse(null);
- // String city = JSON.toJSONString(cityJson);
- Map<String, Object> intentDetails = new HashMap<>();
- intentDetails.put("amount", amount);
- intentDetails.put("currency", currency);
- // intentDetails.put("state",state);
- intentDetails.put("type", type);
- intentDetails.put("createdAt", createdAt);
- intentDetails.put("status", status);
- return new JSONObject(intentDetails);
- }
- @ApiOperation(value = "发起退款")
- @PostMapping("/createARefund")
- public ResponseModel<String> createARefund(@RequestBody RefundRequestBody refundRequestBody) {
- log.info("发起退款");
- String requestId = UUID.randomUUID().toString().trim().replaceAll("-", "");
- // String requestId = refundRequestBody.getRequestId();
- String paymentIntentId = refundRequestBody.getPaymentIntentId();
- Date refundDate = refundRequestBody.getRefundDate();
- // String reason = refundRequestBody.getReason();
- // QueryWrapper<TOrderAbroad> tOrderAbroadQueryWrapper = new QueryWrapper<>();
- // tOrderAbroadQueryWrapper.eq("request_id", requestId);
- // TOrderAbroad orderAbroad = tOrderAbroadService.getOne(tOrderAbroadQueryWrapper);
- LambdaQueryWrapper<TCoinOrder> lambdaQueryWrapper = Wrappers.lambdaQuery();
- lambdaQueryWrapper.eq(TCoinOrder::getPaymentIntentId, paymentIntentId);
- TCoinOrder coinOrder = tCoinOrderService.getOne(lambdaQueryWrapper);
- if (coinOrder == null) {
- return R.fail("订单为空/error");
- }
- // 支付状态:退款中
- coinOrder.setStatus(2);
- // 修改订单表
- // SimpleDateFormat sdf = new SimpleDateFormat();
- // sdf.applyPattern("yyyy-MM-dd HH:mm:ss");
- // orderAbroad.setRefundDate(sdf.format(date));
- // LocalDateTime localDateTime = LocalDateTime.now();
- // DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
- // String format = localDateTime.format(dtf);
- // 退款发起时间
- coinOrder.setRefundDate(refundDate);
- tCoinOrderService.updateById(coinOrder);
- // TODO: 退款要扣除用户钱包中的金额,如果金额为0或者不足,改为负数?或者提示余额不足,联系商家手动退款
- // 发起退款
- // String refund = airwallexService.createARefund(requestId, paymentIntentId, reason);
- String refund = airwallexService.createARefund(requestId, paymentIntentId);
- System.out.println(refund);
- JSONObject jsonObject = JSON.parseObject(refund);
- String status = jsonObject.getString("status");
- // orderAbroad.set;
- // tOrderAbroadService.updateById(orderAbroad);
- // switch (status) {
- // case "RECEIVED" :
- // System.out.println("退款被接收");
- // break;
- // case "ACCEPTED" :
- // System.out.println("退款被接受");
- // break;
- // case "SUCCEEDED" :
- // System.out.println("退款成功");
- // break;
- // case "FAILED" :
- // System.out.println("退款失败");
- // break;
- // }
- // if (!status.equals("FAILED")) {
- if (status.equals("RECEIVED") || status.equals("ACCEPTED") || status.equals("SUCCEEDED")) {
- String refundId = jsonObject.getString("id");
- coinOrder.setRefundId(refundId);
- tCoinOrderService.updateById(coinOrder);
- return R.ok("退款处理中,请稍候查询");
- }
- return R.fail("退款失败");
- // if (Objects.equals(status, "SUCCEEDED")) {
- // String refundId = jsonObject.getString("id");
- // orderAbroad.setRefundId(refundId);
- //// orderAbroad.setPayStatus(3);
- // tOrderAbroadService.updateById(orderAbroad);
- // return R.ok("退款申请中,请稍候查询");
- // } else {
- // return R.ok("退款失败");
- // }
- }
- @ApiOperation(value = "查询某笔退款详情")
- @GetMapping("/retrieveARefund/{id}")
- public Map<String, Object> retrieveARefund(@PathVariable("id") String refundId) {
- log.info("根据rfd_查询某笔退款详情");
- // String requestId = UUID.randomUUID().toString().trim().replaceAll("-", "");
- String refundResp = airwallexService.retrieveARefund(refundId);
- JSONObject jsonObject = JSON.parseObject(refundResp);
- String amount = jsonObject.getString("amount");
- String status = jsonObject.getString("status");
- String currency = jsonObject.getString("currency");
- String paymentIntentId = jsonObject.getString("payment_intent_id");
- String createdAt = jsonObject.getString("created_at");
- Map<String, Object> hashMap = new HashMap<>();
- hashMap.put("amount", amount);
- hashMap.put("status", status);
- hashMap.put("currency", currency);
- hashMap.put("payment_intent_id", paymentIntentId);
- hashMap.put("created_at", createdAt);
- // if (status.equals("SUCCEEDED")) {
- //
- // LambdaQueryWrapper<TOrderAbroad> lambdaQueryWrapper = Wrappers.lambdaQuery();
- // lambdaQueryWrapper.eq(TOrderAbroad::getRefundId, refundId);
- // TOrderAbroad orderAbroad = tOrderAbroadService.getOne(lambdaQueryWrapper);
- //
- //// if (orderAbroad == null ) {
- //// return "订单为空/error";
- //// }
- // if (Objects.isNull(orderAbroad)) {
- // return "订单为空/error";
- // }
- // // 设置支付状态为 3已退款
- // orderAbroad.setPayStatus(3);
- // tOrderAbroadService.updateById(orderAbroad);
- // }
- return hashMap;
- }
- @ApiOperation(value = "新建一笔付款,用于提现")
- @PostMapping("/caPayment")
- public R caPayment(@RequestBody CaPaymentRequestDTO caPaymentRequestDTO) {
- Long adminId = caPaymentRequestDTO.getAdminId();
- String resp = airwallexService.caPayment(caPaymentRequestDTO);
- ObjectMapper objectMapper = new ObjectMapper();
- JsonNode jsonNode = null;
- try {
- jsonNode = objectMapper.readTree(resp);
- } catch (JsonProcessingException e) {
- e.printStackTrace();
- }
- // 断言确保 jsonNode 不为 null
- assert jsonNode != null;
- String paymentId = jsonNode.get("payment_id").asText();
- String paymentCurrency = jsonNode.get("payment_currency").asText();
- String paymentAmountStr = jsonNode.get("payment_amount").asText();
- String beneficiaryId = jsonNode.get("beneficiary_id").asText();
- String createdAtStr = jsonNode.get("created_at").asText();
- // 保存支付提现明细
- TAirwallexPayment tAirwallexPayment = new TAirwallexPayment();
- tAirwallexPayment.setPaymentId(paymentId);
- tAirwallexPayment.setPaymentCurrency(paymentCurrency);
- BigDecimal paymentAmount = new BigDecimal(paymentAmountStr);
- tAirwallexPayment.setPaymentAmount(paymentAmount);
- tAirwallexPayment.setBeneficiaryId(beneficiaryId);
- DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ssZ");
- OffsetDateTime createdAt = OffsetDateTime.parse(createdAtStr, formatter);
- Timestamp from = Timestamp.from(createdAt.toInstant());
- tAirwallexPayment.setCreateTime(from);
- tAirwallexPayment.setAdminId(adminId);
- tAirwallexPaymentService.save(tAirwallexPayment);
- // TODO: 默认每次将余额全部提现,考虑货币
- // tAirwallexWalletService.list()
- // LambdaQueryWrapper<TAirwallexWallet> wrapper = Wrappers.lambdaQuery();
- // wrapper.eq(TAirwallexWallet::getAdminId, adminId);
- //// List<TAirwallexWallet> list = tAirwallexWalletService.list(wrapper);
- // TAirwallexWallet one = tAirwallexWalletService.getOne(wrapper);
- // String accountCurrency = one.getAccountCurrency();
- // BigDecimal accountAmount = one.getAccountAmount();
- // 先判断货币是否一样
- // if (accountCurrency.equals(paymentCurrency)) {
- // accountAmount = accountAmount.subtract(paymentAmount);
- // } else {
- // //
- // }
- // 返回 payment_id
- return R.ok(paymentId);
- }
- @ApiOperation(value = "查询支付结果")
- @GetMapping("/getPaymentById/{payment_id}")
- public R getPaymentById(@PathVariable("payment_id") String paymentId) {
- String resp = airwallexService.getPaymentById(paymentId);
- return R.ok(resp);
- }
- @ApiOperation(value = "查询当前账户余额")
- @GetMapping("/getCurrentBalances")
- public R getCurrentBalances() {
- String resp = airwallexService.getCurrentBalances();
- return R.ok(resp);
- }
- /**
- * 获取 Airwallex 分销明细
- *
- * @param proportion
- * @param price
- * @return
- */
- public ObjectNode getDistributionDetails(TProportion proportion, BigDecimal price) {
- // 获取分账有几方:0:分账方2个,1:分账方3个,2:分账方4个,3:分账方超4个
- Integer type = proportion.getType();
- // 空中云汇 分账明细参数
- // ArrayNode altInfos = new ObjectMapper().createArrayNode();
- ArrayNode altInfos = JsonNodeFactory.instance.arrayNode();
- ObjectNode distributionDetails = JsonNodeFactory.instance.objectNode();
- BigDecimal airProportion = null, // 空中云汇平台分销百分比,假设是0
- selfProportion = null, // 商家自己的分销百分比
- agencyProportion = null, // 一级分销商分销百分比
- merchantProportion = null; // 二级分销商分销百分比
- BigDecimal airAmount = null, // 空中云汇的钱,假设是0
- selfAmount = null, // 商家自己所得的钱
- agencyAmount = null, // 一级分销商所得的钱
- merchantAmount = null; // 二级分销商所得的钱
- TAirwallexWallet selfAirWallet = null, // 商家收款信息
- agencyAirWallet = null, // 一级分销商收款信息
- merchantAirWallet = null; // 二级分销商收款信息
- ObjectNode airJson = null, // 空中云汇
- selfJson = null, // 商家
- agencyJson = null, // 一级
- merchantJson = null; // 二级
- // 取消平台扣手续费,将price四舍五入保留2位小数
- BigDecimal cutPrice = price.setScale(2, RoundingMode.HALF_UP);
- BigDecimal refuseAmount = new BigDecimal(0.00);
- switch (type) {
- case 0: // 分账方有2个:申泽admin + 商家proportion
- // 目前都暂定空中云汇平台分销为 0
- // airProportion = proportion.getAdminProportion();
- // 申泽的分销 eg.1% 不显示
- // adminProportion = proportion.getAdminProportion();
- // 商家自己的分销
- selfProportion = proportion.getProportion();
- // 平台分销获得利润
- // airAmount = cutPrice.multiply(airProportion.divide(new BigDecimal(100))).setScale(2, RoundingMode.HALF_UP);
- // 商家分销获得利润,五舍六入
- selfAmount = cutPrice.multiply(selfProportion.divide(new BigDecimal(100))).setScale(2, RoundingMode.HALF_DOWN);
- // Airwallex 平台收款信息表
- // Long adminId = proportion.getAdminId();
- // LambdaQueryWrapper<TAirwallexMch> wrapper = Wrappers.lambdaQuery();
- // wrapper.eq(TAirwallexMch::getAdminId, proportion.getAdminId());
- // selfAirMch = airwallexMchService.getOne(wrapper);
- // Airwallex 钱包信息
- LambdaQueryWrapper<TAirwallexWallet> query = Wrappers.lambdaQuery();
- query.eq(TAirwallexWallet::getAdminId, proportion.getAdminId());
- selfAirWallet = airwallexWalletService.getOne(query);
- // 平台分销
- // airJson = JsonNodeFactory.instance.objectNode();
- // // 分账方受益人编号
- // airJson.put("altMchId", selfAirMch.getBeneficiaryId());
- // // 受益人所分金额,单位美元$
- // airJson.put("altAirAmount", airAmount.toString());
- // altInfos.add(airJson);
- // 商家分销
- selfJson = JsonNodeFactory.instance.objectNode();
- selfJson.put("airBeneId", selfAirWallet.getAdminId()); // 受益人Bene编号,使用adminId
- selfJson.put("airAmount", selfAmount.toString());
- altInfos.add(selfJson);
- break;
- case 1: // 分账方有3个:申泽admin + 商家proportion + 商家一级agency
- // 商家自己的分销
- selfProportion = proportion.getProportion();
- // 一级代理的分销
- agencyProportion = proportion.getAgencyProportion();
- // 商家分销获得利润
- selfAmount = cutPrice.multiply(selfProportion.divide(new BigDecimal(100))).setScale(2, RoundingMode.HALF_DOWN);
- // Airwallex 平台收款信息表
- agencyAirWallet = airwallexWalletService.getAirWallet(proportion.getAgencyId());
- selfAirWallet = airwallexWalletService.getAirWallet(proportion.getAdminId());
- if (!(agencyProportion.compareTo(refuseAmount) == 0 || agencyProportion == null)) {
- // 一级代理获得利润
- agencyAmount = cutPrice.multiply(agencyProportion.divide(new BigDecimal(100))).setScale(2, RoundingMode.HALF_DOWN);
- agencyJson = JsonNodeFactory.instance.objectNode();
- agencyJson.put("airBeneId", agencyAirWallet.getAdminId());
- agencyJson.put("airAmount", agencyAmount.toString());
- altInfos.add(agencyJson);
- }
- // 商家自己获得利润
- selfJson = JsonNodeFactory.instance.objectNode();
- selfJson.put("airBeneId", selfAirWallet.getAdminId());
- selfJson.put("airAmount", selfAmount.toString());
- altInfos.add(selfJson);
- break;
- case 2: // 分账方有4个:申泽admin + 商家self + 商家一级agency + 商家二级merchant
- // 商家自己的分销
- selfProportion = proportion.getProportion();
- // 一级代理的分销
- agencyProportion = proportion.getAgencyProportion();
- // 二级代理的分销
- merchantProportion = proportion.getMerchantProportion();
- // 商家分销获得利润,五舍六入
- selfAmount = cutPrice.multiply(selfProportion.divide(new BigDecimal(100))).setScale(2, RoundingMode.HALF_DOWN);
- // Airwallex 平台收款信息表
- Long adminId = proportion.getAdminId();
- if (adminId != null) {
- selfAirWallet = airwallexWalletService.getAirWallet(adminId);
- System.out.println("selfAirWallet打印出来》》》" + selfAirWallet);
- }
- Long agencyId = proportion.getAgencyId();
- if (agencyId != null) {
- agencyAirWallet = airwallexWalletService.getAirWallet(agencyId);
- System.out.println("agencyAirWallet打印出来》》》" + agencyAirWallet);
- }
- Long merchantId = proportion.getMerchantId();
- if (merchantId != null ) {
- merchantAirWallet = airwallexWalletService.getAirWallet(merchantId);
- System.out.println("merchantAirWallet打印出来》》》" + merchantAirWallet);
- }
- if (!(agencyProportion.compareTo(refuseAmount) == 0 || agencyProportion == null)) {
- // 一级代理获得利润
- agencyAmount = cutPrice.multiply(agencyProportion.divide(new BigDecimal(100))).setScale(2, RoundingMode.HALF_DOWN);
- agencyJson = JsonNodeFactory.instance.objectNode();
- agencyJson.put("airBeneId", agencyAirWallet.getAdminId());
- agencyJson.put("airAmount", agencyAmount.toString());
- altInfos.add(agencyJson);
- }
- if (!(merchantProportion.compareTo(refuseAmount) == 0 || merchantProportion == null)) {
- // 二级经销商获得利润
- merchantAmount = cutPrice.multiply(merchantProportion.divide(new BigDecimal(100))).setScale(2, RoundingMode.HALF_DOWN);
- merchantJson = JsonNodeFactory.instance.objectNode();
- merchantJson.put("airBeneId", merchantAirWallet.getAdminId());
- merchantJson.put("airAmount", merchantAmount.toString());
- altInfos.add(merchantJson);
- }
- // 商家自己获得利润
- selfJson = JsonNodeFactory.instance.objectNode();
- selfJson.put("airBeneId", selfAirWallet.getAdminId());
- selfJson.put("airAmount", selfAmount.toString());
- altInfos.add(selfJson);
- break;
- case 3: // 分账方超过4个:申泽admin + 商家self + 商家一级agency + 商家二级merchant + 商家三级personage
- // personageProportion = proportion.getPersonageProportion();
- break;
- }
- // 计算airAmount的总和
- BigDecimal sumAmount = BigDecimal.ZERO;
- Iterator<JsonNode> iterator = altInfos.iterator();
- while (iterator.hasNext()) {
- JsonNode jsonNode = iterator.next();
- String airAmounts = jsonNode.get("airAmount").asText();
- if (airAmounts.equals("0.00")) {
- iterator.remove();
- }
- if (jsonNode.has("airAmount")) {
- BigDecimal airAmountSum = new BigDecimal(jsonNode.get("airAmount").asText());
- sumAmount = sumAmount.add(airAmountSum);
- }
- }
- // 如果sumAmount大于原本price
- if (sumAmount.compareTo(price) > 0) {
- BigDecimal subtract = sumAmount.subtract(price);
- Iterator<JsonNode> iterator1 = altInfos.iterator();
- while (iterator1.hasNext()) {
- JsonNode jsonNode = iterator1.next();
- String airBeneId = jsonNode.get("airBeneId").asText();
- // String airBeneId1 = jsonNode.get("airBeneId").toString();
- if (airBeneId.equals(AirwallexConstant.clientid)) {
- BigDecimal airAmount1 = new BigDecimal(jsonNode.get("airAmount").asText());
- BigDecimal fixAirAmount = airAmount1.subtract(subtract).max(BigDecimal.ZERO);
- // ObjectMapper objectMapper = new ObjectMapper();
- // ObjectNode objectNode = objectMapper.convertValue(jsonNode, ObjectNode.class);
- // objectNode.put("airAmount", fixAirAmount.toString());
- ((ObjectNode) jsonNode).put("airAmount", fixAirAmount.toString());
- break;
- }
- }
- }
- distributionDetails.put("alt_infos", altInfos);
- return distributionDetails;
- }
- // 查询实时汇率
- // Retrieve an indicative MarketFX quote
- @ApiOperation(value = "查询实时汇率")
- @GetMapping("/getMarketFX")
- public Map<String, Object> getMarketFX(@RequestParam Map<String, String> params) {
- String buyCurrency = params.get("buy_currency");
- String sellCurrency = params.get("sell_currency");
- BigDecimal buyAmount = new BigDecimal(params.get("buy_amount"));
- Map<String, Object> marketFX = airwallexService.getMarketFX(buyCurrency, sellCurrency, buyAmount);
- return marketFX;
- }
- }
|