Getting started x402 V2

The Mogami Java Client SDK makes it easy to bring x402 payments into your applications. With just a few lines of code, you can fetch requirements, sign payloads, and send transactions securely.

Here is a sample code showing how to make a payment:

final String tipUrl = "https://playground.mogami.tech/tip";
OkHttpClient okHttpClient = new OkHttpClient();

try (Response initialResponse = okHttpClient.newCall(new Request.Builder().url(tipUrl).get().build()).execute()) {
    // Extracting the payments requirements from the header
    paymentRequired = X402V2Client.extractPaymentRequired(getHeaders(initialResponse))
                                    .orElseThrow(() -> new IllegalStateException("PaymentRequired should be present"));
} catch (IOException e) {
    System.err.println("IOException during HTTP request to " + tipUrl + ": " + e.getMessage());
    System.exit(-1);
}

// We create a payment with a valid PaymentPayload
PaymentPayload payload = X402V2Client.buildPaymentPayload(
    paymentRequired,
    paymentRequired.accepts().getFirst(),
    Credentials.create(addressPrivateKey)
);

// We call the protected resource with the payment
try (Response paidResponse = okHttpClient.newCall(new Request.Builder().url(tipUrl).get()
                        .headers(Headers.of(X402V2Client.buildPaymentHeaders(payload)))
                        .build()).execute()) {

    final Optional<SettlementResponse> settlementResponse = X402V2Client.extractSettlementResponse(getHeaders(paidResponse));
    if (settlementResponse.isPresent()) {
        System.out.println("Settlement response received: " + settlementResponse.get());
    }

} catch (IOException e) {
    System.err.println("IOException during HTTP request to " + tipUrl + ": " + e.getMessage());
    System.exit(-1);
}

To use our Java client SDK in your Maven project, add:

or, in your Gradle project, add:

Last updated