Skip to content

Commit 14a1607

Browse files
author
Andrew Farries
committed
Add placeholder webhook handler
Register the handler with the underlying baseserver.
1 parent 0cf6a5f commit 14a1607

File tree

2 files changed

+52
-0
lines changed

2 files changed

+52
-0
lines changed

components/usage/pkg/server/server.go

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -111,6 +111,9 @@ func Start(cfg Config) error {
111111
return fmt.Errorf("failed to register gRPC services: %w", err)
112112
}
113113

114+
h := stripe.NewWebhookHandler()
115+
registerHttpHandlers(srv, h)
116+
114117
err = controller.RegisterMetrics(srv.MetricsRegistry())
115118
if err != nil {
116119
return fmt.Errorf("failed to register controller metrics: %w", err)
@@ -133,3 +136,7 @@ func registerGRPCServices(srv *baseserver.Server, conn *gorm.DB, stripeClient *s
133136
}
134137
return nil
135138
}
139+
140+
func registerHttpHandlers(srv *baseserver.Server, h *stripe.WebhookHandler) {
141+
srv.HTTPMux().HandleFunc("/webhook", h.Handle)
142+
}
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
// Copyright (c) 2022 Gitpod GmbH. All rights reserved.
2+
// Licensed under the GNU Affero General Public License (AGPL).
3+
// See License-AGPL.txt in the project root for license information.
4+
5+
package stripe
6+
7+
import (
8+
"encoding/json"
9+
"fmt"
10+
"io/ioutil"
11+
"net/http"
12+
13+
"github.com/gitpod-io/gitpod/common-go/log"
14+
"github.com/stripe/stripe-go/v72"
15+
)
16+
17+
type WebhookHandler struct{}
18+
19+
func NewWebhookHandler() *WebhookHandler {
20+
return &WebhookHandler{}
21+
}
22+
23+
func (h *WebhookHandler) Handle(w http.ResponseWriter, req *http.Request) {
24+
const maxBodyBytes = int64(65536)
25+
26+
req.Body = http.MaxBytesReader(w, req.Body, maxBodyBytes)
27+
payload, err := ioutil.ReadAll(req.Body)
28+
if err != nil {
29+
log.WithError(err).Error("Stripe webhook error when reading request body")
30+
w.WriteHeader(http.StatusServiceUnavailable)
31+
return
32+
}
33+
34+
event := stripe.Event{}
35+
if err := json.Unmarshal(payload, &event); err != nil {
36+
log.WithError(err).Error("Stripe webhook error while parsing event payload")
37+
w.WriteHeader(http.StatusBadRequest)
38+
return
39+
}
40+
41+
// TODO: verify webhook signature.
42+
// Conditional on there being a secret configured.
43+
44+
fmt.Fprintf(w, "event type: %s", event.Type)
45+
}

0 commit comments

Comments
 (0)