stripe
This commit is contained in:
parent
de22166113
commit
6963a88602
5 changed files with 129 additions and 17 deletions
113
orders/order.go
113
orders/order.go
|
|
@ -1,15 +1,27 @@
|
|||
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
|
||||
|
|
@ -21,6 +33,8 @@ type order struct {
|
|||
items []listItem
|
||||
}
|
||||
|
||||
func InitStripe(secret string) { stripe.Key = secret }
|
||||
|
||||
func parseFloat(input string) (int, error) {
|
||||
val, err := strconv.ParseFloat(input, 64)
|
||||
if err != nil {
|
||||
|
|
@ -37,25 +51,31 @@ func parseFloat(input string) (int, error) {
|
|||
}
|
||||
|
||||
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 = r.PostFormValue("name")
|
||||
if o.name == "" {
|
||||
o.name = strings.TrimSpace(r.PostFormValue("name"))
|
||||
if !validName(o.name) {
|
||||
errorList = append(errorList, fmt.Errorf("Invalid name"))
|
||||
}
|
||||
o.phone, err = parseAndValidatePolishMobile(r.PostFormValue("phone"))
|
||||
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: %e", item.Name, err))
|
||||
errorList = append(errorList, fmt.Errorf("Can't parse the count for %v: %v", item.Name, err))
|
||||
continue
|
||||
}
|
||||
if count%10 == 5 && !item.Halveable {
|
||||
|
|
@ -67,8 +87,89 @@ func parseOrder(r *http.Request) (order, error) {
|
|||
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)
|
||||
|
||||
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"),
|
||||
CancelURL: stripe.String("https://piekarnikgosi.pl/"),
|
||||
})
|
||||
if err != nil {
|
||||
log.Println("ORDER_STRIPE_ERROR", id, err)
|
||||
http.Error(w, "payment error", http.StatusInternalServerError)
|
||||
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) {
|
||||
o, err := parseOrder(r)
|
||||
log.Println(o, err)
|
||||
fmt.Fprintf(w, "%v, %v", o, err)
|
||||
if err != nil {
|
||||
log.Println("ORDER_INVALID", o, err)
|
||||
http.Error(w, err.Error(), http.StatusBadRequest)
|
||||
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)
|
||||
}
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue