Skip to content

Repository files navigation

Square Java Library

fern shieldMaven Central

The Square Java library provides convenient access to the Square APIs from Java.

Table of Contents

Requirements

Use of the Square Java SDK requires:

  • Java 8+

Installation

Gradle

Add the dependency in your build.gradle file:

dependencies {
implementation 'com.squareup:square'
}

Maven

Add the dependency in your pom.xml file:

<dependency>
<groupId>com.squareup</groupId>
<artifactId>square</artifactId>
<version>47.0.1.20260715</version>
</dependency>

Usage

Instantiate and use the client with the following:

packagecom.example.usage;
importcom.squareup.square.SquareClient;
importcom.squareup.square.types.CreatePaymentRequest;
importcom.squareup.square.types.Currency;
importcom.squareup.square.types.Money;
publicclassExample {
publicstaticvoidmain(String[] args) {
SquareClientclient = SquareClient
.builder()
.token("<token>")
.build();
client.payments().create(
CreatePaymentRequest
.builder()
.sourceId("ccof:GaJGNaZa8x4OgDJn4GB")
.idempotencyKey("7b0f3ec5-086a-4871-8f13-3c81b3875218")
.amountMoney(
Money
.builder()
.amount(1000L)
.currency(Currency.USD)
.build()
)
.appFeeMoney(
Money
.builder()
.amount(10L)
.currency(Currency.USD)
.build()
)
.autocomplete(true)
.customerId("W92WH6P11H4Z77CTET0RNTGFW8")
.locationId("L88917AVBK2S5")
.referenceId("123456")
.note("Brief description")
.build()
);
}
}

Instantiation

To get started with the Square SDK, instantiate the SquareClient class as follows:

importcom.squareup.square.SquareClient;
SquareClientsquare = SquareClient.builder().token("SQUARE_TOKEN").build();

Alternatively, you can omit the token when constructing the client. In this case, the SDK will automatically read the token from the SQUARE_TOKEN environment variable:

importcom.squareup.square.SquareClient;
SquareClientsquare = SquareClient.builder().build();

Environment and Custom URLs

This SDK allows you to configure different environments or custom URLs for API requests. You can either use the predefined environments or specify your own custom URL.

Environments

importcom.squareup.square.SquareClient;
importcom.squareup.square.core.Environment;
SquareClientsquare = SquareClient.builder().environment(Environment.PRODUCTION).build();

Custom URL

importcom.squareup.square.SquareClient;
SquareClientsquare = SquareClient.builder().url("https://custom-staging.com").build();

Enums

This SDK wraps enums for forward compatibility. We define enum properties as constant type instances with String properties and use valueOf to specify custom enum types that may not yet be included as constants.

Example Usage

Supported Property

importcom.squareup.square.types.InvoicePaymentRequest;
importcom.squareup.square.types.InvoiceRequestType;
InvoicePaymentRequestpaymentRequest = InvoicePaymentRequest.builder()
.requestType(InvoiceRequestType.BALANCE)
.build();

Custom Property

importcom.squareup.square.types.InvoicePaymentRequest;
importcom.squareup.square.types.InvoiceRequestType;
InvoicePaymentRequestpaymentRequest = InvoicePaymentRequest.builder()
.requestType(InvoiceRequestType.valueOf("CUSTOM"))
.build();

Versioning

By default, the SDK is pinned to the version 2025-03-19. If you would like to override this version you can simply pass in a request option.

client.cards().create(..., RequestOptions.builder()
.version("2024-05-04") // override the version used
.build());

Automatic Pagination

Paginated requests will return an Iterable<T>, which can be used to loop through the underlying items.

importcom.squareup.square.SquareClient;
importcom.squareup.square.core.SyncPagingIterable;
importcom.squareup.square.types.Payment;
importcom.squareup.square.types.PaymentsListRequest;
SquareClientsquare = SquareClient.builder().token("YOUR_TOKEN").build();
SyncPagingIterable<Payment> payments =
square.payments().list(PaymentsListRequest.builder().total(100L).build());
for (Paymentpayment : payments) {
System.out.printf(
"payment: ID: %s Created at: %s, Updated at: %s\n",
payment.getId(), payment.getCreatedAt(), payment.getUpdatedAt());
}

or stream them:

square.payments()
.list(PaymentsListRequest.builder().total(100L).build())
.streamItems()
.map(item -> ...);

or calling nextPage() to perform the pagination manually:

