This commit is contained in:
bronku 2026-11-09 16:29:52 +01:00
parent 6185a59de9
commit 9e16843a29
8 changed files with 178 additions and 123 deletions

99
orders/stripe.go Normal file
View 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)
}