/
checkoutcontroller.go
846 lines (705 loc) · 30.7 KB
/
checkoutcontroller.go
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
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
package controller
import (
"context"
"encoding/gob"
"errors"
"net/http"
"net/url"
"strings"
"go.opencensus.io/trace"
"flamingo.me/flamingo/v3/core/auth"
"flamingo.me/flamingo/v3/framework/flamingo"
"flamingo.me/flamingo/v3/framework/web"
cartApplication "flamingo.me/flamingo-commerce/v3/cart/application"
"flamingo.me/flamingo-commerce/v3/cart/domain/cart"
"flamingo.me/flamingo-commerce/v3/cart/domain/decorator"
"flamingo.me/flamingo-commerce/v3/cart/domain/placeorder"
"flamingo.me/flamingo-commerce/v3/cart/domain/validation"
"flamingo.me/flamingo-commerce/v3/checkout/application"
"flamingo.me/flamingo-commerce/v3/checkout/interfaces/controller/forms"
paymentDomain "flamingo.me/flamingo-commerce/v3/payment/domain"
)
const (
// CheckoutErrorFlashKey is the flash key that stores error infos that are shown on the checkout form page
CheckoutErrorFlashKey = "checkout.error.data"
// CheckoutSuccessFlashKey is the flash key that stores the order infos which are used on the checkout success page
CheckoutSuccessFlashKey = "checkout.success.data"
)
type (
// CheckoutViewData represents the checkout view data
CheckoutViewData struct {
DecoratedCart decorator.DecoratedCart
Form forms.CheckoutFormComposite
CartValidationResult validation.Result
ErrorInfos ViewErrorInfos
AvailablePayments map[string][]paymentDomain.Method
CustomerLoggedIn bool
}
// ViewErrorInfos defines the error info struct of the checkout controller views
ViewErrorInfos struct {
// HasError indicates that an general error happened
HasError bool
// If there is a general error this field is filled and can be used in the template
ErrorMessage string
// if the Error happens during processing payment (can be used in template to behave special in case of payment errors)
HasPaymentError bool
// if payment error occurred holds additional infos
PaymentErrorCode string
}
// SuccessViewData represents the success view data
SuccessViewData struct {
PaymentInfos []application.PlaceOrderPaymentInfo
PlacedOrderInfos placeorder.PlacedOrderInfos
Email string
PlacedDecoratedCart decorator.DecoratedCart
}
// ReviewStepViewData represents the success view data
ReviewStepViewData struct {
DecoratedCart decorator.DecoratedCart
ErrorInfos ViewErrorInfos
}
// PaymentStepViewData represents the payment flow view data
PaymentStepViewData struct {
FlowStatus paymentDomain.FlowStatus
ErrorInfos ViewErrorInfos
}
// PlaceOrderFlashData represents the data passed to the success page - they need to be "glob"able
PlaceOrderFlashData struct {
PlacedOrderInfos placeorder.PlacedOrderInfos
Email string
PaymentInfos []application.PlaceOrderPaymentInfo
PlacedCart cart.Cart
}
// EmptyCartInfo struct defines the data info on empty carts
EmptyCartInfo struct {
CartExpired bool
}
// CheckoutController represents the checkout controller with its injections
CheckoutController struct {
responder *web.Responder
router *web.Router
orderService *application.OrderService
decoratedCartFactory *decorator.DecoratedCartFactory
skipStartAction bool
skipReviewAction bool
showReviewStepAfterPaymentError bool
showEmptyCartPageIfNoItems bool
redirectToCartOnInvalideCart bool
privacyPolicyRequired bool
devMode bool
applicationCartService *cartApplication.CartService
applicationCartReceiverService *cartApplication.CartReceiverService
webIdentityService *auth.WebIdentityService
logger flamingo.Logger
checkoutFormController *forms.CheckoutFormController
}
)
func init() {
gob.Register(PlaceOrderFlashData{})
gob.Register(ViewErrorInfos{})
}
// Inject dependencies
func (cc *CheckoutController) Inject(
responder *web.Responder,
router *web.Router,
orderService *application.OrderService,
decoratedCartFactory *decorator.DecoratedCartFactory,
applicationCartService *cartApplication.CartService,
applicationCartReceiverService *cartApplication.CartReceiverService,
webIdentityService *auth.WebIdentityService,
logger flamingo.Logger,
checkoutFormController *forms.CheckoutFormController,
config *struct {
SkipStartAction bool `inject:"config:commerce.checkout.skipStartAction,optional"`
SkipReviewAction bool `inject:"config:commerce.checkout.skipReviewAction,optional"`
ShowReviewStepAfterPaymentError bool `inject:"config:commerce.checkout.showReviewStepAfterPaymentError,optional"`
ShowEmptyCartPageIfNoItems bool `inject:"config:commerce.checkout.showEmptyCartPageIfNoItems,optional"`
RedirectToCartOnInvalideCart bool `inject:"config:commerce.checkout.redirectToCartOnInvalidCart,optional"`
PrivacyPolicyRequired bool `inject:"config:commerce.checkout.privacyPolicyRequired,optional"`
DevMode bool `inject:"config:debug.mode,optional"`
},
) {
cc.responder = responder
cc.router = router
cc.checkoutFormController = checkoutFormController
cc.orderService = orderService
cc.decoratedCartFactory = decoratedCartFactory
cc.skipStartAction = config.SkipStartAction
cc.skipReviewAction = config.SkipReviewAction
cc.showReviewStepAfterPaymentError = config.ShowReviewStepAfterPaymentError
cc.showEmptyCartPageIfNoItems = config.ShowEmptyCartPageIfNoItems
cc.redirectToCartOnInvalideCart = config.RedirectToCartOnInvalideCart
cc.privacyPolicyRequired = config.PrivacyPolicyRequired
cc.devMode = config.DevMode
cc.applicationCartService = applicationCartService
cc.applicationCartReceiverService = applicationCartReceiverService
cc.webIdentityService = webIdentityService
cc.logger = logger.WithField(flamingo.LogKeyModule, "checkout").WithField(flamingo.LogKeyCategory, "checkoutController")
}
/*
The checkoutController implements a default process for a checkout:
* StartAction (supposed to show a switch to go to guest or customer)
* can be skipped with a configuration
* SubmitCheckoutAction
* This step is supposed to show a big form (validation and default values are configurable as well)
* payment can be selected in this step or in the next
* In cases a customer is logged in the form is pre populated
* ReviewAction (can be skipped through configuration)
* this step is supposed to show the current cart status just before checkout
* optional the paymentmethod can also be selected here
* PaymentAction
* Payment gets initialized in SubmitCheckoutAction or ReviewAction
* Handles different payment stages and reacts to payment status provided by gateway
* PlaceOrderAction
* Place the order if not already placed
* Add Information about the order to the session flash messages
* SuccessStep
* Displays order success page containing the order infos from the previously set flash message
*/
// StartAction handles the checkout start action
func (cc *CheckoutController) StartAction(ctx context.Context, r *web.Request) web.Result {
ctx, span := trace.StartSpan(ctx, "checkout/CheckoutController/StartAction")
defer span.End()
// Guard Clause if Cart cannot be fetched
decoratedCart, e := cc.applicationCartReceiverService.ViewDecoratedCart(ctx, r.Session())
if e != nil {
cc.logger.WithContext(ctx).Error("cart.checkoutcontroller.viewaction: Error ", e)
return cc.responder.Render("checkout/carterror", nil).SetNoCache()
}
guardRedirect := cc.getCommonGuardRedirects(ctx, r.Session(), decoratedCart)
if guardRedirect != nil {
return guardRedirect
}
viewData := cc.getBasicViewData(ctx, r, *decoratedCart)
// Guard Clause if Cart is empty
if decoratedCart.Cart.ItemCount() == 0 {
if cc.showEmptyCartPageIfNoItems {
return cc.responder.Render("checkout/emptycart", nil)
}
return cc.responder.Render("checkout/startcheckout", viewData).SetNoCache()
}
if cc.webIdentityService.Identify(ctx, r) != nil {
return cc.responder.RouteRedirect("checkout", nil)
}
if cc.skipStartAction {
return cc.responder.RouteRedirect("checkout", nil)
}
return cc.responder.Render("checkout/startcheckout", viewData).SetNoCache()
}
// SubmitCheckoutAction handles the main checkout
func (cc *CheckoutController) SubmitCheckoutAction(ctx context.Context, r *web.Request) web.Result {
ctx, span := trace.StartSpan(ctx, "checkout/CheckoutController/SubmitCheckoutAction")
defer span.End()
// Guard Clause if Cart can not be fetched
decoratedCart, e := cc.applicationCartReceiverService.ViewDecoratedCart(ctx, r.Session())
if e != nil {
cc.logger.WithContext(ctx).Error("cart.checkoutcontroller.submitaction: Error ", e)
return cc.responder.Render("checkout/carterror", nil).SetNoCache()
}
guardRedirect := cc.getCommonGuardRedirects(ctx, r.Session(), decoratedCart)
if guardRedirect != nil {
return guardRedirect
}
// reserve an unique order id for later order placing
_, err := cc.applicationCartService.ReserveOrderIDAndSave(ctx, r.Session())
if err != nil {
cc.logger.WithContext(ctx).Error("cart.checkoutcontroller.submitaction: Error ", err)
return cc.responder.Render("checkout/carterror", nil).SetNoCache()
}
return cc.showCheckoutFormAndHandleSubmit(ctx, r, "checkout/checkout")
}
// PlaceOrderAction functions as a return/notification URL for Payment Providers
func (cc *CheckoutController) PlaceOrderAction(ctx context.Context, r *web.Request) web.Result {
ctx, span := trace.StartSpan(ctx, "checkout/CheckoutController/PlaceOrderAction")
defer span.End()
session := web.SessionFromContext(ctx)
decoratedCart, err := cc.orderService.LastPlacedOrCurrentCart(ctx)
if err != nil {
cc.logger.WithContext(ctx).Error("cart.checkoutcontroller.placeorderaction: Error ", err)
return cc.responder.Render("checkout/carterror", nil).SetNoCache()
}
guardRedirect := cc.getCommonGuardRedirects(ctx, session, decoratedCart)
if guardRedirect != nil {
return guardRedirect
}
if cc.showEmptyCartPageIfNoItems && decoratedCart.Cart.ItemCount() == 0 {
return cc.responder.Render("checkout/emptycart", nil).SetNoCache()
}
return cc.placeOrderAction(ctx, r, session, decoratedCart)
}
func (cc *CheckoutController) placeOrderAction(ctx context.Context, r *web.Request, session *web.Session, decoratedCart *decorator.DecoratedCart) web.Result {
ctx, span := trace.StartSpan(ctx, "checkout/CheckoutController/placeOrderAction")
defer span.End()
var placedOrderInfo *application.PlaceOrderInfo
var err error
if cc.orderService.HasLastPlacedOrder(ctx) {
placedOrderInfo, _ = cc.orderService.LastPlacedOrder(ctx)
cc.orderService.ClearLastPlacedOrder(ctx)
} else {
if decoratedCart.Cart.GrandTotal.IsZero() {
// Nothing to pay, so cart can be placed without payment processing.
placedOrderInfo, err = cc.orderService.CurrentCartPlaceOrder(ctx, session, placeorder.Payment{})
} else {
placedOrderInfo, err = cc.orderService.CurrentCartPlaceOrderWithPaymentProcessing(ctx, session)
}
cc.orderService.ClearLastPlacedOrder(ctx)
if err != nil {
if paymentError, ok := err.(*paymentDomain.Error); ok {
if cc.showReviewStepAfterPaymentError && !cc.skipReviewAction {
return cc.redirectToReviewFormWithErrors(ctx, r, paymentError)
}
}
return cc.redirectToCheckoutFormWithErrors(ctx, r, err)
}
}
r.Session().AddFlash(PlaceOrderFlashData{
PlacedOrderInfos: placedOrderInfo.PlacedOrders,
Email: placedOrderInfo.ContactEmail,
PlacedCart: decoratedCart.Cart,
PaymentInfos: placedOrderInfo.PaymentInfos,
}, CheckoutSuccessFlashKey)
return cc.responder.RouteRedirect("checkout.success", nil)
}
// SuccessAction handles the order success action
func (cc *CheckoutController) SuccessAction(ctx context.Context, r *web.Request) web.Result {
ctx, span := trace.StartSpan(ctx, "checkout/CheckoutController/SuccessAction")
defer span.End()
flashes := r.Session().Flashes(CheckoutSuccessFlashKey)
if len(flashes) > 0 {
// if in development mode, then restore the last order in flash session.
if cc.devMode {
r.Session().AddFlash(flashes[len(flashes)-1], CheckoutSuccessFlashKey)
}
if placeOrderFlashData, ok := flashes[len(flashes)-1].(PlaceOrderFlashData); ok {
decoratedCart := cc.decoratedCartFactory.Create(ctx, placeOrderFlashData.PlacedCart)
viewData := SuccessViewData{
Email: placeOrderFlashData.Email,
PaymentInfos: placeOrderFlashData.PaymentInfos,
PlacedDecoratedCart: *decoratedCart,
PlacedOrderInfos: placeOrderFlashData.PlacedOrderInfos,
}
return cc.responder.Render("checkout/success", viewData).SetNoCache()
}
}
return cc.responder.RouteRedirect("checkout.expired", nil).SetNoCache()
}
// ExpiredAction handles the expired cart action
func (cc *CheckoutController) ExpiredAction(ctx context.Context, _ *web.Request) web.Result {
_, span := trace.StartSpan(ctx, "checkout/CheckoutController/ExpiredAction")
defer span.End()
if cc.showEmptyCartPageIfNoItems {
return cc.responder.Render("checkout/emptycart", EmptyCartInfo{
CartExpired: true,
}).SetNoCache()
}
return cc.responder.Render("checkout/expired", nil).SetNoCache()
}
func (cc *CheckoutController) getPaymentReturnURL(r *web.Request) *url.URL {
paymentURL, _ := cc.router.Absolute(r, "checkout.payment", nil)
return paymentURL
}
func (cc *CheckoutController) getBasicViewData(ctx context.Context, request *web.Request, decoratedCart decorator.DecoratedCart) CheckoutViewData {
ctx, span := trace.StartSpan(ctx, "checkout/CheckoutController/getBasicViewData")
defer span.End()
paymentGatewaysMethods := make(map[string][]paymentDomain.Method)
for gatewayCode, gateway := range cc.orderService.GetAvailablePaymentGateways(ctx) {
paymentGatewaysMethods[gatewayCode] = gateway.Methods()
}
return CheckoutViewData{
DecoratedCart: decoratedCart,
CartValidationResult: cc.applicationCartService.ValidateCart(ctx, request.Session(), &decoratedCart),
AvailablePayments: paymentGatewaysMethods,
CustomerLoggedIn: cc.webIdentityService.Identify(ctx, request) != nil,
}
}
// showCheckoutFormAndHandleSubmit - Action that shows the form
func (cc *CheckoutController) showCheckoutFormAndHandleSubmit(ctx context.Context, r *web.Request, template string) web.Result {
ctx, span := trace.StartSpan(ctx, "checkout/CheckoutController/showCheckoutFormAndHandleSubmit")
defer span.End()
session := r.Session()
// Guard Clause if Cart can't be fetched
decoratedCart, e := cc.applicationCartReceiverService.ViewDecoratedCart(ctx, session)
if e != nil {
cc.logger.WithContext(ctx).Error("cart.checkoutcontroller.submitaction: Error ", e)
return cc.responder.Render("checkout/carterror", nil).SetNoCache()
}
if len(cc.orderService.GetAvailablePaymentGateways(ctx)) == 0 {
cc.logger.WithContext(ctx).Error("cart.checkoutcontroller.submitaction: Error No Payment set")
return cc.responder.Render("checkout/carterror", nil).SetNoCache()
}
viewData := cc.getBasicViewData(ctx, r, *decoratedCart)
// Guard Clause if Cart is empty
if decoratedCart.Cart.ItemCount() == 0 {
if cc.showEmptyCartPageIfNoItems {
return cc.responder.Render("checkout/emptycart", nil).SetNoCache()
}
return cc.responder.Render(template, viewData).SetNoCache()
}
if r.Request().Method != http.MethodPost {
// Form not Submitted:
flashViewErrorInfos, found := cc.getViewErrorsFromSessionFlash(r)
if found {
viewData.ErrorInfos = *flashViewErrorInfos
}
form, err := cc.checkoutFormController.GetUnsubmittedForm(ctx, r)
if err != nil {
if !found {
viewData.ErrorInfos = getViewErrorInfo(err)
}
return cc.responder.Render(template, viewData).SetNoCache()
}
viewData.Form = *form
return cc.responder.Render(template, viewData).SetNoCache()
}
// Form submitted:
form, success, err := cc.checkoutFormController.HandleFormAction(ctx, r)
if err != nil {
viewData.ErrorInfos = getViewErrorInfo(err)
return cc.responder.Render(template, viewData).SetNoCache()
}
viewData.Form = *form
if success {
if cc.skipReviewAction {
canProceed, err := cc.checkTermsAndPrivacyPolicy(r)
if !canProceed || err != nil {
viewData.ErrorInfos = getViewErrorInfo(err)
return cc.responder.Render(template, viewData).SetNoCache()
}
cc.logger.WithContext(ctx).Debug("submit checkout succeeded: redirect to checkout.review")
return cc.processPayment(ctx, r)
}
response := cc.responder.RouteRedirect("checkout.review", nil).SetNoCache()
return response
}
// Default: show form with its validation result
return cc.responder.Render(template, viewData).SetNoCache()
}
// redirectToCheckoutFormWithErrors will store the error as a flash message and redirect to the checkout form where it is then displayed
func (cc *CheckoutController) redirectToCheckoutFormWithErrors(ctx context.Context, r *web.Request, err error) web.Result {
ctx, span := trace.StartSpan(ctx, "checkout/CheckoutController/redirectToCheckoutFormWithErrors")
defer span.End()
cc.logger.WithContext(ctx).Info("redirect to checkout form and display error: ", err)
r.Session().AddFlash(getViewErrorInfo(err), CheckoutErrorFlashKey)
return cc.responder.RouteRedirect("checkout", nil).SetNoCache()
}
// redirectToReviewFormWithErrors will store the error as a flash message and redirect to the review form where it is then displayed
func (cc *CheckoutController) redirectToReviewFormWithErrors(ctx context.Context, r *web.Request, err error) web.Result {
ctx, span := trace.StartSpan(ctx, "checkout/CheckoutController/redirectToReviewFormWithErrors")
defer span.End()
cc.logger.WithContext(ctx).Info("redirect to review form and display error: ", err)
r.Session().AddFlash(getViewErrorInfo(err), CheckoutErrorFlashKey)
return cc.responder.RouteRedirect("checkout.review", nil).SetNoCache()
}
func getViewErrorInfo(err error) ViewErrorInfos {
if err == nil {
return ViewErrorInfos{
HasError: true,
HasPaymentError: false,
}
}
hasPaymentError := false
paymentErrorCode := ""
if paymentErr, ok := err.(*paymentDomain.Error); ok {
hasPaymentError = true
if paymentErr.ErrorCode == paymentDomain.PaymentErrorAbortedByCustomer {
// in case of customer payment abort don't show error message in frontend
return ViewErrorInfos{
HasError: false,
HasPaymentError: false,
}
}
paymentErrorCode = paymentErr.ErrorCode
}
return ViewErrorInfos{
HasError: true,
ErrorMessage: err.Error(),
HasPaymentError: hasPaymentError,
PaymentErrorCode: paymentErrorCode,
}
}
func (cc *CheckoutController) processPayment(ctx context.Context, r *web.Request) web.Result {
ctx, span := trace.StartSpan(ctx, "checkout/CheckoutController/processPayment")
defer span.End()
session := web.SessionFromContext(ctx)
// guard clause if cart can not be fetched
decoratedCart, err := cc.applicationCartReceiverService.ViewDecoratedCart(ctx, r.Session())
if err != nil {
cc.logger.WithContext(ctx).Error("cart.checkoutcontroller.submitaction: Error ", err)
return cc.responder.Render("checkout/carterror", nil).SetNoCache()
}
// Cart grand total is zero, so no payment needed.
if decoratedCart.Cart.GrandTotal.IsZero() {
return cc.responder.RouteRedirect("checkout.placeorder", nil)
}
// get the payment gateway for the specified payment selection
gateway, err := cc.orderService.GetPaymentGateway(ctx, decoratedCart.Cart.PaymentSelection.Gateway())
if err != nil {
return cc.redirectToCheckoutFormWithErrors(ctx, r, err)
}
returnURL := cc.getPaymentReturnURL(r)
// start the payment flow
flowResult, err := gateway.StartFlow(ctx, &decoratedCart.Cart, application.PaymentFlowStandardCorrelationID, returnURL)
if err != nil {
return cc.redirectToCheckoutFormWithErrors(ctx, r, err)
}
// payment flow requires an early place order
if flowResult.EarlyPlaceOrder {
payment, err := gateway.OrderPaymentFromFlow(ctx, &decoratedCart.Cart, application.PaymentFlowStandardCorrelationID)
if err != nil {
return cc.redirectToCheckoutFormWithErrors(ctx, r, err)
}
_, err = cc.orderService.CurrentCartPlaceOrder(ctx, session, *payment)
if err != nil {
return cc.redirectToCheckoutFormWithErrors(ctx, r, err)
}
}
return cc.responder.RouteRedirect("checkout.payment", nil)
}
// ReviewAction handles the cart review action
func (cc *CheckoutController) ReviewAction(ctx context.Context, r *web.Request) web.Result {
ctx, span := trace.StartSpan(ctx, "checkout/CheckoutController/ReviewAction")
defer span.End()
if cc.skipReviewAction {
return cc.responder.Render("checkout/carterror", nil)
}
// payment / order already in process redirect to payment status page
if cc.orderService.HasLastPlacedOrder(ctx) {
return cc.responder.RouteRedirect("checkout.payment", nil)
}
// Guard Clause if cart can not be fetched
decoratedCart, err := cc.applicationCartReceiverService.ViewDecoratedCartWithoutCache(ctx, r.Session())
if err != nil {
cc.logger.WithContext(ctx).Error("cart.checkoutcontroller.submitaction: Error ", err)
return cc.responder.Render("checkout/carterror", nil).SetNoCache()
}
if cc.showEmptyCartPageIfNoItems && decoratedCart.Cart.ItemCount() == 0 {
return cc.responder.Render("checkout/emptycart", nil).SetNoCache()
}
guardRedirect := cc.getCommonGuardRedirects(ctx, r.Session(), decoratedCart)
if guardRedirect != nil {
return guardRedirect
}
viewData := ReviewStepViewData{
DecoratedCart: *decoratedCart,
}
flashViewErrorInfos, found := cc.getViewErrorsFromSessionFlash(r)
if found {
viewData.ErrorInfos = *flashViewErrorInfos
return cc.responder.Render("checkout/review", viewData).SetNoCache()
}
// check for terms and conditions and privacy policy
canProceed, err := cc.checkTermsAndPrivacyPolicy(r)
if err != nil {
viewData.ErrorInfos = getViewErrorInfo(err)
}
// Everything valid then return
if canProceed && err == nil {
if decoratedCart.Cart.IsPaymentSelected() {
return cc.processPayment(ctx, r)
}
if decoratedCart.Cart.GrandTotal.IsZero() {
return cc.responder.RouteRedirect("checkout.placeorder", nil)
}
}
return cc.responder.Render("checkout/review", viewData).SetNoCache()
}
// PaymentAction asks the payment adapter about the current payment status and handle it
func (cc *CheckoutController) PaymentAction(ctx context.Context, r *web.Request) web.Result {
ctx, span := trace.StartSpan(ctx, "checkout/CheckoutController/PaymentAction")
defer span.End()
session := web.SessionFromContext(ctx)
decoratedCart, err := cc.orderService.LastPlacedOrCurrentCart(ctx)
if err != nil {
cc.logger.WithContext(ctx).Error(err)
return cc.responder.Render("checkout/carterror", nil).SetNoCache()
}
if decoratedCart.Cart.PaymentSelection == nil {
cc.logger.WithContext(ctx).Info("No PaymentSelection for cart with ID ", decoratedCart.Cart.ID)
return cc.responder.RouteRedirect("checkout.expired", nil).SetNoCache()
}
gateway, err := cc.orderService.GetPaymentGateway(ctx, decoratedCart.Cart.PaymentSelection.Gateway())
if err != nil {
return cc.redirectToCheckoutFormWithErrors(ctx, r, err)
}
flowStatus, err := gateway.FlowStatus(ctx, &decoratedCart.Cart, application.PaymentFlowStandardCorrelationID)
if err != nil {
cc.logger.WithContext(ctx).Error("cart.checkoutcontroller.paymentaction: Error ", err)
// payment failed, reopen the cart to make it still usable.
if cc.orderService.HasLastPlacedOrder(ctx) {
infos, err := cc.orderService.LastPlacedOrder(ctx)
if err != nil {
cc.logger.WithContext(ctx).Error(err)
return cc.responder.RouteRedirect("checkout", nil)
}
_, err = cc.orderService.CancelOrder(ctx, session, infos)
if err != nil {
cc.logger.WithContext(ctx).Error(err)
return cc.responder.RouteRedirect("checkout", nil)
}
cc.orderService.ClearLastPlacedOrder(ctx)
_, _ = cc.applicationCartService.ForceReserveOrderIDAndSave(ctx, r.Session())
}
return cc.redirectToCheckoutFormWithErrors(ctx, r, err)
}
viewData := &PaymentStepViewData{
FlowStatus: *flowStatus,
}
switch flowStatus.Status {
case paymentDomain.PaymentFlowStatusUnapproved:
// payment just started render payment page which handles actions
return cc.responder.Render("checkout/payment", viewData).SetNoCache()
case paymentDomain.PaymentFlowStatusApproved:
// payment is done but not confirmed by customer, confirm it and place order
orderPayment, err := gateway.OrderPaymentFromFlow(ctx, &decoratedCart.Cart, application.PaymentFlowStandardCorrelationID)
if err != nil {
viewData.ErrorInfos = getViewErrorInfo(err)
cc.logger.WithContext(ctx).Error(err)
return cc.responder.Render("checkout/payment", viewData).SetNoCache()
}
err = gateway.ConfirmResult(ctx, &decoratedCart.Cart, orderPayment)
if err != nil {
viewData.ErrorInfos = getViewErrorInfo(err)
cc.logger.WithContext(ctx).Error(err)
return cc.responder.Render("checkout/payment", viewData).SetNoCache()
}
return cc.responder.RouteRedirect("checkout.placeorder", nil)
case paymentDomain.PaymentFlowStatusCompleted:
// payment is done and confirmed, place order
return cc.responder.RouteRedirect("checkout.placeorder", nil)
case paymentDomain.PaymentFlowStatusAborted:
// payment was aborted by user, redirect to checkout so a new payment can be started
if cc.orderService.HasLastPlacedOrder(ctx) {
infos, err := cc.orderService.LastPlacedOrder(ctx)
if err != nil {
cc.logger.WithContext(ctx).Error(err)
if cc.showReviewStepAfterPaymentError && !cc.skipReviewAction {
return cc.redirectToReviewFormWithErrors(ctx, r, flowStatus.Error)
}
return cc.redirectToCheckoutFormWithErrors(ctx, r, err)
}
// ignore restored cart here since it gets fetched newly in checkout
_, err = cc.orderService.CancelOrder(ctx, session, infos)
if err != nil {
cc.logger.WithContext(ctx).Error(err)
}
cc.orderService.ClearLastPlacedOrder(ctx)
_, _ = cc.applicationCartService.ForceReserveOrderIDAndSave(ctx, r.Session())
}
// mark payment selection as new payment to allow the user to retry
newPaymentSelection, err := decoratedCart.Cart.PaymentSelection.GenerateNewIdempotencyKey()
if err != nil {
cc.logger.WithContext(ctx).Error("cart.checkoutcontroller.paymentaction: Error during GenerateNewIdempotencyKey:", err)
} else {
err = cc.applicationCartService.UpdatePaymentSelection(ctx, session, newPaymentSelection)
if err != nil {
cc.logger.WithContext(ctx).Error("cart.checkoutcontroller.paymentaction: Error during UpdatePaymentSelection:", err)
}
}
if cc.showReviewStepAfterPaymentError && !cc.skipReviewAction {
return cc.responder.RouteRedirect("checkout.review", nil)
}
return cc.responder.RouteRedirect("checkout", nil)
case paymentDomain.PaymentFlowStatusFailed, paymentDomain.PaymentFlowStatusCancelled:
// payment failed or is cancelled by payment provider, redirect back to checkout
if cc.orderService.HasLastPlacedOrder(ctx) {
infos, err := cc.orderService.LastPlacedOrder(ctx)
if err != nil {
cc.logger.WithContext(ctx).Error(err)
if cc.showReviewStepAfterPaymentError && !cc.skipReviewAction {
return cc.redirectToReviewFormWithErrors(ctx, r, flowStatus.Error)
}
return cc.redirectToCheckoutFormWithErrors(ctx, r, err)
}
_, err = cc.orderService.CancelOrder(ctx, session, infos)
if err != nil {
cc.logger.WithContext(ctx).Error(err)
}
cc.orderService.ClearLastPlacedOrder(ctx)
_, _ = cc.applicationCartService.ForceReserveOrderIDAndSave(ctx, r.Session())
}
// mark payment selection as new payment to allow the user to retry
newPaymentSelection, err := decoratedCart.Cart.PaymentSelection.GenerateNewIdempotencyKey()
if err != nil {
cc.logger.WithContext(ctx).Error("cart.checkoutcontroller.paymentaction: Error during GenerateNewIdempotencyKey:", err)
} else {
err = cc.applicationCartService.UpdatePaymentSelection(ctx, session, newPaymentSelection)
if err != nil {
cc.logger.WithContext(ctx).Error("cart.checkoutcontroller.paymentaction: Error during UpdatePaymentSelection:", err)
}
}
err = flowStatus.Error
if flowStatus.Error == nil {
// fallback if payment gateway didn't respond with a proper error
switch flowStatus.Status {
case paymentDomain.PaymentFlowStatusCancelled:
err = &paymentDomain.Error{
ErrorCode: paymentDomain.PaymentErrorCodeCancelled,
ErrorMessage: paymentDomain.PaymentErrorCodeCancelled,
}
case paymentDomain.PaymentFlowStatusFailed:
err = &paymentDomain.Error{
ErrorCode: paymentDomain.PaymentErrorCodeFailed,
ErrorMessage: paymentDomain.PaymentErrorCodeFailed,
}
}
}
if cc.showReviewStepAfterPaymentError && !cc.skipReviewAction {
return cc.redirectToReviewFormWithErrors(ctx, r, err)
}
return cc.redirectToCheckoutFormWithErrors(ctx, r, err)
case paymentDomain.PaymentFlowWaitingForCustomer:
// payment pending, waiting for customer
return cc.responder.Render("checkout/payment", viewData).SetNoCache()
default:
// show payment page which can react to unknown payment status
return cc.responder.Render("checkout/payment", viewData).SetNoCache()
}
}
// getCommonGuardRedirects checks config and may return a redirect that should be executed before the common checkou actions
func (cc *CheckoutController) getCommonGuardRedirects(ctx context.Context, session *web.Session, decoratedCart *decorator.DecoratedCart) web.Result {
ctx, span := trace.StartSpan(ctx, "checkout/CheckoutController/getCommonGuardRedirects")
defer span.End()
if cc.redirectToCartOnInvalideCart {
result := cc.applicationCartService.ValidateCart(ctx, session, decoratedCart)
if !result.IsValid() {
cc.logger.WithContext(ctx).Info("StartAction > RedirectToCartOnInvalidCart")
resp := cc.responder.RouteRedirect("cart.view", nil)
resp.SetNoCache()
return resp
}
}
return nil
}
// checkTermsAndPrivacyPolicy checks if TermsAndConditions and PrivacyPolicy is set as required
// the returned error indicates that the check failed
func (cc *CheckoutController) checkTermsAndPrivacyPolicy(r *web.Request) (bool, error) {
proceed, _ := r.Form1("proceed")
termsAndConditions, _ := r.Form1("termsAndConditions")
privacyPolicy, _ := r.Form1("privacyPolicy")
// prepare a minimal slice for error messages
errorMessages := make([]string, 0, 2)
// check for privacy policy if required
if cc.privacyPolicyRequired && privacyPolicy != "1" && proceed == "1" {
errorMessages = append(errorMessages, "privacy_policy_required")
}
// check for terms and conditions if required
if termsAndConditions != "1" {
errorMessages = append(errorMessages, "terms_and_conditions_required")
}
canProceed := proceed == "1" && (!cc.privacyPolicyRequired || privacyPolicy == "1") && termsAndConditions == "1"
if len(errorMessages) == 0 {
return canProceed, nil
}
return canProceed, errors.New(strings.Join(errorMessages, ", "))
}
// getViewErrorsFromSessionFlash check if session flash data contains checkout errors, if so return them and remove the flash message from the session
func (cc *CheckoutController) getViewErrorsFromSessionFlash(r *web.Request) (*ViewErrorInfos, bool) {
flashErrors := r.Session().Flashes(CheckoutErrorFlashKey)
if len(flashErrors) == 1 {
flashViewErrorInfos, ok := flashErrors[0].(ViewErrorInfos)
if ok {
return &flashViewErrorInfos, true
}
}
return nil, false
}