Javascript 条带post到`/create payment intent`返回404
我是条带支付新手,尝试在github存储库之后集成条带代码。 但到目前为止,每次我点击endpointJavascript 条带post到`/create payment intent`返回404,javascript,java,stripe-payments,Javascript,Java,Stripe Payments,我是条带支付新手,尝试在github存储库之后集成条带代码。 但到目前为止,每次我点击endpoint/create payment intent时,我都会得到404。该示例使用spark框架,似乎spark post拦截器无法执行。我的Stripe帐户上甚至没有任何日志 import static spark.Spark.post; import com.google.gson.Gson; import org.slf4j.Logger; import org.slf4j.LoggerFa
/create payment intent
时,我都会得到404。该示例使用spark框架,似乎spark post拦截器无法执行。我的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 "";
});
}
}
@RestController
public class YourController {
@PostMapping("/create-payment-intent")
public String test(HttpServletRequest request, HttpServletResponse response) throws StripeException {
Gson gson = new Gson();
resposne.setContentType("application/json");
try {
StringBuilder buffer = new StringBuilder();
BufferedReader reader = request.getReader();
String line;
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
String dataBody = buffer.toString();
CreatePaymentBody postBody = gson.fromJson(dataBody,
CreatePaymentBody.class);
logger.info(" -------- <<<<<<>>>>>>---------- ---------- POSTBODY
-> {}", dataBody);
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_fXXXXXXXXXXXX",
intent.getClientSecret()));
} catch (JsonSyntaxException e) {
e.printStackTrace();
return "";
} catch (IOException e) {
e.printStackTrace();
return "";
}
}
}
script.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");
}
};
@RestController
public class YourController {
@PostMapping("/create-payment-intent")
public String test(HttpServletRequest request, HttpServletResponse response) throws StripeException {
Gson gson = new Gson();
resposne.setContentType("application/json");
try {
StringBuilder buffer = new StringBuilder();
BufferedReader reader = request.getReader();
String line;
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
String dataBody = buffer.toString();
CreatePaymentBody postBody = gson.fromJson(dataBody,
CreatePaymentBody.class);
logger.info(" -------- <<<<<<>>>>>>---------- ---------- POSTBODY
-> {}", dataBody);
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_fXXXXXXXXXXXX",
intent.getClientSecret()));
} catch (JsonSyntaxException e) {
e.printStackTrace();
return "";
} catch (IOException e) {
e.printStackTrace();
return "";
}
}
}
script.js:12帖子http://localhost:8080/create-支付意图404
您正在使用Spark框架和Spring boot。这似乎不太管用。火花路径在“Main”类中简单地静态定义。一般来说,这不是一个好的设计,因为众所周知的原因,如可测试性和解耦。为什么不利用Spring RestController并为其创建控制器端点,如下所示:
@RestController
public class YourController {
@PostMapping("/create-payment-intent")
public String test(HttpServletRequest request, HttpServletResponse response) throws StripeException {
Gson gson = new Gson();
resposne.setContentType("application/json");
try {
StringBuilder buffer = new StringBuilder();
BufferedReader reader = request.getReader();
String line;
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
String dataBody = buffer.toString();
CreatePaymentBody postBody = gson.fromJson(dataBody,
CreatePaymentBody.class);
logger.info(" -------- <<<<<<>>>>>>---------- ---------- POSTBODY
-> {}", dataBody);
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_fXXXXXXXXXXXX",
intent.getClientSecret()));
} catch (JsonSyntaxException e) {
e.printStackTrace();
return "";
} catch (IOException e) {
e.printStackTrace();
return "";
}
}
}
@RestController
公共类控制器{
@后映射(“/创建支付意图”)
公共字符串测试(HttpServletRequest请求、HttpServletResponse响应)抛出StripeException{
Gson Gson=新的Gson();
setContentType(“应用程序/json”);
试一试{
StringBuilder缓冲区=新的StringBuilder();
BufferedReader reader=request.getReader();
弦线;
而((line=reader.readLine())!=null){
buffer.append(行);
}
字符串dataBody=buffer.toString();
CreatePaymentBody postBody=gson.fromJson(数据体,
CreatePaymentBody.class);
logger.info(“-------------------POSTBODY
->{},数据体);
PaymentIntentCreateParams createParams=新建PaymentIntentCreateParams.Builder()
.setCurrency(postBody.getCurrency()).setAmount(新Long(calculateOrderAmount(postBody.getItems()))
.build();
//使用订单金额和货币创建PaymentIntent
PaymentIntent=PaymentIntent.create(createParams);
//向客户发送可发布的密钥和PaymentIntent详细信息
返回gson.toJson(新的CreatePaymentResponse(“pk\u test\u fxxxxxxxxxx”),
intent.getClientSecret());
}捕获(JsonSyntaxException e){
e、 printStackTrace();
返回“”;
}捕获(IOE异常){
e、 printStackTrace();
返回“”;
}
}
}
您可以对
/webhook
端点执行相同的操作,POST url中包含localhost,而不是远程站点上的位置。如果你的条带帐户位于远程服务器上,这可能就是你不向帐户发布的原因。好的,我为它添加了一个创建的远程url帐户,但现在我收到了相同的错误script.js:12 POSThttps://chat-maryn-demo.herokuapp.com/create-payment-intent 404
@RestController
public class YourController {
@PostMapping("/create-payment-intent")
public String test(HttpServletRequest request, HttpServletResponse response) throws StripeException {
Gson gson = new Gson();
resposne.setContentType("application/json");
try {
StringBuilder buffer = new StringBuilder();
BufferedReader reader = request.getReader();
String line;
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
String dataBody = buffer.toString();
CreatePaymentBody postBody = gson.fromJson(dataBody,
CreatePaymentBody.class);
logger.info(" -------- <<<<<<>>>>>>---------- ---------- POSTBODY
-> {}", dataBody);
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_fXXXXXXXXXXXX",
intent.getClientSecret()));
} catch (JsonSyntaxException e) {
e.printStackTrace();
return "";
} catch (IOException e) {
e.printStackTrace();
return "";
}
}
}