piekarnikgosipl/orders/stripe.go
2026-11-09 22:40:27 +01:00

110 lines
3.3 KiB
Go

package orders
import (
"encoding/json"
"io"
"log"
"net/http"
"os"
"time"
"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")
log.Println(stripe.Key)
log.Println(webhookSecret)
}
func startCheckout(w http.ResponseWriter, r *http.Request, o order) {
log.Println("ORDER_PENDING", o)
s, err := session.New(&stripe.CheckoutSessionParams{
Mode: stripe.String("payment"),
ClientReferenceID: stripe.String(o.id),
Locale: stripe.String("pl"),
ExpiresAt: stripe.Int64(time.Now().Add(time.Hour).Unix()),
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 nr " + 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
}
switch event.Type {
case "checkout.session.completed", "checkout.session.async_payment_succeeded",
"checkout.session.expired", "checkout.session.async_payment_failed":
default:
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
}
id := s.ClientReferenceID
switch {
case event.Type == "checkout.session.expired" || event.Type == "checkout.session.async_payment_failed":
log.Println("ORDER_ABANDONED", id, event.Type)
if err := clearOrder(id); err != nil {
log.Println("ORDER_SHEETS_ERROR", id, err)
}
case s.PaymentStatus != stripe.CheckoutSessionPaymentStatusPaid:
log.Println("ORDER_NOT_YET_PAID", id, s.ID, s.PaymentStatus)
case s.AmountTotal != retainer || s.Currency != stripe.CurrencyPLN:
log.Println("ORDER_PAYMENT_MISMATCH", id, s.ID, s.AmountTotal, s.Currency)
default:
log.Println("ORDER_PAID", id, s.ID)
if err := confirmRow(id); err != nil {
log.Println("ORDER_SHEETS_ERROR", id, err)
}
}
}