CardPaymentHttpClient.java 6.95 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.debug("Sending card payment request: {}", payload);
        LocalDateTime now = LocalDateTime.now();
        HttpResult result = send(uri, payload);
        if (result.statusCode == 200) {
            LOG.debug("Received from card payment pipeline: {}", result.responseText);
            Map<String, Object> response = JsonUtils.fromJsonString(result.responseText, new TypeReference<>() {});
            if ("200".equals(response.get("code"))) {
                String outTradeNo = (String) response.get("data");
                return new CardPaymentResponse(request.getPaymentId(), outTradeNo,
                    OutPaymentType.DILICARD, String.valueOf(request.getAccountId()), 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.debug("Sending card refund request: {}", payload);
        LocalDateTime now = LocalDateTime.now();
        HttpResult result = send(uri, payload);
        if (result.statusCode == 200) {
            LOG.debug("Received from card payment pipeline: {}", 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: {}", payload);
        HttpResult result = send(uri, payload);
        if (result.statusCode == 200) {
            LOG.debug("Received from card payment pipeline: {}", 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;
    }
}