Stripe checkout.js - passing custom params to token callback
<script src="https://checkout.stripe.com/checkout.js"></script>
<button class='pay-deposit' data-booking-id='3455'>Pay Deposit</button>
<button class='pay-deposit' data-booking-id='335'>Pay Deposit</button>
<button class='pay-deposit' data-booking-id='34'>Pay Deposit</button>
# JS file
$('.pay-deposit').on('click', function(event) {
event.preventDefault();
// Get booking information from database
var booking_id = $(this).data('booking-id');
$.getJSON("/bookings/"+booking_id, function(data) {
// Open Checkout with further options
handler = stripe_checkout(booking_id);
handler.open({
name: "My Bookings",
description: data["description"],
amount: data["amount"],
email: data["email"],
});
// Close Checkout on page navigation
$(window).on('popstate', function() {
handler.close();
});
});
});
function stripe_checkout(booking_id) {
var handler = StripeCheckout.configure({
key: 'pk_test_jPVRpCB1MLjWu2P71eTvXBZD',
token: function(token) {
// Send the charge through
$.post("/charges/create",
{ token: token.id, booking_id: booking_id }, function(data) {
if (data["status"] == "ok") {
window.location = "/some-url";
} else {
// Deal with error
alert(data["message"]);
}
});
}
});
return handler;
}
# Bookings controller
class BookingsController < ApplicationController
def show
@booking = Booking.find(params[:id])
attrs = @booking.attributes
attrs.merge!("email" => current_user.email)
respond_to do |format|
format.json { render json: attrs.to_json }
end
end
end
# Charges controller
class ChargesController < ApplicationController
def create
booking = Booking.find(params[:booking_id])
customer = Stripe::Customer.create(card: params[:token])
charge = Stripe::Charge.create(
customer: customer.id,
amount: booking.amount,
description: booking.description,
currency: 'usd'
)
if charge.paid
# Do some things for successful charge
respond_to do |format|
format.json { render json: {status: "ok"}.to_json }
end
else
respond_to do |format|
format.json { render json: {status: "fail", message: "Error with processing payment. Please contact support."}.to_json }
end
end
end
end
No comments:
Post a Comment
Thank You For Comment