Skip to content

Latest commit

History

233 Commits

Folders and files

NameName
Last commit message
Last commit date

Repository files navigation

Checkout Intents Java API Library

Maven Centraljavadoc

The Checkout Intents Java SDK provides convenient access to the Checkout Intents REST API from applications written in Java.

It is generated with Stainless.

The REST API documentation can be found on docs.rye.com. Javadocs are available on javadoc.io.

Installation

Gradle

implementation("com.rye:checkout-intents:0.14.0")

Maven

<dependency>
<groupId>com.rye</groupId>
<artifactId>checkout-intents</artifactId>
<version>0.14.0</version>
</dependency>

Requirements

This library requires Java 8 or later.

Usage

importcom.rye.client.CheckoutIntentsClient;
importcom.rye.client.okhttp.CheckoutIntentsOkHttpClient;
importcom.rye.models.checkoutintents.Buyer;
importcom.rye.models.checkoutintents.CheckoutIntent;
importcom.rye.models.checkoutintents.CheckoutIntentPurchaseParams;
importcom.rye.models.checkoutintents.PaymentMethod;
// Configures using the `checkoutintents.apiKey` and `checkoutintents.baseUrl` system properties// Or configures using the `CHECKOUT_INTENTS_API_KEY` and `CHECKOUT_INTENTS_BASE_URL` environment variablesCheckoutIntentsClientclient = CheckoutIntentsOkHttpClient.fromEnv();
CheckoutIntentPurchaseParamsparams = CheckoutIntentPurchaseParams.builder()
.buyer(Buyer.builder()
.address1("123 Main St")
.city("New York")
.country("US")
.email("john.doe@example.com")
.firstName("John")
.lastName("Doe")
.phone("1234567890")
.postalCode("10001")
.province("NY")
.build())
.paymentMethod(PaymentMethod.StripeTokenPaymentMethod.builder()
.stripeToken("tok_1RkrWWHGDlstla3f1Fc7ZrhH")
.type(PaymentMethod.StripeTokenPaymentMethod.Type.STRIPE_TOKEN)
.build())
.productUrl("https://rye-protocol.myshopify.com/products/rye-sticker")
.quantity(1)
.build();
CheckoutIntentcheckoutIntent = client.checkoutIntents().purchase(params);

Client configuration

Configure the client using system properties or environment variables:

importcom.rye.client.CheckoutIntentsClient;
importcom.rye.client.okhttp.CheckoutIntentsOkHttpClient;
// Configures using the `checkoutintents.apiKey` and `checkoutintents.baseUrl` system properties// Or configures using the `CHECKOUT_INTENTS_API_KEY` and `CHECKOUT_INTENTS_BASE_URL` environment variablesCheckoutIntentsClientclient = CheckoutIntentsOkHttpClient.fromEnv();

Or manually:

importcom.rye.client.CheckoutIntentsClient;
importcom.rye.client.okhttp.CheckoutIntentsOkHttpClient;
CheckoutIntentsClientclient = CheckoutIntentsOkHttpClient.builder()
.apiKey("My API Key")
.build();

Or using a combination of the two approaches:

importcom.rye.client.CheckoutIntentsClient;
importcom.rye.client.okhttp.CheckoutIntentsOkHttpClient;
CheckoutIntentsClientclient = CheckoutIntentsOkHttpClient.builder()
// Configures using the `checkoutintents.apiKey` and `checkoutintents.baseUrl` system properties// Or configures using the `CHECKOUT_INTENTS_API_KEY` and `CHECKOUT_INTENTS_BASE_URL` environment variables
.fromEnv()
.apiKey("My API Key")
.build();

See this table for the available options:

SetterSystem propertyEnvironment variableRequiredDefault value
apiKeycheckoutintents.apiKeyCHECKOUT_INTENTS_API_KEYtrue-
baseUrlcheckoutintents.baseUrlCHECKOUT_INTENTS_BASE_URLtrue"https://staging.api.rye.com"

System properties take precedence over environment variables.

Tip

Don't create more than one client in the same application. Each client has a connection pool and thread pools, which are more efficient to share between requests.

Modifying configuration

To temporarily use a modified client configuration, while reusing the same connection and thread pools, call withOptions() on any client or service:

