Skip to content

Commit ad83286

Browse files
author
Andrew Farries
committed
Add placeholder webhook handler
Register the handler with the underlying baseserver.
1 parent d745809 commit ad83286

File tree

2 files changed

+54
-0
lines changed

2 files changed

+54
-0
lines changed

components/usage/pkg/server/server.go

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

112+
h := stripe.NewWebhookHandler()
113+
registerHttpHandlers(srv, h)
114+
112115
err = controller.RegisterMetrics(srv.MetricsRegistry())
113116
if err != nil {
114117
return fmt.Errorf("failed to register controller metrics: %w", err)
@@ -131,3 +134,7 @@ func registerGRPCServices(srv *baseserver.Server, conn *gorm.DB, stripeClient *s
131134
}
132135
return nil
133136
}
137+
138+
func registerHttpHandlers(srv *baseserver.Server, h *stripe.WebhookHandler) {
139+
srv.HTTPMux().HandleFunc("/webhook", h.Handle)
140+
}
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
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+
stripeWebhookSecret string
19+
}
20+
21+
func NewWebhookHandler(secret string) *WebhookHandler {
22+
return &WebhookHandler{stripeWebhookSecret: secret}
23+
}
24+
25+
func (h *WebhookHandler) Handle(w http.ResponseWriter, req *http.Request) {
26+
const maxBodyBytes = int64(65536)
27+
28+
req.Body = http.MaxBytesReader(w, req.Body, maxBodyBytes)
29+
payload, err := ioutil.ReadAll(req.Body)
30+
if err != nil {
31+
log.WithError(err).Error("Stripe webhook error when reading request body")
32+
w.WriteHeader(http.StatusServiceUnavailable)
33+
return
34+
}
35+
36+
event := stripe.Event{}
37+
if err := json.Unmarshal(payload, &event); err != nil {
38+
log.WithError(err).Error("Stripe webhook error while parsing event payload")
39+
w.WriteHeader(http.StatusBadRequest)
40+
return
41+
}
42+
43+
// TODO: verify webhook signature.
44+
// Conditional on there being a secret configured.
45+
46+
fmt.Fprintf(w, "event type: %s", event.Type)
47+
}

0 commit comments

Comments
 (0)