/**
 * 收銀檯V3支付模擬類
 */
public class CashierV3PaymentServlet extends HttpServlet {

    /**
     * 商戶申請支付數據組裝
     *
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    @Override
    public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        //  商户支付申請數據
        String requestParams = "";
        InputStream in = req.getInputStream();
        InputStreamReader reader = new InputStreamReader(in, "UTF-8");
        BufferedReader bd = new BufferedReader(reader);
        String inputLine = "";
        while ((inputLine = bd.readLine()) != null) {
            requestParams += inputLine;
        }
        RequestForm requestForm = JSONObject.parseObject(requestParams,RequestForm.class);
        // 提交對象
        Map<String, Object> submitDataMap = new HashMap<>();
        // 組裝加密數據
        submitDataMap.put("web",requestForm.getHead().getWeb());
        submitDataMap.put("send_time", requestForm.getHead().getSend_time());

        // 加密組裝好的數據(rsamsg)及驗簽值(content)
        // 將組裝好的數據轉換成JSON字符串
        String params = JSONObject.toJSONString(requestForm);
        String rsamsg = "";
        String content = URLEncoder.encode(params, "UTF-8");
        try {
            rsamsg = RSAUtils.publicEncrypt(content, RSAUtils.getPublicKey(Constant.PUBLIC_KEY));
            content = ShaUtil.encodeSHA256(content + Constant.SHA256);
        } catch (Exception e) {
            resp.getWriter().printf("加密支付訊息失敗,請檢查密鑰是否正確!");
            e.printStackTrace();
            return;
        }
        submitDataMap.put("rsamsg", rsamsg);
        submitDataMap.put("check_value", content);
        Map<String, Object> submitResultMap = new HashMap<>(1);
        submitResultMap.put("result", submitDataMap);
        resp.setContentType("application/json");
        resp.getWriter().printf(JSONObject.toJSONString(submitResultMap));
    }
}

