dev env
This commit is contained in:
parent
6185a59de9
commit
9e16843a29
8 changed files with 178 additions and 123 deletions
1
.gitignore
vendored
1
.gitignore
vendored
|
|
@ -2,3 +2,4 @@ www
|
||||||
.DS_Store
|
.DS_Store
|
||||||
*_templ.go
|
*_templ.go
|
||||||
piekarnikgosi
|
piekarnikgosi
|
||||||
|
.env
|
||||||
|
|
|
||||||
|
|
@ -1,7 +1,16 @@
|
||||||
[
|
[
|
||||||
{
|
{
|
||||||
"label": "Run",
|
"label": "Run",
|
||||||
"command": "go tool templ generate && go run .",
|
"command": "./dev.sh",
|
||||||
|
"use_new_terminal": false,
|
||||||
|
"allow_concurrent_runs": false,
|
||||||
|
"reveal": "always",
|
||||||
|
"shell": "system",
|
||||||
|
"save": "all",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"label": "Build Static Site",
|
||||||
|
"command": "go tool templ generate && go run . -- build",
|
||||||
"use_new_terminal": false,
|
"use_new_terminal": false,
|
||||||
"allow_concurrent_runs": false,
|
"allow_concurrent_runs": false,
|
||||||
"reveal": "always",
|
"reveal": "always",
|
||||||
|
|
|
||||||
|
|
@ -4,8 +4,8 @@
|
||||||
--swieta-red: oklch(45% .15 25);
|
--swieta-red: oklch(45% .15 25);
|
||||||
--border-color: color-mix(in oklab, var(--swieta-green) 25%, transparent);
|
--border-color: color-mix(in oklab, var(--swieta-green) 25%, transparent);
|
||||||
|
|
||||||
--swieta-pad: 2rem; /* outer: section padding, gaps between cards */
|
--swieta-pad: 2rem;
|
||||||
--swieta-card-pad: 2rem; /* inner: padding inside cards and boxes */
|
--swieta-card-pad: 2rem;
|
||||||
}
|
}
|
||||||
|
|
||||||
@media (max-width: 768px) {
|
@media (max-width: 768px) {
|
||||||
|
|
|
||||||
29
dev.sh
Executable file
29
dev.sh
Executable file
|
|
@ -0,0 +1,29 @@
|
||||||
|
#!/bin/bash
|
||||||
|
|
||||||
|
exec 3< <(stripe listen --events checkout.session.completed,checkout.session.async_payment_succeeded --forward-to localhost:8000/webhook 2>&1)
|
||||||
|
CHILD_PID=$!
|
||||||
|
trap "kill -TERM $CHILD_PID 2>/dev/null; exec 3<&-" EXIT
|
||||||
|
|
||||||
|
if [ -f .env ]; then
|
||||||
|
export $(cat .env | xargs)
|
||||||
|
fi
|
||||||
|
export DEV_ENV="TRUE"
|
||||||
|
export WEBHOOK_SECRET=""
|
||||||
|
|
||||||
|
while IFS= read -r line <&3; do
|
||||||
|
matched_value=$(echo "$line" | grep -oP 'whsec_[a-zA-Z0-9]+')
|
||||||
|
if [ -n "$matched_value" ]; then
|
||||||
|
WEBHOOK_SECRET=$matched_value
|
||||||
|
break
|
||||||
|
fi
|
||||||
|
done
|
||||||
|
|
||||||
|
exec 3<&-
|
||||||
|
|
||||||
|
if [ -z "$WEBHOOK_SECRET" ]; then
|
||||||
|
echo "Error: can't get the webhook secret"
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
go tool templ generate
|
||||||
|
go run .
|
||||||
4
main.go
4
main.go
|
|
@ -210,13 +210,11 @@ func main() {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
orders.InitStripe(os.Getenv("STRIPE_SECRET_KEY"))
|
|
||||||
|
|
||||||
mux := http.ServeMux{}
|
mux := http.ServeMux{}
|
||||||
|
|
||||||
mux.Handle("/", http.FileServer(http.Dir("www")))
|
mux.Handle("/", http.FileServer(http.Dir("www")))
|
||||||
mux.Handle("POST /order", orders.Limit(http.HandlerFunc(orders.OrderHandler), 10*time.Second, 5))
|
mux.Handle("POST /order", orders.Limit(http.HandlerFunc(orders.OrderHandler), 10*time.Second, 5))
|
||||||
mux.HandleFunc("POST /webhook", orders.WebhookHandler(os.Getenv("STRIPE_WEBHOOK_SECRET")))
|
mux.HandleFunc("POST /webhook", orders.WebhookHandler)
|
||||||
|
|
||||||
log.Println("listening on :8000")
|
log.Println("listening on :8000")
|
||||||
log.Fatal(http.ListenAndServe(":8000", &mux))
|
log.Fatal(http.ListenAndServe(":8000", &mux))
|
||||||
|
|
|
||||||
|
|
@ -2,8 +2,11 @@ package orders
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"math"
|
||||||
"regexp"
|
"regexp"
|
||||||
|
"strconv"
|
||||||
"strings"
|
"strings"
|
||||||
|
"unicode"
|
||||||
)
|
)
|
||||||
|
|
||||||
func isValidPolishMobile(nineDigitNum string) bool {
|
func isValidPolishMobile(nineDigitNum string) bool {
|
||||||
|
|
@ -55,3 +58,28 @@ func parsePhone(input string) (string, error) {
|
||||||
|
|
||||||
return cleaned, nil
|
return cleaned, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func parseFloat(input string) (int, error) {
|
||||||
|
val, err := strconv.ParseFloat(input, 64)
|
||||||
|
if err != nil {
|
||||||
|
return 0, fmt.Errorf("Nieprawidłowa wartość")
|
||||||
|
}
|
||||||
|
|
||||||
|
if val < 0 || val > 100 {
|
||||||
|
return 0, fmt.Errorf("Wartość musi być między 0 a 100")
|
||||||
|
}
|
||||||
|
|
||||||
|
doubled := val * 2
|
||||||
|
if math.Abs(doubled-math.Round(doubled)) > 1e-9 {
|
||||||
|
return 0, fmt.Errorf("Wartość musi być wielokrotnością 0,5")
|
||||||
|
}
|
||||||
|
|
||||||
|
return int(math.Round(val * 10)), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func validName(name string) bool {
|
||||||
|
if name == "" || len(name) > 100 {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
return strings.IndexFunc(name, unicode.IsControl) == -1
|
||||||
|
}
|
||||||
125
orders/order.go
125
orders/order.go
|
|
@ -3,61 +3,31 @@ package orders
|
||||||
import (
|
import (
|
||||||
"crypto/rand"
|
"crypto/rand"
|
||||||
"encoding/hex"
|
"encoding/hex"
|
||||||
"encoding/json"
|
|
||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
"io"
|
|
||||||
"log"
|
"log"
|
||||||
"math"
|
|
||||||
"net/http"
|
"net/http"
|
||||||
"piekarnikgosipl/data"
|
"piekarnikgosipl/data"
|
||||||
"strconv"
|
"strconv"
|
||||||
"strings"
|
"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 {
|
type listItem struct {
|
||||||
id string
|
id string
|
||||||
count int // count multiplied by 100 to allow for half item purchases
|
count int // count multiplied by 10 to allow for half item purchases
|
||||||
}
|
}
|
||||||
|
|
||||||
type order struct {
|
type order struct {
|
||||||
|
id string
|
||||||
name string
|
name string
|
||||||
phone string
|
phone string
|
||||||
items []listItem
|
items []listItem
|
||||||
}
|
}
|
||||||
|
|
||||||
func InitStripe(secret string) { stripe.Key = secret }
|
func newOrderID() string {
|
||||||
|
b := make([]byte, 8)
|
||||||
func parseFloat(input string) (int, error) {
|
rand.Read(b)
|
||||||
val, err := strconv.ParseFloat(input, 64)
|
return hex.EncodeToString(b)
|
||||||
if err != nil {
|
|
||||||
return 0, fmt.Errorf("Nieprawidłowa wartość")
|
|
||||||
}
|
|
||||||
|
|
||||||
if val < 0 || val > 100 {
|
|
||||||
return 0, fmt.Errorf("Wartość musi być między 0 a 100")
|
|
||||||
}
|
|
||||||
|
|
||||||
doubled := val * 2
|
|
||||||
if math.Abs(doubled-math.Round(doubled)) > 1e-9 {
|
|
||||||
return 0, fmt.Errorf("Wartość musi być wielokrotnością 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) {
|
func parseOrder(r *http.Request) (order, error) {
|
||||||
|
|
@ -90,55 +60,13 @@ func parseOrder(r *http.Request) (order, error) {
|
||||||
}
|
}
|
||||||
total += count * price
|
total += count * price
|
||||||
}
|
}
|
||||||
if total < 5000 {
|
if total < 500 {
|
||||||
errorList = append(errorList, fmt.Errorf("Minimalna wartość zamówienia wynosi 50zł"))
|
errorList = append(errorList, fmt.Errorf("Minimalna wartość zamówienia wynosi 50zł"))
|
||||||
}
|
}
|
||||||
|
o.id = newOrderID()
|
||||||
return o, errors.Join(errorList...)
|
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) {
|
func OrderHandler(w http.ResponseWriter, r *http.Request) {
|
||||||
r.Body = http.MaxBytesReader(w, r.Body, 16<<10)
|
r.Body = http.MaxBytesReader(w, r.Body, 16<<10)
|
||||||
if err := r.ParseForm(); err != nil {
|
if err := r.ParseForm(); err != nil {
|
||||||
|
|
@ -153,40 +81,3 @@ func OrderHandler(w http.ResponseWriter, r *http.Request) {
|
||||||
}
|
}
|
||||||
startCheckout(w, r, o)
|
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)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
|
||||||
99
orders/stripe.go
Normal file
99
orders/stripe.go
Normal file
|
|
@ -0,0 +1,99 @@
|
||||||
|
package orders
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"io"
|
||||||
|
"log"
|
||||||
|
"net/http"
|
||||||
|
"os"
|
||||||
|
|
||||||
|
"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ł
|
||||||
|
|
||||||
|
var siteUrl = "https://piekarnikgosi.pl"
|
||||||
|
var webhookSecret = ""
|
||||||
|
|
||||||
|
func init() {
|
||||||
|
if os.Getenv("DEV_ENV") == "TRUE" {
|
||||||
|
siteUrl = "http://localhost:8000"
|
||||||
|
}
|
||||||
|
log.Println("the url is: ", siteUrl)
|
||||||
|
stripe.Key = os.Getenv("STRIPE_SECRET_KEY")
|
||||||
|
webhookSecret = os.Getenv("WEBHOOK_SECRET")
|
||||||
|
}
|
||||||
|
|
||||||
|
func startCheckout(w http.ResponseWriter, r *http.Request, o order) {
|
||||||
|
log.Println("ORDER_PENDING", o)
|
||||||
|
|
||||||
|
url := r.URL.RequestURI()
|
||||||
|
log.Println(url)
|
||||||
|
|
||||||
|
s, err := session.New(&stripe.CheckoutSessionParams{
|
||||||
|
Mode: stripe.String("payment"),
|
||||||
|
ClientReferenceID: stripe.String(o.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 " + o.id),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}},
|
||||||
|
SuccessURL: stripe.String(siteUrl + "/dziekujemy?order=" + o.id),
|
||||||
|
CancelURL: stripe.String(siteUrl),
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
log.Println("ORDER_STRIPE_ERROR", o.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 WebhookHandler(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"), webhookSecret,
|
||||||
|
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)
|
||||||
|
|
||||||
|
}
|
||||||
Loading…
Add table
Add a link
Reference in a new issue