Skip to content
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { Controller } from '@hotwired/stimulus'
import { loadStripe } from '@stripe/stripe-js'
import { Controller } from "@hotwired/stimulus"
import { loadStripe } from "@stripe/stripe-js"

export default class extends Controller {
static values = {
Expand All @@ -15,7 +15,7 @@ export default class extends Controller {
radioSelector: String,
}

static targets = ['paymentElement', 'message']
static targets = ["paymentElement", "message"]

get submitOutletElement() {
return document.querySelector(this.submitSelectorValue)
Expand All @@ -32,6 +32,9 @@ export default class extends Controller {

// @action
async handleSubmit(e) {
// Bail out if not on the payment method form.
if (e.target !== this.radioOutletElement.form) return
Comment thread
waiting-for-dev marked this conversation as resolved.

// Bail out if the current payment method is not selected.
if (!this.radioOutletElement.checked) return

Expand All @@ -41,10 +44,10 @@ export default class extends Controller {

const { error } = await this.confirmIntent()

if (error.type === 'card_error' || error.type === 'validation_error') {
if (error.type === "card_error" || error.type === "validation_error") {
this.messageTarget.textContent = error.message
} else {
this.messageTarget.textContent = 'An unexpected error occurred.'
this.messageTarget.textContent = "An unexpected error occurred."
}

this.setLoading(false)
Expand All @@ -53,8 +56,8 @@ export default class extends Controller {
confirmIntent() {
let confirmMethod

if (this.flowValue === 'payment') confirmMethod = 'confirmPayment'
if (this.flowValue === 'setup') confirmMethod = 'confirmSetup'
if (this.flowValue === "payment") confirmMethod = "confirmPayment"
if (this.flowValue === "setup") confirmMethod = "confirmSetup"

if (!this.flowValue)
throw new Error("flowValue should be either 'payment' or 'setup'.")
Expand All @@ -69,21 +72,21 @@ export default class extends Controller {

setupPaymentElement() {
this.elements = this.stripe.elements({
appearance: { theme: 'stripe' },
appearance: { theme: "stripe" },
clientSecret: this.clientSecretValue,
})
this.paymentElement = this.elements.create('payment', { layout: 'tabs' })
this.paymentElementTarget.innerHTML = '' // Remove child nodes used for loading
this.paymentElement = this.elements.create("payment", { layout: "tabs" })
this.paymentElementTarget.innerHTML = "" // Remove child nodes used for loading
this.paymentElement.mount(this.paymentElementTarget)
}

setLoading(isLoading) {
const element = this.submitOutletElement

if (isLoading) {
element.setAttribute('disabled', '')
element.setAttribute("disabled", "")
} else {
element.removeAttribute('disabled')
element.removeAttribute("disabled")
}
}
}