How can I modify Stripe Checkout to instead send an AJAX request?

后端 未结 3 848
刺人心
刺人心 2021-01-01 16:14

I\'m using Stripe and Checkout to create a payment form and I want to be able to use Checkout\'s awesome javascript library, but I also want to change the form submission fr

3条回答
  •  青春惊慌失措
    2021-01-01 17:10

    You can do it this way. This example uses PHP, but swap in your preferred server-side language:

    1) Create a nocontent.php file that contains this line: header("HTTP/1.0 204 No Content"); which surprisingly returns a 'HTTP/1.0 204 No Content' header. The browser will appear to do nothing when it requests this page. You can optionally have this page process the POST data, or you can have this simply be a dummy page with that single line.

    2) In your HTML put the nocontent.php path into the tag's action attribute :

    .

    3) Attach a javascript function to the window.onbeforeunload event. This event is triggered as the browser requests the new page, and so is fired even though the browser appears to do nothing. This function is called after Stripe generates its token.

    4) Your form now contains the and elements.

    5) Now you have options, depending on when you handled the form's POST data.

    • a) If your nocontent.php page simply returns a 'no content' header, you can now AJAX re-submit your form's data to another page (as normal) that will actually process the POST data and return Stripe's status information. That's the route I took.

    • b) If your nocontent.php page itself processes the form's POST data, you can store the Stripe response on the server and use your token as a key in an ajax request to retrieve payment status whenever it arrives from Stripe.

    Note that it might be better practice to intercept and prevent Stripe from triggering the submit event on the form itself, but I did not have reliable success with that method.

提交回复
热议问题