shop.tonybtw.com

shop.tonybtw.com

https://git.tonybtw.com/shop.tonybtw.com.git git://git.tonybtw.com/shop.tonybtw.com.git
2,383 bytes raw
1
package handlers
2
3
import (
4
	"fmt"
5
	"net/http"
6
7
	"shop.tonybtw.com/internal/lib"
8
	"shop.tonybtw.com/internal/models"
9
	"shop.tonybtw.com/internal/views"
10
)
11
12
type Checkout_Handler struct {
13
	ctx *lib.App_Context
14
}
15
16
func New_Checkout_Handler(ctx *lib.App_Context) *Checkout_Handler {
17
	return &Checkout_Handler{ctx: ctx}
18
}
19
20
func (h *Checkout_Handler) Show_Checkout(w http.ResponseWriter, r *http.Request) {
21
	session_id := lib.Get_Session_ID(r)
22
	cart_json := h.ctx.Session_Store.Get_Cart(session_id)
23
	cart, _ := models.Parse_Cart(cart_json)
24
25
	if len(cart) == 0 {
26
		lib.Redirect(w, r, "/cart")
27
		return
28
	}
29
30
	items, err := models.Get_Cart_Items_With_Details(h.ctx.DB, cart)
31
	if err != nil {
32
		http.Error(w, "Failed to load cart", http.StatusInternalServerError)
33
		return
34
	}
35
36
	total := models.Get_Cart_Total(items)
37
	csrf_token := lib.Get_CSRF_Token(session_id)
38
	cart_count := models.Count_Cart_Items(cart)
39
40
	views.Checkout(items, total, csrf_token, cart_count).Render(r.Context(), w)
41
}
42
43
func (h *Checkout_Handler) Create_Session(w http.ResponseWriter, r *http.Request) {
44
	session_id := lib.Get_Session_ID(r)
45
	cart_json := h.ctx.Session_Store.Get_Cart(session_id)
46
	cart, _ := models.Parse_Cart(cart_json)
47
48
	if len(cart) == 0 {
49
		lib.Redirect(w, r, "/cart")
50
		return
51
	}
52
53
	items, err := models.Get_Cart_Items_With_Details(h.ctx.DB, cart)
54
	if err != nil {
55
		http.Error(w, "Failed to load cart", http.StatusInternalServerError)
56
		return
57
	}
58
59
	var line_items []lib.Stripe_Line_Item
60
	for _, item := range items {
61
		line_items = append(line_items, lib.Stripe_Line_Item{
62
			Name:     fmt.Sprintf("%s (%s)", item.Name, item.Size),
63
			Amount:   int64(item.Price),
64
			Quantity: int64(item.Quantity),
65
		})
66
	}
67
68
	host := r.Host
69
	scheme := "http"
70
	if r.TLS != nil {
71
		scheme = "https"
72
	}
73
74
	success_url := fmt.Sprintf("%s://%s/success", scheme, host)
75
	cancel_url := fmt.Sprintf("%s://%s/cart", scheme, host)
76
77
	stripe_session, err := lib.Create_Checkout_Session(line_items, success_url, cancel_url)
78
	if err != nil {
79
		cart_count := models.Count_Cart_Items(cart)
80
		views.Error("Failed to create checkout session", cart_count).Render(r.Context(), w)
81
		return
82
	}
83
84
	lib.Redirect(w, r, stripe_session.URL)
85
}
86
87
func (h *Checkout_Handler) Show_Success(w http.ResponseWriter, r *http.Request) {
88
	session_id := lib.Get_Session_ID(r)
89
	h.ctx.Session_Store.Set_Cart(session_id, "")
90
91
	views.Success(0).Render(r.Context(), w)
92
}