diff --git a/main.go b/main.go index 5414840..d0c33c3 100644 --- a/main.go +++ b/main.go @@ -98,6 +98,7 @@ func main() { http.HandleFunc("/lastmetrics", lastmetricsHandler) http.HandleFunc("/save_scale_settings", save_scale_settingsHandler) http.HandleFunc("/getstripesession", getstripesessionHandler) + 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 16bc98a..5a29380 100644 --- a/stripe.go +++ b/stripe.go @@ -4,11 +4,19 @@ import ( "fmt" "log" "strconv" + "os" + "io/ioutil" + "encoding/json" "net/http" "github.com/stripe/stripe-go" "github.com/stripe/stripe-go/checkout/session" + "github.com/stripe/stripe-go/webhook" ) +func getStripeKey() string { + return "sk_test_GJbXPD0IAFNvvGpNEpaeDfhl" +} + func getstripesessionHandler(response http.ResponseWriter, request *http.Request) { name := getUserName(request) if name != "" { @@ -53,7 +61,7 @@ func getstripesessionHandler(response http.ResponseWriter, request *http.Request fmt.Println(charge_amount_rappen[0], "is not an integer.") } - stripe.Key = "sk_test_GJbXPD0IAFNvvGpNEpaeDfhl" + stripe.Key = getStripeKey() params := &stripe.CheckoutSessionParams{ PaymentMethodTypes: stripe.StringSlice([]string{ @@ -83,3 +91,41 @@ func getstripesessionHandler(response http.ResponseWriter, request *http.Request fmt.Fprintf(response, "{ \"rc\": 6, \"msg\": \"Only available for logged in users\" }") } } + +func stripeWebhookHandler(response http.ResponseWriter, request *http.Request) { + body, err := ioutil.ReadAll(request.Body) + if err != nil { + fmt.Fprintf(os.Stderr, "Error reading request body: %v\n", err) + response.WriteHeader(http.StatusServiceUnavailable) + return + } + + // Pass the request body & Stripe-Signature header to ConstructEvent, along with the webhook signing key + // You can find your endpoint's secret in your webhook settings + endpointSecret := "whsec_b1OdRuu9aK6zXt6M1EQRxZ4lhl3rrVtN"; + event, err := webhook.ConstructEvent(body, request.Header.Get("Stripe-Signature"), endpointSecret) + + if err != nil { + fmt.Fprintf(os.Stderr, "Error verifying webhook signature: %v\n", err) + response.WriteHeader(http.StatusBadRequest) // Return a 400 error on a bad signature + return + } + + // Handle the checkout.session.completed event + if event.Type == "checkout.session.completed" { + var session stripe.CheckoutSession + err := json.Unmarshal(event.Data.Raw, &session) + if err != nil { + fmt.Fprintf(os.Stderr, "Error parsing webhook JSON: %v\n", err) + response.WriteHeader(http.StatusBadRequest) + return + } + + // Fulfill the purchase... + //handleCheckoutSession(session) + log.Println("handleCheckoutSession "+session.ID) + } + + response.WriteHeader(http.StatusOK) +} +