package com.stylefeng.guns.modular.system.utils; import com.google.gson.Gson; import com.google.gson.JsonObject; import com.stripe.Stripe; import com.stripe.exception.CardException; import com.stripe.model.PaymentIntent; import com.stripe.param.PaymentIntentCreateParams; import spark.Response; import java.util.HashMap; import java.util.Map; import static spark.Spark.port; import static spark.Spark.post; public class Server { public static void aaa() { port(4242); Stripe.apiKey = "sk_test_4eC39HqLyjWDarjtT1zdp7dc"; post("/pay", (request, response) -> { Gson gson = new Gson(); String paymentMethod = gson.fromJson(request.body(), JsonObject.class).get("payment_method_id").getAsString(); try { PaymentIntent intent = PaymentIntent.create(PaymentIntentCreateParams.builder() .setAmount(1L) .setCurrency("usd") .setPaymentMethod(paymentMethod) // A PaymentIntent can be confirmed some time after creation, // but here we want to confirm (collect payment) immediately. .setConfirm(true) // If the payment requires any follow-up actions from the // customer, like two-factor authentication, Stripe will error // and you will need to prompt them for a new payment method. .setErrorOnRequiresAction(true) .build()); return gson.toJson(buildResponse(response, intent)); } catch (CardException e) { response.status(200); Map errorResponse = new HashMap<>(); errorResponse.put("error", e.getStripeError().getMessage()); return gson.toJson(errorResponse); } }); } private static Map buildResponse(Response response, PaymentIntent intent) { Map responseData = new HashMap<>(); if (intent.getStatus().equals("succeeded")) { // Handle post-payment fulfillment response.status(200); responseData.put("success", true); } else { // Any other status would be unexpected, so error response.status(500); responseData.put("error", "Invalid PaymentIntent status"); } return responseData; } }