importcom.rye.client.CheckoutIntentsClient;
CheckoutIntentsClientclientWithOptions = client.withOptions(optionsBuilder -> {
optionsBuilder.baseUrl("https://example.com");
optionsBuilder.maxRetries(42);
});

The withOptions() method does not affect the original client or service.

Requests and responses

To send a request to the Checkout Intents API, build an instance of some Params class and pass it to the corresponding client method. When the response is received, it will be deserialized into an instance of a Java class.

For example, client.checkoutIntents().purchase(...) should be called with an instance of CheckoutIntentPurchaseParams, and it will return an instance of CheckoutIntent.

Immutability

Each class in the SDK has an associated builder or factory method for constructing it.

Each class is immutable once constructed. If the class has an associated builder, then it has a toBuilder() method, which can be used to convert it back to a builder for making a modified copy.

Because each class is immutable, builder modification will never affect already built class instances.

Asynchronous execution

The default client is synchronous. To switch to asynchronous execution, call the async() method:

importcom.rye.client.CheckoutIntentsClient;
importcom.rye.client.okhttp.CheckoutIntentsOkHttpClient;
importcom.rye.models.checkoutintents.Buyer;
importcom.rye.models.checkoutintents.CheckoutIntent;
importcom.rye.models.checkoutintents.CheckoutIntentPurchaseParams;
importcom.rye.models.checkoutintents.PaymentMethod;
importjava.util.concurrent.CompletableFuture;
// Configures using the `checkoutintents.apiKey` and `checkoutintents.baseUrl` system properties// Or configures using the `CHECKOUT_INTENTS_API_KEY` and `CHECKOUT_INTENTS_BASE_URL` environment variablesCheckoutIntentsClientclient = CheckoutIntentsOkHttpClient.fromEnv();
CheckoutIntentPurchaseParamsparams = CheckoutIntentPurchaseParams.builder()
.buyer(Buyer.builder()
.address1("123 Main St")
.city("New York")
.country("US")
.email("john.doe@example.com")
.firstName("John")
.lastName("Doe")
.phone("1234567890")
.postalCode("10001")
.province("NY")
.build())
.paymentMethod(PaymentMethod.StripeTokenPaymentMethod.builder()
.stripeToken("tok_1RkrWWHGDlstla3f1Fc7ZrhH")
.type(PaymentMethod.StripeTokenPaymentMethod.Type.STRIPE_TOKEN)
.build())
.productUrl("https://rye-protocol.myshopify.com/products/rye-sticker")
.quantity(1)
.build();
CompletableFuture<CheckoutIntent> checkoutIntent = client.async().checkoutIntents().purchase(params);

Or create an asynchronous client from the beginning:

importcom.rye.client.CheckoutIntentsClientAsync;
importcom.rye.client.okhttp.CheckoutIntentsOkHttpClientAsync;
importcom.rye.models.checkoutintents.Buyer;
importcom.rye.models.checkoutintents.CheckoutIntent;
importcom.rye.models.checkoutintents.CheckoutIntentPurchaseParams;
importcom.rye.models.checkoutintents.PaymentMethod;
importjava.util.concurrent.CompletableFuture;
// Configures using the `checkoutintents.apiKey` and `checkoutintents.baseUrl` system properties// Or configures using the `CHECKOUT_INTENTS_API_KEY` and `CHECKOUT_INTENTS_BASE_URL` environment variablesCheckoutIntentsClientAsyncclient = CheckoutIntentsOkHttpClientAsync.fromEnv();
CheckoutIntentPurchaseParamsparams = CheckoutIntentPurchaseParams.builder()
.buyer(Buyer.builder()
.address1("123 Main St")
.city("New York")
.country("US")
.email("john.doe@example.com")
.firstName("John")
.lastName("Doe")
.phone("1234567890")
.postalCode("10001")
.province("NY")
.build())
.paymentMethod(PaymentMethod.StripeTokenPaymentMethod.builder()
.stripeToken("tok_1RkrWWHGDlstla3f1Fc7ZrhH")
.type(PaymentMethod.StripeTokenPaymentMethod.Type.STRIPE_TOKEN)
.build())
.productUrl("https://rye-protocol.myshopify.com/products/rye-sticker")
.quantity(1)
.build();
CompletableFuture<CheckoutIntent> checkoutIntent = client.checkoutIntents().purchase(params);

The asynchronous client supports the same options as the synchronous one, except most methods return CompletableFutures.

Polling helpers

