Java SDK

Looking for the Card Present SDK?
Warning

This page is under construction. Some links throughout the doc could be dead links and some usage demo links might become out of date.

Get started seamlessly integrating WePay's payment solution with the Java Software Development Kit.

This guide will outline how to install, configure, and initialize the Java SDK with code demos of how to execute our most common API Requests.

See the Java SDK Reference for more information on our available methods, objects, and errors.

WePay periodically releases updates which can include new functionality, bug fixes, and security updates, check these changes out here in the Changelog.

Getting started with the Java SDK requires five steps:


Get Started

Getting started with the Java SDK requires three steps:

  1. Download Software requirements
  2. Download and Install the SDK
  3. Download and Install Third Party Dependencies

Download Software requirements

Download Java 1.8 or later

Download and Install the SDK

The prerelease versions of the WePay API include new features that are not widely released yet. If you would like to use a prerelease API version, choose the version in Partner Center and use the Prerelease SDK.

The Prerelease SDK can be downloaded below.

It is named as prerelease-WePay-Java-SDK-version.jar.
  • Copy the file inside your site directory.
  • Add prerelease-WePay-Java-SDK-version.jar as a library for your site. Depending on your project setup, this could be:
    • Adding the .jar as a library through your build management tool.
    • Adding the .jar to your classpath, eg. java -classpath path/to/prerelease-WePay-Java-SDK-version.jar.

Download and Install Third Party Dependencies

Add third party library dependencies as jar files in your project. The dependency jar files can be downloaded from these links:

If using gradle, these dependencies can be installed by adding them as dependencies in your gradle build script:

Copy
Copied
implementation "org.json:json:20090211"
implementation "org.apache.httpcomponents:httpcore:4.4.13"

Use Gradle

To install the SDK, add wepay-java-sdk to the dependencies block of your app/build.gradle file:
Copy
Copied
dependencies {
  implementation "com.wepay:wepay-java-sdk:0.0.1"
//..
}

Next, since the SDK relies on Java 1.8 or later, you'll need to specify that as your target Java version (also in build.gradle):

Copy
Copied
compileOptions {
  sourceCompatibility JavaVersion.VERSION_1_8
  targetCompatibility JavaVersion.VERSION_1_8
}

Public Release

To be updated Q321.


SDK Organization