// First pageList<Payment> pagePayments = payments.getItems();
for (Paymentpayment : pagePayments) {
// ...
}
// Remaining pageswhile (payments.hasNext()) {
pagePayments = payments.nextPage().getItems();
for (Paymentpayment : pagePayments) {
// ...
}
}

Retries

The SDK is instrumented with automatic retries with exponential backoff. A request will be retried as long as the request is deemed retriable and the number of retry attempts has not grown larger than the configured retry limit (default: 2).

A request is deemed retriable when any of the following HTTP status codes is returned:

  • 408 (Timeout)
  • 429 (Too Many Requests)
  • 5XX (Internal Server Errors)

Use the maxRetries request option to configure this behavior.

square.cards().create(..., RequestOptions.builder()
.maxRetries(1)
.build());

Timeouts

The SDK defaults to a 60 second timeout. You can configure this with a timeout option at the client or request level.

square.cards().create(..., RequestOptions.builder()
.timeout(10)
.build());

Environments

This SDK allows you to configure different environments for API requests.

importcom.squareup.square.SquareClient;
importcom.squareup.square.core.Environment;
SquareClientclient = SquareClient
.builder()
.environment(Environment.Production)
.build();

Base Url

You can set a custom base URL when constructing the client.

importcom.squareup.square.SquareClient;
SquareClientclient = SquareClient
.builder()
.url("https://example.com")
.build();

Exception Handling

When the API returns a non-success status code (4xx or 5xx response), an API exception will be thrown.

importcom.squareup.square.core.SquareApiException;
try{
client.payments().create(...);
} catch (SquareApiExceptione){
// Do something with the API exception...
}

Webhook Signature Verification

The SDK provides utility methods that allow you to verify webhook signatures and ensure that all webhook events originate from Square. The WebhooksHelper.verifySignature method can be used to easily verify the signature like so:

importcom.squareup.square.utilities.WebhooksHelper;
booleanisValid = WebhooksHelper.verifySignature(
requestBody,
headers.get("x-square-hmacsha256-signature"),
"YOUR_SIGNATURE_KEY",
"https://example.com/webhook"// The URL where event notifications are sent.
);

Reporting API

The Reporting API lets you query aggregated reporting data. Call reporting().getMetadata() first to discover the available cubes, measures, and dimensions, then run a query with reporting().load(...).

importcom.squareup.square.SquareClient;
importcom.squareup.square.types.LoadRequest;
importcom.squareup.square.types.LoadResponse;
importcom.squareup.square.types.MetadataResponse;
importcom.squareup.square.types.Query;
importjava.util.Collections;
SquareClientclient = SquareClient.builder().token("YOUR_TOKEN").build();
// Discover what you can query.MetadataResponsemetadata = client.reporting().getMetadata();
// Run a query against the discovered schema.LoadResponseresponse = client.reporting()
.load(LoadRequest.builder()
.query(Query.builder()
.measures(Collections.singletonList("Orders.count"))
.build())
.build());

load is asynchronous: while a query is still being computed, the API returns an HTTP 200 whose body is { "error": "Continue wait" } instead of results, and the client is expected to re-send the identical request — with backoff — until the results are ready. The ReportingHelper.loadAndWait utility owns that polling loop for you and returns the resolved results (never the "Continue wait" sentinel):

importcom.squareup.square.types.LoadRequest;
importcom.squareup.square.types.LoadResponse;
importcom.squareup.square.types.Query;
importcom.squareup.square.utilities.ReportingHelper;
importjava.util.Collections;
LoadResponseresponse = ReportingHelper.loadAndWait(
client,
LoadRequest.builder()
.query(Query.builder()
.measures(Collections.singletonList("Orders.count"))
.build())
.build());
System.out.println(response.getData());

By default it polls up to 20 times with exponential backoff (2s → 20s). Tune the behavior via LoadAndWaitOptions; the poll loop also honors thread interruption, so cancelling the calling thread (or its Future) aborts an in-flight wait:

importcom.squareup.square.utilities.LoadAndWaitOptions;
LoadResponseresponse = ReportingHelper.loadAndWait(
client,
request,
LoadAndWaitOptions.builder()
.maxAttempts(10) // default 20
.initialDelayMs(1000) // default 2000
.maxDelayMs(20000) // default 20000
.backoffFactor(2) // default 2
.build());

Reference

A full reference for this library is available here.

Legacy SDK