This SDK includes helper methods for the asynchronous checkout flow. The recommended pattern follows Rye's two-phase checkout:

importcom.rye.client.CheckoutIntentsClient;
importcom.rye.client.okhttp.CheckoutIntentsOkHttpClient;
importcom.rye.models.checkoutintents.Buyer;
importcom.rye.models.checkoutintents.CheckoutIntent;
importcom.rye.models.checkoutintents.CheckoutIntentCreateParams;
importcom.rye.models.checkoutintents.CheckoutIntentConfirmParams;
importcom.rye.models.checkoutintents.PaymentMethod;
CheckoutIntentsClientclient = CheckoutIntentsOkHttpClient.fromEnv();
// Phase 1: Create and wait for offerCheckoutIntentCreateParamscreateParams = CheckoutIntentCreateParams.builder()
.buyer(Buyer.builder()
.address1("123 Main St")
.city("New York")
.country("US")
.email("john.doe@example.com")
.firstName("John")
.lastName("Doe")
.phone("1234567890")
.postalCode("10001")
.province("NY")
.build())
.productUrl("https://example.com/product")
.quantity(1)
.build();
CheckoutIntentintent = client.checkoutIntents().createAndPoll(createParams);
// Handle resultif (intent.isFailed()) {
System.out.println("Failed: " + intent.asFailed().failureReason());
} elseif (intent.isAwaitingConfirmation()) {
// Review pricing with userSystem.out.println("Total: " + intent.asAwaitingConfirmation().offer().total());
// Phase 2: Confirm and wait for completionCheckoutIntentConfirmParamsconfirmParams = CheckoutIntentConfirmParams.builder()
.paymentMethod(PaymentMethod.StripeTokenPaymentMethod.builder()
.stripeToken("tok_visa")
.type(PaymentMethod.StripeTokenPaymentMethod.Type.STRIPE_TOKEN)
.build())
.build();
CheckoutIntentcompleted = client.checkoutIntents()
.confirmAndPoll(intent.asAwaitingConfirmation().id(), confirmParams);
if (completed.isCompleted()) {
System.out.println("Order completed!");
} elseif (completed.isFailed()) {
System.out.println("Order failed: " + completed.asFailed().failureReason());
} else {
thrownewIllegalStateException("Unexpected state: " + completed);
}
} else {
thrownewIllegalStateException("Unexpected state: " + intent);
}

Available polling methods:

  • createAndPoll() - Create and poll until offer is ready (awaiting_confirmation or failed)
  • confirmAndPoll() - Confirm and poll until completion (completed or failed)
  • pollUntilCompleted() - Poll until completed or failed
  • pollUntilAwaitingConfirmation() - Poll until offer is ready or failed

All polling methods support customizable timeouts via PollOptions:

importcom.rye.models.checkoutintents.PollOptions;
importjava.time.Duration;
// Configure polling behaviorPollOptionsoptions = PollOptions.builder()
.pollInterval(Duration.ofSeconds(5)) // Poll every 5 seconds (default)
.maxAttempts(120) // Try up to 120 times, ~10 minutes (default)
.build();
CheckoutIntentintent = client.checkoutIntents().pollUntilCompleted(intentId, options);

Handling polling timeouts

When polling operations exceed maxAttempts, a PollTimeoutException is thrown with helpful context:

importcom.rye.errors.PollTimeoutException;
importcom.rye.models.checkoutintents.PollOptions;
PollOptionsoptions = PollOptions.builder()
.pollInterval(Duration.ofSeconds(5))
.maxAttempts(60)
.build();
try {
CheckoutIntentintent = client.checkoutIntents().pollUntilCompleted(intentId, options);
} catch (PollTimeoutExceptione) {
System.out.println("Polling timed out for intent: " + e.getIntentId());
System.out.println("Attempted " + e.getAttempts() + " times over " +
(e.getAttempts() * e.getPollIntervalMs() / 1000) + "s");
// You can retrieve the current state manuallyCheckoutIntentcurrentIntent = client.checkoutIntents().retrieve(e.getIntentId());
System.out.println("Current state: " + currentIntent);
}

Async polling

The asynchronous client also supports polling methods that return CompletableFuture:

