liujie
2023-05-22 9f2315d92cc93f8f431805a10ea9ce3f79fa7eb2
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
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<String, String> errorResponse = new HashMap<>();
                errorResponse.put("error", e.getStripeError().getMessage());
                return gson.toJson(errorResponse);
            }
        });
    }
 
    private static Map<String, Object> buildResponse(Response response, PaymentIntent intent) {
        Map<String, Object> 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;
    }
}