-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
631 lines (584 loc) · 29.4 KB
/
index.js
File metadata and controls
631 lines (584 loc) · 29.4 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
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
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
/** @type {import('iaptic-js').IapticStripe} */
const iaptic = IapticJS.createAdapter(window.IAPTIC_STRIPE_CREDENTIALS);
function showMessage(type) {
const container = document.getElementById('message-container');
if (type === 'success') {
container.innerHTML = `
<div class="alert alert-success" role="alert">
<h4 class="alert-title">Payment successful</h4>
<div class="text-muted">
Thank you for your subscription!
</div>
</div>
`;
} else if (type === 'cancel') {
container.innerHTML = `
<div class="alert alert-warning" role="alert">
<h4 class="alert-title">Payment canceled</h4>
<div class="text-muted">The payment process was canceled.</div>
</div>
`;
} else if (type === 'success-plan-change') {
container.innerHTML = `
<div class="alert alert-success" role="alert">
<h4 class="alert-title">Plan changed successfully</h4>
<div class="text-muted">
Your subscription has been updated to the new plan.
</div>
</div>
`;
} else if (type === 'error-plan-change') {
container.innerHTML = `
<div class="alert alert-danger" role="alert">
<h4 class="alert-title">Failed to change plan</h4>
<div class="text-muted">
There was an error updating your subscription. Please try again or contact support.
</div>
</div>
`;
}
container.scrollIntoView({ behavior: 'smooth' });
}
function displaySubscriptionDetails(products, purchases) {
const container = document.getElementById('subscription-container');
if (!container) return;
if (purchases && purchases.length > 0) {
const subscriptions = purchases.filter(p => p.renewalIntent && p.expirationDate);
const purchase = subscriptions.find(p => !p.cancelationReason) || subscriptions[0];
// If no subscriptions found, these are one-time purchases only
if (!purchase) {
container.innerHTML = `
<div class="card">
<div class="card-header">
<h3 class="card-title">Your Purchases</h3>
</div>
<div class="card-body">
${purchases.map(p => {
const productId = p.productId.replace('stripe:', '');
const product = products?.find(pr => pr.id === productId);
const purchaseDate = new Date(p.purchaseDate).toLocaleDateString();
return `
<div class="card mb-3">
<div class="card-body">
<table class="table table-sm mb-0">
<tr>
<td class="text-muted">Product:</td>
<td>${product?.title || productId}</td>
</tr>
${product?.description ? `
<tr>
<td class="text-muted">Description:</td>
<td>${product.description}</td>
</tr>
` : ''}
<tr>
<td class="text-muted">Amount:</td>
<td>${IapticJS.Utils.formatCurrency(p.amountMicros, p.currency)}</td>
</tr>
<tr>
<td class="text-muted">Purchase Date:</td>
<td>${purchaseDate}</td>
</tr>
<tr>
<td class="text-muted">Status:</td>
<td><span class="badge bg-success-lt">Purchased</span></td>
</tr>
</table>
</div>
</div>
`;
}).join('')}
</div>
</div>
`;
return;
}
const startDate = new Date(purchase.purchaseDate).toLocaleDateString();
const lastRenewal = new Date(purchase.lastRenewalDate).toLocaleDateString();
const nextRenewal = new Date(purchase.expirationDate).toLocaleDateString();
// Find the corresponding product
const productId = purchase.productId.replace('stripe:', '');
const product = products?.find(p => p.id === productId);
const offer = product?.offers.find(o => o.id === purchase.offerId);
container.innerHTML = `
<div class="card">
<div class="card-header">
<h3 class="card-title">Current Subscription</h3>
</div>
<div class="card-body">
<table class="table table-sm">
<tr>
<td class="text-muted">Plan:</td>
<td>${product?.title || 'Subscription'}</td>
</tr>
${product?.description ? `
<tr>
<td class="text-muted">Description:</td>
<td>${product.description}</td>
</tr>
` : ''}
<tr>
<td class="text-muted">Amount:</td>
<td>${IapticJS.Utils.formatCurrency(purchase.amountMicros, purchase.currency)}</td>
</tr>
<tr>
<td class="text-muted">Billing Period:</td>
<td>${offer && product.type === 'paid subscription' ? IapticJS.Utils.formatBillingPeriodEN(offer.pricingPhases.slice(-1)[0].billingPeriod) : 'Recurring'}</td>
</tr>
<tr>
<td class="text-muted">Status:</td>
<td>
${purchase.cancelationReason
? '<span class="badge bg-danger-lt">Cancelled</span>'
: purchase.renewalIntent === 'Renew'
? '<span class="badge bg-success-lt">Active</span>'
: '<span class="badge bg-warning-lt">Canceling</span>'
}
</td>
</tr>
<tr>
<td class="text-muted">Start Date:</td>
<td>${startDate}</td>
</tr>
<tr>
<td class="text-muted">Last Renewal:</td>
<td>${lastRenewal}</td>
</tr>
<tr>
<td class="text-muted">Next Renewal:</td>
<td>${nextRenewal}</td>
</tr>
${purchase.isTrialPeriod ? `
<tr>
<td class="text-muted">Trial Period:</td>
<td><span class="badge bg-info-lt">Yes</span></td>
</tr>
` : ''}
</table>
<div class="mt-4">
<h4>Change Plan</h4>
<div class="row g-3">
${products
?.filter(product => {
// Only keep subscription products
if (product.type !== 'paid subscription') return false;
// Only keep products with matching currency offers
const hasMatchingOffers = product.offers.some(offer =>
offer.pricingPhases.slice(-1)[0].currency.toLowerCase() === purchase.currency.toLowerCase()
);
// Keep if it's purchasable or if it's the current plan
return (hasMatchingOffers && product.metadata?.canPurchase !== 'false') ||
product.id === productId;
})
// Sort by monthly USD price
.sort((a, b) => {
const getMonthlyPrice = (product) => {
const monthlyOffer = product.offers.find(o =>
o.pricingPhases.slice(-1)[0].currency.toLowerCase() === 'usd' &&
o.pricingPhases.slice(-1)[0].billingPeriod.includes('M')
);
return monthlyOffer ? monthlyOffer.pricingPhases.slice(-1)[0].priceMicros : 0;
};
return getMonthlyPrice(a) - getMonthlyPrice(b);
})
.map(product => {
const isCurrentPlan = product.id === productId;
const matchingOffers = product.offers.filter(offer =>
offer.pricingPhases.slice(-1)[0].currency.toLowerCase() === purchase.currency.toLowerCase()
);
if (matchingOffers.length === 0) return '';
const hasCurrentOffer = matchingOffers.some(o => o.id === purchase.offerId);
// Sort offers by billing period (monthly first)
const sortedOffers = matchingOffers.sort((a, b) => {
const aIsMonthly = a.pricingPhases.slice(-1)[0].billingPeriod.includes('M');
const bIsMonthly = b.pricingPhases.slice(-1)[0].billingPeriod.includes('M');
return aIsMonthly ? -1 : 1;
});
const isCurrentOfferCancelled = purchase.cancelationReason;
return `
<div class="col-3">
<div class="card h-100 ${hasCurrentOffer ? 'bg-primary-lt' : ''}">
<div class="card-body">
<div class="text-center mb-3">
<h5 class="mb-1">${product.title}</h5>
<div class="text-muted small">
${product.description || ''}
</div>
</div>
<div class="text-center mb-3">
<div class="mb-1">
<span class="badge bg-blue-lt">
${product.metadata?.quota || 0} requests/month
</span>
</div>
<div>
<span class="badge bg-purple-lt">
${getSupportLevelLabel(product.metadata?.supportLevel)}
</span>
</div>
</div>
<div class="pricing-options">
${sortedOffers.map(offer => {
const phase = offer.pricingPhases.slice(-1)[0];
const isCurrentOffer = offer.id === purchase.offerId;
const period = IapticJS.Utils.formatBillingPeriodEN(phase.billingPeriod).toLowerCase();
return `
<div class="mb-2 text-center">
<div class="h4 mb-1">
${IapticJS.Utils.formatCurrency(phase.priceMicros, phase.currency)}
<small class="text-muted">/${period}</small>
</div>
${isCurrentOffer
? isCurrentOfferCancelled
? `<button class="btn btn-primary btn-sm"
onclick="handlePlanChange('${offer.id}')">
Renew
</button>`
: '<span class="badge bg-primary-lt">Current Plan</span>'
: `<button class="btn btn-primary btn-sm"
onclick="handlePlanChange('${offer.id}')">
Switch to ${period}
</button>`
}
</div>
`;
}).join('')}
</div>
</div>
</div>
</div>
`;
}).join('')}
</div>
</div>
<div class="mt-3">
<button class="btn btn-sm"
data-bs-toggle="collapse"
data-bs-target="#technicalDetails"
aria-expanded="false">
<span class="text-muted">Show technical details...</span>
</button>
<div class="collapse mt-3" id="technicalDetails">
<div class="card card-body bg-light">
<table class="table table-sm">
<tr>
<td class="text-muted">Purchase ID:</td>
<td><code>${purchase.purchaseId}</code></td>
</tr>
<tr>
<td class="text-muted">Transaction ID:</td>
<td><code>${purchase.transactionId}</code></td>
</tr>
<tr>
<td class="text-muted">Product ID:</td>
<td><code>${purchase.productId}</code></td>
</tr>
<tr>
<td class="text-muted">Offer ID:</td>
<td><code>${purchase.offerId || 'N/A'}</code></td>
</tr>
</table>
<div class="mt-3">
<button class="btn btn-sm"
data-bs-toggle="collapse"
data-bs-target="#rawJson"
aria-expanded="false">
<span class="text-muted">Show raw JSON...</span>
</button>
<div class="collapse mt-2" id="rawJson">
<pre class="bg-dark text-light p-3 rounded"><code>${JSON.stringify(purchase, null, 2)}</code></pre>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
`;
} else {
container.innerHTML = ''; // Clear the container if no subscription
}
}
function showLoadingSpinner(containerId) {
const container = document.getElementById(containerId);
if (!container) return;
container.innerHTML = `
<div class="text-center p-4">
<div class="spinner-border text-primary" role="status"></div>
<div class="text-muted mt-2">Loading...</div>
</div>
`;
}
/** @returns {Purchase[]} */
async function displayPurchases() {
const container = document.getElementById('subscription-container');
if (!container) return [];
showLoadingSpinner('subscription-container');
try {
const purchases = await iaptic.getPurchases();
if (purchases && purchases.length > 0) {
displaySubscriptionDetails(await iaptic.getProducts(), purchases);
} else {
container.innerHTML = ''; // Clear the container if no subscription
}
return purchases;
} catch (error) {
// Silently fail if no purchases found
console.log('No active purchases found:', error);
container.innerHTML = '';
return [];
}
}
async function checkUrlHash() {
const hash = window.location.hash.substring(1);
if (hash === 'success') {
showMessage('success');
history.replaceState(null, '', window.location.pathname);
} else if (hash === 'cancel') {
showMessage('cancel');
history.replaceState(null, '', window.location.pathname);
} else if (hash === 'success-plan-change') {
showMessage('success-plan-change');
history.replaceState(null, '', window.location.pathname);
} else if (hash === 'cancel-plan-change') {
showMessage('cancel-plan-change');
history.replaceState(null, '', window.location.pathname);
}
}
function getSupportLevelLabel(level) {
switch (level) {
case '0': return 'Basic Support';
case '1': return 'Email Support';
case '2': return 'Personalized Support';
default: return 'Support';
}
}
async function displayPrices(purchases) {
const subscriptionContainer = document.getElementById('pricing-container');
const onetimeContainer = document.getElementById('onetime-container');
if (!subscriptionContainer || !onetimeContainer) return;
showLoadingSpinner('pricing-container');
showLoadingSpinner('onetime-container');
try {
const products = await iaptic.getProducts();
// Refresh subscription details now that we have product information
const hasActiveSubscription = purchases && purchases.some(p => p.renewalIntent && p.expirationDate);
displaySubscriptionDetails(products, purchases);
// Clear both containers
subscriptionContainer.innerHTML = '';
onetimeContainer.innerHTML = '';
// Split products by type
const subscriptionProducts = products.filter(p =>
p.type === 'paid subscription' && p.metadata?.canPurchase !== 'false'
);
const otherProducts = products.filter(p =>
(p.type === 'non_consumable' || p.type === 'consumable') &&
p.metadata?.canPurchase !== 'false'
);
if (hasActiveSubscription) {
subscriptionContainer.innerHTML = `
<div class="text-center">
<button class="btn btn-primary" onclick="handleManageSubscription()">
Manage Subscription
</button>
</div>
`;
} else if (subscriptionProducts.length > 0) {
subscriptionContainer.innerHTML = `
<h3 class="mb-3">Subscription Plans</h3>
<div class="row w-100 g-3">
${renderSubscriptionProducts(subscriptionProducts)}
</div>
`;
}
if (otherProducts.length > 0) {
onetimeContainer.innerHTML = `
<h3 class="mb-3">One-time Purchases</h3>
<div class="row w-100 g-3">
${renderOtherProducts(otherProducts)}
</div>
`;
}
} catch (error) {
console.error('Error loading prices:', error);
}
}
// Helper function to render subscription products
function renderSubscriptionProducts(products) {
return products
// Sort by monthly USD price
.sort((a, b) => {
const getMonthlyPrice = (product) => {
const monthlyOffer = product.offers.find(o =>
o.pricingPhases.slice(-1)[0].currency.toLowerCase() === 'usd' &&
o.pricingPhases.slice(-1)[0].billingPeriod.includes('M')
);
return monthlyOffer ? monthlyOffer.pricingPhases.slice(-1)[0].priceMicros : 0;
};
return getMonthlyPrice(a) - getMonthlyPrice(b);
})
.map(product => {
// Sort offers by billing period (monthly first)
const sortedOffers = product.offers.sort((a, b) => {
const aIsMonthly = a.pricingPhases.slice(-1)[0].billingPeriod.includes('M');
const bIsMonthly = b.pricingPhases.slice(-1)[0].billingPeriod.includes('M');
return aIsMonthly ? -1 : 1;
});
return `
<div class="col-3">
<div class="card h-100">
<div class="card-body">
<div class="text-center mb-3">
<h5 class="mb-1">${product.title}</h5>
<div class="text-muted small">
${product.description || ''}
</div>
</div>
<div class="text-center mb-3">
${product.metadata?.quota ? `
<div class="mb-1">
<span class="badge bg-blue-lt">
${product.metadata.quota} requests/month
</span>
</div>
` : ''}
${product.metadata?.supportLevel ? `
<div>
<span class="badge bg-purple-lt">
${getSupportLevelLabel(product.metadata.supportLevel)}
</span>
</div>
` : ''}
</div>
<div class="pricing-options">
${renderSubscriptionOffers(sortedOffers)}
</div>
</div>
</div>
</div>
`;
}).join('');
}
// Helper function to render other products (non-subscription)
function renderOtherProducts(products) {
return products.map(product => {
const offer = product.offers[0]; // Usually only one offer for non-subscription products
const phase = offer?.pricingPhases.slice(-1)[0];
return `
<div class="col-3">
<div class="card h-100">
<div class="card-body">
<div class="text-center mb-3">
<h5 class="mb-1">${product.title}</h5>
<div class="text-muted small">
${product.description || ''}
</div>
</div>
${product.metadata?.quota ? `
<div class="text-center mb-3">
<span class="badge bg-blue-lt">
${product.metadata.quota} requests
</span>
</div>
` : ''}
<div class="text-center">
<div class="h4 mb-3">
${phase ? IapticJS.Utils.formatCurrency(phase.priceMicros, phase.currency) : 'Free'}
</div>
<button class="btn btn-primary"
onclick="handlePurchase('${offer?.id}')">
Purchase
</button>
</div>
</div>
</div>
</div>
`;
}).join('');
}
// Helper function to render subscription offers
function renderSubscriptionOffers(offers) {
return offers.map(offer => {
const phase = offer.pricingPhases.slice(-1)[0];
const period = IapticJS.Utils.formatBillingPeriodEN(phase.billingPeriod).toLowerCase();
const isFree = phase.priceMicros === 0;
return `
<div class="mb-2 text-center">
<div class="h4 mb-1">
${IapticJS.Utils.formatCurrency(phase.priceMicros, phase.currency)}
<small class="text-muted">/${period}</small>
</div>
${!isFree ? `
<button class="btn btn-primary btn-sm"
onclick="handleSubscription('${offer.id}')">
Subscribe ${period}
</button>
` : ''}
</div>
`;
}).join('');
}
// Add this new function to handle one-time purchases
async function handlePurchase(offerId) {
try {
await iaptic.order({
offerId,
applicationUsername: 'user_dev',
successUrl: returnUrl('success'),
cancelUrl: returnUrl('cancel')
});
} catch (error) {
console.error('Error creating purchase:', error);
}
}
function returnUrl(withHash) {
return window.location.href.split('#')[0] + '#' + withHash;
}
async function handleSubscription(offerId) {
try {
await iaptic.order({
offerId,
applicationUsername: 'user_dev',
successUrl: returnUrl('success'),
cancelUrl: returnUrl('cancel')
});
} catch (error) {
console.error('Error creating subscription:', error);
}
}
async function handleManageSubscription() {
try {
await iaptic.redirectToCustomerPortal({
returnUrl: window.location.href
});
} catch (error) {
console.error('Error managing subscription:', error);
}
}
async function handlePlanChange(newOfferId) {
try {
const newPurchase = await iaptic.changePlan({
offerId: newOfferId,
});
// Update the display with the new purchase information
displaySubscriptionDetails({
ok: true,
purchases: [newPurchase]
});
// Show success message
showMessage('success-plan-change');
// Refresh prices display to show updated current plan
displayPrices([newPurchase]);
} catch (error) {
console.error('Error changing plan:', error);
showMessage('error-plan-change');
}
}
// Initialize the display when the page loads
document.addEventListener('DOMContentLoaded', async () => {
const purchases = await displayPurchases();
displayPrices(purchases);
checkUrlHash();
});
// Listen for hash changes
window.addEventListener('hashchange', checkUrlHash);