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());