Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[usage] Handle customer.subscription.deletedevent from Stripe #13016

Merged
merged 5 commits into from
Sep 16, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 11 additions & 1 deletion components/public-api-server/pkg/billingservice/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,14 @@ import (
"context"
"fmt"

"github.com/gitpod-io/gitpod/usage-api/v1"
v1 "github.com/gitpod-io/gitpod/usage-api/v1"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
)

type Interface interface {
FinalizeInvoice(ctx context.Context, invoiceId string) error
CancelSubscription(ctx context.Context, subscriptionId string) error
}

type Client struct {
Expand All @@ -38,3 +39,12 @@ func (c *Client) FinalizeInvoice(ctx context.Context, invoiceId string) error {

return nil
}

func (c *Client) CancelSubscription(ctx context.Context, subscriptionId string) error {
_, err := c.b.CancelSubscription(ctx, &v1.CancelSubscriptionRequest{SubscriptionId: subscriptionId})
if err != nil {
return fmt.Errorf("failed RPC to billing service: %s", err)
}

return nil
}

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 4 additions & 0 deletions components/public-api-server/pkg/billingservice/noop.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,3 +11,7 @@ type NoOpClient struct{}
func (c *NoOpClient) FinalizeInvoice(ctx context.Context, invoiceId string) error {
return nil
}

func (c *NoOpClient) CancelSubscription(ctx context.Context, subscriptionId string) error {
return nil
}
45 changes: 30 additions & 15 deletions components/public-api-server/pkg/webhooks/stripe.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,12 @@
package webhooks

import (
"io"
"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/webhook"
"io"
"net/http"
)

const maxBodyBytes = int64(65536)
Expand Down Expand Up @@ -56,22 +57,36 @@ func (h *webhookHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
return
}

if event.Type != "invoice.finalized" {
switch event.Type {
case "invoice.finalized":
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
}
case "customer.subscription.deleted":
subscriptionId, ok := event.Data.Object["id"].(string)
if !ok {
log.Error("failed to find subscriptionId id in Stripe event payload")
w.WriteHeader(http.StatusBadRequest)
}
err = h.billingService.CancelSubscription(req.Context(), subscriptionId)
if err != nil {
log.WithError(err).Error("Failed to cancel subscription")
w.WriteHeader(http.StatusInternalServerError)
return
}
default:
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
}
}
55 changes: 38 additions & 17 deletions components/public-api-server/pkg/webhooks/stripe_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,12 @@ import (
"bytes"
"encoding/hex"
"fmt"
"github.com/stripe/stripe-go/v72/webhook"
"net/http"
"testing"
"time"

"github.com/stripe/stripe-go/v72/webhook"

"github.com/gitpod-io/gitpod/common-go/baseserver"
"github.com/gitpod-io/gitpod/public-api-server/pkg/billingservice"
mockbillingservice "github.com/gitpod-io/gitpod/public-api-server/pkg/billingservice/mock_billingservice"
Expand All @@ -22,9 +23,10 @@ import (

// https://stripe.com/docs/api/events/types
const (
invoiceUpdatedEventType = "invoice.updated"
invoiceFinalizedEventType = "invoice.finalized"
customerCreatedEventType = "customer.created"
invoiceUpdatedEventType = "invoice.updated"
invoiceFinalizedEventType = "invoice.finalized"
customerCreatedEventType = "customer.created"
customerSubscriptionDeleted = "customer.subscription.deleted"
Comment on lines +26 to +29
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Might make sense to move these as consts in the stripe.go file and re-use in tests

)

const (
Expand Down Expand Up @@ -80,6 +82,10 @@ func TestWebhookIgnoresIrrelevantEvents(t *testing.T) {
EventType: invoiceFinalizedEventType,
ExpectedStatusCode: http.StatusOK,
},
{
EventType: customerSubscriptionDeleted,
ExpectedStatusCode: http.StatusOK,
},
{
EventType: invoiceUpdatedEventType,
ExpectedStatusCode: http.StatusBadRequest,
Expand Down Expand Up @@ -134,6 +140,26 @@ func TestWebhookInvokesFinalizeInvoiceRPC(t *testing.T) {
require.Equal(t, http.StatusOK, resp.StatusCode)
}

func TestWebhookInvokesCancelSubscriptionRPC(t *testing.T) {
ctrl := gomock.NewController(t)
m := mockbillingservice.NewMockInterface(ctrl)
m.EXPECT().CancelSubscription(gomock.Any(), gomock.Eq("in_1LUQi7GadRXm50o36jWK7ehs"))

srv := baseServerWithStripeWebhook(t, m)

url := fmt.Sprintf("%s%s", srv.HTTPAddress(), "/webhook")

payload := payloadForStripeEvent(t, customerSubscriptionDeleted)
req, err := http.NewRequest(http.MethodPost, url, bytes.NewReader(payload))
require.NoError(t, err)

req.Header.Set("Stripe-Signature", generateHeader(payload, testWebhookSecret))

resp, err := http.DefaultClient.Do(req)
require.NoError(t, err)
require.Equal(t, http.StatusOK, resp.StatusCode)
}

func baseServerWithStripeWebhook(t *testing.T, billingService billingservice.Interface) *baseserver.Server {
t.Helper()

Expand All @@ -150,19 +176,14 @@ func baseServerWithStripeWebhook(t *testing.T, billingService billingservice.Int
func payloadForStripeEvent(t *testing.T, eventType string) []byte {
t.Helper()

if eventType != invoiceFinalizedEventType {
return []byte(`{}`)
}
return []byte(`
{
"data": {
"object": {
"id": "in_1LUQi7GadRXm50o36jWK7ehs"
}
},
"type": "invoice.finalized"
}
`)
return []byte(`{
"data": {
"object": {
"id": "in_1LUQi7GadRXm50o36jWK7ehs"
}
},
"type": "` + eventType + `"
}`)
}

func generateHeader(payload []byte, secret string) string {
Expand Down
Loading