diff --git a/handlers.go b/handlers.go index cf048dd..807d5cd 100644 --- a/handlers.go +++ b/handlers.go @@ -387,3 +387,52 @@ func managebilling(w http.ResponseWriter, r *http.Request) { http.Redirect(w, r, result.URL, http.StatusSeeOther); } + +func webhook(w http.ResponseWriter, r *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{}; + + err := json.Unmarshal(payload, &event); + if 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; + } + // Then define and call a func to handle the successful payment intent. + // handlePaymentIntentSucceeded(paymentIntent) + case "payment_method.attached": + var paymentMethod stripe.PaymentMethod; + err := json.Unmarshal(event.Data.Raw, &paymentMethod); + if err != nil { + fmt.Fprintf(os.Stderr, "Error parsing webhook JSON: %v\n", err); + w.WriteHeader(http.StatusBadRequest); + return; + } + // Then define and call a func to handle the successful attachment of a PaymentMethod. + // handlePaymentMethodAttached(paymentMethod) + // ... handle other event types + default: + fmt.Fprintf(os.Stderr, "Unhandled event type: %s\n", event.Type) + } + + w.WriteHeader(http.StatusOK) +}) diff --git a/main.go b/main.go index d2fd44c..8d7bf6a 100644 --- a/main.go +++ b/main.go @@ -79,17 +79,8 @@ func main() { mux.HandleFunc("/deleteaccount", require_authenticated_user(deleteaccount)); mux.HandleFunc("/subscribe", require_authenticated_user(subscribe_stripe)); mux.HandleFunc("/managebilling", require_authenticated_user(managebilling)); + mux.HandleFunc("/webhook", webhook); log.Fatal(http.ListenAndServe(*addr, secure_headers(mux))); } - -//cookie := http.Cookie{; -// Name: "exampleCookie",; -// Value: "Hello world!",; -// Path: "/",; -// HttpOnly: true,; -// Secure: true,; -// SameSite: http.SameSiteLaxMode,; -//}; -//http.SetCookie(w, &cookie);