Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Stripe checkout with AJAX

I have a button that I am using for Stripe checkout (it pops up the Stripe form). What I would like to do is use Ajax to send the inputs to my backend (using a route) and then store that information. How would I do this?

Current code below:

<div class="button_row">
{{ Form::button('Pay $1', array( 
        'id' => 'customButton',
        'class' => 'button',
        )); }}
</div>

<script src="https://checkout.stripe.com/checkout.js"></script>

<script>
  var handler = StripeCheckout.configure({
    key: '*****************',
    image: '/assets/images/1024icon.png',
    token: function(token) {
      // Use the token to create the charge with a server-side script.
      // You can access the token ID with `token.id`
    }
  });

  $('#customButton').on('click', function(e) {
    // Open Checkout with further options
    handler.open({
      name: 'Test',
      description: 'Test',
      amount: 100
    });
    e.preventDefault();
  });

  // Close Checkout on page navigation
  $(window).on('popstate', function() {
    handler.close();
  });
</script>

Backend Controller Function:

public function stripe_pay() {
    // Use the config for the stripe secret key
    Stripe::setApiKey(Config::get('stripe.stripe.secret'));

    // Get the credit card details submitted by the form
    $token = Input::get('stripeToken');

    // Create the charge on Stripe's servers - this will charge the user's card
    try {
        $charge = Stripe_Charge::create(array(
          "amount" => 500, // amount in cents
          "currency" => "usd",
          "card"  => $token,
          "description" => 'Charge for my product')
        );

    } catch(Stripe_CardError $e) {
        $e_json = $e->getJsonBody();
        $error = $e_json['error'];
        // The card has been declined
        // redirect back to checkout page
        return Redirect::to('/artists/'.$artist_id)
            ->withInput()->with('stripe_errors',$error['message']);
    }
    // Maybe add an entry to your DB that the charge was successful, or at least Log the charge or errors
    // Stripe charge was successfull, continue by redirecting to a page with a thank you message
}
like image 668
user1072337 Avatar asked Nov 01 '22 07:11

user1072337


1 Answers

The idea here would be to use jQuery.post() to send the data to your server instead of just submitting the form.

var handler = StripeCheckout.configure({
  key: '***',
  image: '/square-image.png',
  token: function(token) {
    var stripeToken = token.id;
    var stripeEmail = token.email;
    $.post(
        "/charges.php", /* your route here */
        { stripeToken: token.id, stripeEmail: stripeEmail },
        function(data) {
          console.log(data);
        }
    );
  }
});
like image 105
koopajah Avatar answered Nov 10 '22 17:11

koopajah