Skip to content

[usage] Implement CreateStripeSubscription #14044

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

Merged
merged 1 commit into from
Nov 1, 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
86 changes: 85 additions & 1 deletion components/usage/pkg/apiv1/billing.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,18 +23,20 @@ import (
"gorm.io/gorm"
)

func NewBillingService(stripeClient *stripe.Client, conn *gorm.DB, ccManager *db.CostCenterManager) *BillingService {
func NewBillingService(stripeClient *stripe.Client, conn *gorm.DB, ccManager *db.CostCenterManager, stripePrices stripe.StripePrices) *BillingService {
return &BillingService{
stripeClient: stripeClient,
conn: conn,
ccManager: ccManager,
stripePrices: stripePrices,
}
}

type BillingService struct {
conn *gorm.DB
stripeClient *stripe.Client
ccManager *db.CostCenterManager
stripePrices stripe.StripePrices

v1.UnimplementedBillingServiceServer
}
Expand Down Expand Up @@ -165,6 +167,88 @@ func (s *BillingService) CreateStripeCustomer(ctx context.Context, req *v1.Creat
}, nil
}

func (s *BillingService) CreateStripeSubscription(ctx context.Context, req *v1.CreateStripeSubscriptionRequest) (*v1.CreateStripeSubscriptionResponse, error) {
attributionID, err := db.ParseAttributionID(req.GetAttributionId())
if err != nil {
return nil, status.Errorf(codes.InvalidArgument, "Invalid attribution ID %s", attributionID)
}

customer, err := s.GetStripeCustomer(ctx, &v1.GetStripeCustomerRequest{
Identifier: &v1.GetStripeCustomerRequest_AttributionId{
AttributionId: string(attributionID),
},
})
if err != nil {
return nil, err
}

_, err = s.stripeClient.SetDefaultPaymentForCustomer(ctx, customer.Customer.Id, req.SetupIntentId)
if err != nil {
return nil, status.Errorf(codes.InvalidArgument, "Failed to set default payment for customer ID %s", customer.Customer.Id)
}

stripeCustomer, err := s.stripeClient.GetCustomer(ctx, customer.Customer.Id)
if err != nil {
return nil, err
}

priceID, err := getPriceIdentifier(attributionID, stripeCustomer, s)
if err != nil {
return nil, err
}

var isAutomaticTaxSupported bool
if stripeCustomer.Tax != nil {
isAutomaticTaxSupported = stripeCustomer.Tax.AutomaticTax == "supported"
}
if !isAutomaticTaxSupported {
log.Warnf("Automatic Stripe tax is not supported for customer %s", stripeCustomer.ID)
}

subscription, err := s.stripeClient.CreateSubscription(ctx, stripeCustomer.ID, priceID, isAutomaticTaxSupported)
if err != nil {
return nil, status.Errorf(codes.Internal, "Failed to create subscription with customer ID %s", customer.Customer.Id)
}

return &v1.CreateStripeSubscriptionResponse{
Subscription: &v1.StripeSubscription{
Id: subscription.ID,
},
}, nil
}

func getPriceIdentifier(attributionID db.AttributionID, stripeCustomer *stripe_api.Customer, s *BillingService) (string, error) {
preferredCurrency := stripeCustomer.Metadata["preferredCurrency"]
if stripeCustomer.Metadata["preferredCurrency"] == "" {
log.
WithField("stripe_customer_id", stripeCustomer.ID).
Warn("No preferred currency set. Defaulting to USD")
}

entity, _ := attributionID.Values()

switch entity {
case db.AttributionEntity_User:
switch preferredCurrency {
case "EUR":
return s.stripePrices.IndividualUsagePriceIDs.EUR, nil
default:
return s.stripePrices.IndividualUsagePriceIDs.USD, nil
}

case db.AttributionEntity_Team:
switch preferredCurrency {
case "EUR":
return s.stripePrices.TeamUsagePriceIDs.EUR, nil
default:
return s.stripePrices.TeamUsagePriceIDs.USD, nil
}

default:
return "", status.Errorf(codes.InvalidArgument, "Invalid currency %s for customer ID %s", stripeCustomer.Metadata["preferredCurrency"], stripeCustomer.ID)
}
}