The Java SDK contains several packages:

  • com.wepay.exception: Defines exceptions that could be thrown by the APIs. See Handle Errors.
  • com.wepay.endpoints: Functions that are the entry points for making API calls.
  • com.wepay.model.*: These packages contains POJO classes that represent objects used in the WePay API.
    • com.wepay.model.resource: Represent a WePay resource (which is what's returned by most API requests).
    • com.wepay.model.collection: Represent a collection of WePay resources (returned by find() requests).
    • com.wepay.model.request_params: The body of an API request.
    • com.wepay.model.additional_params: Additional data for an API request, such as headers.
    • com.wepay.model.data: Nested objects in the request or response.
    • com.wepay.model.enum: Enumeration values.
  • com.wepay.network: Used internally by the SDK.

Configure the SDK

The SDK must be configured with your app's credentials before it can be used. You can find these in the Partner Center under the Development tab.

Use the table below to determine which testing environment your app will use. The environment inputs are case-sensitive.

Base URLEnvironment
https://stage-api.wepay.comSTAGE
https://api.wepay.comPRODUCTION
Copy
Copied
import com.wepay.network.Configuration;
import com.wepay.network.WePayRequest;

    Configuration configuration = new Configuration();
    configuration.setAppId("<YOUR APP ID>");
    configuration.setAppToken("<YOUR APP TOKEN>");
    configuration.setEnvironment(Configuration.Environment.STAGE);
    WePayRequest.initializeRequest();

Make API Requests

API requests can be made to WePay using the classes under com.wepay.endpoints.*. Each class corresponds to an API resource, and each function corresponds to an operation on that resource.The mapping between SDK methods and API calls is useful for referencing the API Reference and Guides and understanding the structure of the SDK.

The SDK methods are grouped under each top-level API resource. For example, this is the mapping for Accounts:

The input parameters are derived from the WePay API Reference. Each field in the schema has a corresponding field in the SDK.

Handle Errors

All API request methods can throw these exceptions within the SDK:

SDK ErrorDescription
IOExceptionThe SDK failed to establish valid connection to WePay servers.
JSONExceptionThe SDK failed to get a valid JSON response.
WePayExceptionWePay returned an error response.
UnknownWePayExceptionAn unknown exception occurred.
The API request methods have a long list of exceptions in the function signature. All of them (besides IOException and JSONException) are subclasses of WePayException. The exceptions here correspond to the errors described in our Errors Guide.

You have several options for handling API errors.

Handle the relevant WePay errors

This option allows your application to have special handling for any errors it cares about, while handling the rest as generic errors.

Copy
Copied
try {
    AccountsRequestParamData accountsRequestParamData = new AccountsRequestParamData();
    AccountsFindRespData findResult = AccountsApi.find(accountsRequestParamData);
}
catch (InvalidParams e) {
    LOGGER.info("handling invalid params error");
    LOGGER.info(e.getMessage());
}
catch (WePayException e) {
    LOGGER.info("handling any other WePay errors");
}
catch (IOException | JSONException e) {
    LOGGER.info("failed to send the request");
}

Handle every type of error

This option is the most tedious, but it has the benefit of having a strict compile-time check that all exceptions have been caught.

Copy
Copied
try {
    AccountsRequestParamData accountsRequestParamData = new AccountsRequestParamData();
    AccountsFindRespData findResult = AccountsApi.find(accountsRequestParamData);
}
catch (InvalidParams | NotAuthorized e) {
    LOGGER.info("handling some known WePay errors");
}
catch (ThrottleExceeded e) {
    LOGGER.info("handling throttle exceeded");
}
catch (UnknownWePayException | UnexpectedError | ServiceTemporarilyUnavailable | JSONException | IOException e) {
    LOGGER.info("handling non-actionable errors");
}

Handle errors based on the error code

The type of error can also be determined by the exception's error code.

Copy
Copied
try {
    AccountsRequestParamData accountsRequestParamData = new AccountsRequestParamData();
    AccountsFindRespData findResult = AccountsApi.find(accountsRequestParamData);
}
catch (WePayException e) {
    switch (e.getErrorCode() {
        case InvalidParams.ERROR_CODE: break;
        case NotAuthorized.ERROR_CODE: break;
    }
}
catch (IOException | JSONException e) {
    LOGGER.info("failed to send the request");
}

Use Auto Pagination

The find() method request returns a fixed-size page, which may not fetch all results in your query. Instead of manually asking for the next page to get all results, the autoPagingIterable makes this simpler by fetching large lists of resources:
Copy
Copied
    AccountsRequestParamData requestParamData = new AccountsRequestParamData();
    requestParamData.setPageSize(50);
    AccountsFindRespData accounts = AccountsApi.find(new AccountsRequestParamData());
    for (Account account: accounts.autoPagingIterable()) {
        // Do something with `account`
    }

Implement Idempotency

By default, the sdk requests are configured to retry on retry-able error responses as described in detail in our Design a Retry Strategy cookbook. The default retry policy comes with exponential backoff, a deadline of 24 hours and 30 retry attempts maximum. Retries will be attempted only if the Unique-Key header is provided in the original request.

Configure retry policy

Partners can disable retry by configuring the WePayHttpClient with the NO_RETRY policy:
Copy
Copied
WePayRequest.setHttpClient(
    WePayHttpClient.builder().retryPolicy(PredefinedRetryPolicies.NO_RETRY)
    .build()
);
Create your own retry policy with customized BackoffStrategy and RetryCondition.

The default retry condition checks multiple conditions in the following order:

  • If the Unique-Key header is not present;
  • If the retry deadline is past;
  • If the max number of retries is reached;
  • If the error is one of the retry-able errors.

Make async requests

If you are implementing a retry strategy that takes longer than 30 seconds to terminate, use the asynchronous version of methods to make requests. This helps to avoid prolonged and hanging API requests.
Synchronous Example:
Copy
Copied
Payment payment = PaymentsApi.create( paymentsCreateData, paymentsCreateAdditionalParams);
// waiting for line above to finish executing before moving on
Asynchronous Example:
Copy
Copied
CompletableFuture<Payment> paymentCompletableFuture = PaymentsApi.createAsync(
    paymentsCreateData, paymentsCreateAdditionalParams
);
// do some other stuff
Payment paymentCreateResult = paymentCompletableFuture.join();

Persistence

The SDK currently does not provide any persistence support, so partners need to implement a strategy to retrieve and continue in-retry requests in the case of an application restart.

The solution will possibly include persisting the request body and headers with its retryContext which contains the initial request time, number of attempts, etc. The restarted application can load these data and re-attempt the requests.

Clear Usage Demos

Integration GuideUse CaseCode Demo
Onboarding MerchantsCreate a Legal Entity
Create an Account
Legal Entity Demo
Account Demo <!--- need a set controller pw demo --->
Enable MerchantsGet Account Capabilities
Enable Payments
Enable Payouts
Get Account Verifications
Capabilities Demo
Payment Demo
Payment Method Demo
Verifications Demo
Payout MerchantsCreate a Payout Method
Attach a Payout Method
Remove a Payout Method
Payout Method Demo
Attach Payout Method Demo
Payout Method Demo
Respond To DisputesRespond to disputesHandle Dispute Demo
Concede Dispute Demo
<!--- need a challenge dispute demo --->
Issue RefundsIssue refundsRefunds Demo