RtMallSign.java 2.55 KB
package com.diligrp.cashier.mall.sign;

import com.diligrp.cashier.mall.exception.RtMartMallException;
import com.diligrp.cashier.mall.property.RtMallDynamicProperty;
import com.diligrp.cashier.mall.type.RtMarkErrorCode;
import com.diligrp.cashier.mall.util.RtMallSignMd5Utils;
import com.diligrp.cashier.shared.handler.sign.SecuritySign;
import com.diligrp.cashier.shared.util.JsonUtils;
import com.fasterxml.jackson.core.type.TypeReference;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;

import java.util.Objects;
import java.util.TreeMap;

/**
 * @author dengwei
 * @version 1.0.0
 * @ClassName RtMallSign.java
 * @Description RtMallSign
 * 大润发参数验签
 */
@Component
public class RtMallSign implements SecuritySign {
    private static final Logger log = LoggerFactory.getLogger(RtMallSign.class);

    @Resource
    private RtMallDynamicProperty mallDynamicProperty;

    @Override
    public void sign(HttpServletRequest request, HttpServletResponse response, Object data) {
        log.info("allParameters:{}", JsonUtils.toJsonString(data));

        TreeMap<String, Object> paramMap = JsonUtils.fromJsonString(JsonUtils.toJsonString(data), new TypeReference<>() {
        });

        Object appKey = paramMap.get("app_key");
        if (Objects.isNull(appKey)) {
            throw new RtMartMallException(RtMarkErrorCode.E4003.getCode(), RtMarkErrorCode.E4003.getMessage());
        }

        Object sign = paramMap.get("sign");
        if (Objects.isNull(sign)) {
            throw new RtMartMallException(RtMarkErrorCode.E4004.getCode(), RtMarkErrorCode.E4004.getMessage());
        }
        paramMap.remove("sign");

        RtMallDynamicProperty.AppSecretDynamicProperty property = mallDynamicProperty.getByAppKey(appKey.toString());
        if (Objects.isNull(property)) {
            throw new RtMartMallException(RtMarkErrorCode.E4003.getCode(), RtMarkErrorCode.E4003.getMessage());
        }

        try {
            log.info("appKey:{}, secretKey:{}", property.getAppKey(), property.getAppSecret());
            String signKey = RtMallSignMd5Utils.generateSign(paramMap, property.getAppSecret());
            Assert.isTrue(Objects.equals(signKey, sign.toString()), "验签失败!");
        } catch (Exception e) {
            throw new RtMartMallException(RtMarkErrorCode.E4004.getCode(), RtMarkErrorCode.E4004.getMessage());
        }
    }
}