package com.keao.edu.thirdparty.union;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.net.URLEncoder;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

/**
 * 银联商务公众号支付
 */
public class Mp {
    static String appId = "10037e6f6a4e6da4016a62a47e51000c";
    static String appKey = "b4b70d123a724972bc21f445b0b9f75c";
    static String timestamp = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
    static String nonce = UUID.randomUUID().toString().replace("-", "");

    public static byte[] hmacSHA256(byte[] data, byte[] key) throws InvalidKeyException, NoSuchAlgorithmException {
        String algorithm = "HmacSHA256";
        Mac mac = Mac.getInstance(algorithm);
        mac.init(new SecretKeySpec(key, algorithm));
        return mac.doFinal(data);
    }

    public static String getOpenBodySigForNetpay(String appId, String appKey, String timestamp, String nonce, String content) throws Exception {
        String signatureStr = appId + timestamp + nonce + DigestUtils.sha256Hex(content);
        byte[] localSignature = hmacSHA256(signatureStr.getBytes(), appKey.getBytes());
        return ("authorization=OPEN-FORM-PARAM" + "&appId=" + appId + "&timestamp=" + timestamp + "&nonce=" + nonce + "&content=" + URLEncoder.encode(content, "UTF-8") + "&signature=" + URLEncoder.encode(Base64.encodeBase64String(localSignature), "UTF-8"));
    }

    public static void main(String[] args) throws Exception {
        JSONObject json = new JSONObject();

        json.put("instMid", "YUEDANDEFAULT");
        json.put("mid", "898460107420248");
        json.put("tid", "00000001");
        json.put("totalAmount", 4000);

        json.put("orderDesc", "大雅乐盟培训订单");
        // json.put("bizType", "B2B");
        json.put("merOrderId", "1017" + new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date()) + RandomStringUtils.randomNumeric(7));
        json.put("requestTimestamp", DateFormatUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss"));


        String param = getOpenBodySigForNetpay(appId, appKey, timestamp, nonce, json.toString());
        System.out.println("http://58.247.0.18:29015/v1/netpay/webpay/pay?" + param);
//        GetOpenBodySig.sendGet("http://58.247.0.18:29015/v1/netpay/webpay/pay?"+param);
        System.out.println(json.toString());
    }
}

