jquery – 如何使用AJAX进行Stripe checkout

我有一个用于Stripe checkout的按钮(它会弹出Stripe表单).我想要做的是使用Ajax将输入发送到我的后端(使用路由),然后存储该信息.我该怎么做?

目前的代码如下:

<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>

后端控制器功能:

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
}

最佳答案 这里的想法是使用
jQuery.post()将数据发送到您的服务器,而不是仅仅提交表单.

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);
        }
    );
  }
});
点赞