WechatPayHttpClientBuilder.java 2.41 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 48 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
package cn.wisenergy.service.httpClient;


import cn.wisenergy.service.httpClient.auth.CertificatesVerifier;
import cn.wisenergy.service.httpClient.auth.PrivateKeySigner;
import cn.wisenergy.service.httpClient.auth.WechatPay2Credentials;
import cn.wisenergy.service.httpClient.auth.WechatPay2Validator;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.execchain.ClientExecChain;

import java.security.PrivateKey;
import java.security.cert.X509Certificate;
import java.util.List;

public class WechatPayHttpClientBuilder extends HttpClientBuilder {
  private Credentials credentials;
  private Validator validator;

  static final String os = System.getProperty("os.name") + "/" + System.getProperty("os.version");
  static final String version = System.getProperty("java.version");

  private WechatPayHttpClientBuilder() {
    super();

    String userAgent = String.format(
        "WechatPay-Apache-HttpClient/%s (%s) Java/%s",
        getClass().getPackage().getImplementationVersion(),
        os,
        version == null ? "Unknown" : version);
    setUserAgent(userAgent);
  }

  public static WechatPayHttpClientBuilder create() {
    return new WechatPayHttpClientBuilder();
  }

  public WechatPayHttpClientBuilder withMerchant(String merchantId, String serialNo, PrivateKey privateKey) {
    this.credentials =
        new WechatPay2Credentials(merchantId, new PrivateKeySigner(serialNo, privateKey));
    return this;
  }

  public WechatPayHttpClientBuilder withCredentials(Credentials credentials) {
    this.credentials = credentials;
    return this;
  }

  public WechatPayHttpClientBuilder withWechatpay(List<X509Certificate> certificates) {
    this.validator = new WechatPay2Validator(new CertificatesVerifier(certificates));
    return this;
  }

  public WechatPayHttpClientBuilder withValidator(Validator validator) {
    this.validator = validator;
    return this;
  }

  @Override
  public CloseableHttpClient build() {
    if (credentials == null) {
      throw new IllegalArgumentException("缺少身份认证信息");
    }
    if (validator == null) {
      throw new IllegalArgumentException("缺少签名验证信息");
    }

    return super.build();
  }

  @Override
  protected ClientExecChain decorateProtocolExec(final ClientExecChain requestExecutor) {
    return new SignatureExec(this.credentials, this.validator, requestExecutor);
  }
}