简体   繁体   中英

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 . 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. I don't even get any logs on my Stripe account

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

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. It seems not working well along. The Spark routes are simply defined statically in the “Main” class. 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:

@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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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