importcom.rye.client.CheckoutIntentsClientAsync;
importcom.rye.client.okhttp.CheckoutIntentsOkHttpClientAsync;
importjava.util.concurrent.CompletableFuture;
CheckoutIntentsClientAsyncclient = CheckoutIntentsOkHttpClientAsync.fromEnv();
CompletableFuture<CheckoutIntent> intentFuture = client.checkoutIntents()
.createAndPoll(createParams);
intentFuture.thenAccept(intent -> {
if (intent.isAwaitingConfirmation()) {
System.out.println("Offer ready: " + intent.asAwaitingConfirmation().offer().total());
}
});

Webhook verification

To verify webhook signatures and parse events, use client.events().unwrap(). This method verifies the HMAC-SHA256 signature and parses the JSON payload, throwing WebhookSignatureVerificationException if verification fails.

Webhook events are thin—they contain a reference to the source object, not the full data. Use source().id() to fetch the complete object:

importcom.rye.client.CheckoutIntentsClient;
importcom.rye.client.okhttp.CheckoutIntentsOkHttpClient;
importcom.rye.models.checkoutintents.CheckoutIntent;
importcom.rye.models.events.Event;
importcom.rye.models.events.WebhookSignatureVerificationException;
importcom.rye.models.shipments.Shipment;
importjakarta.ws.rs.HeaderParam;
importjakarta.ws.rs.POST;
importjakarta.ws.rs.Path;
importjakarta.ws.rs.core.Response;
importorg.eclipse.microprofile.config.inject.ConfigProperty;
@Path("/webhook")
publicclassWebhookResource {
privatefinalCheckoutIntentsClientclient = CheckoutIntentsOkHttpClient.fromEnv();
@ConfigProperty(name = "rye.hmac.secret")
StringwebhookSecret;
@POSTpublicResponsehandleWebhook(
byte[] body,
@HeaderParam("x-rye-signature") Stringsignature) {
Eventevent;
try {
event = client.events().unwrap(body, signature, webhookSecret);
} catch (WebhookSignatureVerificationExceptione) {
returnResponse.status(401).build();
}
StringsourceId = event.source().id();
switch (event.type().known()) {
caseCHECKOUT_INTENT_COMPLETED -> {
CheckoutIntentintent = client.checkoutIntents().retrieve(sourceId);
System.out.println("Order completed: " + intent.asCompleted().orderIds());
}
caseSHIPMENT_UPDATED -> {
Shipmentshipment = client.shipments().retrieve(sourceId);
System.out.println("Shipment status: " + shipment.status());
}
}
returnResponse.ok().build();
}
}

Raw responses

The SDK defines methods that deserialize responses into instances of Java classes. However, these methods don't provide access to the response headers, status code, or the raw response body.

To access this data, prefix any HTTP method call on a client or service with withRawResponse():

importcom.rye.core.http.Headers;
importcom.rye.core.http.HttpResponseFor;
importcom.rye.models.checkoutintents.Buyer;
importcom.rye.models.checkoutintents.CheckoutIntent;
importcom.rye.models.checkoutintents.CheckoutIntentCreateParams;
CheckoutIntentCreateParamsparams = CheckoutIntentCreateParams.builder()
.buyer(Buyer.builder()
.address1("123 Main St")
.city("New York")
.country("US")
.email("john.doe@example.com")
.firstName("John")
.lastName("Doe")
.phone("1234567890")
.postalCode("10001")
.province("NY")
.build())
.productUrl("https://rye-protocol.myshopify.com/products/rye-sticker")
.quantity(1)
.build();
HttpResponseFor<CheckoutIntent> checkoutIntent = client.checkoutIntents().withRawResponse().create(params);
intstatusCode = checkoutIntent.statusCode();
Headersheaders = checkoutIntent.headers();

You can still deserialize the response into an instance of a Java class if needed:

importcom.rye.models.checkoutintents.CheckoutIntent;
CheckoutIntentparsedCheckoutIntent = checkoutIntent.parse();

Error handling

The SDK throws custom unchecked exception types:

Pagination

The SDK defines methods that return a paginated lists of results. It provides convenient ways to access the results either one page at a time or item-by-item across all pages.

Auto-pagination

To iterate through all results across all pages, use the autoPager() method, which automatically fetches more pages as needed.

When using the synchronous client, the method returns an Iterable

