forked from stripe-archive/stripe-payments-demo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpayments.js
579 lines (534 loc) · 20 KB
/
payments.js
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
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
/**
* payments.js
* Stripe Payments Demo. Created by Romain Huet (@romainhuet).
*
* This modern JavaScript file handles the checkout process using Stripe.
*
* 1. It shows how to accept card payments with the `card` Element, and
* the `paymentRequestButton` Element for Payment Request and Apple Pay.
* 2. It shows how to use the Stripe Sources API to accept non-card payments,
* such as iDEAL, SOFORT, SEPA Direct Debit, and more.
*/
(async () => {
'use strict';
// Retrieve the configuration for the store.
const config = await store.getConfig();
// Create references to the main form and its submit button.
const form = document.getElementById('payment-form');
const submitButton = form.querySelector('button[type=submit]');
/**
* Setup Stripe Elements.
*/
// Create a Stripe client.
const stripe = Stripe(config.stripePublishableKey);
// Create an instance of Elements.
const elements = stripe.elements();
/**
* Implement a Stripe Card Element that matches the look-and-feel of the app.
*
* This makes it easy to collect debit and credit card payments information.
*/
// Create a Card Element and pass some custom styles to it.
const card = elements.create('card', {
style: {
base: {
iconColor: '#666ee8',
color: '#31325f',
fontWeight: 400,
fontFamily:
'-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen-Sans, Ubuntu, Cantarell, "Helvetica Neue", sans-serif',
fontSmoothing: 'antialiased',
fontSize: '15px',
'::placeholder': {
color: '#aab7c4',
},
':-webkit-autofill': {
color: '#666ee8',
},
},
},
});
// Mount the Card Element on the page.
card.mount('#card-element');
// Monitor change events on the Card Element to display any errors.
card.addEventListener('change', ({error}) => {
const cardErrors = document.getElementById('card-errors');
cardErrors.textContent = error ? error.message : '';
cardErrors.classList.toggle('visible', error);
// Reenable the Pay button.
submitButton.disabled = false;
});
/**
* Implement a Stripe Payment Request Button Element.
*
* This automatically supports the Payment Request API (already live on Chrome),
* as well as Apple Pay on the Web on Safari.
* When of these two options is available, this element adds a “Pay” button on top
* of the page to let users pay in just a click (or a tap on mobile).
*/
// Make sure all data is loaded from the store to compute the order amount.
await store.loadProducts();
// Create the payment request.
const paymentRequest = stripe.paymentRequest({
country: config.stripeCountry,
currency: config.currency,
total: {
label: 'Total',
amount: store.getOrderTotal(),
},
requestShipping: true,
requestPayerEmail: true,
shippingOptions: [
{
id: 'free',
label: 'Free Shipping',
detail: 'Delivery within 5 days',
amount: 0,
},
],
});
// Callback when a source is created.
paymentRequest.on('source', async event => {
try {
// Create the order using the email and shipping information from the Payment Request callback.
const order = await store.createOrder(
config.currency,
store.getOrderItems(),
event.payerEmail,
{
name: event.payerName,
address: {
line1: event.shippingAddress.addressLine[0],
city: event.shippingAddress.city,
country: event.shippingAddress.country,
postal_code: event.shippingAddress.postalCode,
state: event.shippingAddress.region,
},
}
);
// Complete the order using the payment source generated by Payment Request.
//await completePayment(order, event.source);
await handleOrder(order, event.source);
event.complete('success');
} catch (error) {
event.complete('fail');
}
});
// Callback when the shipping address is updated.
paymentRequest.on('shippingaddresschange', event => {
event.updateWith({status: 'success'});
});
// Create the Payment Request Button.
const paymentRequestButton = elements.create('paymentRequestButton', {
paymentRequest,
});
// Check if the Payment Request is available (or Apple Pay on the Web).
const paymentRequestSupport = await paymentRequest.canMakePayment();
if (paymentRequestSupport) {
// Display the Pay button by mounting the Element in the DOM.
paymentRequestButton.mount('#payment-request-button');
// Replace the instruction.
document.querySelector('.instruction').innerText =
'Or enter your shipping and payment details below';
// Show the payment request section.
document.getElementById('payment-request').classList.add('visible');
}
/**
* Handle the form submission.
*
* This creates an order and either sends the card information from the Element
* alongside it, or creates a Source and start a redirect to complete the purchase.
*
* Please note this form is not submitted when the user chooses the "Pay" button
* or Apple Pay since they provide name and shipping information directly.
*/
// Listen to changes to the user-selected country.
form
.querySelector('select[name=country]')
.addEventListener('change', event => {
event.preventDefault();
const country = event.target.value;
const zipLabel = form.querySelector('label.zip');
// Only show the state input for the United States.
zipLabel.parentElement.classList.toggle('with-state', country === 'US');
// Update the ZIP label to make it more relevant for each country.
form.querySelector('label.zip span').innerText =
country === 'US'
? 'ZIP'
: country === 'UK' ? 'Postcode' : 'Postal Code';
event.target.parentElement.className = `field ${country}`;
showRelevantPaymentMethods(country);
});
// Submit handler for our payment form.
form.addEventListener('submit', async event => {
event.preventDefault();
// Retrieve the user information from the form.
const payment = form.querySelector('input[name=payment]:checked').value;
const name = form.querySelector('input[name=name]').value;
const country = form.querySelector('select[name=country] option:checked')
.value;
const email = form.querySelector('input[name=email]').value;
const shipping = {
name,
address: {
line1: form.querySelector('input[name=address]').value,
city: form.querySelector('input[name=city]').value,
postal_code: form.querySelector('input[name=postal_code]').value,
state: form.querySelector('input[name=state]').value,
country,
},
};
// Disable the Pay button to prevent multiple click events.
submitButton.disabled = true;
// Create the order using the email and shipping information from the form.
const order = await store.createOrder(
config.currency,
store.getOrderItems(),
email,
shipping
);
if (payment === 'card') {
// Create a Stripe source from the card information and the owner name.
const {source} = await stripe.createSource(card, {
owner: {
name,
},
});
await handleOrder(order, source);
} else {
// Prepare all the Stripe source common data.
const sourceData = {
type: payment,
amount: order.amount,
currency: order.currency,
owner: {
name,
email,
},
redirect: {
return_url: window.location.href,
},
statement_descriptor: 'Stripe Payments Demo',
metadata: {
order: order.id,
},
};
// Add extra source information which are specific to a payment method.
switch (payment) {
case 'sepa_debit':
// SEPA Debit: Pass the IBAN entered by the user.
sourceData.sepa_debit = {
iban: form.querySelector('input[name=iban]').value,
};
break;
case 'sofort':
// SOFORT: The country is required before redirecting to the bank.
sourceData.sofort = {
country,
};
break;
}
// Create a Stripe source with the common data and extra information.
const {source} = await stripe.createSource(sourceData);
await handleOrder(order, source);
}
});
// Handle the order and source activation if required
const handleOrder = async (order, source) => {
const mainElement = document.getElementById('main');
const confirmationElement = document.getElementById('confirmation');
switch (order.metadata.status) {
case 'created':
switch (source.status) {
case 'chargeable':
submitButton.textContent = 'Processing Payment…';
const response = await store.payOrder(order, source);
await handleOrder(response.order, response.source);
break;
case 'pending':
switch (source.flow) {
case 'none':
// Normally, sources with a `flow` value of `none` are chargeable right away,
// but there are exceptions, for instance for WeChat QR codes just below.
if (source.type === 'wechat') {
// Display the QR code.
const qrCode = new QRCode('wechat-qrcode', {
text: source.wechat.qr_code_url,
width: 128,
height: 128,
colorDark: '#424770',
colorLight: '#f8fbfd',
correctLevel: QRCode.CorrectLevel.H,
});
// Hide the previous text and update the call to action.
form.querySelector('.payment-info.wechat p').style.display =
'none';
let amount = store.formatPrice(
store.getOrderTotal(),
config.currency
);
submitButton.textContent = `Scan this QR code on WeChat to pay ${amount}`;
// Start polling the order status.
pollOrderStatus(order.id, 300000);
} else {
console.log('Unhandled none flow.', source);
}
break;
case 'redirect':
// Immediately redirect the customer.
submitButton.textContent = 'Redirecting…';
window.location.replace(source.redirect.url);
break;
case 'code_verification':
// Display a code verification input to verify the source.
break;
case 'receiver':
// Display the receiver address to send the funds to.
mainElement.classList.add('success', 'receiver');
const receiverInfo = confirmationElement.querySelector(
'.receiver .info'
);
if (source.type === 'multibanco') {
// Display the Multibanco payment information to the user.
let amount = store.formatPrice(
source.amount,
config.currency
);
receiverInfo.innerHTML = `
<ul>
<li>
Amount (Montante):
<strong>${amount}</strong>
</li>
<li>
Entity (Entidade):
<strong>${source.multibanco.entity}</strong>
</li>
<li>
Reference (Referencia):
<strong>${source.multibanco.reference}</strong>
</li>
</ul>`;
// Poll the backend and check for an order status.
// The backend updates the status upon receiving webhooks,
// specifically the `source.chargeable` and `charge.succeeded` events.
pollOrderStatus(order.id);
} else {
console.log('Unhandled receiver flow.', source);
}
break;
default:
// Order is received, pending payment confirmation.
break;
}
break;
case 'failed':
case 'canceled':
// Authentication failed, offer to select another payment method.
break;
default:
// Order is received, pending payment confirmation.
break;
}
break;
case 'pending':
// Success! Now waiting for payment confirmation. Update the interface to display the confirmation screen.
mainElement.classList.remove('processing');
// Update the note about receipt and shipping (the payment is not yet confirmed by the bank).
confirmationElement.querySelector('.note').innerText =
'We’ll send your receipt and ship your items as soon as your payment is confirmed.';
mainElement.classList.add('success');
break;
case 'failed':
// Payment for the order has failed.
mainElement.classList.remove('success');
mainElement.classList.remove('processing');
mainElement.classList.remove('receiver');
mainElement.classList.add('error');
break;
case 'paid':
// Success! Payment is confirmed. Update the interface to display the confirmation screen.
mainElement.classList.remove('processing');
mainElement.classList.remove('receiver');
// Update the note about receipt and shipping (the payment has been fully confirmed by the bank).
confirmationElement.querySelector('.note').innerText =
'We just sent your receipt to your email address, and your items will be on their way shortly.';
mainElement.classList.add('success');
break;
}
};
/**
* Monitor the status of a source after a redirect flow.
*
* This means there is a `source` parameter in the URL, and an active order.
* When this happens, we'll monitor the status of the order and present real-time
* information to the user.
*/
const pollOrderStatus = async (
orderId,
timeout = 30000,
interval = 500,
start = null
) => {
start = start ? start : Date.now();
const endStates = ['paid', 'failed'];
// Retrieve the latest order status.
const order = await store.getOrderStatus(orderId);
await handleOrder(order, {status: null});
if (
!endStates.includes(order.metadata.status) &&
Date.now() < start + timeout
) {
// Not done yet. Let's wait and check again.
setTimeout(pollOrderStatus, interval, orderId, timeout, interval, start);
} else {
if (!endStates.includes(order.metadata.status)) {
// Status has not changed yet. Let's time out.
console.warn(new Error('Polling timed out.'));
}
}
};
const orderId = store.getActiveOrderId();
const mainElement = document.getElementById('main');
if (orderId && window.location.search.includes('source')) {
// Update the interface to display the processing screen.
mainElement.classList.add('success', 'processing');
// Poll the backend and check for an order status.
// The backend updates the status upon receiving webhooks,
// specifically the `source.chargeable` and `charge.succeeded` events.
pollOrderStatus(orderId);
} else {
// Update the interface to display the checkout form.
mainElement.classList.add('checkout');
}
/**
* Display the relevant payment methods for a selected country.
*/
// List of relevant countries for the payment methods supported in this demo.
// Read the Stripe guide: https://stripe.com/payments/payment-methods-guide
const paymentMethods = {
alipay: {
name: 'Alipay',
flow: 'redirect',
countries: ['CN', 'HK', 'SG'],
},
bancontact: {
name: 'Bancontact',
flow: 'redirect',
countries: ['BE'],
},
card: {
name: 'Card',
flow: 'none',
},
eps: {
name: 'EPS',
flow: 'redirect',
countries: ['AT'],
},
ideal: {
name: 'iDEAL',
flow: 'redirect',
countries: ['NL'],
},
giropay: {
name: 'Giropay',
flow: 'redirect',
countries: ['DE'],
},
multibanco: {
name: 'Multibanco',
flow: 'receiver',
countries: ['PT'],
},
sepa_debit: {
name: 'SEPA Direct Debit',
flow: 'none',
countries: ['FR', 'DE', 'ES', 'BE', 'NL', 'LU', 'IT', 'PT', 'AT', 'IE'],
},
sofort: {
name: 'SOFORT',
flow: 'redirect',
countries: ['DE', 'AT'],
},
wechat: {
name: 'WeChat',
flow: 'none',
countries: ['CN', 'HK', 'SG'],
},
};
// Update the main button to reflect the payment method being selected.
const updateButtonLabel = paymentMethod => {
let amount = store.formatPrice(store.getOrderTotal(), config.currency);
let name = paymentMethods[paymentMethod].name;
let label = `Pay ${amount}`;
if (paymentMethod !== 'card') {
label = `Pay ${amount} with ${name}`;
}
if (paymentMethod === 'wechat') {
label = `Generate QR code to pay ${amount} with ${name}`;
}
submitButton.innerText = label;
};
// Show only the payment methods that are relevant to the selected country.
const showRelevantPaymentMethods = country => {
if (!country) {
country = form.querySelector('select[name=country] option:checked').value;
}
const paymentInputs = form.querySelectorAll('input[name=payment]');
for (let i = 0; i < paymentInputs.length; i++) {
let input = paymentInputs[i];
input.parentElement.classList.toggle(
'visible',
input.value === 'card' ||
paymentMethods[input.value].countries.includes(country)
);
}
// Hide the tabs if card is the only available option.
const paymentMethodsTabs = document.getElementById('payment-methods');
paymentMethodsTabs.classList.toggle(
'visible',
paymentMethodsTabs.querySelectorAll('li.visible').length > 1
);
// Check the first payment option again.
paymentInputs[0].checked = 'checked';
form.querySelector('.payment-info.card').classList.add('visible');
form.querySelector('.payment-info.sepa_debit').classList.remove('visible');
form.querySelector('.payment-info.wechat').classList.remove('visible');
form.querySelector('.payment-info.redirect').classList.remove('visible');
updateButtonLabel(paymentInputs[0].value);
};
// Listen to changes to the payment method selector.
for (let input of document.querySelectorAll('input[name=payment]')) {
input.addEventListener('change', event => {
event.preventDefault();
const payment = form.querySelector('input[name=payment]:checked').value;
const flow = paymentMethods[payment].flow;
// Update button label.
updateButtonLabel(event.target.value);
// Show the relevant details, whether it's an extra element or extra information for the user.
form
.querySelector('.payment-info.card')
.classList.toggle('visible', payment === 'card');
form
.querySelector('.payment-info.sepa_debit')
.classList.toggle('visible', payment === 'sepa_debit');
form
.querySelector('.payment-info.wechat')
.classList.toggle('visible', payment === 'wechat');
form
.querySelector('.payment-info.redirect')
.classList.toggle('visible', flow === 'redirect');
form
.querySelector('.payment-info.receiver')
.classList.toggle('visible', flow === 'receiver');
});
}
// Select the default country from the config on page load.
const countrySelector = document.getElementById('country');
countrySelector.querySelector(`option[value=${config.country}]`).selected =
'selected';
countrySelector.className = `field ${config.country}`;
// Trigger the method to show relevant payment methods on page load.
showRelevantPaymentMethods();
})();