Jake Vanderwerf
2026-05-12 c32ed859f4abd1591c882f4f2a6ee16b1ec275e2
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
/**
 * CheckoutSquare — Square Web Payments SDK checkout
 *
 * Extends CartCheckout with:
 *   - Square Web Payments SDK initialization
 *   - Card tokenization (new card or saved card)
 *   - Square-specific API submission
 *   - Saved cards via Square Customers API
 *
 * All cart management, totals, UI, order tracking, etc. are
 * inherited from CartCheckout (cart-checkout.min.js).
 *
 * HTML structure: Checkout.php (JVBase\ui\Checkout)
 *   - Mounts card form into #payment-container
 *   - Uses data-catalog-id (mapped to catalog_object_id for Square API)
 */
class CheckoutSquare extends window.jvbCheckout {
    constructor(config = {}) {
        super({
            ...window.squareConfig,
            ...config,
        });
 
        // Square-specific
        this.payments = null;
        this.card     = null;
    }
 
    /*****************************************************************
     * INIT — Square Web Payments SDK
     *****************************************************************/
 
    async init() {
        if (!window.Square) {
            console.error('Square Web Payments SDK not loaded');
            return;
        }
 
        try {
            this.payments = window.Square.payments(
                this.config.application_id,
                this.config.location_id
            );
 
            await this.initializePaymentMethods();
 
            this.isInitialized = true;
 
            document.dispatchEvent(new CustomEvent('checkoutReady', {
                detail: { checkout: this, provider: 'square' }
            }));
 
        } catch (error) {
            console.error('Failed to initialize Square payments:', error);
            this.handleError(error);
        }
    }
 
    async initializePaymentMethods() {
        const cardContainer = document.getElementById('payment-container');
        if (!cardContainer) return;
 
        try {
            this.card = await this.payments.card({
                style: this.getCardStyle()
            });
            await this.card.attach('#payment-container');
 
            this.card.addEventListener('cardBrandChanged', (event) => {
                console.log('Card brand:', event.detail.cardBrand);
            });
        } catch (error) {
            console.error('Failed to initialize card:', error);
            throw error;
        }
    }
 
    getCardStyle() {
        return {
            input: {
                fontSize: '16px',
                fontFamily: 'inherit',
                color: '#333',
                backgroundColor: '#fff'
            },
            '.input-container': {
                borderColor: '#ccc',
                borderRadius: '4px'
            },
            '.input-container.is-focus': {
                borderColor: '#006AFF',
                borderWidth: '2px',
                outline: '2px solid #006AFF',
                outlineOffset: '2px'
            },
            '.input-container.is-error': {
                borderColor: '#d63638'
            }
        };
    }
 
    /*****************************************************************
     * PAYMENT — Square tokenization
     *****************************************************************/
 
    async processPayment(orderData) {
        try {
            let sourceToken = null;
 
            if (this.selectedCardId) {
                // Use saved card
                sourceToken = this.selectedCardId;
            } else {
                // Tokenize new card
                const tokenResult = await this.card.tokenize({
                    verificationDetails: {
                        amount: String(orderData.total),
                        currencyCode: this.config.currency || 'CAD',
                        intent: 'CHARGE',
                        customerInitiated: true,
                        billingContact: {
                            givenName: orderData.customer.name.split(' ')[0],
                            familyName: orderData.customer.name.split(' ').slice(1).join(' '),
                            email: orderData.customer.email,
                            phone: orderData.customer.phone,
                        }
                    }
                });
 
                if (tokenResult.status !== 'OK') {
                    const errors = tokenResult.errors?.map(e => e.message).join(', ') || 'Unknown error';
                    throw new Error(`Card tokenization failed: ${errors}`);
                }
 
                sourceToken = tokenResult.token;
 
                if (tokenResult.details?.userChallenged) {
                    console.log('3D Secure verification completed');
                }
            }
 
            return await this.submitToServer(sourceToken, orderData, !!this.selectedCardId);
 
        } catch (error) {
            console.error('Payment processing failed:', error);
            throw error;
        }
    }
 
    /*****************************************************************
     * SERVER — Square REST endpoint
     *****************************************************************/
 
    async submitToServer(sourceToken, orderData, isSavedCard = false) {
        if (!this.isOpen) {
            throw new Error('Store is currently closed');
        }
 
        const response = await fetch(this.config.api_url + 'process-payment', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-WP-Nonce': this.config.nonce,
            },
            body: JSON.stringify({
                source_id:     sourceToken,
                is_saved_card: isSavedCard,
                cart_id:       this.getCartId(),
                amount:        orderData.total,
                items:         orderData.items,
                customer: {
                    email: this.isLoggedIn ? this.userEmail : orderData.customer.email,
                    name:  orderData.customer.name,
                    phone: orderData.customer.phone,
                },
                note:        orderData.note,
                pickup_time: orderData.pickup_time,
            }),
        });
 
        const result = await response.json();
 
        if (!response.ok) {
            throw new Error(result.message || 'Payment processing failed');
        }
 
        this.clearCart();
        return result;
    }
 
    /*****************************************************************
     * ORDER DATA — Square-specific field mapping
     *
     * Base class builds the generic structure. We override to map
     * catalog_id → catalog_object_id for the Square Orders API.
     *****************************************************************/
 
    extractOrderData(form) {
        const base = super.extractOrderData(form);
 
        // Remap for Square's Orders API
        base.items = base.items.map(item => ({
            catalog_object_id: item.catalog_id,
            quantity:          item.quantity,
            price:             item.price,
            note:              item.note,
        }));
 
        return base;
    }
 
    /*****************************************************************
     * SAVED CARDS — Square Customers API
     *****************************************************************/
 
    async loadSavedCards() {
        try {
            const response = await fetch(this.config.api_url + 'saved-cards', {
                method: 'GET',
                headers: { 'X-WP-Nonce': this.config.nonce },
            });
 
            const result = await response.json();
 
            if (result.success && result.cards) {
                this.savedCards = result.cards;
                this.renderSavedCards();
            }
        } catch (error) {
            console.error('Failed to load saved cards:', error);
        }
    }
}
 
/*****************************************************************
 * BOOTSTRAP — only init if Square is the active provider
 *****************************************************************/
 
document.addEventListener('DOMContentLoaded', () => {
    const form = document.querySelector('#checkout[data-provider="square"]');
    if (form) {
        window.squareCheckout = new CheckoutSquare();
    }
});