简体   繁体   English

Stripe post 到 `/create-payment-intent` 返回 404

[英]Stripe post to `/create-payment-intent` returns 404

I'm new to Stripe payment and trying to integrate a stripe code following this github repository https://github.com/stripe-samples/accept-a-card-payment/tree/master/using-webhooks .我是 Stripe 支付的新手,并尝试在此 github 存储库https://github.com/stripe-samples/accept-a-card-payment/tree/master/using-webhooks之后集成条带代码。 But so far every time I hit endpoint /create-payment-intent I'm getting 404. The sample uses spark framework and seems like spark post interceptor does't get executed.但到目前为止,每次我点击端点/create-payment-intent我都会收到 404。该示例使用了 spark 框架,并且似乎没有执行 spark post 拦截器。 I don't even get any logs on my Stripe account我什至没有在我的 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 "";
        }); 

    }

}

script.js脚本.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

You're using Spark framework along with Spring boot.您正在使用 Spark 框架和 Spring boot。 It seems not working well along.它似乎不能很好地工作。 The Spark routes are simply defined statically in the “Main” class. Spark 路由只是在“Main”类中静态定义的。 That is not a good design generally speaking due to well known reasons like testability and decoupling.由于众所周知的原因,例如可测试性和解耦,这通常不是一个好的设计。 Why don't you take advantage from using Spring RestController and create Controller endpoints for it like so:为什么不利用 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 "";
            }

    }       
}

the same you can do for the /webhook endpoint您可以对/webhook端点执行相同的操作

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM