package com.hzs.third.pay.controller.base;

import cn.hutool.crypto.SecureUtil;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * @Description: 京东基础控制器
 * @Author: jiang chao
 * @Time: 2022/12/27 17:47
 * @Classname: JdBaseController
 * @PackageName: com.hzs.third.pay.controller.base
 */
public class JdBaseController {

    /**
     * 获取请求体
     *
     * @param request
     * @return
     * @throws Exception
     */
    protected String getRequestBody(HttpServletRequest request) throws IOException {
        BufferedReader br = null;
        try {
            br = new BufferedReader(new InputStreamReader(request.getInputStream()));
            String line;
            StringBuilder sb = new StringBuilder();
            while ((line = br.readLine()) != null) {
                sb.append(line);
            }
            return sb.toString();
        } finally {
            if (null != br) {
                try {
                    br.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 校验token
     *
     * @param request
     * @param reqBody
     * @param secretKey
     * @return
     */
    protected boolean checkToken(HttpServletRequest request, String reqBody, String secretKey) {
        // SHA1 加密串
        String shaStr = "secretKey=" + secretKey +
                "&timestamp=" + request.getHeader("timestamp") +
                "&body=" + reqBody;
        String tokenCheck = SecureUtil.sha1(shaStr).toUpperCase();
        return tokenCheck.equals(request.getHeader("token"));
    }

}