importcom.rye.models.checkoutintents.CheckoutIntent;
importcom.rye.models.checkoutintents.CheckoutIntentListPage;
CheckoutIntentListPagepage = client.checkoutIntents().list();
// Process as an Iterablefor (CheckoutIntentcheckoutIntent : page.autoPager()) {
System.out.println(checkoutIntent);
}
// Process as a Streampage.autoPager()
.stream()
.limit(50)
.forEach(checkoutIntent -> System.out.println(checkoutIntent));

When using the asynchronous client, the method returns an AsyncStreamResponse:

importcom.rye.core.http.AsyncStreamResponse;
importcom.rye.models.checkoutintents.CheckoutIntent;
importcom.rye.models.checkoutintents.CheckoutIntentListPageAsync;
importjava.util.Optional;
importjava.util.concurrent.CompletableFuture;
CompletableFuture<CheckoutIntentListPageAsync> pageFuture = client.async().checkoutIntents().list();
pageFuture.thenRun(page -> page.autoPager().subscribe(checkoutIntent -> {
System.out.println(checkoutIntent);
}));
// If you need to handle errors or completion of the streampageFuture.thenRun(page -> page.autoPager().subscribe(newAsyncStreamResponse.Handler<>() {
@OverridepublicvoidonNext(CheckoutIntentcheckoutIntent) {
System.out.println(checkoutIntent);
}
@OverridepublicvoidonComplete(Optional<Throwable> error) {
if (error.isPresent()) {
System.out.println("Something went wrong!");
thrownewRuntimeException(error.get());
} else {
System.out.println("No more!");
}
}
}));
// Or use futurespageFuture.thenRun(page -> page.autoPager()
.subscribe(checkoutIntent -> {
System.out.println(checkoutIntent);
})
.onCompleteFuture()
.whenComplete((unused, error) -> {
if (error != null) {
System.out.println("Something went wrong!");
thrownewRuntimeException(error);
} else {
System.out.println("No more!");
}
}));

Manual pagination

To access individual page items and manually request the next page, use the items(), hasNextPage(), and nextPage() methods:

importcom.rye.models.checkoutintents.CheckoutIntent;
importcom.rye.models.checkoutintents.CheckoutIntentListPage;
CheckoutIntentListPagepage = client.checkoutIntents().list();
while (true) {
for (CheckoutIntentcheckoutIntent : page.items()) {
System.out.println(checkoutIntent);
}
if (!page.hasNextPage()) {
break;
}
page = page.nextPage();
}

Logging

Enable logging by setting the CHECKOUT_INTENTS_LOG environment variable to info:

export CHECKOUT_INTENTS_LOG=info

Or to debug for more verbose logging:

export CHECKOUT_INTENTS_LOG=debug

Or configure the client manually using the logLevel method:

importcom.rye.client.CheckoutIntentsClient;
importcom.rye.client.okhttp.CheckoutIntentsOkHttpClient;
importcom.rye.core.LogLevel;
CheckoutIntentsClientclient = CheckoutIntentsOkHttpClient.builder()
.fromEnv()
.logLevel(LogLevel.INFO)
.build();

ProGuard and R8

Although the SDK uses reflection, it is still usable with ProGuard and R8 because checkout-intents-core is published with a configuration file containing keep rules.

ProGuard and R8 should automatically detect and use the published rules, but you can also manually copy the keep rules if necessary.

Jackson

The SDK depends on Jackson for JSON serialization/deserialization. It is compatible with version 2.13.4 or higher, but depends on version 2.18.2 by default.

The SDK throws an exception if it detects an incompatible Jackson version at runtime (e.g. if the default version was overridden in your Maven or Gradle config).

If the SDK threw an exception, but you're certain the version is compatible, then disable the version check using the checkJacksonVersionCompatibility on CheckoutIntentsOkHttpClient or CheckoutIntentsOkHttpClientAsync.

Caution

We make no guarantee that the SDK works correctly when the Jackson version check is disabled.

Also note that there are bugs in older Jackson versions that can affect the SDK. We don't work around all Jackson bugs (example) and expect users to upgrade Jackson for those instead.

Network options

Retries

The SDK automatically retries 2 times by default, with a short exponential backoff between requests.

Only the following error types are retried:

  • Connection errors (for example, due to a network connectivity problem)
  • 408 Request Timeout
  • 409 Conflict
  • 429 Rate Limit
  • 5xx Internal

The API may also explicitly instruct the SDK to retry or not retry a request.

To set a custom number of retries, configure the client using the maxRetries method:

