-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathCheckoutServices.js
758 lines (703 loc) · 31.5 KB
/
CheckoutServices.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
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
'use strict';
var page = module.superModule;
var server = require('server');
var URLUtils = require('dw/web/URLUtils');
var BasketMgr = require('dw/order/BasketMgr');
var payerAuthentication = require('~/cartridge/scripts/http/payerAuthentication');
var configObject = require('~/cartridge/configuration/index');
server.extend(page);
var currentBasket = BasketMgr.getCurrentBasket();
var paymentMethod = currentBasket && currentBasket.paymentInstrument && currentBasket.paymentInstrument.paymentMethod;
var isVisaSRC = paymentMethod && paymentMethod === 'CLICK_TO_PAY';
// eslint-disable-next-line no-undef
if (configObject.payerAuthenticationEnabled && configObject.cartridgeEnabled && empty(session.privacy.encryptedDataGP)
&& !isVisaSRC
) {
// eslint-disable-next-line consistent-return
server.prepend('PlaceOrder', server.middleware.https, function (req, res, next) {
// eslint-disable-next-line no-shadow
var URLUtils = require('dw/web/URLUtils');
if (session.custom.Flag3ds === false) {
// eslint-disable-next-line no-shadow
var BasketMgr = require('dw/order/BasketMgr');
var OrderMgr = require('dw/order/OrderMgr');
var Resource = require('dw/web/Resource');
var Transaction = require('dw/system/Transaction');
var basketCalculationHelpers = require('*/cartridge/scripts/helpers/basketCalculationHelpers');
var hooksHelper = require('*/cartridge/scripts/helpers/hooks');
var COHelpers = require('*/cartridge/scripts/checkout/checkoutHelpers');
var validationHelpers = require('*/cartridge/scripts/helpers/basketValidationHelpers');
var addressHelpers = require('*/cartridge/scripts/helpers/addressHelpers');
res.setHttpHeader("Content-Security-Policy", "script-src 'self'");
// eslint-disable-next-line no-shadow
var currentBasket = BasketMgr.getCurrentBasket();
if (!currentBasket) {
res.json({
error: true,
cartError: true,
fieldErrors: [],
serverErrors: [],
redirectUrl: URLUtils.url('Cart-Show').toString()
});
return next();
}
var validatedProducts = validationHelpers.validateProducts(currentBasket);
if (validatedProducts.error) {
res.json({
error: true,
cartError: true,
fieldErrors: [],
serverErrors: [],
redirectUrl: URLUtils.url('Cart-Show').toString()
});
return next();
}
if (req.session.privacyCache.get('fraudDetectionStatus')) {
res.json({
error: true,
cartError: true,
redirectUrl: URLUtils.url('Error-ErrorCode', 'err', '01').toString(),
errorMessage: Resource.msg('error.technical', 'checkout', null)
});
return next();
}
var validationOrderStatus = hooksHelper('app.validate.order', 'validateOrder', currentBasket, require('*/cartridge/scripts/hooks/validateOrder').validateOrder);
if (validationOrderStatus.error) {
res.json({
error: true,
errorMessage: validationOrderStatus.message
});
return next();
}
// Check to make sure there is a shipping address
if (currentBasket.defaultShipment.shippingAddress === null) {
res.json({
error: true,
errorStage: {
stage: 'shipping',
step: 'address'
},
errorMessage: Resource.msg('error.no.shipping.address', 'checkout', null)
});
return next();
}
// Check to make sure billing address exists
if (!currentBasket.billingAddress) {
res.json({
error: true,
errorStage: {
stage: 'payment',
step: 'billingAddress'
},
errorMessage: Resource.msg('error.no.billing.address', 'checkout', null)
});
return next();
}
// Calculate the basket
Transaction.wrap(function () {
basketCalculationHelpers.calculateTotals(currentBasket);
});
// Re-validates existing payment instruments
var validPayment = COHelpers.validatePayment(req, currentBasket);
if (validPayment.error) {
res.json({
error: true,
errorStage: {
stage: 'payment',
step: 'paymentInstrument'
},
errorMessage: Resource.msg('error.payment.not.valid', 'checkout', null)
});
return next();
}
// Re-calculate the payments.
var calculatedPaymentTransactionTotal = COHelpers.calculatePaymentTransaction(currentBasket);
if (calculatedPaymentTransactionTotal.error) {
res.json({
error: true,
errorMessage: Resource.msg('error.technical', 'checkout', null)
});
return next();
}
// Creates a new order.
var order = COHelpers.createOrder(currentBasket);
if (!order) {
res.json({
error: true,
errorMessage: Resource.msg('error.technical', 'checkout', null)
});
return next();
}
// eslint-disable-next-line no-undef
session.privacy.orderID = order.orderNo;
// eslint-disable-next-line no-undef
session.privacy.orderToken = order.orderToken;
var fraudDetectionStatus = hooksHelper('app.fraud.detection', 'fraudDetection', currentBasket, require('*/cartridge/scripts/hooks/fraudDetection').fraudDetection);
if (fraudDetectionStatus.status === 'fail') {
Transaction.wrap(function () {
OrderMgr.failOrder(order, true);
});
// fraud detection failed
req.session.privacyCache.set('fraudDetectionStatus', true);
res.json({
error: true,
cartError: true,
redirectUrl: URLUtils.url('Error-ErrorCode', 'err', fraudDetectionStatus.errorCode).toString(),
errorMessage: Resource.msg('error.technical', 'checkout', null)
});
return next();
}
if (req.currentCustomer.addressBook) {
// save all used shipping addresses to address book of the logged in customer
var allAddresses = addressHelpers.gatherShippingAddresses(order);
allAddresses.forEach(function (address) {
if (!addressHelpers.checkIfAddressStored(address, req.currentCustomer.addressBook.addresses)) {
addressHelpers.saveAddress(address, req.currentCustomer, addressHelpers.generateAddressName(address));
}
});
}
// eslint-disable-next-line no-undef
session.privacy.localeId = req.locale.id;
// Reset usingMultiShip after successful Order placement
req.session.privacyCache.set('usingMultiShipping', false);
}
var billingForm = server.forms.getForm('billing');
var order = getOrder();
var paymentInstruments = order.paymentInstruments;
var paymentInstrument = paymentInstruments[0];
var card = {
token: paymentInstrument.creditCardToken,
jwttoken: billingForm.creditCardFields.flexresponse.value,
securityCode: billingForm.creditCardFields.securityCode.value,
fluidData: paymentInstrument.custom.fluidData,
callId: paymentInstrument.custom.callID
};
var setupResponse = payerAuthentication.paSetup(billingForm, session.privacy.orderID, card);
var accessToken = setupResponse.consumerAuthenticationInformation.accessToken;
session.privacy.deviceDataCollectionUrl = setupResponse.consumerAuthenticationInformation.deviceDataCollectionUrl;
session.privacy.ReferenceId = setupResponse.consumerAuthenticationInformation.referenceId;
if (session.custom.Flag3ds === true) {
res.redirect(URLUtils.https('PayerAuthentication-createDeviceDataCollection', 'accessToken', accessToken).toString());
}
else {
res.json({
error: false,
cartError: false,
createDeviceDataCollection: true,
fieldErrors: [],
serverErrors: [],
redirectUrl: URLUtils.https('PayerAuthentication-createDeviceDataCollection', 'accessToken', accessToken).toString()
});
}
this.emit('route:Complete', req, res);
});
}
server.append('PlaceOrder', server.middleware.https, function (req, res, next) {
// eslint-disable-next-line no-undef
if (session.privacy.AuthorizeErrors) {
// eslint-disable-next-line no-undef
var message = session.privacy.AuthorizeErrors;
try {
var messageObject = JSON.parse(message);
if ('message' in messageObject) {
message = messageObject.message;
}
// eslint-disable-next-line no-empty
} catch (e) { }
res.json({
error: true,
errorMessage: message
});
// eslint-disable-next-line no-undef
delete session.privacy.AuthorizeErrors;
} else {
//For Googlepay and Visa Checkeout Redirect to COPlaceOrder-SubmitOrderConformation.
res.json({
error: false,
ID: session.privacy.orderID,
token: session.privacy.orderToken,
continueUrl: URLUtils.url('COPlaceOrder-SubmitOrderConformation').toString()
});
}
return next();
});
/**
* @returns {*} *
*/
function getOrder() {
var OrderMgr = require('dw/order/OrderMgr');
// eslint-disable-next-line no-undef
var orderNo = session.privacy.orderID;
var order = OrderMgr.getOrder(orderNo);
return order;
}
/**
* Send Email Confirmation
*/
function sendConfirmationEmail() {
var COHelpers = require('*/cartridge/scripts/checkout/checkoutHelpers');
var order = getOrder();
if (order.getCustomerEmail()) {
// eslint-disable-next-line no-undef
COHelpers.sendConfirmationEmail(order, session.privacy.localeId);
}
}
server.post('getResponse', server.middleware.https, function (req, res, next) {
var Transaction = require('dw/system/Transaction');
var OrderMgr = require('dw/order/OrderMgr');
var Resource = require('dw/web/Resource');
var mapper = require('~/cartridge/scripts/util/mapper.js');
var COHelpers = require('*/cartridge/scripts/checkout/checkoutHelpers');
var hooksHelper = require('*/cartridge/scripts/helpers/hooks');
// eslint-disable-next-line no-shadow
var currentBasket = BasketMgr.getCurrentBasket();
var order = getOrder();
// eslint-disable-next-line no-undef
var referenceId = session.privacy.ReferenceId;
var billingForm = server.forms.getForm('billing');
var shippingAddress = order.shipments[0].shippingAddress;
var redirect = false;
if (order != null) {
var lineItems = mapper.MapOrderLineItems(order.allLineItems, true);
var totalAmount = order.totalGrossPrice.value;
var currencyCode = order.currencyCode;
var paymentInstruments = order.paymentInstruments;
var paymentInstrument = paymentInstruments[0];
var card = {
token: paymentInstrument.creditCardToken,
jwttoken: billingForm.creditCardFields.flexresponse.value,
securityCode: billingForm.creditCardFields.securityCode.value,
fluidData: paymentInstrument.custom.fluidData,
callId: paymentInstrument.custom.callID
};
}
try {
// eslint-disable-next-line block-scoped-var, no-undef
var enrollResponse = payerAuthentication.paEnroll(billingForm, shippingAddress, session.privacy.orderID, totalAmount, currencyCode, referenceId, card, lineItems, order);
if (enrollResponse.status === 'PENDING_AUTHENTICATION' && enrollResponse.errorInformation.reason === 'CONSUMER_AUTHENTICATION_REQUIRED') {
if (enrollResponse.consumerAuthenticationInformation.acsUrl
&& enrollResponse.consumerAuthenticationInformation.stepUpUrl
&& enrollResponse.consumerAuthenticationInformation.pareq
&& enrollResponse.consumerAuthenticationInformation.authenticationTransactionId) {
var jwtToken = enrollResponse.consumerAuthenticationInformation.accessToken;
var stepUpUrl = enrollResponse.consumerAuthenticationInformation.stepUpUrl;
// eslint-disable-next-line no-undef
session.privacy.transactionId = enrollResponse.consumerAuthenticationInformation.authenticationTransactionId;
// eslint-disable-next-line no-shadow
this.on('route:BeforeComplete', function (req, res) {
res.render('payerAuthentication/postToStepUpUrl', {
stepUpUrl: stepUpUrl,
jwtToken: jwtToken
});
});
}
} else if (enrollResponse.status === 'AUTHORIZED' || enrollResponse.status === 'AUTHORIZED_PENDING_REVIEW') {
redirect = false;
var fraudDetectionStatus = hooksHelper('app.fraud.detection', 'fraudDetection', currentBasket, require('*/cartridge/scripts/hooks/fraudDetection').fraudDetection);
var placeOrderResult = COHelpers.placeOrder(order, fraudDetectionStatus);
if (placeOrderResult.error) {
redirect = true;
res.json({
error: true,
errorMessage: Resource.msg('error.technical', 'checkout', null)
});
}
sendConfirmationEmail();
// eslint-disable-next-line no-undef
session.privacy.orderID = '';
// eslint-disable-next-line no-undef
session.privacy.orderToken = '';
}
// eslint-disable-next-line
else if (enrollResponse.errorInformation.reason === 'CUSTOMER_AUTHENTICATION_REQUIRED' && session.custom.Flag3ds === false) {
session.custom.Flag3ds = true;
// eslint-disable-next-line no-shadow
res.render('payerAuthentication/scaRedirect', {
orderID: order.orderNo,
});
return next();
}
else {
redirect = true;
Transaction.wrap(function () {
OrderMgr.failOrder(order);
});
// eslint-disable-next-line no-undef
session.privacy.orderID = '';
// eslint-disable-next-line no-undef
session.privacy.orderToken = '';
}
res.render('payerAuthentication/checkoutRedirect', {
redirect: redirect,
errorMessage: Resource.msg('message.payerAuthError', 'error', null),
orderID: order.orderNo,
orderToken: order.orderToken,
continueUrl: URLUtils.url('COPlaceOrder-SubmitOrderConformation').toString()
});
} catch (e) {
if (!order) {
redirect = true;
res.render('payerAuthentication/checkoutRedirect', {
redirect: redirect,
errorMessage: Resource.msg('message.payerAuthError', 'error', null)
});
} else {
Transaction.wrap(function () {
OrderMgr.failOrder(order);
});
}
}
return next();
});
server.post('handlingConsumerAuthResponse', server.middleware.https, function (req, res, next) {
// eslint-disable-next-line no-shadow
var BasketMgr = require('dw/order/BasketMgr');
// eslint-disable-next-line no-shadow
var currentBasket = BasketMgr.getCurrentBasket();
var Transaction = require('dw/system/Transaction');
var COHelpers = require('*/cartridge/scripts/checkout/checkoutHelpers');
var hooksHelper = require('*/cartridge/scripts/helpers/hooks');
var OrderMgr = require('dw/order/OrderMgr');
var Resource = require('dw/web/Resource');
var redirect;
var billingForm = server.forms.getForm('billing');
var order = getOrder();
if (order != null) {
var totalAmount = order.totalGrossPrice.value;
var currencyCode = order.currencyCode;
var paymentInstruments = order.paymentInstruments;
var paymentInstrument = paymentInstruments[0];
var card = {
token: paymentInstrument.creditCardToken,
jwttoken: billingForm.creditCardFields.flexresponse.value,
securityCode: billingForm.creditCardFields.securityCode.value,
fluidData: paymentInstrument.custom.fluidData,
callId: paymentInstrument.custom.callID
};
}
var mapper = require('~/cartridge/scripts/util/mapper.js');
var lineItems = mapper.MapOrderLineItems(order.allLineItems, true);
// eslint-disable-next-line no-undef, block-scoped-var
var authenticateResponse = payerAuthentication.paConsumerAuthenticate(billingForm, session.privacy.orderID, totalAmount, currencyCode, session.privacy.transactionId, card, lineItems, order);
if (authenticateResponse.status === 'AUTHORIZED' || authenticateResponse.status === 'AUTHORIZED_PENDING_REVIEW') {
var fraudDetectionStatus = hooksHelper('app.fraud.detection', 'fraudDetection', currentBasket, require('*/cartridge/scripts/hooks/fraudDetection').fraudDetection);
var placeOrderResult = COHelpers.placeOrder(order, fraudDetectionStatus);
redirect = false;
if (placeOrderResult.error) {
redirect = true;
res.json({
error: true,
errorMessage: Resource.msg('error.technical', 'checkout', null)
});
}
// Sending Email Confirmation
sendConfirmationEmail();
// eslint-disable-next-line no-undef
session.privacy.orderID = '';
// eslint-disable-next-line no-undef
session.privacy.orderToken = '';
}
// eslint-disable-next-line
else if ((authenticateResponse.errorInformation ? authenticateResponse.errorInformation.reason === 'CUSTOMER_AUTHENTICATION_REQUIRED' : false) && session.custom.Flag3ds === false) {
session.custom.Flag3ds = true;
// eslint-disable-next-line no-shadow
res.render('payerAuthentication/scaRedirect', {
orderID: order.orderNo,
});
return next();
}
else {
redirect = true;
Transaction.wrap(function () {
OrderMgr.failOrder(order);
});
// eslint-disable-next-line no-undef
session.privacy.orderID = '';
// eslint-disable-next-line no-undef
session.privacy.orderToken = '';
}
res.render('payerAuthentication/checkoutRedirect', {
redirect: redirect,
errorMessage: Resource.msg('message.payerAuthError', 'error', null) + ' ' + authenticateResponse.status,
orderID: order.orderNo,
orderToken: order.orderToken,
continueUrl: URLUtils.url('COPlaceOrder-SubmitOrderConformation').toString()
});
return next();
});
server.post('SubmitPaymentGP', function (req, res, next) {
var COHelpers = require('*/cartridge/scripts/checkout/checkoutHelpers');
var Encoding = require('dw/crypto/Encoding');
var paymentForm = server.forms.getForm('billing');
var billingFormErrors = {};
var viewData = {};
// eslint-disable-next-line no-shadow
var BasketMgr = require('dw/order/BasketMgr');
var cart = BasketMgr.getCurrentBasket();
var Locale = require('dw/util/Locale');
var OrderModel = require('*/cartridge/models/order');
var currentLocale = Locale.getLocale(req.locale.id);
var usingMultiShipping = false;
var basketModel = new OrderModel(cart, {
usingMultiShipping: usingMultiShipping,
countryCode: currentLocale.country,
containerView: 'basket'
});
// eslint-disable-next-line no-undef
session.privacy.ipAddress = request.httpHeaders['x-is-remote_addr'];
// eslint-disable-next-line no-undef
var paymentData = JSON.parse(request.httpParameterMap.googletoken);
var GPtoken = paymentData.paymentMethodData.tokenizationData.token;
// eslint-disable-next-line no-undef
session.privacy.encryptedDataGP = Encoding.toBase64(new dw.util.Bytes(GPtoken));
billingFormErrors = COHelpers.validateBillingForm(paymentForm.addressFields);
var contactFieldsErrors = COHelpers.validateBillingForm(paymentForm.contactInfoFields);
if (Object.keys(billingFormErrors).length) {
// respond with form data and errors
res.json({
form: paymentForm,
fieldErrors: [billingFormErrors],
serverErrors: [],
error: true
});
} else if (Object.keys(contactFieldsErrors).length) {
res.json({
form: paymentForm,
fieldErrors: [contactFieldsErrors],
serverErrors: [],
error: true
});
} else {
viewData.address = {
firstName: {
value: paymentForm.addressFields.firstName.value
},
lastName: {
value: paymentForm.addressFields.lastName.value
},
address1: {
value: paymentForm.addressFields.address1.value
},
address2: {
value: paymentForm.addressFields.address2.value
},
city: {
value: paymentForm.addressFields.city.value
},
postalCode: {
value: paymentForm.addressFields.postalCode.value
},
countryCode: {
value: paymentForm.addressFields.country.value
}
};
if (Object.prototype.hasOwnProperty
.call(paymentForm.addressFields, 'states')) {
viewData.address.stateCode = {
value: paymentForm.addressFields.states.stateCode.value
};
}
viewData.paymentMethod = {
value: paymentForm.paymentMethod.value,
htmlName: paymentForm.paymentMethod.value
};
viewData.email = {
value: cart.customerEmail
};
viewData.phone = {
value: paymentForm.contactInfoFields.phone.value
};
viewData.saveCard = paymentForm.creditCardFields.saveCard.checked;
// Code to update card type details on place order page
var paymentInstrument = null;
// eslint-disable-next-line no-undef
if (!empty(cart.getPaymentInstruments())) {
paymentInstrument = cart.getPaymentInstruments()[0];
}
var cardType;
if (paymentInstrument != null) {
cardType = paymentInstrument.creditCardType;
}
if (paymentInstrument != null && paymentInstrument.paymentMethod === 'DW_GOOGLE_PAY') {
basketModel.billing.payment.selectedPaymentInstruments[0].type = cardType;
basketModel.billing.payment.selectedPaymentInstruments[0].maskedCreditCardNumber = paymentInstrument.creditCardNumber;
}
viewData.order = basketModel;
res.setViewData(viewData);
this.on('route:BeforeComplete', function (req, res) { // eslint-disable-line no-shadow
// eslint-disable-next-line no-shadow
var BasketMgr = require('dw/order/BasketMgr');
var Resource = require('dw/web/Resource');
var Transaction = require('dw/system/Transaction');
// eslint-disable-next-line no-shadow
var URLUtils = require('dw/web/URLUtils');
var basketCalculationHelpers = require('*/cartridge/scripts/helpers/basketCalculationHelpers');
// eslint-disable-next-line no-shadow
var currentBasket = BasketMgr.getCurrentBasket();
var billingData = res.getViewData();
if (!currentBasket) {
delete billingData.paymentInformation;
res.json({
error: true,
cartError: true,
fieldErrors: [],
serverErrors: [],
redirectUrl: URLUtils.url('Cart-Show').toString()
});
return;
}
var billingAddress = currentBasket.billingAddress;
var billingForm = server.forms.getForm('billing');
billingForm.creditCardFields.cardNumber.htmlValue = '';
billingForm.creditCardFields.securityCode.htmlValue = '';
Transaction.wrap(function () {
if (!billingAddress) {
billingAddress = currentBasket.createBillingAddress();
}
billingAddress.setFirstName(billingData.address.firstName.value);
billingAddress.setLastName(billingData.address.lastName.value);
billingAddress.setAddress1(billingData.address.address1.value);
billingAddress.setAddress2(billingData.address.address2.value);
billingAddress.setCity(billingData.address.city.value);
billingAddress.setPostalCode(billingData.address.postalCode.value);
if (Object.prototype.hasOwnProperty.call(billingData.address, 'stateCode')) {
billingAddress.setStateCode(billingData.address.stateCode.value);
}
billingAddress.setCountryCode(billingData.address.countryCode.value);
if (billingData.storedPaymentUUID) {
billingAddress.setPhone(req.currentCustomer.profile.phone);
currentBasket.setCustomerEmail(req.currentCustomer.profile.email);
} else {
billingAddress.setPhone(billingData.phone.value);
currentBasket.setCustomerEmail(billingData.email.value);
}
});
// Add hook to call google payment
var mobileAdaptor = require('*/cartridge/scripts/mobilepayments/MobilePaymentsAdapter');
var result = mobileAdaptor.updateBilling(currentBasket, paymentData.paymentMethodData.info, billingData.email.value);
// Calculate the basket
Transaction.wrap(function () {
basketCalculationHelpers.calculateTotals(currentBasket);
});
// Re-calculate the payments.
var calculatedPaymentTransaction = COHelpers.calculatePaymentTransaction(currentBasket);
if (calculatedPaymentTransaction.error) {
res.json({
form: paymentForm,
fieldErrors: [],
serverErrors: [Resource.msg('error.technical', 'checkout', null)],
error: true
});
return;
}
// return back google
if (result.success) {
// eslint-disable-next-line no-undef
if (request.httpParameterMap.paymentData != null) {
res.json({
error: false
});
}
}
});
}
return next();
});
/**
* *
* @param {*} cart *
* @param {*} shippingdetails *
* @returns {*} *
*/
function shippingUpdate(cart, shippingdetails) {
var logger = require('dw/system/Logger');
var mobileAdaptor;
var shipment = cart.defaultShipment;
// eslint-disable-next-line no-undef
if (!empty(shipment.getShippingAddress())) {
mobileAdaptor = require('*/cartridge/scripts/mobilepayments/MobilePaymentsAdapter');
mobileAdaptor.updateShipping(shippingdetails);
return {
success: true
};
}
try {
mobileAdaptor = require('*/cartridge/scripts/mobilepayments/MobilePaymentsAdapter');
mobileAdaptor.updateShipping(shippingdetails);
return {
success: true
};
} catch (err) {
logger.error('Error creating shipment from Google pay address: {0}', err.message);
return {
error: true,
errorMsg: err.message
};
}
}
// eslint-disable-next-line consistent-return
server.post('GetGooglePayToken', function (req, res, next) {
var Encoding = require('dw/crypto/Encoding');
// eslint-disable-next-line no-undef
var response = JSON.parse(request.httpParameterMap.paymentData);
var CardHelper = require('../scripts/helpers/CardHelper');
var Resource = require('dw/web/Resource');
// eslint-disable-next-line no-shadow
var BasketMgr = require('dw/order/BasketMgr');
var cart = BasketMgr.getCurrentBasket();
var shippingdetails = response.shippingAddress; // add condition for only cart
var COHelpers = require('*/cartridge/scripts/checkout/checkoutHelpers');
// eslint-disable-next-line no-shadow
var URLUtils = require('dw/web/URLUtils');
var mobileAdaptor = require('*/cartridge/scripts/mobilepayments/MobilePaymentsAdapter');
var Transaction = require('dw/system/Transaction');
var logger = require('dw/system/Logger');
// eslint-disable-next-line no-undef
session.privacy.ipAddress = request.httpHeaders['x-is-remote_addr'];
var result = mobileAdaptor.updateBilling(cart, response.paymentMethodData.info, response.email);
if (result.success) {
result = shippingUpdate(cart, shippingdetails);
if (result.success) {
cart = BasketMgr.getCurrentBasket();
// calculate cart and redirect to summary page
COHelpers.recalculateBasket(cart);
var ShippingHelper = require('*/cartridge/scripts/checkout/shippingHelpers');
Transaction.wrap(function () {
ShippingHelper.selectShippingMethod(cart.defaultShipment, null);
});
var GPtoken = response.paymentMethodData.tokenizationData.token;
// eslint-disable-next-line no-undef
session.privacy.encryptedDataGP = Encoding.toBase64(new dw.util.Bytes(GPtoken));
} else {
logger.error('Error in google Checkout payment: problem in billing details');
Transaction.wrap(function () {
CardHelper.removeExistingPaymentInstruments(cart);
});
COHelpers.recalculateBasket(cart);
res.json({
redirectUrl: URLUtils.url('Checkout-Begin', 'stage', 'payment', 'payerAuthError', Resource.msg('message.payerAuthError', 'error', null)),
error: true
});
return next();
}
// eslint-disable-next-line no-undef
if (request.httpParameterMap.paymentData != null) {
res.json({
status: 'success'
});
return next();
}
} else {
logger.error('Error in google Checkout payment: problem in billing details');
Transaction.wrap(function () {
CardHelper.removeExistingPaymentInstruments(cart);
});
COHelpers.recalculateBasket(cart);
res.json({
redirectUrl: URLUtils.url('Checkout-Begin', 'stage', 'payment', 'payerAuthError', 'error').toString(),
error: true
});
return next();
}
});
module.exports = server.exports();