func (s *BillingService) ReconcileInvoices(ctx context.Context, in *v1.ReconcileInvoicesRequest) (*v1.ReconcileInvoicesResponse, error) {
balances, err := db.ListBalance(ctx, s.conn)
if err != nil {
Expand Down
14 changes: 2 additions & 12 deletions components/usage/pkg/server/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -44,17 +44,7 @@ type Config struct {
DefaultSpendingLimit db.DefaultSpendingLimit `json:"defaultSpendingLimit"`

// StripePrices configure which Stripe Price IDs should be used
StripePrices StripePrices `json:"stripePrices"`
}

type PriceConfig struct {
EUR string `json:"eur"`
USD string `json:"usd"`
}

type StripePrices struct {
IndividualUsagePriceIDs PriceConfig `json:"individualUsagePriceIds"`
TeamUsagePriceIDs PriceConfig `json:"teamUsagePriceIds"`
StripePrices stripe.StripePrices `json:"stripePrices"`
}

func Start(cfg Config, version string) error {
Expand Down Expand Up @@ -188,7 +178,7 @@ func registerGRPCServices(srv *baseserver.Server, conn *gorm.DB, stripeClient *s
if stripeClient == nil {
v1.RegisterBillingServiceServer(srv.GRPC(), &apiv1.BillingServiceNoop{})
} else {
v1.RegisterBillingServiceServer(srv.GRPC(), apiv1.NewBillingService(stripeClient, conn, ccManager))
v1.RegisterBillingServiceServer(srv.GRPC(), apiv1.NewBillingService(stripeClient, conn, ccManager, cfg.StripePrices))
}
return nil
}
86 changes: 86 additions & 0 deletions components/usage/pkg/stripe/stripe.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,16 @@ type ClientConfig struct {
SecretKey string `json:"secretKey"`
}

type PriceConfig struct {
EUR string `json:"eur"`
USD string `json:"usd"`
}

type StripePrices struct {
IndividualUsagePriceIDs PriceConfig `json:"individualUsagePriceIds"`
TeamUsagePriceIDs PriceConfig `json:"teamUsagePriceIds"`
}

func ReadConfigFromFile(path string) (ClientConfig, error) {
bytes, err := os.ReadFile(path)
if err != nil {
Expand Down Expand Up @@ -320,6 +330,82 @@ func (c *Client) GetSubscriptionWithCustomer(ctx context.Context, subscriptionID
return subscription, nil
}

func (c *Client) CreateSubscription(ctx context.Context, customerID string, priceID string, isAutomaticTaxSupported bool) (*stripe.Subscription, error) {
if customerID == "" {
return nil, fmt.Errorf("no customerID specified")
}
if priceID == "" {
return nil, fmt.Errorf("no priceID specified")
}

startOfNextMonth := getStartOfNextMonth(time.Now())

params := &stripe.SubscriptionParams{
Customer: stripe.String(customerID),
Items: []*stripe.SubscriptionItemsParams{
{
Price: stripe.String(priceID),
},
},
AutomaticTax: &stripe.SubscriptionAutomaticTaxParams{
Enabled: stripe.Bool(isAutomaticTaxSupported),
},
BillingCycleAnchor: stripe.Int64(startOfNextMonth.Unix()),
}

subscription, err := c.sc.Subscriptions.New(params)
if err != nil {
return nil, fmt.Errorf("failed to get subscription with customer ID %s", customerID)
}

return subscription, err
}

func getStartOfNextMonth(t time.Time) time.Time {
currentYear, currentMonth, _ := t.Date()

firstOfMonth := time.Date(currentYear, currentMonth, 1, 0, 0, 0, 0, time.UTC)
startOfNextMonth := firstOfMonth.AddDate(0, 1, 0)

return startOfNextMonth
}

func (c *Client) SetDefaultPaymentForCustomer(ctx context.Context, customerID string, setupIntentId string) (*stripe.Customer, error) {
if customerID == "" {
return nil, fmt.Errorf("no customerID specified")
}

if setupIntentId == "" {
return nil, fmt.Errorf("no setupIntentID specified")
}

setupIntent, err := c.sc.SetupIntents.Get(setupIntentId, &stripe.SetupIntentParams{
Params: stripe.Params{
Context: ctx,
},
})
if err != nil {
return nil, fmt.Errorf("Failed to retrieve setup intent with id %s", setupIntentId)
}

paymentMethod, err := c.sc.PaymentMethods.Attach(setupIntent.PaymentMethod.ID, &stripe.PaymentMethodAttachParams{Customer: &customerID})
if err != nil {
return nil, fmt.Errorf("Failed to attach payment method to setup intent ID %s", setupIntentId)
}

customer, _ := c.sc.Customers.Update(customerID, &stripe.CustomerParams{
InvoiceSettings: &stripe.CustomerInvoiceSettingsParams{
DefaultPaymentMethod: stripe.String(paymentMethod.ID)},
Address: &stripe.AddressParams{
Line1: stripe.String(paymentMethod.BillingDetails.Address.Line1),
Country: stripe.String(paymentMethod.BillingDetails.Address.Country)}})
if err != nil {
return nil, fmt.Errorf("Failed to update customer with id %s", customerID)
}

return customer, nil
}

func GetAttributionID(ctx context.Context, customer *stripe.Customer) (db.AttributionID, error) {
if customer == nil {
log.Error("No customer information available for invoice.")
Expand Down
10 changes: 9 additions & 1 deletion components/usage/pkg/stripe/stripe_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,10 @@ package stripe

import (
"fmt"
"github.com/gitpod-io/gitpod/usage/pkg/db"
"testing"
"time"

"github.com/gitpod-io/gitpod/usage/pkg/db"

"github.com/stretchr/testify/require"
)
Expand Down Expand Up @@ -89,3 +91,9 @@ func TestCustomerQueriesForTeamIds_MultipleQueries(t *testing.T) {
})
}
}

func TestStartOfNextMonth(t *testing.T) {
ts := time.Date(2022, 10, 1, 0, 0, 0, 0, time.UTC)

require.Equal(t, time.Date(2022, 11, 1, 0, 0, 0, 0, time.UTC), getStartOfNextMonth(ts))
}
7 changes: 4 additions & 3 deletions install/installer/pkg/components/usage/configmap.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import (
"github.com/gitpod-io/gitpod/common-go/baseserver"
"github.com/gitpod-io/gitpod/usage/pkg/db"
"github.com/gitpod-io/gitpod/usage/pkg/server"
"github.com/gitpod-io/gitpod/usage/pkg/stripe"

"github.com/gitpod-io/gitpod/installer/pkg/common"
"github.com/gitpod-io/gitpod/installer/pkg/config/v1/experimental"
Expand Down Expand Up @@ -39,12 +40,12 @@ func configmap(ctx *common.RenderContext) ([]runtime.Object, error) {

expWebAppConfig := getExperimentalWebAppConfig(ctx)
if expWebAppConfig != nil && expWebAppConfig.Stripe != nil {
cfg.StripePrices = server.StripePrices{
IndividualUsagePriceIDs: server.PriceConfig{
cfg.StripePrices = stripe.StripePrices{
IndividualUsagePriceIDs: stripe.PriceConfig{
EUR: expWebAppConfig.Stripe.IndividualUsagePriceIDs.EUR,
USD: expWebAppConfig.Stripe.IndividualUsagePriceIDs.USD,
},
TeamUsagePriceIDs: server.PriceConfig{
TeamUsagePriceIDs: stripe.PriceConfig{
EUR: expWebAppConfig.Stripe.TeamUsagePriceIDs.EUR,
USD: expWebAppConfig.Stripe.TeamUsagePriceIDs.USD,
},
Expand Down