-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathstripe_button_controller.js
More file actions
480 lines (428 loc) · 15.6 KB
/
stripe_button_controller.js
File metadata and controls
480 lines (428 loc) · 15.6 KB
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
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
import { Controller } from '@hotwired/stimulus'
import { loadStripe } from '@stripe/stripe-js/pure'
import showFlashMessage from 'spree/storefront/helpers/show_flash_message'
export default class extends Controller {
static values = {
apiKey: String,
orderToken: String,
clientSecret: String,
currency: String,
amount: Number,
availableCountries: Array,
giftCardCode: String,
giftCardAmount: Number,
borderRadius: Number,
height: Number,
theme: String,
maxRows: Number,
maxColumns: Number,
buttonWidth: Number,
checkoutPath: String,
checkoutAdvancePath: String,
checkoutSelectShippingMethodPath: String,
checkoutValidateGiftCardDataPath: String,
checkoutValidateOrderForPaymentPath: String,
shippingRequired: { type: Boolean, default: true },
returnUrl: String,
phoneRequired: { type: Boolean, default: false },
}
static targets = ['container']
connect() {
this.paymentMethod = null
this.initStripe()
this.shippingRates = []
this.currentShippingOptionId = null
}
initStripe() {
if (typeof Stripe === 'undefined') {
loadStripe(this.apiKeyValue).then((stripe) => {
this.stripe = stripe
this.prepareExpressCheckoutElement()
})
} else if (typeof this.stripe !== 'function') {
this.stripe = Stripe(this.apiKeyValue)
this.prepareExpressCheckoutElement()
}
}
prepareExpressCheckoutElement() {
this.elements = this.stripe.elements({
mode: 'payment',
currency: this.currencyValue,
amount: parseInt(this.amountValue),
appearance: {
theme: 'stripe',
variables: {
borderRadius: this.hasBorderRadiusValue ? `${this.borderRadiusValue}px` : undefined
}
},
paymentMethodCreation: 'manual'
})
const prButton = this.elements.create('expressCheckout', {
wallets: { applePay: 'always', googlePay: 'always' },
buttonHeight: this.heightValue > 0 ? this.heightValue : undefined,
buttonTheme: {
applePay: this.themeValue.length ? this.themeValue : undefined,
googlePay: this.themeValue.length ? this.themeValue : undefined
},
layout: {
overflow: this.maxRowsValue > 0 ? 'auto' : 'never',
maxColumns: this.maxColumnsValue > 0 ? this.maxColumnsValue : undefined,
maxRows: this.maxRowsValue > 0 ? this.maxRowsValue : undefined
},
buttonType: {
applePay: 'check-out',
googlePay: 'checkout'
},
paymentMethodOrder: ['applePay', 'googlePay', 'link']
})
prButton.mount('#payment-request-button')
prButton.on('ready', ({ availablePaymentMethods }) => {
if (!availablePaymentMethods) {
this.containerTarget.style.display = 'hidden'
return
}
const availableMethodsCount = Object.keys(availablePaymentMethods).filter(
(key) => availablePaymentMethods[key]
).length
if (this.buttonWidthValue > 0) {
this.containerTarget.style.setProperty(
'--desktop-max-width',
this.buttonWidthValue * availableMethodsCount + 'px'
)
this.containerTarget.classList.add('desktop-max-width')
}
window.parent?.postMessage({ enabledPaymentMethodsCount: availableMethodsCount }, '*')
})
prButton.on('click', (event) => {
this.paymentMethod = event.expressPaymentType
event.resolve({
emailRequired: true,
phoneNumberRequired: this.phoneRequiredValue,
shippingAddressRequired: this.shippingRequiredValue,
allowedShippingCountries: this.availableCountriesValue,
// If we want to collect shipping address then we need to provide at least one shipping option, it will be updated to the real ones in the `shippingaddresschange` event
shippingRates: this.shippingRequiredValue ? [{ id: 'loading', displayName: 'Loading...', amount: 0 }] : [],
lineItems: [
{ name: 'Subtotal', amount: 0 },
{ name: 'Shipping', amount: 0 },
{ name: 'Store credit', amount: 0 },
{ name: 'Discount', amount: 0 },
{ name: 'Tax', amount: 0 }
]
})
})
if (this.shippingRequiredValue) {
prButton.on('shippingaddresschange', this.handleAddressChange.bind(this))
prButton.on('shippingratechange', this.handleShippingOptionChange.bind(this))
}
prButton.on('confirm', this.handleFinalizePayment.bind(this))
prButton.on('cancel', this.handleCancelPayment.bind(this))
}
async handleAddressChange(ev) {
// Perform server-side request to fetch shipping options
// https://stripe.com/docs/js/payment_request/events/on_shipping_address_change#payment_request_on_shipping_address_change-handler-shippingAddress
const orderUpdatePayload = {
order: {
ship_address_attributes: {
// we need to use quick checkout option to skip first/last/street address validation
// as at this point we don't receive this information as browsers do not share it with us
quick_checkout: true,
firstname: ev.name.split(' ')[0],
lastname: ev.name.split(' ')[1],
city: ev.address.city,
zipcode: ev.address.postal_code,
country_iso: ev.address.country,
state_name: ev.address.state
},
bill_address_id: 'CLEAR' // we need to clear out the bill address to avoid order being pushed to confirm/complete state
}
}
// 1st we need to persist the address to the order
const saveAddressResponse = await fetch(this.checkoutPathValue, {
method: 'PATCH',
headers: {
'X-Spree-Order-Token': this.orderTokenValue,
'Content-Type': 'application/json'
},
body: JSON.stringify(orderUpdatePayload)
})
// 2nd we need to push the order to delivery state to generate shipping rates
if (saveAddressResponse.status === 200) {
// In case of any error here we have to allow user try again
try {
const response = await fetch(
this.checkoutAdvancePathValue,
{
method: 'PATCH',
headers: {
'X-Spree-Order-Token': this.orderTokenValue,
'Content-Type': 'application/json'
},
body: JSON.stringify({
state: 'delivery',
include: 'shipments.shipping_rates',
quick_checkout: true,
shipping_method_id: this.currentShippingOptionId
})
}
)
const newOrderResponse = await response.json()
this.shippingRates = newOrderResponse.included.filter((item) => item.type === 'shipping_rate')
if (this.shippingRates.length > 0) {
this.elements.update({ amount: newOrderResponse.data.attributes.total_minus_store_credits_cents })
const shippingRates = this.shippingOptions(this.shippingRates)
// We need to select first shipping rate as default, because Apple Pay sometimes doesn't trigger `shippingratechange` event when the modal is opened
this.currentShippingOptionId = String(shippingRates[0].id)
ev.resolve({
shippingRates: shippingRates,
lineItems: this.buildLineItems(newOrderResponse)
})
return
}
} catch (error) {
ev.reject()
return
}
}
ev.reject()
}
async handleShippingOptionChange(ev) {
const { resolve, shippingRate, reject } = ev
if (shippingRate) {
const shippingRateId = String(shippingRate.id).replace(/_google_pay_\d+/, '')
if (shippingRateId === 'standard') return resolve()
if (shippingRateId === 'loading') return reject()
this.currentShippingOptionId = shippingRateId
const response = await fetch(this.checkoutSelectShippingMethodPathValue, {
method: 'PATCH',
headers: {
'X-Spree-Order-Token': this.orderTokenValue,
'Content-Type': 'application/json'
},
body: JSON.stringify({ shipping_method_id: shippingRateId })
})
if (response.status === 200) {
const newOrderResponse = await response.json()
this.elements.update({ amount: newOrderResponse.data.attributes.total_minus_store_credits_cents })
resolve({ lineItems: this.buildLineItems(newOrderResponse) })
} else {
reject()
}
} else {
reject()
}
}
async handleFinalizePayment(ev) {
let shippingRateId = (ev.shippingRate?.id || this.currentShippingOptionId)
if (shippingRateId) {
shippingRateId = String(shippingRateId).replace(/_google_pay_\d+/, '')
}
if (this.shippingRequiredValue && (!shippingRateId || shippingRateId === 'loading')) {
ev.paymentFailed({ reason: 'invalid_shipping_address' })
return
}
if (this.giftCardCodeValue && this.giftCardAmountValue && this.checkoutValidateGiftCardDataPathValue) {
const giftCardValidationResponse = await fetch(
this.checkoutValidateGiftCardDataPathValue,
{
method: 'POST',
headers: {
'X-Spree-Order-Token': this.orderTokenValue,
'Content-Type': 'application/json'
},
body: JSON.stringify({
gift_card_code: this.giftCardCodeValue,
gift_card_amount: this.giftCardAmountValue
})
}
)
if (giftCardValidationResponse.status === 422) {
ev.paymentFailed()
return
}
}
const validationResponse = await fetch(
this.checkoutValidateOrderForPaymentPathValue,
{
method: 'POST',
headers: {
'X-Spree-Order-Token': this.orderTokenValue,
'Content-Type': 'application/json'
},
body: JSON.stringify({ skip_state: true })
}
)
if (validationResponse.status === 422) {
ev.paymentFailed()
return
}
// Confirm the PaymentIntent without handling potential next actions (yet).
const { error: confirmError } = await this.elements.submit()
if (confirmError) {
if (confirmError.length > 0) {
showFlashMessage(confirmError, 'error')
}
return
}
// we need to persist some information about the customer to move the order to the next state
const orderUpdatePayload = {
order: {
email: ev.billingDetails.email,
ship_address_attributes: this.ShipAddressAttributes(ev)
},
do_not_change_state: true
}
const updateResponse = await fetch(this.checkoutPathValue, {
method: 'PATCH',
headers: {
'X-Spree-Order-Token': this.orderTokenValue,
'Content-Type': 'application/json'
},
body: JSON.stringify(orderUpdatePayload)
})
if (updateResponse.status !== 200) {
ev.paymentFailed()
return
}
const advanceResponse = await fetch(this.checkoutAdvancePathValue, {
method: 'PATCH',
headers: {
'X-Spree-Order-Token': this.orderTokenValue,
'Content-Type': 'application/json'
},
body: JSON.stringify({
state: 'payment',
shipping_method_id: shippingRateId
})
})
if (advanceResponse.status !== 200) {
ev.paymentFailed()
return
}
try {
const { error: paymentMethodError, paymentMethod } = await this.stripe.createPaymentMethod({
elements: this.elements
})
if (paymentMethodError) {
showFlashMessage(paymentMethodError, 'error')
return
}
const { error } = await this.stripe.confirmPayment({
clientSecret: this.clientSecretValue,
confirmParams: {
payment_method: paymentMethod.id,
// Stripe will automatically add `payment_intent` and `payment_intent_client_secret` params
return_url: this.returnUrlValue
}
})
if (error?.length > 0) {
showFlashMessage(error, 'error')
}
} catch (e) {
console.log(e)
}
}
async handleCancelPayment(ev) {
const orderUpdatePayload = {
order: {
ship_address_id: 'CLEAR',
bill_address_id: 'CLEAR'
}
}
// reset shipping method for some cases when user select paid shipping method then reload page
// do not reset shipping method if we have only one or is multivendor order
let defaultShippingMethodId = this.shippingRates[0]?.attributes?.shipping_method_id
if (defaultShippingMethodId) {
defaultShippingMethodId = String(defaultShippingMethodId)
}
if (this.shippingRates?.length > 1 && this.currentShippingOptionId !== defaultShippingMethodId) {
// reset shipping choice
await fetch(this.checkoutSelectShippingMethodPathValue, {
method: 'PATCH',
headers: {
'X-Spree-Order-Token': this.orderTokenValue,
'Content-Type': 'application/json'
},
body: JSON.stringify({ shipping_method_id: defaultShippingMethodId })
})
}
// reset addresses
await fetch(this.checkoutPathValue, {
method: 'PATCH',
headers: {
'X-Spree-Order-Token': this.orderTokenValue,
'Content-Type': 'application/json'
},
body: JSON.stringify(orderUpdatePayload)
})
this.currentShippingOptionId = null
}
shippingOptions(shippingRates) {
return shippingRates.map((rate) => {
let id = String(rate.attributes.shipping_method_id)
if (this.paymentMethod === 'google_pay') {
// We need to add some random data to the shipping rate to avoid weird issue with Google Pay, in which it clears the shipping rates when a new address is added
id += `_google_pay_${Math.floor(Math.random() * 100)}`
}
return {
id: id, // shipping rates can be refreshed and removed, shipping methods are more reliable
displayName: rate.attributes.name,
deliveryEstimate: rate.attributes.display_delivery_range || '',
amount: parseInt(rate.attributes.final_price_cents)
}
})
}
multiVendorOrder(newOrderResponse) {
const vendorIds = newOrderResponse.included.filter((item) => item.type === 'vendor').map((vendor) => vendor.id)
return [...new Set(vendorIds)].length > 1
}
buildLineItems(newOrderResponse) {
return [
{ name: 'Subtotal', amount: newOrderResponse.data.attributes.subtotal_cents },
{ name: 'Shipping', amount: newOrderResponse.data.attributes.ship_total_cents },
this.buildStoreCreditLine(newOrderResponse),
this.buildDiscountLine(newOrderResponse),
this.buildTaxLine(newOrderResponse)
].filter((i) => i)
}
buildStoreCreditLine(newOrderResponse) {
const amount = newOrderResponse.data.attributes.store_credit_total_cents
if (amount > 0) {
return { name: 'Store credit', amount: -amount }
}
}
buildDiscountLine(newOrderResponse) {
const amount = newOrderResponse.data.attributes.promo_total_cents
if (amount > 0) {
return { name: 'Discount', amount: -amount }
}
}
buildTaxLine(newOrderResponse) {
const attributes = newOrderResponse.data.attributes
const isTaxIncluded = parseInt(attributes.included_tax_total) > 0
if (isTaxIncluded) return null
const amount = attributes.tax_total_cents
return { name: 'Tax', amount: amount }
}
ShipAddressAttributes(ev) {
if (ev.shippingAddress) {
return {
quick_checkout: true,
firstname: ev.shippingAddress.name.split(' ')[0],
lastname: ev.shippingAddress.name.split(' ')[1],
address1: ev.shippingAddress.address.line1,
address2: ev.shippingAddress.address.line2,
city: ev.shippingAddress.address.city,
zipcode: ev.shippingAddress.address.postal_code,
country_iso: ev.shippingAddress.address.country,
state_name: ev.shippingAddress.address.state,
phone: ev.billingDetails.phone
}
}
else {
return {
quick_checkout: true,
}
}
}
}