CardPaymentHttpClient.java 7.51 KB
package com.diligrp.cashier.pipeline.client;

import com.diligrp.cashier.pipeline.domain.OnlineRefundRequest;
import com.diligrp.cashier.pipeline.domain.OnlineRefundResponse;
import com.diligrp.cashier.pipeline.domain.card.CardPaymentRequest;
import com.diligrp.cashier.pipeline.domain.card.CardPaymentResponse;
import com.diligrp.cashier.pipeline.domain.card.UserCardDTO;
import com.diligrp.cashier.pipeline.exception.PaymentPipelineException;
import com.diligrp.cashier.pipeline.type.OutPaymentType;
import com.diligrp.cashier.pipeline.type.PaymentState;
import com.diligrp.cashier.shared.ErrorCode;
import com.diligrp.cashier.shared.service.ServiceEndpointSupport;
import com.diligrp.cashier.shared.type.SourceType;
import com.diligrp.cashier.shared.util.JsonUtils;
import com.fasterxml.jackson.core.type.TypeReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

public class CardPaymentHttpClient extends ServiceEndpointSupport {

    private static final Logger LOG = LoggerFactory.getLogger(CardPaymentHttpClient.class);

    private static final String PAYMENT_URL = "/api/cashier/pay";

    private static final String REFUND_URL = "/api/cashier/refund";

    private static final String LIST_CARD_URL = "/cashier/query/accountList";

    private final String baseUri;

    private final Long outMchId;

    private final Long accountId;

    public CardPaymentHttpClient(String baseUri, Long outMchId, Long accountId) {
        this.baseUri = baseUri;
        this.outMchId = outMchId;
        this.accountId = accountId;
    }

    public CardPaymentResponse sendPaymentRequest(CardPaymentRequest request) {
        String uri = String.format("%s%s", baseUri, PAYMENT_URL);
        SourceType sourceType = request.getObject("source", SourceType.class);
        Map<String, Object> params = new LinkedHashMap<>();
        params.put("mchId", outMchId); // 市场ID
        params.put("accountId", accountId); // 市场ID
        params.put("fromCardNo", request.getCardNo());
        params.put("fromAccountId", request.getAccountId());
        params.put("amount", request.getAmount());
        params.put("serviceCost", 0);
        params.put("password", request.getPassword());
        params.put("outTradeNo", request.getPaymentId());
        params.put("goodsDesc", request.getGoods());
        params.put("description", request.getDescription());
        if (sourceType != null) {
            params.put("sourceId", sourceType.getCode());
            params.put("sourceName", sourceType.getName());
        }
        String payload = JsonUtils.toJsonString(params);

        LOG.info("Sending card payment request: {}\n{}", request.getPaymentId(), payload);
        LocalDateTime now = LocalDateTime.now();
        HttpResult result = send(uri, payload);
        if (result.statusCode == 200) {
            LOG.debug("Card payment response received: {}\n{}", request.getPaymentId(), result.responseText);
            Map<String, Object> response = JsonUtils.fromJsonString(result.responseText, new TypeReference<>() {});
            if ("200".equals(response.get("code"))) {
                @SuppressWarnings("unchecked")
                Map<String, Object> data = (Map<String, Object>) response.get("data");
                String outTradeNo = (String) data.get("tradeId");
                Map<String, Object> payerId = new LinkedHashMap<>();
                payerId.put("customerId", convertLong(data.get("customerId")));
                payerId.put("accountId", convertLong(data.get("accountId")));
                payerId.put("cardNo", data.get("cardNo"));
                payerId.put("name", data.get("customerName"));
                return new CardPaymentResponse(request.getPaymentId(), outTradeNo, OutPaymentType.DILICARD,
                    JsonUtils.toJsonString(payerId), now, PaymentState.SUCCESS, "园区卡支付成功");
            } else {
                throw new PaymentPipelineException(ErrorCode.SERVICE_ACCESS_ERROR, "园区卡支付失败: " + response.get("message"));
            }
        }
        throw new PaymentPipelineException(ErrorCode.SERVICE_ACCESS_ERROR, "园区卡支付失败: 支付通道调用失败");
    }

    public OnlineRefundResponse sendRefundRequest(OnlineRefundRequest request) {
        String uri = String.format("%s%s", baseUri, REFUND_URL);
        Map<String, Object> params = new LinkedHashMap<>();
        params.put("refundId", request.getRefundId());
        params.put("outTradeNo", request.getPaymentId());
        params.put("amount", request.getAmount());
        String payload = JsonUtils.toJsonString(params);

        LOG.info("Sending card refund request: {}\n{}", request.getRefundId(), payload);
        LocalDateTime now = LocalDateTime.now();
        HttpResult result = send(uri, payload);
        if (result.statusCode == 200) {
            LOG.debug("Card refund response received: {}\n{}", request.getRefundId(), result.responseText);
            Map<String, Object> response = JsonUtils.fromJsonString(result.responseText, new TypeReference<>() {});
            if ("200".equals(response.get("code"))) {
                return new OnlineRefundResponse(request.getRefundId(), null, now,
                        PaymentState.SUCCESS, "园区卡退款成功");
            } else {
                throw new PaymentPipelineException(ErrorCode.SERVICE_ACCESS_ERROR, "园区卡支付退款失败: " + response.get("message"));
            }
        }
        throw new PaymentPipelineException(ErrorCode.SERVICE_ACCESS_ERROR, "园区卡支付退款失败: 支付通道调用失败");
    }

    public List<UserCardDTO> listUserCards(String userId) {
        String uri = String.format("%s%s", baseUri, LIST_CARD_URL);
        Map<String, Object> params = new LinkedHashMap<>();
        params.put("mchId", outMchId);
        params.put("customerId", Long.parseLong(userId));
        String payload = JsonUtils.toJsonString(params);

        LOG.debug("Sending list user card request: {}\n{}", userId, payload);
        HttpResult result = send(uri, payload);
        if (result.statusCode == 200) {
            LOG.debug("List user card response received: {}\n{}", userId, result.responseText);
            Map<String, Object> response = JsonUtils.fromJsonString(result.responseText, new TypeReference<>() {});
            if ("200".equals(response.get("code"))) {
                List<UserCardDTO> userCards = new ArrayList<>();
                Object data = response.get("data");
                if (data != null) {
                    List<Map<String, Object>> cardList = JsonUtils.convertValue(data, new TypeReference<>() {});
                    for (Map<String, Object> card : cardList) {
                        UserCardDTO userCard = new UserCardDTO(convertLong(card.get("customerId")),
                            convertLong(card.get("accountId")), (String) card.get("cardNo"),
                            (String) card.get("customerName"), convertLong(card.get("amount")));
                        userCards.add(userCard);
                    }
                }

                return userCards;
            } else {
                throw new PaymentPipelineException(ErrorCode.SERVICE_ACCESS_ERROR, "查询园区卡失败: " + response.get("message"));
            }
        }
        throw new PaymentPipelineException(ErrorCode.SERVICE_ACCESS_ERROR, "查询园区卡失败: 支付通道调用失败");
    }

    private Long convertLong(Object value) {
        return value != null ? ((Number) value).longValue() : null;
    }
}