piekarnikgosipl/orders/order.go
2026-11-08 20:32:49 +01:00

183 lines
4.9 KiB
Go

package orders
import (
"crypto/rand"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"io"
"log"
"math"
"net/http"
"piekarnikgosipl/data"
"strconv"
"strings"
"unicode"
"github.com/stripe/stripe-go/v82"
"github.com/stripe/stripe-go/v82/checkout/session"
"github.com/stripe/stripe-go/v82/webhook"
)
const retainer = 5000 // 50zł
type listItem struct {
id string
count int // count multiplied by 100 to allow for half item purchases
}
type order struct {
name string
phone string
items []listItem
}
func InitStripe(secret string) { stripe.Key = secret }
func parseFloat(input string) (int, error) {
val, err := strconv.ParseFloat(input, 64)
if err != nil {
return 0, fmt.Errorf("Invalid float format")
}
if val < 0 || val > 100 {
return 0, fmt.Errorf("Value must be between 0 and 100")
}
doubled := val * 2
if math.Abs(doubled-math.Round(doubled)) > 1e-9 {
return 0, fmt.Errorf("Value must be a multiple of 0.5")
}
return int(math.Round(val * 100)), nil
}
func validName(name string) bool {
if name == "" || len(name) > 100 {
return false
}
return strings.IndexFunc(name, unicode.IsControl) == -1
}
func parseOrder(r *http.Request) (order, error) {
var o order
var err error
var errorList []error
o.name = strings.TrimSpace(r.PostFormValue("name"))
if !validName(o.name) {
errorList = append(errorList, fmt.Errorf("Invalid name"))
}
o.phone, err = parsePhone(r.PostFormValue("phone"))
if err != nil {
errorList = append(errorList, err)
}
for _, item := range data.Swieta {
count, err := parseFloat(r.PostFormValue(item.Id))
if err != nil {
errorList = append(errorList, fmt.Errorf("Can't parse the count for %v: %v", item.Name, err))
continue
}
if count%10 == 5 && !item.Halveable {
errorList = append(errorList, fmt.Errorf("This item can't be bought in fractions %v", item.Name))
continue
}
o.items = append(o.items, listItem{item.Id, count})
}
return o, errors.Join(errorList...)
}
func newOrderID() string {
b := make([]byte, 8)
rand.Read(b)
return hex.EncodeToString(b)
}
func startCheckout(w http.ResponseWriter, r *http.Request, o order) {
id := newOrderID()
log.Println("ORDER_PENDING", id, o)
url := r.URL.RequestURI()
log.Println(url)
s, err := session.New(&stripe.CheckoutSessionParams{
Mode: stripe.String("payment"),
ClientReferenceID: stripe.String(id),
Locale: stripe.String("pl"),
LineItems: []*stripe.CheckoutSessionLineItemParams{{
Quantity: stripe.Int64(1),
PriceData: &stripe.CheckoutSessionLineItemPriceDataParams{
Currency: stripe.String("pln"),
UnitAmount: stripe.Int64(retainer),
ProductData: &stripe.CheckoutSessionLineItemPriceDataProductDataParams{
Name: stripe.String("Zaliczka na zamówienie " + id),
},
},
}},
SuccessURL: stripe.String("https://piekarnikgosi.pl/dziekujemy?order=" + id),
CancelURL: stripe.String("https://piekarnikgosi.pl/"),
})
if err != nil {
log.Println("ORDER_STRIPE_ERROR", id, err)
writeErrors(w, r, http.StatusInternalServerError, "Nie udało się przejść do płatności. Spróbuj ponownie lub zadzwoń: 690 214 515.")
return
}
if r.Header.Get("HX-Request") == "true" {
w.Header().Set("HX-Redirect", s.URL)
w.WriteHeader(http.StatusOK)
return
}
http.Redirect(w, r, s.URL, http.StatusSeeOther)
}
func OrderHandler(w http.ResponseWriter, r *http.Request) {
r.Body = http.MaxBytesReader(w, r.Body, 16<<10)
if err := r.ParseForm(); err != nil {
writeErrors(w, r, http.StatusRequestEntityTooLarge, "Formularz jest nieprawidłowy.")
return
}
o, err := parseOrder(r)
if err != nil {
log.Println("ORDER_INVALID", o, err)
writeErrors(w, r, http.StatusUnprocessableEntity, errorMessages(err)...)
return
}
startCheckout(w, r, o)
}
func WebhookHandler(secret string) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
body, err := io.ReadAll(http.MaxBytesReader(w, r.Body, 65536))
if err != nil {
http.Error(w, "bad body", http.StatusBadRequest)
return
}
event, err := webhook.ConstructEventWithOptions(body, r.Header.Get("Stripe-Signature"), secret,
webhook.ConstructEventOptions{IgnoreAPIVersionMismatch: true})
if err != nil {
http.Error(w, "bad signature", http.StatusBadRequest)
return
}
if event.Type != "checkout.session.completed" && event.Type != "checkout.session.async_payment_succeeded" {
w.WriteHeader(http.StatusOK)
return
}
var s stripe.CheckoutSession
if err := json.Unmarshal(event.Data.Raw, &s); err != nil {
http.Error(w, "bad event", http.StatusBadRequest)
return
}
switch {
case s.PaymentStatus != stripe.CheckoutSessionPaymentStatusPaid:
log.Println("ORDER_NOT_YET_PAID", s.ClientReferenceID, s.ID, s.PaymentStatus)
case s.AmountTotal != retainer || s.Currency != stripe.CurrencyPLN:
log.Println("ORDER_PAYMENT_MISMATCH", s.ClientReferenceID, s.ID, s.AmountTotal, s.Currency)
default:
log.Println("ORDER_PAID", s.ClientReferenceID, s.ID)
}
w.WriteHeader(http.StatusOK)
}
}