While the new SDK has a lot of improvements, we at Square understand that it takes time to upgrade when there are breaking changes. To make the migration easier, the new SDK also exports the legacy SDK as com.squareup.square.legacy.... Here's an example of how you can use the legacy SDK alongside the new SDK inside a single file:

importcom.squareup.square.SquareClient;
importcom.squareup.square.core.Environment;
SquareClientsquare = SquareClient.builder()
.environment(Environment.PRODUCTION)
.token("YOUR_TOKEN")
.build();
com.squareup.square.legacy.SquareClientlegacyClient = newcom.squareup.square.legacy.SquareClient.Builder()
.environment(com.squareup.square.legacy.Environment.PRODUCTION)
.accessToken("YOUR_TOKEN")
.build();

We recommend migrating to the new SDK using the following steps:

  1. Include the following dependencies in your project

Gradle:

dependencies {
implementation 'com.squareup:square:47.0.1.20260715'
implementation 'com.squareup:square-legacy:47.0.1.20260715'
}

Maven:

<dependency>
<groupId>com.squareup</groupId>
<artifactId>square</artifactId>
<version>47.0.1.20260715</version>
</dependency>
<dependency>
<groupId>com.squareup</groupId>
<artifactId>square-legacy</artifactId>
<version>47.0.1.20260715</version>
</dependency>
  1. Search and replace all imports from com.squareup.square to com.squareup.square-legacy
  2. Gradually move over to use the new SDK by importing it from the com.squareup.square import

Advanced

Custom Client

This SDK is built to work with any instance of OkHttpClient. By default, if no client is provided, the SDK will construct one. However, you can pass your own client like so:

importcom.squareup.square.SquareClient;
importokhttp3.OkHttpClient;
OkHttpClientcustomClient = ...;
SquareClientclient = SquareClient
.builder()
.httpClient(customClient)
.build();

Retries

The SDK is instrumented with automatic retries with exponential backoff. A request will be retried as long as the request is deemed retryable and the number of retry attempts has not grown larger than the configured retry limit (default: 2). Before defaulting to exponential backoff, the SDK will first attempt to respect the Retry-After header (as either in seconds or as an HTTP date), and then the X-RateLimit-Reset header (as a Unix timestamp in epoch seconds); failing both of those, it will fall back to exponential backoff.

A request is deemed retryable when any of the following HTTP status codes is returned:

  • 408 (Timeout)
  • 429 (Too Many Requests)
  • 5XX (Internal Server Errors)

Use the maxRetries client option to configure this behavior.

importcom.squareup.square.SquareClient;
SquareClientclient = SquareClient
.builder()
.maxRetries(1)
.build();

Timeouts

The SDK defaults to a 60 second timeout. You can configure this with a timeout option at the client or request level.

importcom.squareup.square.SquareClient;
importcom.squareup.square.core.RequestOptions;
// Client levelSquareClientclient = SquareClient
.builder()
.timeout(60)
.build();
// Request levelclient.payments().create(
...,
RequestOptions
.builder()
.timeout(60)
.build()
);

Custom Headers

The SDK allows you to add custom headers to requests. You can configure headers at the client level or at the request level.

importcom.squareup.square.SquareClient;
importcom.squareup.square.core.RequestOptions;
// Client levelSquareClientclient = SquareClient
.builder()
.addHeader("X-Custom-Header", "custom-value")
.addHeader("X-Request-Id", "abc-123")
.build();
;
// Request levelclient.payments().create(
...,
RequestOptions
.builder()
.addHeader("X-Request-Header", "request-value")
.build()
);

Access Raw Response Data

The SDK provides access to raw response data, including headers, through the withRawResponse() method. The withRawResponse() method returns a raw client that wraps all responses with body() and headers() methods. (A normal client's response is identical to a raw client's response.body().)

CreateHttpResponseresponse = client.payments().withRawResponse().create(...);
System.out.println(response.body());
System.out.println(response.headers().get("X-My-Header"));

Contributing

While we value open-source contributions to this SDK, this library is generated programmatically. Additions made directly to this library would have to be moved over to our generation code, otherwise they would be overwritten upon the next generated release. Feel free to open a PR as a proof of concept, but know that we will not be able to merge it as-is. We suggest opening an issue first to discuss with us!

On the other hand, contributions to the README are always very welcome!

About

Java client library for the Square API

Topics

Resources

Stars

70 stars

Watchers

11 watching

Forks

Releases

Packages

Used by

Contributors

Languages