Sample code for 30+ languages & platforms
Java Requires Chilkat v11.0.0+

PayPal: List merchant invoices across pages

See more PayPal Examples

List invoices for the authenticated merchant. Request totals, iterate every page, and keep the PayPal ID alongside the human-readable number and current status.

PayPal documentation

Chilkat Java Downloads

Java
import com.chilkatsoft.chilkat2.ChilkatException;
import com.chilkatsoft.chilkat2.Http;
import com.chilkatsoft.chilkat2.HttpResponse;
import com.chilkatsoft.chilkat2.JsonObject;
import com.chilkatsoft.chilkat2.StringBuilder;

public class ChilkatExample {

    public static void main(String[] args) {
        // See Unlock Chilkat before making requests.
        // For the merchant's internal backoffice application. Load the sandbox token
        // from the merchant's credential store. Keep it out of publicly distributed apps.
        // See Get a PayPal access token.
        Http http = new Http();
        http.setAuthToken("SANDBOX_ACCESS_TOKEN");
        HttpResponse resp = new HttpResponse();

        // Request total_pages so a merchant with more than one page sees every invoice.
        int page = 1;
        int lastPage = 1;
        while (page <= lastPage) {
            StringBuilder url = new StringBuilder();
            url.append("https://api-m.sandbox.paypal.com/v2/invoicing/invoices?total_required=true&page_size=20&page=");
            url.appendInt(page);
            try {
                http.httpNoBody("GET", url.getAsString(), resp);
            } catch (ChilkatException e) {
                System.out.println("No HTTP response: " + e.getLastErrorText());
                return;
            }

            if ((resp.getStatusCode() < 200) || (resp.getStatusCode() >= 300)) {
                JsonObject errorInfo = new JsonObject();
                errorInfo.load(resp.getBodyStr());
                System.out.println("HTTP " + resp.getStatusCode() + " " + errorInfo.stringOf("name") + " " + errorInfo.stringOf("details[0].issue"));
                System.out.println("PayPal debug ID: " + errorInfo.stringOf("debug_id"));
                return;
            }

            JsonObject result = new JsonObject();
            try {
                result.load(resp.getBodyStr());
            } catch (ChilkatException e) {
                System.out.println("Expected a JSON response; HTTP " + resp.getStatusCode());
                return;
            }

            int i = 0;
            int count = result.sizeOfArray("items");
            while (i < count) {
                result.setI(i);
                System.out.println(result.stringOf("items[i].id") + "  " + result.stringOf("items[i].detail.invoice_number") + "  " + result.stringOf("items[i].status"));
                i = i + 1;
            }

            lastPage = result.intOf("total_pages");
            page = page + 1;
        }
    }
}