From 59e83c7cc0c4ef62f293c4080a05485403e5def2 Mon Sep 17 00:00:00 2001 From: Joerg Lehmann Date: Sat, 4 Jan 2020 17:58:40 +0100 Subject: [PATCH] refactor payment process - another step --- main.go | 1 + stripe.go | 43 +++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 44 insertions(+) diff --git a/main.go b/main.go index cd762e7..6b5bc1d 100644 --- a/main.go +++ b/main.go @@ -89,6 +89,7 @@ func main() { http.HandleFunc("/lastmetrics", lastmetricsHandler) http.HandleFunc("/save_scale_settings", save_scale_settingsHandler) http.HandleFunc("/getstripepaymentintent", getstripepaymentintentHandler) + http.HandleFunc("/stripewebhook", stripeWebhookHandler) logit("Starting Web Application...") http.ListenAndServe("127.0.0.1:4000", nil) diff --git a/stripe.go b/stripe.go index b8bc3f6..d0ff9c3 100644 --- a/stripe.go +++ b/stripe.go @@ -3,6 +3,9 @@ package main import ( "fmt" "log" + "os" + "io/ioutil" + "encoding/json" "net/http" "strings" "strconv" @@ -47,6 +50,7 @@ func getstripepaymentintentHandler(response http.ResponseWriter, request *http.R Currency: stripe.String(string(stripe.CurrencyCHF)), ReceiptEmail: stripe.String(name), } + params.AddMetadata("charge_data", charge_data[0]) paymentintent, err := paymentintent.New(params) if err != nil { @@ -59,3 +63,42 @@ func getstripepaymentintentHandler(response http.ResponseWriter, request *http.R fmt.Fprintf(response, "{ \"rc\": 6, \"msg\": \"Only available for logged in users\" }") } } + +func stripeWebhookHandler(w http.ResponseWriter, req *http.Request) { + const MaxBodyBytes = int64(65536) + req.Body = http.MaxBytesReader(w, req.Body, MaxBodyBytes) + payload, err := ioutil.ReadAll(req.Body) + if err != nil { + fmt.Fprintf(os.Stderr, "Error reading request body: %v\n", err) + w.WriteHeader(http.StatusServiceUnavailable) + return + } + + event := stripe.Event{} + + if err := json.Unmarshal(payload, &event); err != nil { + fmt.Fprintf(os.Stderr, "Failed to parse webhook body json: %v\n", err.Error()) + w.WriteHeader(http.StatusBadRequest) + return + } + + // Unmarshal the event data into an appropriate struct depending on its Type + switch event.Type { + case "payment_intent.succeeded": + var paymentIntent stripe.PaymentIntent + err := json.Unmarshal(event.Data.Raw, &paymentIntent) + if err != nil { + fmt.Fprintf(os.Stderr, "Error parsing webhook JSON: %v\n", err) + w.WriteHeader(http.StatusBadRequest) + return + } + fmt.Printf("PaymentIntent was successful (charge_data: %s, amount: %d)!\n", paymentIntent.Metadata["charge_data"], paymentIntent.Amount) + // ... handle other event types + default: + fmt.Fprintf(os.Stderr, "Unexpected event type: %s\n", event.Type) + w.WriteHeader(http.StatusBadRequest) + return + } + + w.WriteHeader(http.StatusOK) +}