package com.izouma.agpay;

import cfca.org.bouncycastle.util.encoders.Base64;
import cfca.x509.certificate.X509Cert;
import com.alibaba.fastjson.JSON;
import com.izouma.agpay.bean.ApiHead;
import com.izouma.agpay.bean.ApiMessage;
import com.izouma.agpay.bean.DemoReqBody;
import com.izouma.agpay.util.HttpClient431Util;
import com.izouma.agpay.util.MessageUtil;
import com.izouma.agpay.util.RsaP1Util;

import java.io.FileInputStream;
import java.util.HashMap;
import java.util.Map;

/**
 * @author cuishilei
 * 创建时间：17-9-26下午1:53
 */
public class demo {
	public static void main(String[] args) {
		String url = "http://ip:port/gateway/agpay/apiservice.do";
		String merchantPfxPath = "/app/platform/merchant.pfx";
		String publicKeyPath = "/app/platform/platform.cer";


		RsaP1Util rsaP1Util = new RsaP1Util();
		try {
			//按照要求组装好报文
			ApiHead head = new ApiHead();
			DemoReqBody body = new DemoReqBody();

			head.setClienttime("20171025175923");
			head.setPlatmerid("CF2000417315");
			head.setTrancode("QR1007");
			head.setTranflow("TEST20171025175923002");

			body.setOriginflowno("CF200041731513540367");
			//head和body组装对应的报文
			ApiMessage father = new ApiMessage();
			ApiMessage.Message message = father.new Message();
			ApiMessage.Message.Data data = message.new Data();
			data.setHead(head);
			data.setBody(body);
			message.setData(data);

			String bodyStr = JSON.toJSONString(data.getBody());
			//生成对应的待签名串 只签名报文体
			String signMessage = MessageUtil.getSignStr(bodyStr);
			//生成签名
			String sign = rsaP1Util.rsaP1Sign(signMessage, merchantPfxPath, "umbpay");
			//得到sign后继续组装对应报文，然后加密
			message.setSign(sign);
			father.setMessage(message);
			String messageStr = JSON.toJSONString(father);
			String reqMsg = new String(rsaP1Util.envelopMessage(messageStr, publicKeyPath));
			Map<String, String> params = new HashMap<String, String>();
			params.put("data", reqMsg);
			params.put("formatType", "json");
			params.put("cryptType", "cert");
			params.put("signType", "cert");
			//发送请求得到结果
			String result = HttpClient431Util.doPost(params, url, "UTF-8", "UTF-8");
			//解密得到明文
			String platinMsg = new String(rsaP1Util.openMessage(result, merchantPfxPath, "umbpay"));
			System.out.println(platinMsg);
			//在返回报文明文 platinMsg中获取系统返回的签名
			//在返回报文明文 platinMsg中自己重新组装待签名串

			ApiMessage resfather = JSON.parseObject(platinMsg, ApiMessage.class);
			System.out.println(resfather);
			//准备验签
			FileInputStream is = new FileInputStream(publicKeyPath);
			X509Cert x509Cert = new X509Cert(is);
			String cert = new String(Base64.encode(x509Cert.getEncoded()), "UTF-8");
			//验签
			String signdata = MessageUtil.getSignStr(JSON.toJSONString(resfather.getMessage().getData().getBody()));
			if (rsaP1Util.rsaP1Verify(resfather.getMessage().getSign(), signdata, cert.getBytes("UTF-8"))) {
				//验签成功，业务处理
			} else {
				//验签失败，数据可能被篡改
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
