-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex-js.html
406 lines (352 loc) · 14.3 KB
/
index-js.html
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
---
---
<script src="https://js.stripe.com/v3/"></script>
<script type="module">
class TweVariationParamsParser {
static parse() {
const queryParams = new URLSearchParams(location.search);
const rawParams = queryParams.get('product');
const trial = queryParams.get('trial') ?? null;
if (!rawParams) {
throw new Error('MISSING_VARIATION_PARAMS');
}
try {
const { id, variation, title, qty } = JSON.parse(decodeURIComponent(rawParams));
return { id, variation, title, qty, trial };
} catch (e) {
console.error(e);
throw new Error('INVALID_VARIATION_PARAMS');
}
}
}
class TweCheckout {
constructor() {
this.stripeCard = null;
this.stripe = Stripe('pk_live_GWR9mWvess9zYZONfgf33YQC00lCa4JiRF');
this.elements = this.stripe.elements();
this.user = null;
this.userGeoData = {
currency: '',
price: '',
};
this.variationParams = TweVariationParamsParser.parse();
this.isTrial = this.variationParams.trial !== null && this.variationParams.trial > 0;
}
run() {
this.stripeCard = this.elements.create('card', { hidePostalCode: true });
this.stripeCard.mount('#payment-element');
this.initEvents();
this.buildSummary();
const event = new CustomEvent('checkout_initialized', {
bubbles: true,
cancelable: true,
});
document.dispatchEvent(event);
}
initEvents() {
document.getElementById('payment-form').addEventListener('submit', (e) => {
e.preventDefault();
this.submit();
});
document.addEventListener('dpl_loaded', (e) => {
this._loadGeodata();
this.user = e.detail;
if (this.user === null || !this.user.isLoggedIn) return;
document.getElementById('account-fields').remove();
document.getElementById('billing-email').value = this.user.email;
});
document.getElementById('validate-billing-btn').addEventListener('click', (e) => {
e.preventDefault();
e.stopImmediatePropagation();
const valid = this.validateBillingFields();
if (valid) {
const switchTargetSelector = e.target.getAttribute('data-switch-to');
this._switchTabTo(switchTargetSelector);
} else {
this._showToast('warning', 'Please correct the billing information.');
}
});
document.querySelectorAll('[data-switch-to]').forEach((el) => {
el.addEventListener('click', (e) => {
const switchTargetSelector = el.getAttribute('data-switch-to');
this._switchTabTo(switchTargetSelector);
});
});
// document.getElementById('apply-coupon-btn').addEventListener('click', (e) => {
// this._applyCoupon();
// });
if (this.variationParams.trial !== null && this.variationParams.trial > 0) {
document.querySelector('#trial-pay-info').style.display = 'block';
const placeOrderBtn = document.getElementById('submit');
placeOrderBtn.innerHTML = 'START TRIAL';
}
}
_loadGeodata() {
const symbols = {
USD: '$',
EUR: '€',
GBP: '£',
// 'INR': '₹'
};
fetch(`${CONFIG.docsApiUrl}/payments/stripe/geodata/?variationId=${this.variationParams.variation}`, {
method: 'GET',
credentials: 'include',
})
.then((response) => response.json())
.then((response) => {
this.userGeoData.currency = symbols[response.currency];
this.userGeoData.price = response.price.sale || response.price.regular;
document
.querySelectorAll('.currency-symbol')
.forEach((el) => (el.innerText = symbols[response.currency.toUpperCase()]));
document
.querySelectorAll('.product-price')
.forEach((el) => (el.innerText = (this.userGeoData.price * this.variationParams.qty).toFixed(2)));
document.getElementById('billing-country').value = response.countryCode.toUpperCase();
if (this.variationParams.trial !== null && this.variationParams.trial > 0) {
document.getElementById('summary-total').querySelector('.product-price').innerText = '0';
}
});
}
_switchTabTo(switchTargetSelector) {
const tabEl = document.querySelector(`[data-te-target="${switchTargetSelector}"]`);
const tab = new te.Tab(tabEl);
tab.show();
}
validateBillingFields() {
let valid = true;
document
.getElementById('pills-billing')
.querySelectorAll('input.required-field, select.required-field')
.forEach((input) => {
if (!input.value) {
valid = false;
input.parentElement.querySelectorAll('[data-te-input-notch-ref] div').forEach((el) => {
const style = el.getAttribute('style') || '';
el.setAttribute('style', style + 'border-color: #dc3545 !important;');
});
} else {
input.parentElement.querySelectorAll('[data-te-input-notch-ref] div').forEach((el) => {
const style = el.getAttribute('style') || '';
el.setAttribute('style', style.replace('border-color: #dc3545 !important;', ''));
});
}
});
return valid;
}
buildSummary() {
const itemsList = document.getElementById('summary-items-list');
const summarySubtotal = document.getElementById('summary-subtotal');
const summaryTotal = document.getElementById('summary-total');
const summaryTrial = document.getElementById('summary-trial');
const itemTemplate = document.createElement('template');
itemTemplate.innerHTML = `<li class="align-center flex justify-between border-0 px-0 pb-0">
<div class="product-name py-3">
${this.variationParams.title}
<strong class="product-quantity">× ${this.variationParams.qty}</strong>
</div>
<span class="flex items-center product-total">
<bdi>
<span class="currency-symbol">${this.userGeoData.currency}</span>
<span class="product-price">${Number(this.userGeoData.price * this.variationParams.qty).toFixed(
2
)}</span> 
<small class="text-muted product-billing" style="font-size: 16px">/ annual</small>
</bdi>
</span>
</li>`;
itemsList.prepend(itemTemplate.content);
summarySubtotal.querySelector('.product-price').innerHTML = Number(
this.userGeoData.price * this.variationParams.qty
).toFixed(2);
if (this.variationParams.trial !== null && this.variationParams.trial > 0) {
summaryTrial.style.display = 'block';
summaryTrial.querySelector('.trial-days').innerHTML = this.variationParams.trial;
summaryTotal.querySelector('.product-price').innerHTML = '0';
} else {
summaryTotal.querySelector('.product-price').innerHTML = Number(this.userGeoData.price).toFixed(2);
}
}
submit() {
const valid = this.validateBillingFields();
if (!valid) {
this._showToast('warning', 'Please correct the billing information.');
return this._switchTabTo('#pills-billing');
}
this._showLoader();
return this._createPaymentMethod()
.then((response) => this._createSubscription(response))
.then((response) => this._confirmCardPayment(response))
.then((result) => {
if (result.error) {
this._showToast('error', 'Something went wrong. Please try again.');
return console.error('result.error', result.error);
}
if (this.isTrial && result.status === 'succeeded') {
this._showToast('success', 'Your trial has started. You will be now redirected.');
location.href = '/billing/';
} else if (result.paymentIntent.status === 'succeeded') {
this._showToast('success', 'Your payment has succeeded. You will be now redirected.');
location.href = '/billing/';
} else {
this._showToast('warning', 'There might be some error. Please check your console for more info.');
}
console.log('success', result.paymentIntent.status);
})
.catch((err) => {
console.error('err', err);
this._showToast('error', err || 'Something went wrong. Please try again.');
})
.finally(() => this._hideLoader());
}
_showLoader() {
this.stripeCard.update({ disabled: true });
const icon = document.createElement('template');
icon.innerHTML = '<i class="spinner-border-sm spinner-border loading-icon ms-2 place-order-loader"></i>';
const placeOrderBtn = document.getElementById('submit');
placeOrderBtn.classList.add('disabled');
placeOrderBtn.setAttribute('disabled', 'disabled');
placeOrderBtn.appendChild(icon.content);
document
.getElementById('pills-billing')
.querySelectorAll('input, select')
.forEach((input) => {
input.classList.add('disabled');
input.setAttribute('disabled', 'disabled');
});
}
_hideLoader() {
this.stripeCard.update({ disabled: false });
document.querySelector('i.place-order-loader').remove();
const placeOrderBtn = document.getElementById('submit');
placeOrderBtn.classList.remove('disabled');
placeOrderBtn.removeAttribute('disabled');
document
.getElementById('pills-billing')
.querySelectorAll('input, select')
.forEach((input) => {
input.classList.remove('disabled');
input.removeAttribute('disabled');
});
}
_showToast(color, body) {
const toastId =
color === 'success'
? 'toast-success'
: color === 'warning'
? 'toast-warning'
: color === 'error'
? 'toast-danger'
: '';
const toastEl = document.getElementById(toastId);
toastEl.querySelector('.toast-body').innerText = body;
const toast = te.Toast.getOrCreateInstance(toastEl);
toast.show();
}
_createPaymentMethod() {
return this.stripe.createPaymentMethod({
type: 'card',
card: this.stripeCard,
});
}
_createSubscription(paymentMethodResponse) {
const response = paymentMethodResponse;
return new Promise((resolve, reject) => {
this.paymentMethodId = response.paymentMethod.id;
const billing = {
email: document.getElementById('billing-email').value,
country: document.getElementById('billing-country').value,
};
let account;
if (!this.user) {
account = {
firstName: document.getElementById('account-first-name').value,
username: document.getElementById('account-username').value,
password: document.getElementById('account-password').value,
repeatPassword: document.getElementById('account-repeat-password').value,
};
}
// const coupon = document.getElementById('billing-coupon-code').value;
const endpoint = this.isTrial ? '/payments/stripe/dd/trial' : '/payments/stripe/dd/subscription';
fetch(`${CONFIG.docsApiUrl}${endpoint}`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
productId: this.variationParams.id,
variationId: this.variationParams.variation,
paymentMethodId: this.paymentMethodId,
billing,
account,
trialDays: this.isTrial ? this.variationParams.trial : null,
// ...!!coupon && { coupon }
}),
credentials: 'include',
})
.then((response) => response.json())
.then((response) => resolve(response))
.catch((error) => reject(error));
});
}
_confirmCardPayment(response) {
if (this.isTrial) {
return { status: 'succeeded' };
}
const clientSecret = response.clientSecret;
return this.stripe.confirmCardPayment(clientSecret, {
payment_method: this.paymentMethodId,
});
}
_applyCoupon() {
const couponCode = document.getElementById('coupon_code').value;
if (!couponCode) {
return;
}
fetch(
`${CONFIG.appsApiUrl}/payments/stripe/coupon/${couponCode}/${this.variationParams.id}/${this.variationParams.variation}`,
{
method: 'GET',
credentials: 'include',
}
)
.then((response) => response.json())
.then((response) => {
const coupon = response.coupon;
if (
coupon &&
coupon.metadata &&
coupon.metadata.product_id === this.variationParams.id &&
coupon.metadata.variation_id === this.variationParams.variation
) {
this._calculateDiscountAndShow(coupon);
} else {
this._showToast('error', response.message);
}
})
.catch((error) => this._showToast('error', error));
}
_calculateDiscountAndShow(coupon) {
const percentOff = coupon.percent_off / 100;
const couponAmount = (Number(this.userGeoData.price) * percentOff).toFixed(2);
const newPrice = (Number(this.userGeoData.price) - Number(this.userGeoData.price) * percentOff).toFixed(2);
const couponCodeField = document.getElementById('summary-coupon-code');
const summarySubtotal = document.getElementById('summary-subtotal');
const summaryTotal = document.getElementById('summary-total');
const couponHTML = `<li class="list-group-item d-flex justify-content-between align-items-center border-0 px-0 pb-0">
<div class="coupon-applied">
Coupon: <strong class="coupon-id">${coupon.id}</strong>
</div>
<span class="product-coupon">
<bdi><span class="currency-symbol">- ${this.userGeoData.currency}</span><span class="product-price">${couponAmount}</span></bdi>
</span>
</li>`;
couponCodeField.insertAdjacentHTML('beforebegin', couponHTML);
couponCodeField.classList.add('d-none');
summarySubtotal.querySelector('.product-price').innerHTML = newPrice;
summaryTotal.querySelector('.product-price').innerHTML = newPrice;
}
}
const p = new TweCheckout();
p.run();
</script>