Downloading invoices in NA
Document API allows you to download invoice documents for transactions retrieved via Reconciliation API. In North American (NA) regions, you can use Document API to download invoices and credit memos of orders paid using Pay by Invoice (PBI). With this workflow, you can programmatically retrieve documents required as part of the payment reconciliation process.
Prerequisites
To successfully complete this tutorial, do these steps:
- Complete the API onboarding process to register as a developer, create an app client, and retrieve API access and refresh tokens. For more information, see Onboarding overview.
- Gain access to the Business Purchase Reconciliation role. For more information, see Amazon Business API roles.
- Call the Reconciliation API
getTransactions
operation to retrieve theorderId
,orderLineItemId
, andshipmentId
for each desired line item. Save the data you see in these parameters. For more information about calling this API, see Retrieving business transactions. - To request the invoice numbers associated with the above line items, call the
getInvoiceDetailsByOrderLineItems
operation by passing theorderId
,orderLineIte``mId
, andshipmentId
you retrieved in the previous step. A successful request returns theinvoiceNumber
matching the provided line item details. For more information on calling this API, see Retrieving invoice details.
Step 1. Request a report
Request a report by calling the createReport operation and passing these parameters in the request body:
Name | Description | Type | Required |
---|---|---|---|
reportOptions | Additional information passed to reports. This varies by report type. | ReportOptions | Yes |
reportType | Supported value is GET_AB_INVOICE_PDF. | string | Yes |
marketplaceIds | A list of Amazon Business marketplace identifiers. The report contains data for all of the specified Amazon Business marketplace, unless the report type indicates otherwise. | < string > array | Yes |
Provide the following fields in the reportOptions
object to identify the type of document to download:
Name | Description | Type | Required |
---|---|---|---|
invoiceId | The unique invoice identifier. Based on this identifier, the correct invoice or credit memo document will be vended. This value is the invoiceNumber value you retrieved in Prerequisites Step 4. | string | Yes |
invoiceType | [Note: invoiceType will be deprecated. To download invoice documents, use documentType instead.] Type of invoice to download. Supported value is PBI_INVOICE . | string | No |
documentType | The type of document to download. Supported values include Invoice or Credits . | string | No |
Either
invoiceType
ordocumentType
can be included inreportOptions
. If neither field is included, both invoice and credit memo documents are downloaded. If both fields are included, the request is invalid.
https://na.business-api.amazon.com/reports/2021-09-30/reports
{
"reportOptions":
{
"invoiceId":"1111-2222-3333",
"documentType": "Credits"
},
"reportType": "GET_AB_INVOICE_PDF",
"marketplaceIds": ["ATVPDKIKX0DER"]
}
import requests
url = "https://na.business-api.amazon.com/reports/2021-09-30/reports"
payload = {
"reportOptions": {
"invoiceId": "1111-2222-3333",
"documentType": "Credits"
},
"marketplaceIds": ["ATVPDKIKX0DER"],
"reportType": "GET_AB_INVOICE_PDF"
}
headers = {
"accept": "application/json",
"x-amz-access-token": "<Access token retrieved in Prerequisites Step 1>",
}
response = requests.post(url, json=payload, headers=headers)
print(response.text)
A successful response includes the following fields:
Name | Description | Type | Required |
---|---|---|---|
reportId | The identifier for the report. This identifier is unique only in combination with Amazon Business customer. | string | Yes |
{
"reportId": "ID323"
}
After you call the createReport
operation, Amazon Business receives the request and processes the report.
Step 2. Confirm completion of the report process
- The Document API response is asynchronous. To confirm completion of the report process, call the
getReport
operation periodically by passing thereportId
value.
Name | Description | Type | Required |
---|---|---|---|
reportId | The identifier for the report. This identifier is unique only in combination with the Amazon Business customer. | string | Yes |
The
getReport
operation only serves information for on-demand or scheduled report requests that were created within the last 30 days.
- The report process has ended if the
processingStatus
indicates CANCELLED, DONE, or FATAL. The report process hasn't ended if the values indicate IN_PROGRESS or IN_QUEUE. If the report process is complete, proceed to Step 3. Retrieve the report. If the report process isn't complete, resend thegetReport
request. - Continue to call the
getReport
operation until the value in the response indicates that report process has ended.
GET https://na.business-api.amazon.com/reports/2021-09-30/reports/ID323
import requests
url = "https://na.business-api.amazon.com/reports/2021-09-30/reports/ID323"
headers = {
"accept": "application/json",
"x-amz-access-token": "<Access token retrieved in Prerequisites Step 1>",
}
response = requests.get(url, headers=headers)
print(response.text)
A successful response includes:
Name | Description | Schema |
---|---|---|
Report | The payload for the getReport operation. | Report |
{
"reportId": "ID323",
"reportType": "GET_AB_INVOICE_PDF",
"dataStartTime": "2019-12-11T13:47:20.677Z",
"dataEndTime": "2019-12-12T13:47:20.677Z",
"createdTime": "2019-12-10T13:47:20.677Z",
"processingStatus": "DONE",
"processingStartTime": "2019-12-10T13:47:20.677Z",
"marketplaceIds": [
"A1PA6795UKMFR9"
],
"processingEndTime": "2019-12-12T13:47:20.677Z",
"reportOptions": {
"orderId": "503-5002996-6583839",
"orderLineItemId": "9253990283445",
"shipmentId": "Drs80HLSQ",
"documentType": "Invoice"
}
"reportDocumentId": "DOC-b8b0-4226-b4b9-0ee058ea5760"
}
If a report is available, the response will include a
reportDocumentId
.
Step 3. Retrieve the report
- Call the
getReportDocument
operation by passing thereportDocumentId
path parameter.
Name | Description | Type | Required |
---|---|---|---|
reportDocumentId | The identifier for the report document. | string | Yes |
The report includes a presigned URL. If the content is compressed, the report will include the compression algorithm.
GET https://na.business-api.amazon.com/reports/2021-09-30/documents/DOC-b8b0-4226-b4b9-0ee058ea5760
import requests
url = "https://na.business-api.amazon.com/reports/2021-09-30/documents/DOC-b8b0-4226-b4b9-0ee058ea5760"
headers = {
"accept": "application/json",
"x-amz-access-token": "<Access token retrieved in Prerequisites Step 1>",
}
response = requests.get(url, headers=headers)
print(response.text)
A successful response includes:
Name | Description | Type |
---|---|---|
reportDocumentId | The identifier for the report document. This identifier is unique only in combination with Amazon Business customer. | string |
url | A presigned URL for the report document. This URL expires after five minutes. | string |
compressionAlgorithm | If present, the report document contents have been compressed with the provided algorithm. | string |
{
"reportDocumentId": "DOC-b8b0-4226-b4b9-0ee058ea5760",
"compressionAlgorithm": "GZIP",
"url": "https://d34o8swod1owfl.cloudfront.net/SampleResult%2BKey%3DSample%2BINITVEC%3D58+fa+bf+a7+08+11+95+0f+c1+a8+c6+e0+d5+6f+ae+c8"
}
- Save the
url
andcompressionAlgorithm
(optional). You'll need these to download a report.
Reports contain sensitive information. Don't save unencrypted report on a disk, even temporarily.
- Download the report using the
url
andcompressionAlgorithm
(optional) values.
The downloaded file is compressed twice: first with zip, then with gzip. To view the PDF, decompress the file in reverse order: first use gzip to decompress the file, then unzip the resulting file to access the PDF.
This sample code demonstrates how to download a plain text report document. You can use this example for other programming languages or types of documents, such as XML, CSV, and TSV.
// DownloadExample.java
import java.io.BufferedReader;import java.io.Closeable;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;import java.nio.charset.Charset;import java.util.zip.GZIPInputStream;
import com.squareup.okhttp.MediaType;import com.squareup.okhttp.OkHttpClient;import com.squareup.okhttp.Request;import com.squareup.okhttp.Response;import com.squareup.okhttp.ResponseBody;
/**
* Example that downloads a document.
*/
public class DownloadExample {
public static void main(String args[]) {
String url = "<URL from the getFeedDocument/getReportDocument response>";
String compressionAlgorithm = "<compressionAlgorithm from the getFeedDocument/getReportDocument response>";
DownloadExample obj = new DownloadExample();
try {
obj.download(url, compressionAlgorithm);
} catch (IOException e) {
//Handle exception here.
} catch (IllegalArgumentException e) {
//Handle exception here.
}
}
/**
* Download and optionally decompress the document retrieved from the given url.
*
* @param url the url pointing to a document
* @param compressionAlgorithm the compressionAlgorithm used for the document
* @throws IOException when there is an error reading the response
* @throws IllegalArgumentException when the charset is missing
*/
public void download(String url, String compressionAlgorithm) throws IOException, IllegalArgumentException {
OkHttpClient httpclient = new OkHttpClient();
Request request = new Request.Builder()
.url(url)
.get()
.build();
Response response = httpclient.newCall(request).execute();
if (!response.isSuccessful()) {
System.out.println(
String.format("Call to download content was unsuccessful with response code: %d and message: %s",
response.code(), response.message()));
return;
}
try (ResponseBody responseBody = response.body()) {
MediaType mediaType = MediaType.parse(response.header("Content-Type"));
Charset charset = mediaType.charset();
if (charset == null) {
throw new IllegalArgumentException(String.format(
"Could not parse character set from '%s'", mediaType.toString()));
}
Closeable closeThis = null;
try {
InputStream inputStream = responseBody.byteStream();
closeThis = inputStream;
if ("GZIP".equals(compressionAlgorithm)) {
inputStream = new GZIPInputStream(inputStream);
closeThis = inputStream;
}
// This example assumes that the download content has a charset in the content-type header, e.g.
// text/plain; charset=UTF-8
if ("text".equals(mediaType.type()) && "plain".equals(mediaType.subtype())) {
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, charset);
closeThis = inputStreamReader;
BufferedReader reader = new BufferedReader(inputStreamReader);
closeThis = reader;
String line;
do {
line = reader.readLine();
// Process line by line.
} while (line != null);
} else {
//Handle content with binary data/other media types here.
}
} finally {
if (closeThis != null) {
closeThis.close();
}
}
}
}
}
Poll the
getReportId
every 15 seconds to check the status of the report request.
Frequently asked questions
- When does a transaction appears in the
GET
endpoint?
The transaction appears in theGET
endpoint once the transaction event takes place on Amazon Business for a given order. - When is the invoice document available for download?
The invoice document is available for download once the shipment event takes place for a given order.
Updated about 1 month ago