Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save cjavilla-stripe/b2879fb51bbe1e86f3e2349b1017d7cb to your computer and use it in GitHub Desktop.
Save cjavilla-stripe/b2879fb51bbe1e86f3e2349b1017d7cb to your computer and use it in GitHub Desktop.
class SubscriptionsController < ApplicationController
def new
@customer = Stripe::Customer.create
@subscription = Stripe::Subscription.create(
customer: @customer.id,
items: [{
price: 'price_1KW5LPG3pPSOzbKUr6hQmTAr',
}],
payment_behavior: 'default_incomplete',
expand: ['latest_invoice.payment_intent']
)
end
end
<h1>Subscriptions</h1>
<!-- Display a payment form -->
<form id="payment-form">
<div id="payment-element">
<!--Stripe.js injects the Payment Element-->
</div>
<button id="submit">
<div class="spinner hidden" id="spinner"></div>
<span id="button-text">Pay now</span>
</button>
<div id="payment-message" class="hidden"></div>
</form>
<script>
// This is your test publishable API key.
const stripe = Stripe("<%= Rails.application.credentials.dig(:stripe, :public_key) %>");
checkStatus();
document
.querySelector("#payment-form")
.addEventListener("submit", handleSubmit);
const appearance = {
theme: 'stripe',
};
const elements = stripe.elements({ appearance, clientSecret: "<%= @subscription.latest_invoice.payment_intent.client_secret %>" });
const paymentElement = elements.create("payment");
paymentElement.mount("#payment-element");
async function handleSubmit(e) {
e.preventDefault();
const { error } = await stripe.confirmPayment({
elements,
confirmParams: {
// Make sure to change this to your payment completion page
return_url: "http://localhost:3000/subscriptions",
},
});
// This point will only be reached if there is an immediate error when
// confirming the payment. Otherwise, your customer will be redirected to
// your `return_url`. For some payment methods like iDEAL, your customer will
// be redirected to an intermediate site first to authorize the payment, then
// redirected to the `return_url`.
if (error.type === "card_error" || error.type === "validation_error") {
alert(error.message);
} else {
alert("An unexpected error occured.");
}
}
// Fetches the payment intent status after payment submission
async function checkStatus() {
const clientSecret = new URLSearchParams(window.location.search).get(
"payment_intent_client_secret"
);
if (!clientSecret) {
return;
}
const { paymentIntent } = await stripe.retrievePaymentIntent(clientSecret);
switch (paymentIntent.status) {
case "succeeded":
showMessage("Payment succeeded!");
break;
case "processing":
showMessage("Your payment is processing.");
break;
case "requires_payment_method":
showMessage("Your payment was not successful, please try again.");
break;
default:
showMessage("Something went wrong.");
break;
}
}
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment