Skip to content

Instantly share code, notes, and snippets.

@nissicreative
Last active July 19, 2020 20:16
Show Gist options
  • Save nissicreative/84381a1e52d83f010d3dcead2274b287 to your computer and use it in GitHub Desktop.
Save nissicreative/84381a1e52d83f010d3dcead2274b287 to your computer and use it in GitHub Desktop.
Vue Component with StripeElement
<template>
<form @submit.prevent="onSubmit" @keyup="form.errors.clear($event.target.name)">
<!-- Stripe Elements -->
<div class="stripe-element">
<stripe-elements ref="card" @change="stripeEvent($event);"></stripe-elements>
<small v-if="cardError" class="form-text text-danger">{{ cardError }}</small>
</div>
<!-- Errors -->
<div v-show="form.errors.any()" class="alert alert-danger">
<ul class="list-unstyled mb-0">
<li v-for="messages, key in form.errors.all()">
{{ messages[0] }}
</li>
</ul>
</div>
<div>
<submit-button ref="submitBtn" :disabled="form.errors.any()" data-icon="fas fa-lock"></submit-button>
</div>
</form>
</template>
<script>
import Form from 'form-backend-validation';
export default {
props: {},
data() {
return {
form: new Form({
stripe_token: '',
}, {
resetOnSuccess: false,
}),
cardError: false,
cardComplete: false,
}
},
computed: {},
methods: {
onSubmit() {
// Get the token from Stripe
this.$refs.card.createToken()
.then((result) => {
console.log('Stripe result', result);
if (result.error) {
this.cardError = result.error.message;
this.cardComplete = false;
this.$refs.submitBtn.enableBtn();
return;
}
// Add Stripe token to form data
this.form.stripe_token = result.token.id;
// Post the form
this.form.post(`https://httpbin.org/anything`)
.then(response => {
console.log(response);
})
.catch(e => {
console.log(e.response.data);
this.$refs.submitBtn.enableBtn();
});
})
},
stripeEvent(event) {
console.log('Stripe event', event);
this.cardError = event.error ? event.error.message : false,
this.cardComplete = event.complete;
},
},
}
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment