Card Payment with Vue.js Tokenize Fail

I figured it out and would like to share my solution here. Welcome any comments or suggestions or better solutions.

The original issue was that the card is a listener, which can not be stored as a data element. I solved it by adding the card to button listener without storing it as a data element. For the sake of simplicity, I stripped out unrelated coding like error handling, etc.

<template>
    <div class="page-makepayment">
        <form id="payment-form">
            <div id="card-container"></div>
            <button type="button" ref="card_button">
                Make Payment
            </button>
        </form>
        <div id="payment-status-container"></div>
    </div>
</template>

<script>

export default {
    name: "MakePayment",

    data() {
        return {
            // card: null,   originally wanted to hold a listener which was the issue
            errors: []
        }
    },
    mounted() {
        this.initializeCard()
    },
    methods: {
        async initializeCard() {
            const square_appid = 'replace with square app id'
            const square_locid = 'replace with square location id'
            const payments = window.Square.payments(square_appid, square_locid)
            let card = await payments.card()        // this card is a listener which cannot be stored as a data element
            await card.attach("#card-container")

            var self = this
            this.$refs.card_button.addEventListener("click", async function (event) {
                const tokenResult = await card.tokenize()
                self.make_payment(tokenResult)
            })
        },

        async make_payment(tokenResult) {
            if ((tokenResult.status == "OK") && (tokenResult.token.length)) {

                // code to process payment with tokenResult.token
            }                
        }
    }
}
</script>
1 Like