Я новичок в оплате Stripe и пытаюсь интегрировать код полосы после этого репозитория github https://github.com/stripe-samples/accept-a-card-payment/tree/master/using-webhooks. Но до сих пор каждый раз, когда я достигаю конечной точки /create-payment-intent
, я получаю 404. Образец использует платформу искры и кажется, что перехватчик искры не выполняется. Я даже не получаю журналы на моем аккаунте Stripe
import static spark.Spark.post;
import com.google.gson.Gson;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import com.stripe.Stripe;
import com.stripe.exception.SignatureVerificationException;
import com.stripe.model.Event;
import com.stripe.model.PaymentIntent;
import com.stripe.net.Webhook;
import com.stripe.param.PaymentIntentCreateParams;
import com.patrykmaryn.springbootclientrabbitmq.Server.CreatePaymentBody;
import static com.patrykmaryn.springbootclientrabbitmq.Server.calculateOrderAmount;
import static com.patrykmaryn.springbootclientrabbitmq.Server.CreatePaymentResponse;
@SpringBootApplication
@ComponentScan(basePackageClasses = MainController.class)
public class SpringbootClientRabbitmqApplication {
private static Logger logger = LoggerFactory.getLogger(SpringbootClientRabbitmqApplication.class);
@Bean
PostBean postBean() {
return new PostBean();
}
public static void main(String[] args) {
SpringApplication.run(SpringbootClientRabbitmqApplication.class, args);
Gson gson = new Gson();
Stripe.apiKey = "sk_test_XXXXXXXXXXXXXXXXX";
post("/create-payment-intent", (request, response) -> {
logger.info(" -------- ---------- create-payment-intent -> {}", request.body());
response.type("application/json");
CreatePaymentBody postBody = gson.fromJson(request.body(), CreatePaymentBody.class);
PaymentIntentCreateParams createParams = new PaymentIntentCreateParams.Builder()
.setCurrency(postBody.getCurrency()).setAmount(new Long(calculateOrderAmount(postBody.getItems())))
.build();
// Create a PaymentIntent with the order amount and currency
PaymentIntent intent = PaymentIntent.create(createParams);
// Send publishable key and PaymentIntent details to client
return gson.toJson(new CreatePaymentResponse("pk_test_XXXXXXXXXXXXXXXXXX",
intent.getClientSecret()));
});
post("/webhook", (request,response) -> {
String payload = request.body();
String sigHeader = request.headers("Stripe-Signature");
String endpointSecret = "whsec_XXXXXXXXXXXXXXXXX";
Event event = null;
try {
event = Webhook.constructEvent(payload, sigHeader, endpointSecret);
} catch (SignatureVerificationException e) {
// Invalid signature
response.status(400);
return "";
}
switch (event.getType()) {
case "payment_intent.succeeded":
// fulfill any orders, e-mail receipts, etc
//to cancel a payment you will need to issue a Refund
System.out.println("------------ Payment received");
break;
case "payment_intent.payment_failed":
break;
default:
// unexpected event type
response.status(400);
return "";
}
response.status(200);
return "";
});
}
}
скрипт. js
var stripe;
var orderData = {
items: [{ id: "photo-subscription" }],
currency: "usd"
};
// Disable the button until we have Stripe set up on the page
document.querySelector("button").disabled = true;
fetch("/create-payment-intent", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(orderData)
})
.then(function(result) {
return result.json();
})
.then(function(data) {
return setupElements(data);
})
.then(function({ stripe, card, clientSecret }) {
document.querySelector("button").disabled = false;
// Handle form submission.
var form = document.getElementById("payment-form");
form.addEventListener("submit", function(event) {
event.preventDefault();
// Initiate payment when the submit button is clicked
pay(stripe, card, clientSecret);
});
});
// Set up Stripe.js and Elements to use in checkout form
var setupElements = function(data) {
stripe = Stripe(data.publishableKey);
var elements = stripe.elements();
var style = {
base: {
color: "#32325d",
fontFamily: '"Helvetica Neue", Helvetica, sans-serif',
fontSmoothing: "antialiased",
fontSize: "16px",
"::placeholder": {
color: "#aab7c4"
}
},
invalid: {
color: "#fa755a",
iconColor: "#fa755a"
}
};
var card = elements.create("card", { style: style });
card.mount("#card-element");
return {
stripe: stripe,
card: card,
clientSecret: data.clientSecret
};
};
/*
* Calls stripe.confirmCardPayment which creates a pop-up modal to
* prompt the user to enter extra authentication details without leaving your page
*/
var pay = function(stripe, card, clientSecret) {
changeLoadingState(true);
// Initiate the payment.
// If authentication is required, confirmCardPayment will automatically display a modal
stripe
.confirmCardPayment(clientSecret, {
payment_method: {
card: card
}
})
.then(function(result) {
if (result.error) {
// Show error to your customer
showError(result.error.message);
} else {
// The payment has been processed!
orderComplete(clientSecret);
}
});
};
/* ------- Post-payment helpers ------- */
/* Shows a success / error message when the payment is complete */
var orderComplete = function(clientSecret) {
// Just for the purpose of the sample, show the PaymentIntent response object
stripe.retrievePaymentIntent(clientSecret).then(function(result) {
var paymentIntent = result.paymentIntent;
var paymentIntentJson = JSON.stringify(paymentIntent, null, 2);
document.querySelector(".sr-payment-form").classList.add("hidden");
document.querySelector("pre").textContent = paymentIntentJson;
document.querySelector(".sr-result").classList.remove("hidden");
setTimeout(function() {
document.querySelector(".sr-result").classList.add("expand");
}, 200);
changeLoadingState(false);
});
};
var showError = function(errorMsgText) {
changeLoadingState(false);
var errorMsg = document.querySelector(".sr-field-error");
errorMsg.textContent = errorMsgText;
setTimeout(function() {
errorMsg.textContent = "";
}, 4000);
};
// Show a spinner on payment submission
var changeLoadingState = function(isLoading) {
if (isLoading) {
document.querySelector("button").disabled = true;
document.querySelector("#spinner").classList.remove("hidden");
document.querySelector("#button-text").classList.add("hidden");
} else {
document.querySelector("button").disabled = false;
document.querySelector("#spinner").classList.add("hidden");
document.querySelector("#button-text").classList.remove("hidden");
}
};
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Stripe Card Elements sample</title>
<meta name="description" content="A demo of Stripe Payment Intents" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="icon" href="favicon.ico" type="image/x-icon" />
<link rel="stylesheet" href="css/normalize.css" />
<link rel="stylesheet" href="css/global.css" />
<script src="https://js.stripe.com/v3/"></script>
<script src="/script.js" defer></script>
</head>
<body>
<div class="sr-root">
Stripe
<div class="sr-main">
<form id="payment-form" class="sr-payment-form">
<div class="sr-combo-inputs-row">
<div class="sr-input sr-card-element" id="card-element"></div>
</div>
<div class="sr-field-error" id="card-errors" role="alert"></div>
<button id="submit">
<div class="spinner hidden" id="spinner"></div>
<span id="button-text">Pay</span><span id="order-amount"></span>
</button>
</form>
<div class="sr-result hidden">
<p>Payment completed<br /></p>
<pre>
<code>
script.js:12 POST http://localhost:8080/create-payment-intent 404