public class Server {
private static final Gson gson = new Gson();
public static void main(String[] args) {
port(4242);
options("/*", (request, response) -> {
String accessControlRequestHeaders = request.headers("Access-Control-Request-Headers");
if (accessControlRequestHeaders != null) {
response.header("Access-Control-Allow-Headers", accessControlRequestHeaders);
}
String accessControlRequestMethod = request.headers("Access-Control-Request-Method");
if (accessControlRequestMethod != null) {
response.header("Access-Control-Allow-Methods", accessControlRequestMethod);
}
return "OK";
});
before((request, response) -> {
response.header("Access-Control-Allow-Origin", "*"); // Allow all origins
response.header("Access-Control-Allow-Headers", "*");
response.header("Access-Control-Allow-Methods", "GET,POST,OPTIONS");
response.header("Access-Control-Allow-Credentials", "true");
});
// Set Stripe API keys directly in the code
Stripe.apiKey = "sk_test_yHMt2Vkexample";
// Domain URL
String domainUrl = "http://localhost:4242";
get("/config", (request, response) -> {
response.type("application/json");
Map responseData = new HashMap();
responseData.put("publishableKey", "pk_test_51PccgFRo1v56iAOxEVEimciGkyyLOcjVE98T3rqOHLuvx28QNxI8sfvYN0zwSka8vLRIIIEdkOHorjb5OJUdwhIx00VRs64Seu");
responseData.put("proPrice", "price_1PfUDSRo1v56iAOxxLORAlv9");
return gson.toJson(responseData);
});
// Fetch the Checkout Session to display the JSON result on the success page
get("/checkout-session", (request, response) -> {
response.type("application/json");
String sessionId = request.queryParams("sessionId");
Session session = Session.retrieve(sessionId);
return gson.toJson(session);
});
post("/create-customer", (request, response) -> {
response.type("application/json");
Map requestData = gson.fromJson(request.body(), Map.class);
String email = (String) requestData.get("email");
String name = (String) requestData.get("name");
try {
CustomerCreateParams params = CustomerCreateParams.builder()
.setEmail(email)
.setName(name)
.build();
Customer customer = Customer.create(params);
Map responseData = new HashMap();
responseData.put("customerId", customer.getId());
responseData.put("email", customer.getEmail());
responseData.put("name", customer.getName());
return gson.toJson(responseData);
} catch (StripeException e) {
response.status(400);
Map errorData = new HashMap();
errorData.put("error", e.getMessage());
return gson.toJson(errorData);
}
});
post("/create-checkout-session", (request, response) -> {
response.type("application/json");
// Parse request body as JSON
Map requestData = gson.fromJson(request.body(), Map.class);
// Retrieve the priceId from the JSON payload
String priceId = (String) requestData.get("priceId");
// Create session parameters
SessionCreateParams params = new SessionCreateParams.Builder()
.setSuccessUrl(domainUrl + "/success.html?session_id={CHECKOUT_SESSION_ID}")
.setCancelUrl(domainUrl + "/canceled.html")
.setMode(SessionCreateParams.Mode.SUBSCRIPTION)
.addLineItem(new SessionCreateParams.LineItem.Builder()
.setQuantity(1L)
.setPrice(priceId)
.build()
)
.build();
try {
Session session = Session.create(params);
response.status(303); // HTTP 303 See Other
response.redirect(session.getUrl());
return ""; // Returning an empty string to indicate no body content
} catch (Exception e) {
Map messageData = new HashMap();
messageData.put("message", e.getMessage());
Map responseData = new HashMap();
responseData.put("error", messageData);
response.status(400);
return gson.toJson(responseData);
}
});
post("/customer-portal", (request, response) -> {
String sessionId = request.queryParams("sessionId");
// Retrieve the Checkout Session to get the customer ID
Session checkoutSession;
try {
checkoutSession = Session.retrieve(sessionId);
} catch (Exception e) {
response.status(400);
return gson.toJson(Collections.singletonMap("error", "Failed to retrieve session: " + e.getMessage()));
}
String customer = checkoutSession.getCustomer();
// Create a Billing Portal session
com.stripe.param.billingportal.SessionCreateParams params =
new com.stripe.param.billingportal.SessionCreateParams.Builder()
.setReturnUrl(domainUrl + "/account") // Redirect to your account page after managing billing
.setCustomer(customer)
.build();
com.stripe.model.billingportal.Session portalSession;
try {
portalSession = com.stripe.model.billingportal.Session.create(params);
} catch (Exception e) {
response.status(400);
return gson.toJson(Collections.singletonMap("error", "Failed to create billing portal session: " + e.getMessage()));
}
// Redirect to the billing portal
response.redirect(portalSession.getUrl(), 303);
return "";
});
post("/webhook", (request, response) -> {
String payload = request.body();
String sigHeader = request.headers("Stripe-Signature");
String endpointSecret = "your_webhook_secret"; // Replace with your actual webhook secret
Event event;
try {
event = Webhook.constructEvent(payload, sigHeader, endpointSecret);
} catch (SignatureVerificationException e) {
response.status(400);
return gson.toJson(Collections.singletonMap("error", "Invalid signature"));
}
// Handle the event
switch (event.getType()) {
case "checkout.session.completed":
// Handle successful payment
System.out.println("Checkout Session completed: " + event.getDataObjectDeserializer().getObject().toString());
response.status(200);
break;
case "invoice.payment_succeeded":
// Handle successful payment for invoices
System.out.println("Invoice payment succeeded: " + event.getDataObjectDeserializer().getObject().toString());
response.status(200);
break;
case "invoice.payment_failed":
// Handle failed payment for invoices
System.out.println("Invoice payment failed: " + event.getDataObjectDeserializer().getObject().toString());
response.status(200);
break;
case "customer.subscription.created":
// Handle subscription creation
System.out.println("Subscription created: " + event.getDataObjectDeserializer().getObject().toString());
response.status(200);
break;
case "customer.subscription.deleted":
// Handle subscription cancellation
System.out.println("Subscription canceled: " + event.getDataObjectDeserializer().getObject().toString());
response.status(200);
break;
default:
response.status(200);
System.out.println("Unhandled event type: " + event.getType());
break;
}
return "";
});
}
}
Итак, эта ошибка возникает, когда выполняется функция инициализации платежа, но полоса не принимает запрос OPTIONS из-за ограничения AWS, исходя из моего javascript, могу ли я что-нибудь сделать, чтобы предотвратить это, потому что я мое приложение работает на ПОРТЕ 8443. Я вижу, что создание клиента происходит на полосе, но не удается произвести платеж.
Map responseData = new HashMap(); responseData.put("publishableKey", "pk_test_51PccgFRo1v56iAOxEVEimciGkyyLOcjVE98T3rqOHLuvx28QNxI8sfvYN0zwSka8vLRIIIEdkOHorjb5OJUdwhIx00VRs64Seu"); responseData.put("proPrice", "price_1PfUDSRo1v56iAOxxLORAlv9");
return gson.toJson(responseData); });
// Fetch the Checkout Session to display the JSON result on the success page get("/checkout-session", (request, response) -> { response.type("application/json");
[/code] Итак, эта ошибка возникает, когда выполняется функция инициализации платежа, но полоса не принимает запрос OPTIONS из-за ограничения AWS, исходя из моего javascript, могу ли я что-нибудь сделать, чтобы предотвратить это, потому что я мое приложение работает на ПОРТЕ 8443. Я вижу, что создание клиента происходит на полосе, но не удается произвести платеж.