If you’d like a working example, you can obtain the example server source code by clicking or by running git clone https://github.com/mogami-tech/x402-examples.git.
Once retrieved, go inside the project directory and type:
mvn test
This will start a server with a x402 protected URL and call the integration test using the client API:
MvcResult result = mockMvc.perform(get("/weather"))
.andExpect(status().isPaymentRequired())
.andReturn();
// Retrieve the payment required from the response body.
var paymentRequired = X402PaymentHelper.getPaymentRequiredFromBody(result.getResponse().getContentAsString())
.orElseThrow(() -> new IllegalStateException("Payment requirements not found in response"));
// Generate a payment payload (without a signature) from the payment requirements.
var paymentPayload = X402PaymentHelper.getPayloadFromPaymentRequirements(
null,
TEST_CLIENT_WALLET_ADDRESS_1,
paymentRequired.accepts().getFirst());
// Sign the payment payload.
var signedPayload = X402PaymentHelper.getSignedPayload(
Credentials.create(TEST_CLIENT_WALLET_ADDRESS_1_PRIVATE_KEY),
paymentRequired.accepts().getFirst(),
paymentPayload);
mockMvc.perform(get("/weather")
.header(X402_X_PAYMENT_HEADER, X402PaymentHelper.getPayloadHeader(signedPayload)))
.andDo(print());
}