Mogami
  • Home
  • Roadmap & ideas
  • x402 in French
  • Java client SDK
    • Getting started
    • Example client
  • Java server SDK
    • Getting started
    • Example server
    • Configuration
  • Faciliator server
    • Getting started
    • Verifications
  • Learning X402
    • Protocol explanation
      • Get /weather without X-PAYMENT
      • Get /weather with X-PAYMENT
      • Payment verification on server
      • Payment settlement on server
    • X402 hands-on
    • Useful links
  • Contact
    • Email
    • Twitter
Powered by GitBook
On this page
  1. Java client SDK

Getting started

This guide shows you—step‑by‑step—how to satisfy an HTTP 402 Payment Required challenge using X402PaymentHelper.

Here is a test code showing how we are using it:

// 1️⃣  Issue the initial request. The server responds with HTTP 402 + JSON body.
MvcResult result = mockMvc.perform(get("/weather"))
        .andExpect(status().isPaymentRequired())
        .andReturn();

// 1️⃣  Parse the JSON body into a PaymentRequired object.
var paymentRequired = X402PaymentHelper.getPaymentRequiredFromBody(
        result.getResponse().getContentAsString())
    .orElseThrow(() -> new IllegalStateException("Payment requirements not found"));

// 2️⃣  Create an *unsigned* PaymentPayload from the first accepted option.
var unsignedPayload = X402PaymentHelper.getPayloadFromPaymentRequirements(
        null,                               // signature will be added later
        TEST_CLIENT_WALLET_ADDRESS_1,       // payer's EOA address (0x…)
        paymentRequired.accepts().getFirst());

// 3️⃣  Sign the payload with the private key (EIP‑712 compliant).
var signedPayload = X402PaymentHelper.getSignedPayload(
        Credentials.create(TEST_CLIENT_WALLET_ADDRESS_1_PRIVATE_KEY),
        paymentRequired.accepts().getFirst(),
        unsignedPayload);

// 4️⃣  Encode the signed payload → Base64 → X‑Payment header & retry.
mockMvc.perform(get("/weather")
                .header(X402_X_PAYMENT_HEADER,
                        X402PaymentHelper.getPayloadHeader(signedPayload)))
       .andExpect(status().isOk());

To use it in your Maven project :

<dependency>
        <groupId>tech.mogami.spring</groupId>
        <artifactId>mogami-x402-java-client</artifactId>
        <version>0.1.0</version>
</dependency>

and in your Gradle project:

dependencies {
    implementation 'tech.mogami.spring:mogami-x402-java-client:0.1.0'
}
Previousx402 in FrenchNextExample client

Last updated 14 days ago