importcom.rye.client.CheckoutIntentsClient;
importcom.rye.client.okhttp.CheckoutIntentsOkHttpClient;
CheckoutIntentsClientclient = CheckoutIntentsOkHttpClient.builder()
.fromEnv()
.maxRetries(4)
.build();

Timeouts

Requests time out after 1 minute by default.

To set a custom timeout, configure the method call using the timeout method:

importcom.rye.models.checkoutintents.CheckoutIntent;
CheckoutIntentcheckoutIntent = client.checkoutIntents().create(
params, RequestOptions.builder().timeout(Duration.ofSeconds(30)).build()
);

Or configure the default for all method calls at the client level:

importcom.rye.client.CheckoutIntentsClient;
importcom.rye.client.okhttp.CheckoutIntentsOkHttpClient;
importjava.time.Duration;
CheckoutIntentsClientclient = CheckoutIntentsOkHttpClient.builder()
.fromEnv()
.timeout(Duration.ofSeconds(30))
.build();

Proxies

To route requests through a proxy, configure the client using the proxy method:

importcom.rye.client.CheckoutIntentsClient;
importcom.rye.client.okhttp.CheckoutIntentsOkHttpClient;
importjava.net.InetSocketAddress;
importjava.net.Proxy;
CheckoutIntentsClientclient = CheckoutIntentsOkHttpClient.builder()
.fromEnv()
.proxy(newProxy(
Proxy.Type.HTTP, newInetSocketAddress(
"https://example.com", 8080
)
))
.build();

If the proxy responds with 407 Proxy Authentication Required, supply credentials by also configuring proxyAuthenticator:

importcom.rye.client.CheckoutIntentsClient;
importcom.rye.client.okhttp.CheckoutIntentsOkHttpClient;
importcom.rye.core.http.ProxyAuthenticator;
CheckoutIntentsClientclient = CheckoutIntentsOkHttpClient.builder()
.fromEnv()
.proxy(...)
// Or a custom implementation of `ProxyAuthenticator`.
.proxyAuthenticator(ProxyAuthenticator.basic("username", "password"))
.build();

Connection pooling

To customize the underlying OkHttp connection pool, configure the client using the maxIdleConnections and keepAliveDuration methods:

importcom.rye.client.CheckoutIntentsClient;
importcom.rye.client.okhttp.CheckoutIntentsOkHttpClient;
importjava.time.Duration;
CheckoutIntentsClientclient = CheckoutIntentsOkHttpClient.builder()
.fromEnv()
// If `maxIdleConnections` is set, then `keepAliveDuration` must be set, and vice versa.
.maxIdleConnections(10)
.keepAliveDuration(Duration.ofMinutes(2))
.build();

If both options are unset, OkHttp's default connection pool settings are used.

HTTPS

Note

Most applications should not call these methods, and instead use the system defaults. The defaults include special optimizations that can be lost if the implementations are modified.

To configure how HTTPS connections are secured, configure the client using the sslSocketFactory, trustManager, and hostnameVerifier methods:

importcom.rye.client.CheckoutIntentsClient;
importcom.rye.client.okhttp.CheckoutIntentsOkHttpClient;
CheckoutIntentsClientclient = CheckoutIntentsOkHttpClient.builder()
.fromEnv()
// If `sslSocketFactory` is set, then `trustManager` must be set, and vice versa.
.sslSocketFactory(yourSSLSocketFactory)
.trustManager(yourTrustManager)
.hostnameVerifier(yourHostnameVerifier)
.build();

Environments

The SDK sends requests to the staging by default. To send requests to a different environment, configure the client like so:

importcom.rye.client.CheckoutIntentsClient;
importcom.rye.client.okhttp.CheckoutIntentsOkHttpClient;
CheckoutIntentsClientclient = CheckoutIntentsOkHttpClient.builder()
.fromEnv()
.production()
.build();

Custom HTTP client

The SDK consists of three artifacts:

This structure allows replacing the SDK's default HTTP client without pulling in unnecessary dependencies.

Customized OkHttpClient

Tip

Try the available network options before replacing the default client.

To use a customized OkHttpClient:

  1. Replace your checkout-intents dependency with checkout-intents-core
  2. Copy checkout-intents-client-okhttp's OkHttpClient class into your code and customize it
  3. Construct CheckoutIntentsClientImpl or CheckoutIntentsClientAsyncImpl, similarly to CheckoutIntentsOkHttpClient or CheckoutIntentsOkHttpClientAsync, using your customized client

