WxPayUtil.java 6.71 KB
Newer Older
licc's avatar
licc committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
package cn.wisenergy.service.util;

import cn.wisenergy.common.utils.R;
import cn.wisenergy.model.dto.PayPageDto;
import cn.wisenergy.service.httpClient.WechatPayHttpClientBuilder;
import cn.wisenergy.service.httpClient.auth.AutoUpdateCertificatesVerifier;
import cn.wisenergy.service.httpClient.auth.PrivateKeySigner;
import cn.wisenergy.service.httpClient.auth.WechatPay2Credentials;
import cn.wisenergy.service.httpClient.auth.WechatPay2Validator;
import cn.wisenergy.service.httpClient.util.PemUtil;
import cn.wisenergy.service.wxpay.WxCommon;
import com.alibaba.fastjson.JSONObject;
import okhttp3.HttpUrl;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.junit.After;
import org.junit.Before;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.SignatureException;
import java.security.spec.InvalidKeySpecException;
import java.util.UUID;

public class WxPayUtil {


    /**
     * 商户号
     */
    private static String mchId = WxCommon.MCHID;
    // 商户证书序列号
    private static String mchSerialNo = WxCommon.SERIAL_NO;
    // api密钥
    private static String apiV3Key = WxCommon.SECRET_KEY;

    // 你的商户私钥
licc's avatar
licc committed
48
    private static String privateKey = "-----BEGIN PRIVATE KEY-----\n" +WxCommon.SECRET_KEY
licc's avatar
licc committed
49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173
            + "-----END PRIVATE KEY-----\n";

    private static CloseableHttpClient httpClient;
    private static AutoUpdateCertificatesVerifier verifier;


    static  {
        PrivateKey merchantPrivateKey = null;
        try {
            merchantPrivateKey = PemUtil.loadPrivateKey(
                    new ByteArrayInputStream(privateKey.getBytes("utf-8")));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        //使用自动更新的签名验证器,不需要传入证书
        try {
            verifier = new AutoUpdateCertificatesVerifier(
                    new WechatPay2Credentials(mchId, new PrivateKeySigner(mchSerialNo, merchantPrivateKey)),
                    apiV3Key.getBytes("utf-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        httpClient = WechatPayHttpClientBuilder.create()
                .withMerchant(mchId, mchSerialNo, merchantPrivateKey)
                .withValidator(new WechatPay2Validator(verifier))
                .build();
    }

    @After
    public void after() throws IOException {
        httpClient.close();
    }

    public static void main(String[] args) throws IOException, NoSuchAlgorithmException, SignatureException, InvalidKeySpecException, InvalidKeyException {
        HttpPost httpPost = new HttpPost(WxCommon.WX_PAY_URL);

        long timestamp = System.currentTimeMillis() / 1000;
        String nonceStr = UUID.randomUUID().toString().replace("-", "");
        String method = "POST";
        String tradeNo = "21" + System.currentTimeMillis();
        HttpUrl httpurl = HttpUrl.parse(WxCommon.WX_PAY_URL);

        // 请求body参数
        String reqdata = "{"
                + "\"time_expire\":\"2021-02-07T10:34:56+08:00\","
                + "\"amount\": {"
                + "\"total\":100,"
                + "\"currency\":\"CNY\""
                + "},"
                + "\"mchid\":\"" + WxCommon.MCHID + "\","
                + "\"description\":\"Image形象店-深圳腾大-QQ公仔\","
                + "\"notify_url\":\"" + WxCommon.NOTIFY_URL + "\","
                + "\"out_trade_no\":\"" + tradeNo + "\","
                + "\"goods_tag\":\"WXG\","
                + "\"appid\":\"" + WxCommon.APP_ID + "\","
                + "\"attach\":\"自定义数据说明\","
                + "\"detail\": {"
                + "\"invoice_id\":\"wx123\","
                + "\"goods_detail\": ["
                + "{"
                + "\"goods_name\":\"iPhoneX 256G\","
                + "\"wechatpay_goods_id\":\"1001\","
                + "\"quantity\":1,"
                + "\"merchant_goods_id\":\"商品编码\","
                + "\"unit_price\":828800"
                + "},"
                + "{"
                + "\"goods_name\":\"iPhoneX 256G\","
                + "\"wechatpay_goods_id\":\"1001\","
                + "\"quantity\":1,"
                + "\"merchant_goods_id\":\"商品编码\","
                + "\"unit_price\":828800"
                + "}"
                + "],"
                + "\"cost_price\":608800"
                + "},"
                + "\"scene_info\": {"
                + "\"store_info\": {"
                + "\"address\":\"广东省深圳市南山区科技中一道10000号\","
                + "\"area_code\":\"440305\","
                + "\"name\":\"腾讯大厦分店\","
                + "\"id\":\"0001\""
                + "},"
                + "\"device_id\":\"013467007045764\","
                + "\"payer_client_ip\":\"14.23.150.211\""
                + "}"
                + "}";
        StringEntity reqEntity = new StringEntity(
                reqdata, ContentType.create("application/json", "utf-8"));
        httpPost.setEntity(reqEntity);
        httpPost.addHeader("Accept", "application/json");

//        //构造签名参数
//        //构造签名参数
//        JSONObject jsonObject = new JSONObject();
//        jsonObject.put("appid", WxCommon.APP_ID);
//        jsonObject.put("mchid", WxCommon.MCHID);
//        jsonObject.put("description", "充值");
//        jsonObject.put("out_trade_no", tradeNo);
//        jsonObject.put("notify_url", WxCommon.NOTIFY_URL);
//        PayPageDto payPageDto=new PayPageDto();
//        payPageDto.setTotal(100);
//        jsonObject.put("amount", payPageDto);
//        String token = SignDemo.getToken(method, httpurl, jsonObject.toJSONString(), nonceStr, timestamp);
//        httpPost.setHeader("Authorization", "WECHATPAY2-SHA256-RSA2048" + " " + token);

        //完成签名并执行请求
        CloseableHttpResponse response = httpClient.execute(httpPost);


        try {
            if (response.getStatusLine().getStatusCode() == 200) {
                HttpEntity httpEntity = response.getEntity();
                String content = EntityUtils.toString(httpEntity, "utf8");
                System.out.println(content.length());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            response.close();
        }
    }
}