-
-
Save cliftonscott/d60f23f17c2a0bd056afd7aa60b5eb73 to your computer and use it in GitHub Desktop.
Renderless VueJS component for Payment Requests using Stripe Element
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| export default { | |
| props: { | |
| stripe: { | |
| type: String, | |
| required: true, | |
| }, | |
| options: { | |
| type: Object, | |
| required: true, | |
| } | |
| }, | |
| data () { | |
| const stripeInstance = Stripe(this.stripe) | |
| return { | |
| loading: true, | |
| canMakePayment: false, | |
| elements: stripeInstance.elements({ locale: this.$root.locale }), | |
| paymentRequest: stripeInstance.paymentRequest(this.options), | |
| } | |
| }, | |
| methods: { | |
| init (canMakePayment) { | |
| this.loading = false | |
| this.canMakePayment = canMakePayment | |
| this.$nextTick(this.createPaymentRequestButton) | |
| }, | |
| createPaymentRequestButton () { | |
| if (!this.canMakePayment || !this.$refs.element) return | |
| this.elements | |
| .create('paymentRequestButton', { paymentRequest: this.paymentRequest }) | |
| .mount(this.$refs.element) | |
| } | |
| }, | |
| mounted () { | |
| // Check the availability of the Payment Request API first. | |
| this.paymentRequest.canMakePayment().then(this.init) | |
| // Notify the parent component when we receive a token. | |
| this.paymentRequest.on('token', event => this.$emit('token', event)) | |
| }, | |
| render (createElement) { | |
| // Render a loading slot if we are waiting for canMakePayment. | |
| if (this.loading) { | |
| return this.$slots.loading && this.$slots.loading[0] | |
| } | |
| // Render a warning slot if payment request isn't available. | |
| if (! this.canMakePayment) { | |
| return this.$slots.unavailable && this.$slots.unavailable[0] | |
| } | |
| // Render scoped slot if provided. | |
| if (this.$scopedSlots.default) { | |
| return this.$scopedSlots.default({ | |
| listeners: { click: event => this.paymentRequest.show() }, | |
| canMakePayment: this.canMakePayment, | |
| }) | |
| } | |
| // Otherwise render default Stripe Element button. | |
| return createElement('div', { ref: 'element' }) | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment