gpt4 book ai didi

javascript - Stripe 发送到 `/create-payment-intent` 返回 404

转载 作者:行者123 更新时间:2023-12-01 18:11:58 24 4
gpt4 key购买 nike

我是 Stripe 支付新手,并尝试按照此 github 存储库集成 Stripe 代码 https://github.com/stripe-samples/accept-a-card-payment/tree/master/using-webhooks 。但到目前为止,每次我点击端点 /create- payment-intent 时,我都会收到 404。该示例使用 Spark 框架,并且似乎 Spark 后拦截器没有被执行。我什至没有在我的 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></code>
</pre>
</div>
</div>
</div>
</body>
</html>

script.js:12 POST http://localhost:8080/create- payment-intent 404

最佳答案

您正在使用 Spark 框架和 Spring boot。看起来效果不太好。 Spark 路由只是在“Main”类中静态定义。一般来说,由于可测试性和解耦等众所周知的原因,这不是一个好的设计。为什么不利用 Spring RestController 并为其创建 Controller 端点,如下所示:

@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 "";
}

}
}

您可以对 /webhook 端点执行相同的操作

关于javascript - Stripe 发送到 `/create-payment-intent` 返回 404,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60453992/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com