Skip to content

gr4vy/gr4vy-java

Repository files navigation

Gr4vy Java SDK (Beta)

Developer-friendly & type-safe Java SDK specifically catered to leverage Gr4vy API.

Maven Central Version



Important

This is a Beta release of our latest SDK. Please refer to the legacy Java SDK for the latest stable build.

Summary

Gr4vy Java SDK

The official Gr4vy SDK for Java provides a convenient way to interact with the Gr4vy API from your server-side application. This SDK allows you to seamlessly integrate Gr4vy's powerful payment orchestration capabilities, including:

  • Creating Transactions: Initiate and process payments with various payment methods and services.
  • Managing Buyers: Store and manage buyer information securely.
  • Storing Payment Methods: Securely store and tokenize payment methods for future use.
  • Handling Webhooks: Easily process and respond to webhook events from Gr4vy.
  • And much more: Access the full suite of Gr4vy API payment features.

This SDK is designed to simplify development, reduce boilerplate code, and help you get up and running with Gr4vy quickly and efficiently. It handles authentication, request signing, and provides easy-to-use methods for most API endpoints.

Table of Contents

SDK Installation

Getting started

JDK 11 or later is required.

The samples below show how a published SDK artifact is used:

Gradle:

implementation 'com.gr4vy:sdk:1.0.0-beta.10'

Maven:

<dependency>
    <groupId>com.gr4vy</groupId>
    <artifactId>sdk</artifactId>
    <version>1.0.0-beta.10</version>
</dependency>

How to build

After cloning the git repository to your file system you can build the SDK artifact from source to the build directory by running ./gradlew build on *nix systems or gradlew.bat on Windows systems.

If you wish to build from source and publish the SDK artifact to your local Maven repository (on your filesystem) then use the following command (after cloning the git repo locally):

On *nix:

./gradlew publishToMavenLocal -Pskip.signing

On Windows:

gradlew.bat publishToMavenLocal -Pskip.signing

Logging

A logging framework/facade has not yet been adopted but is under consideration.

For request and response logging (especially json bodies) use:

SpeakeasyHTTPClient.setDebugLogging(true); // experimental API only (may change without warning)

Example output:

