Jake Vanderwerf
2026-02-08 df6c00db050e188a6bd5707e72c4f1f331ced923
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
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
/**
 * HelcimCheckout — extends CartCheckout for HelcimPay.js payments
 *
 * Payment flow:
 *   1. User clicks checkout → extractOrderData()
 *   2. Server call to /helcim/initialize-checkout → returns checkoutToken
 *   3. Call appendHelcimPayIframe(checkoutToken) → Helcim renders modal
 *   4. Listen for window 'message' event → SUCCESS / CANCELLED / ERROR
 *   5. On SUCCESS, validate transaction server-side
 *
 * @see https://devdocs.helcim.com/docs/helcim-pay-js
 */
class CheckoutHelcim extends window.jvbCheckout {
    constructor(config = {}) {
        super({
            ...window.helcimConfig,
            ...config,
        });
        this.pendingSecretToken = null;
    }
 
    /*****************************************************************
     * INIT — HelcimPay.js SDK (loaded externally)
     *****************************************************************/
 
    async init() {
        // HelcimPay.js is loaded via <script> tag, no SDK init needed.
        // We just need the global appendHelcimPayIframe function.
        if (typeof window.appendHelcimPayIframe !== 'function') {
            console.warn('HelcimPay.js SDK not loaded — payment will initialize on first checkout');
        }
 
        this.isInitialized = true;
 
        // Listen for HelcimPay.js message events
        window.addEventListener('message', (e) => this.handleHelcimMessage(e));
 
        document.dispatchEvent(new CustomEvent('checkoutReady', {
            detail: { checkout: this, provider: 'helcim' }
        }));
    }
 
    /*****************************************************************
     * PAYMENT FLOW
     *****************************************************************/
 
    async processPayment(orderData) {
        // If using a saved card, process server-side directly
        if (this.selectedCardId) {
            return this.submitToServer({
                card_id:   this.selectedCardId,
                is_saved:  true,
            }, orderData);
        }
 
        // Otherwise, initialize HelcimPay.js checkout
        const session = await this.initializeCheckoutSession(orderData);
        if (!session.success) {
            throw new Error(session.message || 'Failed to initialize checkout');
        }
 
        // Store secretToken for server-side validation after payment
        this.pendingSecretToken = session.secretToken;
        this.pendingOrderData   = orderData;
 
        // Open HelcimPay.js iframe modal
        window.appendHelcimPayIframe(session.checkoutToken, {
            type: 'modal', // 'modal' or 'inline'
        });
 
        // The flow continues in handleHelcimMessage() when the iframe posts back
        // Return a promise that resolves when payment completes
        return new Promise((resolve, reject) => {
            this._paymentResolve = resolve;
            this._paymentReject  = reject;
        });
    }
 
    /**
     * Server call: initialize a HelcimPay.js checkout session
     */
    async initializeCheckoutSession(orderData) {
        const response = await fetch(this.config.api_url + 'initialize-checkout', {
            method:  'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-WP-Nonce':   this.config.nonce,
            },
            body: JSON.stringify({
                amount:      orderData.total / 100, // Convert cents back to dollars
                customer:    orderData.customer,
                items:       orderData.items,
                cart_id:     this.getCartId(),
            }),
        });
 
        return response.json();
    }
 
    /**
     * Handle postMessage events from HelcimPay.js iframe
     */
    handleHelcimMessage(event) {
        const data = event.data;
 
        // HelcimPay.js sends messages with specific event types
        if (!data || typeof data !== 'object') return;
 
        // Helcim sends eventStatus: 'ABORTED' | 'SUCCESS' | 'FAILED'
        if (data.eventStatus === 'SUCCESS') {
            this.handleHelcimSuccess(data);
        } else if (data.eventStatus === 'ABORTED') {
            this.handleHelcimCancelled();
        } else if (data.eventStatus === 'FAILED') {
            this.handleHelcimError(data);
        }
    }
 
    async handleHelcimSuccess(data) {
        try {
            // Validate the transaction server-side using secretToken
            const result = await this.submitToServer({
                transaction_id: data.transactionId,
                secret_token:   this.pendingSecretToken,
                event_data:     data,
            }, this.pendingOrderData);
 
            this.clearPending();
            this._paymentResolve?.(result);
        } catch (error) {
            this.clearPending();
            this._paymentReject?.(error);
        }
    }
 
    handleHelcimCancelled() {
        this.clearPending();
        window.jvbLoading?.hideLoading?.();
        this.a11y.announce('Payment cancelled');
        this._paymentReject?.(new Error('Payment cancelled by user'));
    }
 
    handleHelcimError(data) {
        this.clearPending();
        window.jvbLoading?.hideLoading?.();
        const message = data.errorMessage || 'Payment failed';
        this._paymentReject?.(new Error(message));
    }
 
    clearPending() {
        this.pendingSecretToken = null;
        this.pendingOrderData   = null;
    }
 
    /*****************************************************************
     * SERVER COMMUNICATION
     *****************************************************************/
 
    async submitToServer(paymentData, orderData) {
        if (!this.isOpen) {
            throw new Error('Store is currently closed');
        }
 
        const endpoint = paymentData.is_saved
            ? 'process-saved-payment'
            : 'validate-transaction';
 
        const response = await fetch(this.config.api_url + endpoint, {
            method:  'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-WP-Nonce':   this.config.nonce,
            },
            body: JSON.stringify({
                ...paymentData,
                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;
    }
 
    /*****************************************************************
     * SAVED CARDS
     *****************************************************************/
 
    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);
        }
    }
 
    /*****************************************************************
     * INVOICES — Helcim-specific (source of truth is Helcim)
     *****************************************************************/
 
    async loadInvoices() {
        try {
            const response = await fetch(this.config.api_url + 'invoices', {
                headers: { 'X-WP-Nonce': this.config.nonce },
            });
            const result = await response.json();
            if (result.success) {
                return result.invoices || [];
            }
        } catch (error) {
            console.error('Failed to load invoices:', error);
        }
        return [];
    }
 
    async payInvoice(invoiceId) {
        const session = await fetch(this.config.api_url + 'initialize-checkout', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-WP-Nonce':   this.config.nonce,
            },
            body: JSON.stringify({
                invoice_id: invoiceId,
            }),
        }).then(r => r.json());
 
        if (!session.success) {
            throw new Error(session.message || 'Failed to initialize invoice payment');
        }
 
        this.pendingSecretToken = session.secretToken;
        this.pendingOrderData   = { total: 0, items: [], customer: {} };
 
        window.appendHelcimPayIframe(session.checkoutToken, { type: 'modal' });
 
        return new Promise((resolve, reject) => {
            this._paymentResolve = resolve;
            this._paymentReject  = reject;
        });
    }
}
 
document.addEventListener('DOMContentLoaded', () => {
    // Only init if Helcim is the active provider
    const form = document.querySelector('#checkout[data-provider="helcim"]');
    if (form) {
        window.jvbHelcim = new CheckoutHelcim();
    }
});