---
url: "https://pay.weixin.qq.com/doc/v3/partner/4015792574-java.md"
title: "开具通用行业电子发票-请求示例-java"
doc_id: 4015792574
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 IssueGeneralIndustryFapiaoApplications {
  private static String HOST = "https://api.mch.weixin.qq.com";
  private static String METHOD = "POST";
  private static String PATH = "/v3/new-tax-control-fapiao/fapiao-applications/issue-general";

  public static void main(String[] args) {
    // TODO: 请准备商户开发必要参数，参考：https://pay.weixin.qq.com/doc/v3/partner/4013080340
    IssueGeneralIndustryFapiaoApplications client = new IssueGeneralIndustryFapiaoApplications(
      "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"           // 微信支付公钥文件路径，本地文件路径
    );

    IssueGeneralFapiaoRequest request = new IssueGeneralFapiaoRequest();
    request.subMchid = "example_sub_mchid";
    request.fapiaoApplyId = "example_fapiao_apply_id";
    request.buyerInformation = new UserTitleEntity();
    request.buyerInformation.type = BuyerType.INDIVIDUAL;
    request.buyerInformation.name = "深圳市南山区测试企业";
    request.buyerInformation.taxpayerId = "202003261233701778";
    request.buyerInformation.address = "深圳市南山区深南大道10000号";
    request.buyerInformation.telephone = "075512345678";
    request.buyerInformation.bankName = "测试银行";
    request.buyerInformation.bankAccount = "62001234567890";
    request.buyerInformation.phone = client.encrypt("phone");
    request.buyerInformation.email = client.encrypt("email");
    request.buyerInformation.amount = 1000L;
    request.buyerInformation.outTradeNo = "order_20200701_123456";
    request.buyerInformation.fapiaoBillType = FapiaoBillType.COMM_FAPIAO;
    request.buyerInformation.userApplyMessage = "用户留言";
    request.fapiaoInformation = new IssueGeneralFapiaoInfo();
    request.fapiaoInformation.fapiaoId = "20200701123456";
    request.fapiaoInformation.totalAmount = 382895L;
    request.fapiaoInformation.items = new ArrayList<>();
    {
      IssueGeneralFapiaoItem itemsItem = new IssueGeneralFapiaoItem();
      itemsItem.taxCode = "3010101020203000000";
      itemsItem.goodsName = "*xxx*服务";
      itemsItem.specification = "米";
      itemsItem.unit = "米";
      itemsItem.quantity = 100000000L;
      itemsItem.totalAmount = 429900L;
      itemsItem.taxRate = 1300L;
      itemsItem.discount = false;
      itemsItem.preferentialPolicyCode = 1L;
      request.fapiaoInformation.items.add(itemsItem);
    };
    request.fapiaoInformation.exportBusinessPolicyCode = 1L;
    request.fapiaoInformation.vatRefundLevyCode = 1L;
    request.fapiaoInformation.billingPersonId = "128279891283";
    request.fapiaoInformation.billingPerson = "**伟 0020";
    request.fapiaoInformation.fapiaoBillType = FapiaoBillType.COMM_FAPIAO;
    request.fapiaoInformation.transactionInformation = new ArrayList<>();
    {
      TransactionInfo transactionInformationItem = new TransactionInfo();
      transactionInformationItem.payChannel = PayChannel.WECHAT_PAY;
      transactionInformationItem.transactionId = "4200000008202508080512076713";
      transactionInformationItem.outTradeNo = "order_20200701_123456";
      transactionInformationItem.amount = 382895L;
      request.fapiaoInformation.transactionInformation.add(transactionInformationItem);
    };
    request.fapiaoInformation.remark = "备注";
    try {
      client.run(request);
    } catch (WXPayUtility.ApiException e) {
        // TODO: 请求失败，根据状态码执行不同的逻辑
        e.printStackTrace();
    }
  }

  public void run(IssueGeneralFapiaoRequest request) {
    String uri = PATH;
    String reqBody = WXPayUtility.toJson(request);

    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, reqBody));
    reqBuilder.addHeader("Content-Type", "application/json");
    RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), reqBody);
    reqBuilder.method(METHOD, requestBody);
    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);

        return;
      } 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 IssueGeneralIndustryFapiaoApplications(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 String encrypt(String plainText) {
    return WXPayUtility.encrypt(this.wechatPayPublicKey, plainText);
  }

  public static class IssueGeneralFapiaoRequest {
    @SerializedName("sub_mchid")
    public String subMchid;

    @SerializedName("fapiao_apply_id")
    public String fapiaoApplyId;

    @SerializedName("buyer_information")
    public UserTitleEntity buyerInformation;

    @SerializedName("fapiao_information")
    public IssueGeneralFapiaoInfo fapiaoInformation;
  }

  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 IssueGeneralFapiaoInfo {
    @SerializedName("fapiao_id")
    public String fapiaoId;

    @SerializedName("total_amount")
    public Long totalAmount;

    @SerializedName("items")
    public List<IssueGeneralFapiaoItem> items = new ArrayList<IssueGeneralFapiaoItem>();

    @SerializedName("export_business_policy_code")
    public Long exportBusinessPolicyCode;

    @SerializedName("vat_refund_levy_code")
    public Long vatRefundLevyCode;

    @SerializedName("billing_person_id")
    public String billingPersonId;

    @SerializedName("billing_person")
    public String billingPerson;

    @SerializedName("fapiao_bill_type")
    public FapiaoBillType fapiaoBillType;

    @SerializedName("transaction_information")
    public List<TransactionInfo> transactionInformation = new ArrayList<TransactionInfo>();

    @SerializedName("remark")
    public String remark;
  }

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

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

  public static class IssueGeneralFapiaoItem {
    @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("total_amount")
    public Long totalAmount;

    @SerializedName("tax_rate")
    public Long taxRate;

    @SerializedName("discount")
    public Boolean discount;

    @SerializedName("preferential_policy_code")
    public Long preferentialPolicyCode;
  }

  public static class TransactionInfo {
    @SerializedName("pay_channel")
    public PayChannel payChannel;

    @SerializedName("transaction_id")
    public String transactionId;

    @SerializedName("out_trade_no")
    public String outTradeNo;

    @SerializedName("amount")
    public Long amount;
  }

  public enum PayChannel {
    @SerializedName("WECHAT_PAY")
    WECHAT_PAY
  }

}

```
