Skip to Content
Docs

Java

Call the Pay.com API from Java with typed methods and builders, automatic paging, and webhook verification, with no dependencies.

pay-com-java has a typed method for each API operation, named after its resource: pay.charges().create(), pay.holds().capture(), and pay.valueLists().items().create(). Parameters are builders, and responses have a getter for each field, in camelCase. For example, receipt_email is receiptEmail(...) and getReceiptEmail().

Requirements and install

You need Java 11 or later. The library has no dependencies. With Maven:

pom.xml

<dependency>
  <groupId>com.pay</groupId>
  <artifactId>pay-com-java</artifactId>
  <version>0.1.0</version>
</dependency>

With Gradle:

build.gradle.kts

implementation("com.pay:pay-com-java:0.1.0")

Pay is thread-safe. Create one instance and reuse it across requests.

Set your key

Keep the key out of your code. The SDK reads it from PAY_COM_API_KEY:

Terminal

export PAY_COM_API_KEY='sk-pay-com-sandbox-…'

The SDK selects the sandbox or live environment automatically from the key prefix (sk-pay-com-sandbox- or sk-pay-com-live-). The key is never written to the SDK's logs or errors.

Create your first charge

Charge a saved payment method. Amounts are integers in minor units (for example, 2000 is $20.00 USD):

CreateCharge.java

import com.pay.Pay;
import com.pay.model.Charge;
import com.pay.model.ChargesCreateParams;

public class CreateCharge {
  public static void main(String[] args) {
    Pay pay = new Pay();

    Charge charge = pay.charges().create(ChargesCreateParams.builder()
        .amount(2000)
        .currency("usd")
        .source("pm_card_685125127054035968")
        .reference("order-6735")
        .build());

    System.out.println(charge.getId() + " " + charge.getStatus());
  }
}

A field you never set isn't sent. A getter returns null for a field the response leaves out.

The SDK sends a new idempotency key with each POST and DELETE, and the same one when it retries. To use your own, pass it after the parameters: pay.charges().create(params, RequestOptions.builder().idempotencyKey(key).build()).

It retries twice by default after a network error, a timeout, 409 request_in_progress, 421, 429, 502, 503, or 504. To decide yourself, set maxRetries to 0, and set a reference on payments to help you find out what was created.

The SDK retries these only after a 429, or when they never left your server: every PUT and PATCH, webhookEndpoints().create(), and networkTokens().retrieveCryptogram(). If one of these requests receives no response, check whether it succeeded before sending it again.

When you call paymentLinks().update(), pass every field you want to keep, amount and currency included. An update without amount sets the link's amount to 0.

List every item

A list method returns its first page, which is also an Iterable over every item on every page:

ListCharges.java

import com.pay.Pay;
import com.pay.model.Charge;
import com.pay.model.ChargesListParams;

public class ListCharges {
  public static void main(String[] args) {
    Pay pay = new Pay();

    System.out.println(pay.charges().list(ChargesListParams.builder().limit(10).build()).getData().size());

    for (Charge charge : pay.charges().list(ChargesListParams.builder().createdGreaterThan("2026-11-01T00:00:00Z").build())) {
      System.out.println(charge.getId());
    }
  }
}

To collect them, with a limit, use pay.charges().list().stream().limit(500).collect(Collectors.toList()). nextPage() fetches one more page. Lists that use page numbers work the same way.

Catch a decline

A decline throws PaymentMethodException:

Decline.java

import com.pay.InvalidRequestException;
import com.pay.Pay;
import com.pay.PaymentMethodException;
import com.pay.model.ChargesCreateParams;

public class Decline {
  public static void main(String[] args) {
    Pay pay = new Pay();

    try {
      pay.charges().create(ChargesCreateParams.builder()
          .amount(2000)
          .currency("usd")
          .source("pm_card_685125127054035968")
          .build());
    } catch (PaymentMethodException e) {
      System.out.println("Declined: " + e.getDeclineCode());
    } catch (InvalidRequestException e) {
      System.out.println("Fix the request: " + e.getCode() + " " + e.getMessage());
    }
  }
}

Every exception is a PayException, which is unchecked, with getType(), getCode(), getStatusCode(), and the API's body as getRaw(). Include getRequestId() when contacting Pay.com support. It is empty when the API didn't get or couldn't read the request. After retries, getCause() holds an earlier attempt's error. The exception's class tells you what happened:

Error classCause
PaymentMethodExceptionPayment declined by the issuer or blocked by a risk rule (400)
InvalidRequestException400 or 422. NotFoundException, for 404, is one too
AuthenticationException401
PermissionException403
IdempotencyExceptionAn idempotency key in use, or used for another request
ConflictExceptionAny other 409
RateLimitException429
ApiException5xx, a redirect (none is followed), or a response the SDK didn't expect
ApiConnectionExceptionNo complete response. ApiTimeoutException is one too

See Handle errors for what to do with each.

Verify a webhook

Pass the raw body, the Pay-Signature header, and the endpoint's whole signing secret. Cap the body, since anyone can send to your URL. An event can be over 1 MB, so take up to 5 MB. Return HTTP 400 only when SignatureVerificationException is thrown. Let other errors return 500 so Pay.com retries delivery:

WebhookHandler.java

import com.pay.SignatureVerificationException;
import com.pay.Webhooks;
import com.pay.event.ChargeSucceededEvent;
import com.pay.event.Event;

public class WebhookHandler {
  /** Takes the raw body and its Pay-Signature header, and returns the HTTP status code to send. */
  public static int handle(byte[] body, String signatureHeader) {
    Event event;
    try {
      event = Webhooks.constructEvent(body, signatureHeader, System.getenv("PAY_COM_WEBHOOK_SECRET"));
    } catch (SignatureVerificationException e) {
      return 400;
    }
    if (event instanceof ChargeSucceededEvent) {
      System.out.println("Paid: " + ((ChargeSucceededEvent) event).getData().getId());
    }
    return 200;
  }
}

Any other exception is a 500 from your server, and Pay.com sends the event again. Skip events whose id you've already handled.

Each event type has its class, such as ChargeSucceededEvent, whose getData() is a Charge. In your tests, Webhooks.generateTestHeaderString(payload, secret) makes a valid header.

Options

Pass these to new Pay(PayOptions.builder()...build()).

apiKeyString
The secret key.

Default: PAY_COM_API_KEY

environmentEnvironment
Environment.SANDBOX or Environment.LIVE, for a key without either prefix.
merchantIdString
Target merchant ID for multi-workspace API keys.
timeoutDuration
How long each attempt can take, reading the response included.

Default: 60 seconds

maxRetriesint
Maximum number of automatic retry attempts.

Default: 2

baseUrlString
Custom API base URL for local mocks or proxies.
defaultHeadersMap<String, String>
Headers sent with every request.
httpClientjava.net.http.HttpClient
Your own client, for a proxy, an executor, or TLS settings. It must not follow redirects.
logLevelSystem.Logger.Level
Log verbosity level, written through System.Logger. Also read from PAY_COM_LOG.

Default: WARNING

merchantId, timeout, maxRetries, and idempotencyKey can also be set for one request, in a RequestOptions after the parameters. The sandbox's simulate endpoints are under pay.testHelpers(). pay.documents().upload() takes an Upload with the file and its content type. See Upload and download files.

Was this page helpful?