Completely custom HTTP client

To use a completely custom HTTP client:

  1. Replace your checkout-intents dependency with checkout-intents-core
  2. Write a class that implements the HttpClient interface
  3. Construct CheckoutIntentsClientImpl or CheckoutIntentsClientAsyncImpl, similarly to CheckoutIntentsOkHttpClient or CheckoutIntentsOkHttpClientAsync, using your new client class

Undocumented API functionality

The SDK is typed for convenient usage of the documented API. However, it also supports working with undocumented or not yet supported parts of the API.

Parameters

To set undocumented parameters, call the putAdditionalHeader, putAdditionalQueryParam, or putAdditionalBodyProperty methods on any Params class:

importcom.rye.core.JsonValue;
importcom.rye.models.checkoutintents.CheckoutIntentPurchaseParams;
CheckoutIntentPurchaseParamsparams = CheckoutIntentPurchaseParams.builder()
.putAdditionalHeader("Secret-Header", "42")
.putAdditionalQueryParam("secret_query_param", "42")
.putAdditionalBodyProperty("secretProperty", JsonValue.from("42"))
.build();

These can be accessed on the built object later using the _additionalHeaders(), _additionalQueryParams(), and _additionalBodyProperties() methods.

To set undocumented parameters on nested headers, query params, or body classes, call the putAdditionalProperty method on the nested class:

importcom.rye.core.JsonValue;
importcom.rye.models.checkoutintents.Buyer;
importcom.rye.models.checkoutintents.CheckoutIntentPurchaseParams;
CheckoutIntentPurchaseParamsparams = CheckoutIntentPurchaseParams.builder()
.buyer(Buyer.builder()
.putAdditionalProperty("secretProperty", JsonValue.from("42"))
.build())
.build();

These properties can be accessed on the nested built object later using the _additionalProperties() method.

To set a documented parameter or property to an undocumented or not yet supported value, pass a JsonValue object to its setter:

importcom.rye.core.JsonValue;
importcom.rye.models.checkoutintents.CheckoutIntentPurchaseParams;
importcom.rye.models.checkoutintents.PaymentMethod;
CheckoutIntentPurchaseParamsparams = CheckoutIntentPurchaseParams.builder()
.buyer(JsonValue.from(42))
.paymentMethod(PaymentMethod.StripeTokenPaymentMethod.builder()
.stripeToken("tok_1RkrWWHGDlstla3f1Fc7ZrhH")
.type(PaymentMethod.StripeTokenPaymentMethod.Type.STRIPE_TOKEN)
.build())
.productUrl("https://rye-protocol.myshopify.com/products/rye-sticker")
.quantity(1)
.build();

The most straightforward way to create a JsonValue is using its from(...) method:

importcom.rye.core.JsonValue;
importjava.util.List;
importjava.util.Map;
// Create primitive JSON valuesJsonValuenullValue = JsonValue.from(null);
JsonValuebooleanValue = JsonValue.from(true);
JsonValuenumberValue = JsonValue.from(42);
JsonValuestringValue = JsonValue.from("Hello World!");
// Create a JSON array value equivalent to `["Hello", "World"]`JsonValuearrayValue = JsonValue.from(List.of(
"Hello", "World"
));
// Create a JSON object value equivalent to `{ "a": 1, "b": 2 }`JsonValueobjectValue = JsonValue.from(Map.of(
"a", 1,
"b", 2
));
// Create an arbitrarily nested JSON equivalent to:// {// "a": [1, 2],// "b": [3, 4]// }JsonValuecomplexValue = JsonValue.from(Map.of(
"a", List.of(
1, 2
),
"b", List.of(
3, 4
)
));

Normally a Builder class's build method will throw IllegalStateException if any required parameter or property is unset.

To forcibly omit a required parameter or property, pass JsonMissing:

importcom.rye.core.JsonMissing;
importcom.rye.models.checkoutintents.CheckoutIntentPurchaseParams;
importcom.rye.models.checkoutintents.PaymentMethod;
CheckoutIntentPurchaseParamsparams = CheckoutIntentPurchaseParams.builder()
.paymentMethod(PaymentMethod.StripeTokenPaymentMethod.builder()
.stripeToken("tok_1RkrWWHGDlstla3f1Fc7ZrhH")
.type(PaymentMethod.StripeTokenPaymentMethod.Type.STRIPE_TOKEN)
.build())
.productUrl("https://www.amazon.com/dp/B0DFC9MT8Q")
.quantity(1)
.buyer(JsonMissing.of())
.build();

