

package com.upay.sdk.onlinepay;

import com.alibaba.fastjson.JSONObject;
import com.upay.sdk.FastJsonUtils;
import com.upay.sdk.cashier.bindcard.executer.BindCardExecuter;
import com.upay.sdk.exception.HmacVerifyException;
import com.upay.sdk.exception.ResponseException;
import com.upay.sdk.exception.UnknownException;
import com.upay.sdk.executer.ResultListenerAdpater;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

public class BindCardNotifyServlet extends HttpServlet {
	static final Logger LOGGER = LoggerFactory.getLogger(BindCardNotifyServlet.class);

    private static final String ENCRYPT_KEY = "encryptKey";
    private static final String MERCHANT_ID = "merchantId";

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doPost(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		BindCardExecuter executer = new BindCardExecuter();
	    try{
            JSONObject json = FastJsonUtils.convert(req.getInputStream());
            json.put(ENCRYPT_KEY,req.getHeader(ENCRYPT_KEY));
            json.put(MERCHANT_ID,req.getHeader(MERCHANT_ID));
		    executer.callBack(json, new ResultListenerAdpater() {
				@Override
	            public void success(JSONObject jsonObject) {
	                LOGGER.info("通知绑卡完成，绑卡成功！");
	                LOGGER.info(jsonObject.toJSONString());
	            }
	        });
	    }
		catch(ResponseException e){
			LOGGER.info("响应异常");
			LOGGER.info(e.toString());
		}
		catch(HmacVerifyException e){
			LOGGER.info("签名验证异常");
			LOGGER.info(e.toString());
		}
		catch(UnknownException e){
			LOGGER.info("未知异常");
			LOGGER.info(e.toString());
		}
	    
	    LOGGER.info("BindCardNotifyServlet notify success...");
		PrintWriter out = resp.getWriter();
		out.print("SUCCESS");
	}
}
