China Invoice Verification API in Java
Use Java HttpClient to submit fields from a Chinese VAT invoice to ChinaValidate and interpret the verification response.
Verify a Chinese invoice using its printed details.

Use Java's standard HTTP client to post structured Chinese invoice fields to ChinaValidate. The example below reads a JSON invoice request from a file, sends it as UTF-8, and prints the application code or verification status. This is the field-based API. It is useful when your application already has invoice values from entry or another extraction step. If your input is a whole PDF or OFD file, check the corresponding document operation before building your upload handling. Invoice Verification API
Identify the invoice type before choosing its request fields. An invoice number and a date do not by themselves tell the client which amount or additional value should be sent. The service defines separate inputs for digital invoices, legacy VAT ordinary invoices and legacy VAT special invoices. The code illustrates a digital invoice call and uses the same transport for the other supported types.
Assemble the request file
For a fully digital invoice, use the documented digital type, 20-digit invoice number, issue date in year-month-day digits and amount including tax. Keep the invoice number, date and the amount as strings. The file below repeats the documented request example. Save it as invoice-request.json to understand its shape, then replace the fixture values with the exact fields from a document you are authorized to check before making a real request. State Taxation Administration invoice checking instructions
{
"invoice_type": "digital",
"invoice_number": "25322000000000123456",
"issue_date": "20250318",
"total_amount": "1130.00",
"language": "zh-CN"
}
| Supported type | Type-specific fields to check |
|---|---|
| Digital invoice | Twenty-digit invoice number and the printed tax-inclusive total |
| Legacy VAT ordinary invoice | Eight-digit invoice number, invoice code and the last six digits of the printed verification code |
| Legacy VAT special invoice | Eight-digit invoice number, invoice code and the pre-tax amount |
Use the exact field names and combination documented for the selected type. For example, the digital request uses the total including tax, while the legacy special type expects the amount before tax. A printed number starting with zero must keep that zero. Avoid converting identifiers through a numeric representation in a spreadsheet, JSON mapping or Java form binding. Extract the raw text first and validate for the applicable field before sending it. OpenAPI request schema
Make the Java request
Use Java 21 for this walkthrough, and add Gson to read the response. The sample declares a separate connection timeout and overall request timeout. It sends a body as JSON rather than uploading the source invoice document. Run it from your server or a developer workstation with the key injected into the process. Do not put the key into the invoice file or print the header with the credential. Java HttpClient reference · Gson source and release notes
Save the source as InvoiceCheck.java. Use the documented fixture for local parser and request-building tests. This program performs a paid network call when you execute it with a real API key and file. Keep those credentials and real invoice data out of test fixtures.
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.time.Duration;
class InvoiceCheck {
public static void main(String[] args) throws Exception {
String key = System.getenv("CHINAVALIDATE_API_KEY");
if (args.length != 1 || key == null || key.isBlank()) {
throw new IllegalArgumentException("Supply the request file and CHINAVALIDATE_API_KEY");
}
String json = Files.readString(Path.of(args[0]), StandardCharsets.UTF_8);
HttpRequest request = HttpRequest.newBuilder(
URI.create("https://api.chinavalidate.com/v1/invoices/verify"))
.timeout(Duration.ofSeconds(45))
.header("Authorization", "Bearer " + key)
.header("Accept", "application/json")
.header("Content-Type", "application/json")
.POST(HttpRequest.BodyPublishers.ofString(json, StandardCharsets.UTF_8))
.build();
HttpClient client = HttpClient.newBuilder()
.connectTimeout(Duration.ofSeconds(10))
.build();
HttpResponse<String> response = client.send(
request, HttpResponse.BodyHandlers.ofString(StandardCharsets.UTF_8));
String requestId = response.headers().firstValue("X-CV-Request-Id").orElse("-");
if (response.statusCode() != 200) {
throw new IllegalStateException("HTTP " + response.statusCode() + " request " + requestId);
}
JsonObject envelope = JsonParser.parseString(response.body()).getAsJsonObject();
int code = envelope.get("code").getAsInt();
if (code != 200) {
throw new IllegalStateException("API code " + code + " request " + requestId);
}
var rows = envelope.getAsJsonObject("data").getAsJsonArray("items");
if (rows.isEmpty()) {
System.out.println("No verification rows returned. Request " + requestId);
}
for (JsonElement item : rows) {
JsonElement status = item.getAsJsonObject().get("verification_status");
System.out.println("Verification status: " +
(status == null || status.isJsonNull() ? "[unavailable]" : status.getAsString()) +
" | Request " + requestId);
}
}
}
Get the Gson library with Maven or use the dependency from your existing Java project. The shell commands below show a local, separate example without changing a project build file. On Windows, change the Java classpath separator from a colon to a semicolon and use the syntax for the shell you run.
mvn dependency:copy -Dartifact=com.google.code.gson:gson:2.13.2 -DoutputDirectory=lib
java -cp 'lib/gson-2.13.2.jar' InvoiceCheck.java invoice-request.json
Read the result before changing a record
The API's HTTP status and JSON code answer different questions. The Java code checks the transport status, decodes the JSON object and reads its application code. It walks the available verification items only when the application reports success. If the JSON is unavailable or changes shape, the command fails rather than inventing a verification result. An application can convert those failures into its own statuses and retain the operation and request ID for review.
A verification item may have a status such as matched, mismatch or not found. Display the status in the context of the exact document fields sent. For a mismatch, compare the selected type, issue date, and amount or verification code with the printed document. If fields were manually entered, use the original source to establish which value was incorrect. An ordinary no-result response can consume credits, so correcting the input before you submit another request helps cut unnecessary calls.
A result that includes a matched invoice can still leave a separate purchasing decision. Save the verification record with the original invoice or internal document reference. Compare the seller, buyer or transaction evidence through the correct internal process, where relevant. A match states the outcome for that invoice lookup. It does not tell the Java client which invoice gets paid. Keep this state distinct in a payment application. API pricing and billing
Check the integration before repeated calls
Test a digital invoice request, a legacy request with leading zeros and an empty result using local example data. Test an API code for bad input or unavailable credits so an application does not turn these errors into a mismatch. Check how your UI handles a real no-result response and a network failure. An operator needs a different next step for each. A client-side timeout does not establish that the request never reached the server.
If your system accepts invoice uploads, identify the PDF and OFD operations before designing the request body. Their inputs differ from the JSON fields used here. In an application that supports more than one operation, give each verifier an explicit entry point and attach the operation to its saved result. Changes to the document intake then do not require guessing what format an earlier response represented. Full API reference
Use one permitted live check when the parser and request tests pass. Compare the request values with the original, confirm the chosen API operation, and review the actual response and any charge information. For production Java code, reuse HttpClient, move request-file construction behind your normal validated input layer, and keep key storage on the server. An individual result can then be interpreted without a developer having to reconstruct which fields and response path the integration used.
Preserve the inputs and the output type
If you build the request in Java instead of reading a JSON file, use strings for the invoice number, code and printable date. A Java String preserves leading zeros and can represent the exact value extracted from a document. For monetary arithmetic elsewhere in your application, a decimal type such as BigDecimal is appropriate. Convert the final amount into the text required by the chosen request type, with the same value as the source. Integer and floating-point parsing are poor substitutes for these two different jobs.
Use the operation and document type as explicit fields in the request log. Keep the original issue date for the document and the compact date used for the API as distinct representations. If a person later consults a PDF or scans a paper form, the log can show both the text used for verification and the returned status. A useful operational record also says whether a human corrected extracted characters before the request was made.
The sample surfaces application errors through an exception. A service can map that exception to an operator message with a request reference, without displaying the original input or response body to people who do not need it. For example, a malformed file can prompt someone to recheck the input, while an invalid key requires the integration owner to inspect the account. Treat the service's reported status as a value from the verification step. The application can add its own evidence and decision without overwriting that value.