---
url: "https://pay.weixin.qq.com/doc/v3/partner/4015792567-java.md"
title: "查询电子发票-请求示例-java"
doc_id: 4015792567
example_lang: "java"
---

## Java


需配合微信支付工具库 WXPayUtility 使用，请参考 [Java](https://pay.weixin.qq.com/doc/v3/partner/4014985777.md)

```
package com.java.demo;

import com.java.utils.WXPayUtility; // 引用微信支付工具库，参考：https://pay.weixin.qq.com/doc/v3/partner/4014985777

import com.google.gson.annotations.SerializedName;
import com.google.gson.annotations.Expose;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

import java.io.IOException;
import java.io.UncheckedIOException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 查询电子发票
 */
public class GetFapiaoApplications {
  private static String HOST = "https://api.mch.weixin.qq.com";
  private static String METHOD = "GET";
  private static String PATH = "/v3/new-tax-control-fapiao/fapiao-applications/{fapiao_apply_id}";

  public static void main(String[] args) {
    // TODO: 请准备商户开发必要参数，参考：https://pay.weixin.qq.com/doc/v3/partner/4013080340
    GetFapiaoApplications client = new GetFapiaoApplications(
      "19xxxxxxxx",                    // 商户号，是由微信支付系统生成并分配给每个商户的唯一标识符，商户号获取方式参考 https://pay.weixin.qq.com/doc/v3/partner/4013080340
      "1DDE55AD98Exxxxxxxxxx",         // 商户API证书序列号，如何获取请参考 https://pay.weixin.qq.com/doc/v3/partner/4013058924
      "/path/to/apiclient_key.pem",     // 商户API证书私钥文件路径，本地文件路径
      "PUB_KEY_ID_xxxxxxxxxxxxx",      // 微信支付公钥ID，如何获取请参考 https://pay.weixin.qq.com/doc/v3/partner/4013038589
      "/path/to/wxp_pub.pem"           // 微信支付公钥文件路径，本地文件路径
    );

    GetFapiaoApplicationsRequest request = new GetFapiaoApplicationsRequest();
    request.fapiaoApplyId = "4200000444201910177461284488";
    request.subMchid = "1900000109";
    request.fapiaoId = "20200701123456";
    try {
      FapiaoApplicationsEntity response = client.run(request);
        // TODO: 请求成功，继续业务逻辑
        System.out.println(response);
    } catch (WXPayUtility.ApiException e) {
        // TODO: 请求失败，根据状态码执行不同的逻辑
        e.printStackTrace();
    }
  }

  public FapiaoApplicationsEntity run(GetFapiaoApplicationsRequest request) {
    String uri = PATH;
    uri = uri.replace("{fapiao_apply_id}", WXPayUtility.urlEncode(request.fapiaoApplyId));
    Map<String, Object> args = new HashMap<>();
    args.put("sub_mchid", request.subMchid);
    args.put("fapiao_id", request.fapiaoId);
    String queryString = WXPayUtility.urlEncode(args);
    if (!queryString.isEmpty()) {
        uri = uri + "?" + queryString;
    }

    Request.Builder reqBuilder = new Request.Builder().url(HOST + uri);
    reqBuilder.addHeader("Accept", "application/json");
    reqBuilder.addHeader("Wechatpay-Serial", wechatPayPublicKeyId);
    reqBuilder.addHeader("Authorization", WXPayUtility.buildAuthorization(mchid, certificateSerialNo, privateKey, METHOD, uri, null));
    reqBuilder.method(METHOD, null);
    Request httpRequest = reqBuilder.build();

    // 发送HTTP请求
    OkHttpClient client = new OkHttpClient.Builder().build();
    try (Response httpResponse = client.newCall(httpRequest).execute()) {
      String respBody = WXPayUtility.extractBody(httpResponse);
      if (httpResponse.code() >= 200 && httpResponse.code() < 300) {
        // 2XX 成功，验证应答签名
        WXPayUtility.validateResponse(this.wechatPayPublicKeyId, this.wechatPayPublicKey,
            httpResponse.headers(), respBody);

        // 从HTTP应答报文构建返回数据
        return WXPayUtility.fromJson(respBody, FapiaoApplicationsEntity.class);
      } else {
        throw new WXPayUtility.ApiException(httpResponse.code(), respBody, httpResponse.headers());
      }
    } catch (IOException e) {
      throw new UncheckedIOException("Sending request to " + uri + " failed.", e);
    }
  }

  private final String mchid;
  private final String certificateSerialNo;
  private final PrivateKey privateKey;
  private final String wechatPayPublicKeyId;
  private final PublicKey wechatPayPublicKey;

  public GetFapiaoApplications(String mchid, String certificateSerialNo, String privateKeyFilePath, String wechatPayPublicKeyId, String wechatPayPublicKeyFilePath) {
    this.mchid = mchid;
    this.certificateSerialNo = certificateSerialNo;
    this.privateKey = WXPayUtility.loadPrivateKeyFromPath(privateKeyFilePath);
    this.wechatPayPublicKeyId = wechatPayPublicKeyId;
    this.wechatPayPublicKey = WXPayUtility.loadPublicKeyFromPath(wechatPayPublicKeyFilePath);
  }

  public static class GetFapiaoApplicationsRequest {
    @SerializedName("sub_mchid")
    @Expose(serialize = false)
    public String subMchid;

    @SerializedName("fapiao_apply_id")
    @Expose(serialize = false)
    public String fapiaoApplyId;

    @SerializedName("fapiao_id")
    @Expose(serialize = false)
    public String fapiaoId;
  }

  public static class FapiaoApplicationsEntity {
    @SerializedName("total_count")
    public Long totalCount;

    @SerializedName("fapiao_information")
    public List<FapiaoEntity> fapiaoInformation;
  }

  public static class FapiaoEntity {
    @SerializedName("fapiao_id")
    public String fapiaoId;

    @SerializedName("status")
    public Status status;

    @SerializedName("blue_fapiao")
    public FapiaoInfo blueFapiao;

    @SerializedName("red_fapiao")
    public FapiaoInfo redFapiao;

    @SerializedName("card_information")
    public CardInfo cardInformation;

    @SerializedName("total_amount")
    public Long totalAmount;

    @SerializedName("tax_amount")
    public Long taxAmount;

    @SerializedName("amount")
    public Long amount;

    @SerializedName("seller_information")
    public SellerInfo sellerInformation;

    @SerializedName("buyer_information")
    public UserTitleEntity buyerInformation;

    @SerializedName("extra_information")
    public ExtraInfo extraInformation;

    @SerializedName("items")
    public List<FapiaoItem> items;

    @SerializedName("remark")
    public String remark;

    @SerializedName("fapiao_error_code")
    public String fapiaoErrorCode;

    @SerializedName("fapiao_error_message")
    public String fapiaoErrorMessage;
  }

  public enum Status {
    @SerializedName("ISSUE_ACCEPTED")
    ISSUE_ACCEPTED,
    @SerializedName("ISSUED")
    ISSUED,
    @SerializedName("REVERSE_ACCEPTED")
    REVERSE_ACCEPTED,
    @SerializedName("REVERSED")
    REVERSED,
    @SerializedName("ISSUE_FAILED")
    ISSUE_FAILED,
    @SerializedName("REVERSE_FAILED")
    REVERSE_FAILED
  }

  public static class FapiaoInfo {
    @SerializedName("fapiao_code")
    public String fapiaoCode;

    @SerializedName("fapiao_number")
    public String fapiaoNumber;

    @SerializedName("check_code")
    public String checkCode;

    @SerializedName("password")
    public String password;

    @SerializedName("fapiao_time")
    public String fapiaoTime;
  }

  public static class CardInfo {
    @SerializedName("card_appid")
    public String cardAppid;

    @SerializedName("card_openid")
    public String cardOpenid;

    @SerializedName("card_id")
    public String cardId;

    @SerializedName("card_code")
    public String cardCode;

    @SerializedName("card_status")
    public CardStatus cardStatus;
  }

  public static class SellerInfo {
    @SerializedName("name")
    public String name;

    @SerializedName("taxpayer_id")
    public String taxpayerId;

    @SerializedName("address")
    public String address;

    @SerializedName("telephone")
    public String telephone;

    @SerializedName("bank_name")
    public String bankName;

    @SerializedName("bank_account")
    public String bankAccount;
  }

  public static class UserTitleEntity {
    @SerializedName("type")
    public BuyerType type;

    @SerializedName("name")
    public String name;

    @SerializedName("taxpayer_id")
    public String taxpayerId;

    @SerializedName("address")
    public String address;

    @SerializedName("telephone")
    public String telephone;

    @SerializedName("bank_name")
    public String bankName;

    @SerializedName("bank_account")
    public String bankAccount;

    @SerializedName("phone")
    public String phone;

    @SerializedName("email")
    public String email;

    @SerializedName("amount")
    public Long amount;

    @SerializedName("out_trade_no")
    public String outTradeNo;

    @SerializedName("fapiao_bill_type")
    public FapiaoBillType fapiaoBillType;

    @SerializedName("user_apply_message")
    public String userApplyMessage;
  }

  public static class ExtraInfo {
    @SerializedName("drawer")
    public String drawer;
  }

  public static class FapiaoItem {
    @SerializedName("tax_code")
    public String taxCode;

    @SerializedName("goods_name")
    public String goodsName;

    @SerializedName("specification")
    public String specification;

    @SerializedName("unit")
    public String unit;

    @SerializedName("quantity")
    public Long quantity;

    @SerializedName("unit_price")
    public Long unitPrice;

    @SerializedName("amount")
    public Long amount;

    @SerializedName("tax_amount")
    public Long taxAmount;

    @SerializedName("total_amount")
    public Long totalAmount;

    @SerializedName("tax_rate")
    public Long taxRate;

    @SerializedName("tax_prefer_mark")
    public TaxPreferMark taxPreferMark;

    @SerializedName("discount")
    public Boolean discount;
  }

  public enum CardStatus {
    @SerializedName("INSERT_ACCEPTED")
    INSERT_ACCEPTED,
    @SerializedName("INSERTED")
    INSERTED,
    @SerializedName("DISCARD_ACCEPTED")
    DISCARD_ACCEPTED,
    @SerializedName("DISCARDED")
    DISCARDED
  }

  public enum BuyerType {
    @SerializedName("INDIVIDUAL")
    INDIVIDUAL,
    @SerializedName("ORGANIZATION")
    ORGANIZATION
  }

  public enum FapiaoBillType {
    @SerializedName("COMM_FAPIAO")
    COMM_FAPIAO,
    @SerializedName("VAT_FAPIAO")
    VAT_FAPIAO
  }

  public enum TaxPreferMark {
    @SerializedName("NO_FAVORABLE")
    NO_FAVORABLE,
    @SerializedName("OUTSIDE_VAT")
    OUTSIDE_VAT,
    @SerializedName("VAT_EXEMPT")
    VAT_EXEMPT,
    @SerializedName("NORMAL_ZERO_RATED")
    NORMAL_ZERO_RATED,
    @SerializedName("EXPORT_ZERO_RATED")
    EXPORT_ZERO_RATED
  }

}

```