Response properties

To access undocumented response properties, call the _additionalProperties() method:

importcom.rye.core.JsonValue;
importjava.util.Map;
Map<String, JsonValue> additionalProperties = client.checkoutIntents().retrieveOrder(params)._additionalProperties();
JsonValuesecretPropertyValue = additionalProperties.get("secretProperty");
Stringresult = secretPropertyValue.accept(newJsonValue.Visitor<>() {
@OverridepublicStringvisitNull() {
return"It's null!";
}
@OverridepublicStringvisitBoolean(booleanvalue) {
return"It's a boolean!";
}
@OverridepublicStringvisitNumber(Numbervalue) {
return"It's a number!";
}
// Other methods include `visitMissing`, `visitString`, `visitArray`, and `visitObject`// The default implementation of each unimplemented method delegates to `visitDefault`, which throws by default, but can also be overridden
});

To access a property's raw JSON value, which may be undocumented, call its _ prefixed method:

importcom.rye.core.JsonField;
importjava.util.Optional;
JsonField<Object> field = client.checkoutIntents().retrieveOrder(params)._field();
if (field.isMissing()) {
// The property is absent from the JSON response
} elseif (field.isNull()) {
// The property was set to literal null
} else {
// Check if value was provided as a string// Other methods include `asNumber()`, `asBoolean()`, etc.Optional<String> jsonString = field.asString();
// Try to deserialize into a custom typeMyClassmyObject = field.asUnknown().orElseThrow().convert(MyClass.class);
}

Response validation

In rare cases, the API may return a response that doesn't match the expected type. For example, the SDK may expect a property to contain a String, but the API could return something else.

By default, the SDK will not throw an exception in this case. It will throw CheckoutIntentsInvalidDataException only if you directly access the property.

Validating the response is not forwards compatible with new types from the API for existing fields.

If you would still prefer to check that the response is completely well-typed upfront, then either call validate():

importcom.rye.models.orders.Order;
Orderorder = client.checkoutIntents().retrieveOrder(params).validate();

Or configure the method call to validate the response using the responseValidation method:

importcom.rye.models.checkoutintents.CheckoutIntent;
CheckoutIntentcheckoutIntent = client.checkoutIntents().purchase(
params, RequestOptions.builder().responseValidation(true).build()
);

Or configure the default for all method calls at the client level:

importcom.rye.client.CheckoutIntentsClient;
importcom.rye.client.okhttp.CheckoutIntentsOkHttpClient;
CheckoutIntentsClientclient = CheckoutIntentsOkHttpClient.builder()
.fromEnv()
.responseValidation(true)
.build();

FAQ

Why don't you use plain enum classes?

Java enum classes are not trivially forwards compatible. Using them in the SDK could cause runtime exceptions if the API is updated to respond with a new enum value.

Why do you represent fields using JsonField<T> instead of just plain T?

Using JsonField<T> enables a few features:

Why don't you use data classes?

It is not backwards compatible to add new fields to a data class and we don't want to introduce a breaking change every time we add a field to a class.

Why don't you use checked exceptions?

Checked exceptions are widely considered a mistake in the Java programming language. In fact, they were omitted from Kotlin for this reason.

Checked exceptions:

  • Are verbose to handle
  • Encourage error handling at the wrong level of abstraction, where nothing can be done about the error
  • Are tedious to propagate due to the function coloring problem
  • Don't play well with lambdas (also due to the function coloring problem)

Semantic versioning

This package generally follows SemVer conventions, though certain backwards-incompatible changes may be released as minor versions:

  1. Changes to library internals which are technically public but not intended or documented for external use. (Please open a GitHub issue to let us know if you are relying on such internals.)
  2. Changes that we do not expect to impact the vast majority of users in practice.

We take backwards-compatibility seriously and work hard to ensure you can rely on a smooth upgrade experience.

We are keen for your feedback; please open an issue with questions, bugs, or suggestions.

About

Official Java library for the Rye Checkout Intents API

Resources

Security policy

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Used by

Contributors

Languages