Sending request: http://localhost:35123/bearer#global GET
Request headers: {Accept=[application/json], Authorization=[******], Client-Level-Header=[added by client], Idempotency-Key=[some-key], x-speakeasy-user-agent=[speakeasy-sdk/java 0.0.1 internal 0.1.0 org.openapis.openapi]}
Received response: (GET http://localhost:35123/bearer#global) 200
Response headers: {access-control-allow-credentials=[true], access-control-allow-origin=[*], connection=[keep-alive], content-length=[50], content-type=[application/json], date=[Wed, 09 Apr 2025 01:43:29 GMT], server=[gunicorn/19.9.0]}
Response body:
{
  "authenticated": true, 
  "token": "global"
}

WARNING: This should only used for temporary debugging purposes. Leaving this option on in a production system could expose credentials/secrets in logs. Authorization headers are redacted by default and there is the ability to specify redacted header names via SpeakeasyHTTPClient.setRedactedHeaders.

Another option is to set the System property -Djdk.httpclient.HttpClient.log=all. However, this second option does not log bodies.

SDK Example Usage

Example

package hello.world;

import com.gr4vy.sdk.BearerSecuritySource;
import com.gr4vy.sdk.Gr4vy;
import com.gr4vy.sdk.Gr4vy.AvailableServers;
import com.gr4vy.sdk.models.components.AccountUpdaterJobCreate;
import com.gr4vy.sdk.models.errors.*;
import com.gr4vy.sdk.models.operations.ListTransactionsRequest;
import java.lang.Exception;
import java.util.List;

public class Application {

    public static void main(String[] args) throws Exception {

        String privateKey = "-----BEGIN PRIVATE KEY-----\n...."; // a valid private key

        Gr4vy sdk = Gr4vy.builder()
                .id("example")
                .server(AvailableServers.SANDBOX)
                .merchantAccountId("default")
                .securitySource(new BearerSecuritySource.Builder(privateKey).build())
            .build();

        ListTransactionsRequest req = ListTransactionsRequest.builder()          
            .build();

        sdk.transactions().list()
            .request(req)
            .callAsStream()
            .forEach(item -> {
                // handle item
            });
    }
}

Bearer token generation

Alternatively, you can create a token for use with the SDK or with your own client library.

import com.gr4vy.sdk.Auth;

Auth.getToken(privateKey, Arrays.asList(JWTScope.READ_ALL, JWTScope.WRITE_ALL), 3600);

Note: This will only create a token once. Use securitySource when initializing the SDK to dynamically generate a token for every request.

Embed token generation

Alternatively, you can create a token for use with Embed as follows.

import com.gr4vy.sdk.Auth;

Map<String, Object> embedParams = ...; // a map of extra params to use with Embed
String privateKey = "-----BEGIN PRIVATE KEY-----\n...."; // a valid private key
String checkoutSessionId = ""; // a valid ID for a checkout session
String token = Auth.getEmbedToken(privateKey, embedParams, checkoutSessionId);

Note: This will only create a token once. Use securitySource when initializing the SDK to dynamically generate a token for every request.

Merchant account ID selection

Depending on the key used, you might need to explicitly define a merchant account ID to use. In our API, this uses the X-GR4VY-MERCHANT-ACCOUNT-ID header. When using the SDK, you can set the merchantAccountId on every request.

sdk.transactions().list()
    .request(request)
    .merchantAccountId("my-merchant-account-id")
    .callAsStream()
    .forEach(item -> {
        // handle item
    });

Alternatively, the merchant account ID can also be set when initializing the SDK.

Gr4vy sdk = Gr4vy.builder()
        .id("example")
        .server(AvailableServers.SANDBOX)
        .merchantAccountId("my-merchant-account-id")
        .securitySource(new BearerSecuritySource.Builder(privateKey).build())
    .build()

Webhooks verification

The SDK provides a verifyWebhook method to validate incoming webhook requests from Gr4vy. This ensures that the webhook payload is authentic and has not been tampered with.

import com.gr4vy.sdk.Webhooks;

String payload = 'your-webhook-payload';
String secret = 'your-webhook-secret';
String signatureHeader = 'signatures-from-header';
String timestampHeader = 'timestamp-from-header';
String timestampTolerance = 300; // optional, in seconds (default: 0)

try {
    Webhooks.verifyWebhook(payload, secret, wrongSignatureHeader, timestampTolerance, timestampHeader);
    System.out.println("Webhook verified successfully.");
} catch (IllegalArgumentException e) {
    System.err.println("Invalid input: " + e.getMessage());
}

Parameters

  • payload: The raw payload string received in the webhook request.
  • secret: The secret used to sign the webhook. This is provided in your Gr4vy dashboard.
  • signatureHeader: The X-Gr4vy-Signature header from the webhook request.
  • timestampHeader: The X-Gr4vy-Timestamp header from the webhook request.
  • timestampTolerance: (Optional) The maximum allowed difference (in seconds) between the current time and the timestamp in the webhook. Defaults to 0 (no tolerance).

Available Resources and Operations

Available methods
  • create - Create account updater job
  • list - List audit log entries
  • list - List gift cards for a buyer
  • list - List payment methods for a buyer
  • create - Add buyer shipping details
  • list - List a buyer's shipping details
  • get - Get buyer shipping details
  • update - Update a buyer's shipping details
  • delete - Delete a buyer's shipping details
  • list - List card scheme definitions
  • create - Create checkout session
  • update - Update checkout session
  • get - Get checkout session
  • delete - Delete checkout session
  • create - Register digital wallet
  • list - List digital wallets
  • get - Get digital wallet
  • delete - Delete digital wallet
  • update - Update digital wallet
  • create - Register a digital wallet domain
  • delete - Remove a digital wallet domain
  • get - Get gift card
  • delete - Delete a gift card
  • create - Create gift card
  • list - List gift cards
  • list - List gift card balances
  • list - List all merchant accounts
  • create - Create a merchant account
  • get - Get a merchant account
  • update - Update a merchant account
  • create - Add a payment link
  • list - List all payment links
  • expire - Expire a payment link
  • get - Get payment link
  • list - List all payment methods
  • create - Create payment method
  • get - Get payment method
  • delete - Delete payment method
  • list - List network tokens
  • create - Provision network token
  • suspend - Suspend network token
  • resume - Resume network token
  • delete - Delete network token
  • create - Provision network token cryptogram
  • list - List payment service tokens
  • create - Create payment service token
  • delete - Delete payment service token
  • list - List payment options
  • list - List payment service definitions
  • get - Get a payment service definition
  • session - Create a session for apayment service definition
  • list - List payment services
  • create - Update a configured payment service
  • get - Get payment service
  • update - Configure a payment service
  • delete - Delete a configured payment service
  • verify - Verify payment service credentials
  • session - Create a session for apayment service definition
  • list - List payouts created.
  • create - Create a payout.
  • get - Get a payout.
  • get - Get refund
  • list - List configured reports
  • create - Add a report
  • get - Get a report
  • put - Update a report
  • list - List executions for report
  • url - Create URL for executed report
  • all - List executed reports
  • get - Get executed report
  • list - List transactions
  • create - Create transaction
  • get - Get transaction
  • capture - Capture transaction
  • void_ - Void transaction
  • sync - Sync transaction
  • list - List transaction events
  • list - List transaction refunds
  • create - Create transaction refund
  • get - Get transaction refund
  • create - Create batch transaction refund

Pagination

Some of the endpoints in this SDK support pagination. To use pagination, you make your SDK calls as usual, but the returned response object will have a next method that can be called to pull down the next group of results. The next function returns an Optional value, which isPresent until there are no more pages to be fetched.

Here's an example of one such pagination call:

package hello.world;

import com.gr4vy.sdk.Gr4vy;
import com.gr4vy.sdk.models.errors.*;
import com.gr4vy.sdk.models.operations.ListBuyersRequest;
import java.lang.Exception;

public class Application {

    public static void main(String[] args) throws Exception {

        Gr4vy sdk = Gr4vy.builder()
                .merchantAccountId("default")
                .bearerAuth("<YOUR_BEARER_TOKEN_HERE>")
            .build();

        ListBuyersRequest req = ListBuyersRequest.builder()
                .cursor("ZXhhbXBsZTE")
                .search("John")
                .externalIdentifier("buyer-12345")
                .build();

        sdk.buyers().list()
                .request(req)
                .callAsStream()
                .forEach(item -> {
                   // handle item
                });

    }
}

Retries

Some of the endpoints in this SDK support retries. If you use the SDK without any configuration, it will fall back to the default retry strategy provided by the API. However, the default retry strategy can be overridden on a per-operation basis, or across the entire SDK.

To change the default retry strategy for a single API call, you can provide a RetryConfig object through the retryConfig builder method:

package hello.world;

import com.gr4vy.sdk.Gr4vy;
import com.gr4vy.sdk.models.errors.*;
import com.gr4vy.sdk.models.operations.ListBuyersRequest;
import com.gr4vy.sdk.utils.BackoffStrategy;
import com.gr4vy.sdk.utils.RetryConfig;
import java.lang.Exception;
import java.util.concurrent.TimeUnit;

public class Application {

    public static void main(String[] args) throws Exception {

        Gr4vy sdk = Gr4vy.builder()
                .merchantAccountId("default")
                .bearerAuth("<YOUR_BEARER_TOKEN_HERE>")
            .build();

        ListBuyersRequest req = ListBuyersRequest.builder()
                .cursor("ZXhhbXBsZTE")
                .search("John")
                .externalIdentifier("buyer-12345")
                .build();

        sdk.buyers().list()
                .request(req)
                .retryConfig(RetryConfig.builder()
                    .backoff(BackoffStrategy.builder()
                        .initialInterval(1L, TimeUnit.MILLISECONDS)
                        .maxInterval(50L, TimeUnit.MILLISECONDS)
                        .maxElapsedTime(1000L, TimeUnit.MILLISECONDS)
                        .baseFactor(1.1)
                        .jitterFactor(0.15)
                        .retryConnectError(false)
                        .build())
                    .build())
                .callAsStream()
                .forEach(item -> {
                   // handle item
                });

    }
}

If you'd like to override the default retry strategy for all operations that support retries, you can provide a configuration at SDK initialization:

package hello.world;

import com.gr4vy.sdk.Gr4vy;
import com.gr4vy.sdk.models.errors.*;
import com.gr4vy.sdk.models.operations.ListBuyersRequest;
import com.gr4vy.sdk.utils.BackoffStrategy;
import com.gr4vy.sdk.utils.RetryConfig;
import java.lang.Exception;
import java.util.concurrent.TimeUnit;

public class Application {

    public static void main(String[] args) throws Exception {

        Gr4vy sdk = Gr4vy.builder()
                .retryConfig(RetryConfig.builder()
                    .backoff(BackoffStrategy.builder()
                        .initialInterval(1L, TimeUnit.MILLISECONDS)
                        .maxInterval(50L, TimeUnit.MILLISECONDS)
                        .maxElapsedTime(1000L, TimeUnit.MILLISECONDS)
                        .baseFactor(1.1)
                        .jitterFactor(0.15)
                        .retryConnectError(false)
                        .build())
                    .build())
                .merchantAccountId("default")
                .bearerAuth("<YOUR_BEARER_TOKEN_HERE>")
            .build();

        ListBuyersRequest req = ListBuyersRequest.builder()
                .cursor("ZXhhbXBsZTE")
                .search("John")
                .externalIdentifier("buyer-12345")
                .build();

        sdk.buyers().list()
                .request(req)
                .callAsStream()
                .forEach(item -> {
                   // handle item
                });

    }
}

Error Handling

Handling errors in this SDK should largely match your expectations. All operations return a response object or raise an exception.

By default, an API error will throw a models/errors/APIException exception. When custom error responses are specified for an operation, the SDK may also throw their associated exception. You can refer to respective Errors tables in SDK docs for more details on possible exception types for each operation. For example, the create method throws the following exceptions:

Error Type Status Code Content Type
models/errors/Error400 400 application/json
models/errors/Error401 401 application/json
models/errors/Error403 403 application/json
models/errors/Error404 404 application/json
models/errors/Error405 405 application/json
models/errors/Error409 409 application/json
models/errors/HTTPValidationError 422 application/json
models/errors/Error425 425 application/json
models/errors/Error429 429 application/json
models/errors/Error500 500 application/json
models/errors/Error502 502 application/json
models/errors/Error504 504 application/json
models/errors/APIException 4XX, 5XX */*

Example

package hello.world;

import com.gr4vy.sdk.Gr4vy;
import com.gr4vy.sdk.models.components.AccountUpdaterJobCreate;
import com.gr4vy.sdk.models.errors.*;
import com.gr4vy.sdk.models.operations.CreateAccountUpdaterJobResponse;
import java.lang.Exception;
import java.util.List;

public class Application {

    public static void main(String[] args) throws Exception {

        Gr4vy sdk = Gr4vy.builder()
                .merchantAccountId("default")
                .bearerAuth("<YOUR_BEARER_TOKEN_HERE>")
            .build();

        CreateAccountUpdaterJobResponse res = sdk.accountUpdater().jobs().create()
                .accountUpdaterJobCreate(AccountUpdaterJobCreate.builder()
                    .paymentMethodIds(List.of(
                        "ef9496d8-53a5-4aad-8ca2-00eb68334389",
                        "f29e886e-93cc-4714-b4a3-12b7a718e595"))
                    .build())
                .call();

        if (res.accountUpdaterJob().isPresent()) {
            // handle response
        }
    }
}

Server Selection

Select Server by Name

You can override the default server globally using the .server(AvailableServers server) builder method when initializing the SDK client instance. The selected server will then be used as the default on the operations that use it. This table lists the names associated with the available servers:

Name Server Variables Description
production https://api.{id}.gr4vy.app id
sandbox https://api.sandbox.{id}.gr4vy.app id

If the selected server has variables, you may override its default values using the associated builder method(s):

Variable BuilderMethod Default Description
id id(String id) "example" The subdomain for your Gr4vy instance.

Example

package hello.world;

import com.gr4vy.sdk.Gr4vy;
import com.gr4vy.sdk.models.components.AccountUpdaterJobCreate;
import com.gr4vy.sdk.models.errors.*;
import com.gr4vy.sdk.models.operations.CreateAccountUpdaterJobResponse;
import java.lang.Exception;
import java.util.List;

public class Application {

    public static void main(String[] args) throws Exception {

        Gr4vy sdk = Gr4vy.builder()
                .server(Gr4vy.AvailableServers.SANDBOX)
                .id("<id>")
                .merchantAccountId("default")
                .bearerAuth("<YOUR_BEARER_TOKEN_HERE>")
            .build();

        CreateAccountUpdaterJobResponse res = sdk.accountUpdater().jobs().create()
                .accountUpdaterJobCreate(AccountUpdaterJobCreate.builder()
                    .paymentMethodIds(List.of(
                        "ef9496d8-53a5-4aad-8ca2-00eb68334389",
                        "f29e886e-93cc-4714-b4a3-12b7a718e595"))
                    .build())
                .call();

        if (res.accountUpdaterJob().isPresent()) {
            // handle response
        }
    }
}

Override Server URL Per-Client

The default server can also be overridden globally using the .serverURL(String serverUrl) builder method when initializing the SDK client instance. For example:

package hello.world;

import com.gr4vy.sdk.Gr4vy;
import com.gr4vy.sdk.models.components.AccountUpdaterJobCreate;
import com.gr4vy.sdk.models.errors.*;
import com.gr4vy.sdk.models.operations.CreateAccountUpdaterJobResponse;
import java.lang.Exception;
import java.util.List;

public class Application {

    public static void main(String[] args) throws Exception {

        Gr4vy sdk = Gr4vy.builder()
                .serverURL("https://api.example.gr4vy.app")
                .merchantAccountId("default")
                .bearerAuth("<YOUR_BEARER_TOKEN_HERE>")
            .build();

        CreateAccountUpdaterJobResponse res = sdk.accountUpdater().jobs().create()
                .accountUpdaterJobCreate(AccountUpdaterJobCreate.builder()
                    .paymentMethodIds(List.of(
                        "ef9496d8-53a5-4aad-8ca2-00eb68334389",
                        "f29e886e-93cc-4714-b4a3-12b7a718e595"))
                    .build())
                .call();

        if (res.accountUpdaterJob().isPresent()) {
            // handle response
        }
    }
}

Development

Testing

To run the tests, install Java, ensure to download the private_key.pem for the test environment, and run the following.

E2E=true ./gradlew clean test

Maturity

This SDK is in beta, and there may be breaking changes between versions without a major version update. Therefore, we recommend pinning usage to a specific package version. This way, you can install the same version each time without breaking changes unless you are intentionally looking for the latest version.

Contributions

While we value open-source contributions to this SDK, this library is generated programmatically. Any manual changes added to internal files will be overwritten on the next generation. We look forward to hearing your feedback. Feel free to open a PR or an issue with a proof of concept and we'll do our best to include it in a future release.

SDK Created by Speakeasy

About

Java SDK for Gr4vy API

Resources

Stars

Watchers

Forks

Contributors 9

Languages