-
Notifications
You must be signed in to change notification settings - Fork 0
/
availabletrain.html
828 lines (753 loc) · 35.4 KB
/
availabletrain.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
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
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
<!DOCTYPE html>
<html>
<head>
<head>
<!-- for-mobile-apps -->
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="theme-color" content="#25274d">
<meta name="description" content="A Train seat reservation system ">
<meta name="author" content="James Muriitih">
<meta name="keywords" content="bus,bus seats,">
<meta property="og:site_name" content="google.com">
<meta property="og:title" content="Bus Seat Reservation System" />
<meta property="og:description" content="A Train seat reservation system" />
<meta property="og:image:url" itemprop="image" content="A bus seat reservation system made by James">
<meta property="og:image" content="https://james-muriithi.github.io/bus/images/logo-400.png" />
<meta property="og:image:url" content="https://james-muriithi.github.io/bus/images/logo-400.png" />
<meta property="og:image:secure_url" content="https://james-muriithi.github.io/bus/images/logo-400.png" />
<meta property="og:image:type" content="image/png" />
<meta property="og:image:width" content="400" />
<meta property="og:image:height" content="400" />
<meta property="og:locale" content="en_GB" />
<meta property="og:type" content="website" />
<meta name="application-name" content="My Bus" />
<meta name="apple-mobile-web-app-title" content="My Bus" />
<meta name="msapplication-TileColor" content="#2b5797" />
<!-- //for-mobile-apps -->
<title>Train Seat Reservation System</title>
<!-- icons -->
<link rel="icon" type="image/png" href="images/logo-96.png" sizes="96x96" />
<link rel="icon" type="image/png" href="images/logo-16.png" sizes="16x16" />
<link rel="icon" type="image/png" href="images/logo-32.png" sizes="32x32" />
<link rel="icon" type="image/png" href="images/logo-64.png" sizes="64x64" />
<link rel="icon" type="image/png" href="images/logo-128.png" sizes="128x128" />
<link rel="apple-touch-icon" sizes="120x120" href="images/apple-touch-icon.png" />
<link rel="mask-icon" href="images/safari-pinned-tab.svg" color="#5bbad5" />
<link rel="manifest" href="site.webmanifest">
<!-- end of icons -->
<!-- css -->
<link rel="stylesheet" type="text/css" href="css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="css/bootstrapValidator.css">
<link rel="stylesheet" type="text/css" href="css/nice-select.css">
<link rel="stylesheet" type="text/css" href="css/util.css">
<link rel="stylesheet" type="text/css" href="css/jquery.seat-charts.css">
<link rel="stylesheet" type="text/css" href="fonts/font-awesome/css/font-awesome.min.css">
<link href="fonts/material-design-icons/material-icon.css" rel="stylesheet" type="text/css" />
<link rel="stylesheet" href="plugins/material-datetimepicker/bootstrap-material-datetimepicker.css" />
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" type="text/css" href="css/animate.css">
<link rel="stylesheet" type="text/css" href="css/material.min.css">
<link rel="stylesheet" type="text/css" href="plugins/lobibox/css/lobibox.min.css">
<link rel="stylesheet" type="text/css" href="css/simplelightbox.min.css">
<link rel="stylesheet" type="text/css" href="css/style.css">
<title> </title>
</head>
<body>
<nav class="navbar navbar-expand-lg navbar-dark static-top">
<div class="container">
<a class="navbar-brand" href="index.html">
<h1>
<img src="images/p1.png" alt="logo" width="120" height="55" style="margin-top: -10px">
<span>T</span>
<span>R</span>
<span>A</span>
<span>I</span>
<span>N</span>
</h1>
</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarResponsive" aria-controls="navbarResponsive" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarResponsive">
<ul class="navbar-nav ml-auto">
<!-- <li class="nav-item active">
<a class="nav-link" href="#">Reprint
<span class="sr-only">(current)</span>
</a>
</li> -->
<li class="nav-item">
<a href="index.html"><button class="btn btn-outline-warning my-2 my-sm-0 ml-3" type="submit">Login</button></a>
</li>
<li class="nav-item">
<a href="index.html"> <button class="btn btn-outline-warning my-2 my-sm-0 ml-2" type="submit">Sign Up</button></a>
</li>
<!-- <li class="nav-item">
<a class="nav-link" href="#">Contact</a>
</li> -->
</ul>
</div>
</div>
</nav>
<main class="col-md-12">
<div class="col-md-11 col-lg-9 col-xl-8 mx-auto window">
<section class="stepper">
<ul id="progressbar" style="padding-inline-start:8px;">
<a href="firstpage.html"> <li>Passenger Details</li> </a>
<a href="availabletrain.html"> <li class="active"> Train Details</li> </a>
<a href="food.html"> <li> Book Food </li> </a>
<a href="fetch.html"> <li> Ticket</li> </a>
</ul>
</section>
</div>
</main>
<br> <br> <br> <br> <br>
<fieldset class="animated fadeIn">
<div id="results">
<!-- <h6>3 buses found</h6> -->
<div class="row">
<div class="col-md-12">
<div class="card">
<div class="card-body">
<div class="row">
<div class="col-md-3 bus-image">
<img src="images/p.jpg" alt="bus" height="210" width="210">
</div>
<div class="col-md-8 bus-details">
<h5 class="card-title bus-name">KCD 452G (<span class="bus-type fs-13">Pandiyan Express</span>)</h5>
<div class="row card-text m-b-10 bus-description">
<div class="col-sm-6 fs-14">
<i class="material-icons" style="font-size: 13px;">watch</i> Departure: <span class="p-r-5 fr">20:30hr </span>
</div>
<div class="col-sm-6 fs-14">
<i class="fa fa-road"></i> Route:
<span class="p-r-5 fr"><span class="from"></span> - <span class="to"></span>Via Madurai </span>
</div>
<div class="col-sm-6 fs-14">
<i class="material-icons" style="font-size: 13px;">event_seat</i> Availability:
<span class="p-r-5 fr"><span class="seats-left">32</span> seats left </span>
</div>
<div class="col-sm-6 fs-14">
<i class="fa fa-money"></i> Fare:
<span class="p-r-5 fr">3000 Rs </span>
</div>
</div>
<div class="p-t-13">
<a href="fetch.html" class="btn btn-circle btn-success book_btn" data-bus="1">Book Seats</a>
<a href="#" class="fr p-t-13 g-link">View Gallery</a>
<div class="gallery1" style="display: none;">
<a href="gallery/majaoni1.jpg">
<img src="gallery/majaoni1.jpg" alt="" title="Majaoni Secondary Bus" />
</a>
<a href="gallery/majaoni2.jpg">
<img src="gallery/majaoni2.jpg" alt="" title="Majaoni Secondary Bus" />
</a>
<a href="gallery/majaoni3.jpg">
<img src="gallery/majaoni3.jpg" alt="" title="Majaoni Secondary Bus" />
</a>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="col-md-12">
<div class="card">
<div class="card-body">
<div class="row">
<div class="col-md-3 bus-image">
<img src="images/p3.png" alt="bus" height="190" width="190">
</div>
<div class="col-md-8 bus-details">
<h5 class="card-title bus-name">KCP 578X (<span class="bus-type">Brindavan </span> Express)</h5>
<div class="row card-text m-b-10 bus-description">
<div class="col-md-6 fs-14">
<i class="material-icons" style="font-size: 13px;">watch</i> Departure: <span class="p-r-5 fr">20:30hr </span>
</div>
<div class="col-md-6 fs-14">
<i class="fa fa-road"></i> Route:
<span class="p-r-5 fr"><span class="from"></span> - <span class="to"></span>Via Coimbatore </span> </div>
<div class="col-md-6 fs-14">
<i class="material-icons" style="font-size: 13px;">event_seat</i> Availability:
<span class="p-r-5 fr">0 seats left </span>
</div>
<div class="col-md-6 fs-14">
<i class="fa fa-money"></i> Fare:
<span class="p-r-5 fr">1400 Rs </span>
</div>
</div>
<center> <div id="container"></div>
<script async src="https://pay.google.com/gp/p/js/pay.js"
onload="onGooglePayLoaded()"></script>
</center>
<div class="p-t-13">
<a href="fetch.html" class="btn btn-circle btn-success book_btn">Book Seats</a>
<a href="#" class="fr p-t-10">View Gallery</a>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="col-md-12">
<div class="card">
<div class="card-body">
<div class="row">
<div class="col-md-3 bus-image">
<img src="images/p2.jpg" alt="bus" height="190" width="190">
</div>
<div class="col-md-8 bus-details">
<h5 class="card-title bus-name">KCK 122Y (<span class="bus-type">Intercity</span> Express)</h5>
<div class="row card-text m-b-10 bus-description">
<div class="col-md-6 fs-14">
<i class="material-icons" style="font-size: 13px;">watch</i> Departure: <span class="p-r-5 fr">21:30hr </span>
</div>
<div class="col-md-6 fs-14">
<i class="fa fa-road"></i> Route:
<span class="p-r-5 fr"><span class="from"></span> - <span class="to"></span>Via Bangalore </span> </div>
<div class="col-md-6 fs-14">
<i class="material-icons" style="font-size: 13px;">event_seat</i> Availability:
<span class="p-r-5 fr">0 seats left </span>
</div>
<div class="col-md-6 fs-14">
<i class="fa fa-money"></i> Fare:
<span class="p-r-5 fr">1200 Rs </span>
</div>
</div>
<div class="p-t-13">
<a href="fetch.html"
class="btn btn-circle btn-success book_btn">Book Seats</a>
<a href="#" class="fr p-t-10">View Gallery</a>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="row justify-content-center buttons">
<button type="button " class="btn previous_button">Back</button>
</div>
</fieldset>
</body>
</html>
<script type="text/javascript " src="js/jquery.min.js "></script>
<script type="text/javascript " src="js/popper.min.js "></script>
<script type="text/javascript " src="js/bootstrap.min.js "></script>
<script type="text/javascript " src="js/bootstrapValidator.js"></script>
<script type="text/javascript " src="js/jquery-easing.min.js "></script>
<script type="text/javascript " src="js/jquery.nice-select.js "></script>
<script type="text/javascript " src="js/jquery.seat-charts.js "></script>
<script src="plugins/material-datetimepicker/moment-with-locales.min.js "></script>
<script src="plugins/material-datetimepicker/bootstrap-material-datetimepicker.js "></script>
<script src="plugins/material-datetimepicker/datetimepicker.js "></script>
<script type="text/javascript" src="js/simple-lightbox.min.js"></script>
<script type="text/javascript" src="plugins/lobibox/js/lobibox.min.js"></script>
<script type="text/javascript " src="js/script.js "></script>
<script type="text/javascript">
$('select').niceSelect();
$('.g-link').on('click', function(event) {
$('.gallery1 a').trigger('click')
});
var $gallery = $('.gallery1 a').simpleLightbox();
//jQuery time
var current_fs, next_fs, previous_fs, busId=0,seatsArray = []; //fieldsets
var left, opacity, scale; //fieldset properties which we will animate
var animating; //flag to prevent quick multi-click glitches
$(".next_button").on('click', function(event) {
if (animating) return false;
animating = true;
current_fs = $(this).parent().parent();
next_fs = current_fs.next();
if ($("fieldset").index(next_fs) == 1) {
$('span.from').text($('select.from').val());
$('span.to').text($('input.to').val());
$.ajax({
method: 'GET', //https://examinationcomplaint.theschemaqhigh.co.ke/HCI/api/book/
url: 'https://examinationcomplaint.theschemaqhigh.co.ke/HCI/api/book/?bus_id=1&booked_seats',
success: function (data) {
$('span.seats-left').text(51 - data.length);
},
error: function (data) {
console.log(data)
}
});
}
if ($("fieldset").index(current_fs) == 2) {
if ($('ul#selected-seats li').length == 0) {
animating = false;
Lobibox.notify('error', {
showClass: 'fadeInDown',
hideClass: 'fadeUpDown',
iconSource: 'fontAwesome',
// img: 'images/logo-96.png',
title: "No Seat Selected!",
continueDelayOnInactiveTab: true,
size: 'mini',
msg: 'Please select at least one seat from the selected bus.'
});
} else {
goNext(next_fs, current_fs)
seatsArray.splice(0,seatsArray.length);
sc.find('selected').each(function() {
seatsArray.push(this.settings.label)
});
}
} else if ($("fieldset").index(current_fs) == 3) {
animating = false;
if (!verifyInfoForm()) {
} else {
goNext(next_fs, current_fs)
$('span.show-email').text($('input[name="email"]').val());
}
} else {
goNext(next_fs, current_fs)
if ($("fieldset").index(next_fs) == 5) {
$data = {
'busId' : busId,
'seats' : seatsArray.toString(),
'personalInfo' : $('form').serializeArray()
}
$data = JSON.stringify($data)
console.log($data);
$.ajax({
method: 'POST',//https://examinationcomplaint.theschemaqhigh.co.ke/HCI/api/book/
url: 'api/book.php',
data: $data,
dataType: 'json',
success: function (data) {
console.log(data)
},
error: function (data) {
console.log(data)
}
});
}
}
// let date = $('#date').val();
// let regexp = /^(\d{4})[\/\-](0?[1-9]|1[012])[\/\-](0?[1-9]|[12][0-9]|3[01])$/;
// if (!regexp.test(date)) return 0;
// }
//go to next fs
// $(".next_button").unbind('click',goNext(next_fs, current_fs));
});
$(".book_btn").click(function() {
busId = Number($(this).data('bus')); //determine which bus was choosen
let busName = $(this).parents('.bus-details').children('.bus-name').text();
$('span.number_plate').text($(this).parents('.bus-details').children('.bus-name').text())
if (animating) return false;
animating = true;
current_fs = $(this).parents('fieldset');
next_fs = current_fs.next();
if ($("fieldset").index(next_fs) == 2) {
booked_seats(busId);
setInterval( booked_seats(busId),3000);
}
//de-activate current step on progressbar
goNext(next_fs, current_fs)
});
$(".previous_button").click(function() {
current_fs = $(this).parent().parent();
previous_fs = current_fs.prev();
if ($("fieldset").index(previous_fs) == 2) {
booked_seats(busId);
setInterval( booked_seats(busId),3000);
}
//de-activate current step on progressbar
if (previous_fs.length > 0) {
if (animating) return false;
animating = true;
$("#progressbar li ").eq($("fieldset").index(current_fs)).removeClass("active");
//show the previous fieldset
previous_fs.show();
//hide the current fieldset with style
current_fs.animate({
opacity: 0
}, {
duration: 100,
complete: function() {
current_fs.hide();
previous_fs.css('opacity', 1);
animating = false;
},
//this comes from the custom easing plugin
easing: 'easeInOutBack'
});
}
});
function goNext(next_fs, current_fs) {
$("#progressbar li ").eq($("fieldset").index(next_fs)).addClass("active");
//show the next fieldset
next_fs.show();
current_fs.animate({
opacity: 0
}, {
duration: 10,
complete: function() {
current_fs.hide();
animating = false;
},
//this comes from the custom easing plugin
easing: 'easeInOutBack'
});
}
function verifyInfoForm() {
let name = $('input[name="name"]'),
id = $('input[name="id"]'),
phone = $('input[name="phone"]'),
email = $('input[name="email"]'),
nameRegexp = /^[a-zA-Z]+\s+[a-zA-Z\s]+$/,
idRegexp = /^\d{4}$/,
emailRegexp = /^[A-Z0-9._%+-]+@([A-Z0-9-]+\.)+[A-Z]{2,4}$/i,
phoneRegexp = /^\d{10}$/,
isValid = []
if ($.trim(name.val()) == '') {
name.addClass('is-invalid')
name.parent().find('small.text-danger').remove()
name.parent().append('<small class="text-danger">Name field cannot be empty</small>')
isValid['name'] = false;
} else if (!nameRegexp.test($.trim(name.val()))) {
name.addClass('is-invalid')
name.parent().find('small.text-danger').remove()
name.parent().append('<small class="text-danger">Full name can only consist of alphabetical and atlest two names.</small>')
isValid['name'] = false;
} else {
name.removeClass('is-invalid')
name.addClass('is-valid')
name.parent().find('small.text-danger').remove();
isValid['name'] = true;
}
// phone no
if ($.trim(phone.val()) == '') {
phone.addClass('is-invalid')
phone.parent().find('small.text-danger').remove()
phone.parent().append('<small class="text-danger">Phone No field cannot be empty</small>')
isValid['phone'] = false;
} else if (!phoneRegexp.test($.trim(phone.val()))) {
phone.addClass('is-invalid')
phone.parent().find('small.text-danger').remove()
phone.parent().append('<small class="text-danger">Please provide a valid phone number.</small>')
isValid['phone'] = false;
} else {
phone.removeClass('is-invalid')
phone.addClass('is-valid')
phone.parent().find('small.text-danger').remove();
isValid['phone'] = true;
}
// id
if ($.trim(id.val()) == '') {
id.addClass('is-invalid')
id.parent().find('small.text-danger').remove()
id.parent().append('<small class="text-danger">Id field cannot be empty</small>')
isValid['id'] = false;
} else if (!idRegexp.test($.trim(id.val()))) {
id.addClass('is-invalid')
id.parent().find('small.text-danger').remove()
id.parent().append('<small class="text-danger">Please provide a valid ID number.</small>')
isValid['id'] = false;
} else {
id.removeClass('is-invalid')
id.addClass('is-valid')
id.parent().find('small.text-danger').remove();
isValid['id'] = true;
}
// email
if ($.trim(email.val()) == '') {
email.addClass('is-invalid')
email.parent().find('small.text-danger').remove()
email.parent().append('<small class="text-danger">Email field cannot be empty</small>')
isValid['email'] = false;
} else if (!emailRegexp.test($.trim(email.val()))) {
email.addClass('is-invalid')
email.parent().find('small.text-danger').remove()
email.parent().append('<small class="text-danger">Please provide a valid email address.</small>')
isValid['email'] = false;
} else {
email.removeClass('is-invalid')
email.addClass('is-valid')
email.parent().find('small.text-danger').remove();
isValid['email'] = true;
}
return Object.values(isValid).every(function (value) {
return value == true;
});
}
$('#date_form').on('submit', (event) => {
event.preventDefault();
})
$('ul#progressbar').on('click', 'li', function(event) {
let i = $('#progressbar li').index(this)
let j = $('#progressbar').find('li.active').length - 1
if (i > j) {
if (j == 1) {
Lobibox.notify('error', {
showClass: 'fadeInDown',
hideClass: 'fadeUpDown',
iconSource: 'fontAwesome',
// img: 'images/logo-96.png',
title: "No Train Selected!",
continueDelayOnInactiveTab: true,
size: 'mini',
msg: 'Please select a Train from which you want to book.'
});
}else{
$("fieldset").eq(j).find('.next_button').trigger('click')
}
}else if (i < j) $("fieldset").eq(j).find('.previous_button').trigger('click')
});
if ('serviceWorker' in navigator) {
window.addEventListener('load', function() {
navigator.serviceWorker.register('service-worker.js')
.then(function() {
console.log("Service Worker Registered,");
});
});
}
<script type="text/javascript">
/**
* Define the version of the Google Pay API referenced when creating your
* configuration
*
* @see {@link https://developers.google.com/pay/api/web/reference/request-objects#PaymentDataRequest|apiVersion in PaymentDataRequest}
*/
const baseRequest = {
apiVersion: 2,
apiVersionMinor: 0
};
/**
* Card networks supported by your site and your gateway
*
* @see {@link https://developers.google.com/pay/api/web/reference/request-objects#CardParameters|CardParameters}
* @todo confirm card networks supported by your site and gateway
*/
const allowedCardNetworks = ["AMEX", "DISCOVER", "INTERAC", "JCB", "MASTERCARD", "VISA"];
/**
* Card authentication methods supported by your site and your gateway
*
* @see {@link https://developers.google.com/pay/api/web/reference/request-objects#CardParameters|CardParameters}
* @todo confirm your processor supports Android device tokens for your
* supported card networks
*/
const allowedCardAuthMethods = ["PAN_ONLY", "CRYPTOGRAM_3DS"];
/**
* Identify your gateway and your site's gateway merchant identifier
*
* The Google Pay API response will return an encrypted payment method capable
* of being charged by a supported gateway after payer authorization
*
* @todo check with your gateway on the parameters to pass
* @see {@link https://developers.google.com/pay/api/web/reference/request-objects#gateway|PaymentMethodTokenizationSpecification}
*/
const tokenizationSpecification = {
type: 'PAYMENT_GATEWAY',
parameters: {
'gateway': 'example',
'gatewayMerchantId': 'exampleGatewayMerchantId'
}
};
/**
* Describe your site's support for the CARD payment method and its required
* fields
*
* @see {@link https://developers.google.com/pay/api/web/reference/request-objects#CardParameters|CardParameters}
*/
const baseCardPaymentMethod = {
type: 'CARD',
parameters: {
allowedAuthMethods: allowedCardAuthMethods,
allowedCardNetworks: allowedCardNetworks
}
};
/**
* Describe your site's support for the CARD payment method including optional
* fields
*
* @see {@link https://developers.google.com/pay/api/web/reference/request-objects#CardParameters|CardParameters}
*/
const cardPaymentMethod = Object.assign(
{},
baseCardPaymentMethod,
{
tokenizationSpecification: tokenizationSpecification
}
);
/**
* An initialized google.payments.api.PaymentsClient object or null if not yet set
*
* @see {@link getGooglePaymentsClient}
*/
let paymentsClient = null;
/**
* Configure your site's support for payment methods supported by the Google Pay
* API.
*
* Each member of allowedPaymentMethods should contain only the required fields,
* allowing reuse of this base request when determining a viewer's ability
* to pay and later requesting a supported payment method
*
* @returns {object} Google Pay API version, payment methods supported by the site
*/
function getGoogleIsReadyToPayRequest() {
return Object.assign(
{},
baseRequest,
{
allowedPaymentMethods: [baseCardPaymentMethod]
}
);
}
/**
* Configure support for the Google Pay API
*
* @see {@link https://developers.google.com/pay/api/web/reference/request-objects#PaymentDataRequest|PaymentDataRequest}
* @returns {object} PaymentDataRequest fields
*/
function getGooglePaymentDataRequest() {
const paymentDataRequest = Object.assign({}, baseRequest);
paymentDataRequest.allowedPaymentMethods = [cardPaymentMethod];
paymentDataRequest.transactionInfo = getGoogleTransactionInfo();
paymentDataRequest.merchantInfo = {
// @todo a merchant ID is available for a production environment after approval by Google
// See {@link https://developers.google.com/pay/api/web/guides/test-and-deploy/integration-checklist|Integration checklist}
// merchantId: '01234567890123456789',
merchantName: 'Example Merchant'
};
paymentDataRequest.callbackIntents = ["PAYMENT_AUTHORIZATION"];
return paymentDataRequest;
}
/**
* Return an active PaymentsClient or initialize
*
* @see {@link https://developers.google.com/pay/api/web/reference/client#PaymentsClient|PaymentsClient constructor}
* @returns {google.payments.api.PaymentsClient} Google Pay API client
*/
function getGooglePaymentsClient() {
if ( paymentsClient === null ) {
paymentsClient = new google.payments.api.PaymentsClient({
environment: 'TEST',
paymentDataCallbacks: {
onPaymentAuthorized: onPaymentAuthorized
}
});
}
return paymentsClient;
}
/**
* Handles authorize payments callback intents.
*
* @param {object} paymentData response from Google Pay API after a payer approves payment through user gesture.
* @see {@link https://developers.google.com/pay/api/web/reference/response-objects#PaymentData object reference}
*
* @see {@link https://developers.google.com/pay/api/web/reference/response-objects#PaymentAuthorizationResult}
* @returns Promise<{object}> Promise of PaymentAuthorizationResult object to acknowledge the payment authorization status.
*/
function onPaymentAuthorized(paymentData) {
return new Promise(function(resolve, reject){
// handle the response
processPayment(paymentData)
.then(function() {
resolve({transactionState: 'SUCCESS'});
})
.catch(function() {
resolve({
transactionState: 'ERROR',
error: {
intent: 'PAYMENT_AUTHORIZATION',
message: 'Insufficient funds, try again. Next attempt should work.',
reason: 'PAYMENT_DATA_INVALID'
}
});
});
});
}
/**
* Initialize Google PaymentsClient after Google-hosted JavaScript has loaded
*
* Display a Google Pay payment button after confirmation of the viewer's
* ability to pay.
*/
function onGooglePayLoaded() {
const paymentsClient = getGooglePaymentsClient();
paymentsClient.isReadyToPay(getGoogleIsReadyToPayRequest())
.then(function(response) {
if (response.result) {
addGooglePayButton();
}
})
.catch(function(err) {
// show error in developer console for debugging
console.error(err);
});
}
/**
* Add a Google Pay purchase button alongside an existing checkout button
*
* @see {@link https://developers.google.com/pay/api/web/reference/request-objects#ButtonOptions|Button options}
* @see {@link https://developers.google.com/pay/api/web/guides/brand-guidelines|Google Pay brand guidelines}
*/
function addGooglePayButton() {
const paymentsClient = getGooglePaymentsClient();
const button =
paymentsClient.createButton({onClick: onGooglePaymentButtonClicked});
document.getElementById('container').appendChild(button);
}
/**
* Provide Google Pay API with a payment amount, currency, and amount status
*
* @see {@link https://developers.google.com/pay/api/web/reference/request-objects#TransactionInfo|TransactionInfo}
* @returns {object} transaction info, suitable for use as transactionInfo property of PaymentDataRequest
*/
function getGoogleTransactionInfo() {
return {
displayItems: [
{
label: "Subtotal",
type: "SUBTOTAL",
price: "11.00",
},
{
label: "Tax",
type: "TAX",
price: "1.00",
}
],
countryCode: 'US',
currencyCode: "USD",
totalPriceStatus: "FINAL",
totalPrice: "12.00",
totalPriceLabel: "Total"
};
}
/**
* Show Google Pay payment sheet when Google Pay payment button is clicked
*/
function onGooglePaymentButtonClicked() {
const paymentDataRequest = getGooglePaymentDataRequest();
paymentDataRequest.transactionInfo = getGoogleTransactionInfo();
const paymentsClient = getGooglePaymentsClient();
paymentsClient.loadPaymentData(paymentDataRequest);
}
let attempts = 0;
/**
* Process payment data returned by the Google Pay API
*
* @param {object} paymentData response from Google Pay API after user approves payment
* @see {@link https://developers.google.com/pay/api/web/reference/response-objects#PaymentData|PaymentData object reference}
*/
function processPayment(paymentData) {
return new Promise(function(resolve, reject) {
setTimeout(function() {
// @todo pass payment token to your gateway to process payment
paymentToken = paymentData.paymentMethodData.tokenizationData.token;
if (attempts++ % 2 == 0) {
reject(new Error('Every other attempt fails, next one should succeed'));
} else {
resolve({});
}
}, 500);
});
}
</script>