Skip to content

[usage] Use CreateStripeSubscription behind feature flag #14287

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

Closed
wants to merge 3 commits into from
Closed
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
15 changes: 15 additions & 0 deletions components/server/ee/src/workspace/gitpod-server-impl.ts
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,7 @@ import { UsageServiceDefinition } from "@gitpod/usage-api/lib/usage/v1/usage.pb"
import { BillingServiceClient, BillingServiceDefinition } from "@gitpod/usage-api/lib/usage/v1/billing.pb";
import { IncrementalPrebuildsService } from "../prebuilds/incremental-prebuilds-service";
import { ConfigProvider } from "../../../src/workspace/config-provider";
import { getExperimentsClientForBackend } from "@gitpod/gitpod-protocol/lib/experiments/configcat-server";

@injectable()
export class GitpodServerEEImpl extends GitpodServerImpl {
Expand Down Expand Up @@ -2177,6 +2178,7 @@ export class GitpodServerEEImpl extends GitpodServerImpl {

const user = this.checkAndBlockUser("subscribeToStripe");

let team: Team | undefined;
try {
if (attrId.kind === "team") {
const team = await this.guardTeamOperation(attrId.teamId, "update");
Expand All @@ -2189,6 +2191,19 @@ export class GitpodServerEEImpl extends GitpodServerImpl {
throw new Error(`No Stripe customer profile for '${attributionId}'`);
}

const createStripeSubscriptionOnUsage = await getExperimentsClientForBackend().getValueAsync(
"createStripeSubscriptionOnUsage",
false,
{
user: user,
teamId: team ? team.id : undefined,
},
);

if (createStripeSubscriptionOnUsage) {
await this.billingService.createStripeSubscription({ attributionId, setupIntentId, usageLimit });
}

await this.stripeService.setDefaultPaymentMethodForCustomer(customerId, setupIntentId);
await this.stripeService.createSubscriptionForCustomer(customerId, attributionId);

Expand Down
156 changes: 83 additions & 73 deletions components/usage-api/go/v1/billing.pb.go

Large diffs are not rendered by default.

18 changes: 14 additions & 4 deletions components/usage-api/typescript/src/usage/v1/billing.pb.ts
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,7 @@ export interface CreateStripeCustomerResponse {

export interface CreateStripeSubscriptionRequest {
attributionId: string;
customerId: string;
setupIntentId: string;
usageLimit: number;
}
Expand Down Expand Up @@ -623,19 +624,22 @@ export const CreateStripeCustomerResponse = {
};

function createBaseCreateStripeSubscriptionRequest(): CreateStripeSubscriptionRequest {
return { attributionId: "", setupIntentId: "", usageLimit: 0 };
return { attributionId: "", customerId: "", setupIntentId: "", usageLimit: 0 };
}

export const CreateStripeSubscriptionRequest = {
encode(message: CreateStripeSubscriptionRequest, writer: _m0.Writer = _m0.Writer.create()): _m0.Writer {
if (message.attributionId !== "") {
writer.uint32(10).string(message.attributionId);
}
if (message.customerId !== "") {
writer.uint32(18).string(message.customerId);
}
if (message.setupIntentId !== "") {
writer.uint32(18).string(message.setupIntentId);
writer.uint32(26).string(message.setupIntentId);
}
if (message.usageLimit !== 0) {
writer.uint32(24).int64(message.usageLimit);
writer.uint32(32).int64(message.usageLimit);
}
return writer;
},
Expand All @@ -651,9 +655,12 @@ export const CreateStripeSubscriptionRequest = {
message.attributionId = reader.string();
break;
case 2:
message.setupIntentId = reader.string();
message.customerId = reader.string();
break;
case 3:
message.setupIntentId = reader.string();
break;
case 4:
message.usageLimit = longToNumber(reader.int64() as Long);
break;
default:
Expand All @@ -667,6 +674,7 @@ export const CreateStripeSubscriptionRequest = {
fromJSON(object: any): CreateStripeSubscriptionRequest {
return {
attributionId: isSet(object.attributionId) ? String(object.attributionId) : "",
customerId: isSet(object.customerId) ? String(object.customerId) : "",
setupIntentId: isSet(object.setupIntentId) ? String(object.setupIntentId) : "",
usageLimit: isSet(object.usageLimit) ? Number(object.usageLimit) : 0,
};
Expand All @@ -675,6 +683,7 @@ export const CreateStripeSubscriptionRequest = {
toJSON(message: CreateStripeSubscriptionRequest): unknown {
const obj: any = {};
message.attributionId !== undefined && (obj.attributionId = message.attributionId);
message.customerId !== undefined && (obj.customerId = message.customerId);
message.setupIntentId !== undefined && (obj.setupIntentId = message.setupIntentId);
message.usageLimit !== undefined && (obj.usageLimit = Math.round(message.usageLimit));
return obj;
Expand All @@ -683,6 +692,7 @@ export const CreateStripeSubscriptionRequest = {
fromPartial(object: DeepPartial<CreateStripeSubscriptionRequest>): CreateStripeSubscriptionRequest {
const message = createBaseCreateStripeSubscriptionRequest();
message.attributionId = object.attributionId ?? "";
message.customerId = object.customerId ?? "";
message.setupIntentId = object.setupIntentId ?? "";
message.usageLimit = object.usageLimit ?? 0;
return message;
Expand Down
5 changes: 3 additions & 2 deletions components/usage-api/usage/v1/billing.proto
Original file line number Diff line number Diff line change
Expand Up @@ -78,8 +78,9 @@ message CreateStripeCustomerResponse {

message CreateStripeSubscriptionRequest {
string attribution_id = 1;
string setup_intent_id = 2;
int64 usage_limit = 3;
string customer_id = 2;
string setup_intent_id = 3;
int64 usage_limit = 4;
}

message CreateStripeSubscriptionResponse {
Expand Down
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))
}
Loading