mirror of
https://github.com/gitpod-io/gitpod.git
synced 2025-12-08 17:36:30 +00:00
Construct and pass a billingservice client to the Stripe webhook so that it can invoke the `FinalizeInvoice` RPC when the webhook is triggered.
65 lines
1.7 KiB
Go
65 lines
1.7 KiB
Go
// Copyright (c) 2022 Gitpod GmbH. All rights reserved.
|
|
// Licensed under the GNU Affero General Public License (AGPL).
|
|
// See License-AGPL.txt in the project root for license information.
|
|
|
|
package webhooks
|
|
|
|
import (
|
|
"encoding/json"
|
|
"net/http"
|
|
|
|
"github.com/gitpod-io/gitpod/common-go/log"
|
|
"github.com/gitpod-io/gitpod/public-api-server/pkg/billingservice"
|
|
"github.com/stripe/stripe-go/v72"
|
|
)
|
|
|
|
type webhookHandler struct {
|
|
billingService billingservice.Interface
|
|
}
|
|
|
|
func NewStripeWebhookHandler(billingService billingservice.Interface) *webhookHandler {
|
|
return &webhookHandler{billingService: billingService}
|
|
}
|
|
|
|
func (h *webhookHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
|
|
const maxBodyBytes = int64(65536)
|
|
|
|
if req.Method != http.MethodPost {
|
|
log.Errorf("Bad HTTP method: %s", req.Method)
|
|
w.WriteHeader(http.StatusBadRequest)
|
|
return
|
|
}
|
|
|
|
// TODO: verify webhook signature.
|
|
// Conditional on there being a secret configured.
|
|
|
|
req.Body = http.MaxBytesReader(w, req.Body, maxBodyBytes)
|
|
|
|
event := stripe.Event{}
|
|
err := json.NewDecoder(req.Body).Decode(&event)
|
|
if err != nil {
|
|
log.WithError(err).Error("Stripe webhook error while parsing event payload")
|
|
w.WriteHeader(http.StatusBadRequest)
|
|
return
|
|
}
|
|
|
|
if event.Type != "invoice.finalized" {
|
|
log.Errorf("Unexpected Stripe event type: %s", event.Type)
|
|
w.WriteHeader(http.StatusBadRequest)
|
|
return
|
|
}
|
|
|
|
invoiceId, ok := event.Data.Object["id"].(string)
|
|
if !ok {
|
|
log.Error("failed to find invoice id in Stripe event payload")
|
|
w.WriteHeader(http.StatusBadRequest)
|
|
}
|
|
|
|
err = h.billingService.FinalizeInvoice(req.Context(), invoiceId)
|
|
if err != nil {
|
|
log.WithError(err).Error("Failed to finalize invoice")
|
|
w.WriteHeader(http.StatusInternalServerError)
|
|
return
|
|
}
|
|
}
|