Skip to content

Commit 619525a

Browse files
author
Andrew Farries
committed
Make stripe package return clients
`Authenticate` now returns a Client object rather than acting as a singleton. Change the `UpdateUsage` function to be a method on the client type. See: https://github.com/stripe/stripe-go#with-a-client
1 parent 800bf0f commit 619525a

File tree

1 file changed

+14
-10
lines changed

1 file changed

+14
-10
lines changed

components/usage/pkg/stripe/stripe.go

Lines changed: 14 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -13,35 +13,39 @@ import (
1313

1414
"github.com/gitpod-io/gitpod/common-go/log"
1515
"github.com/stripe/stripe-go/v72"
16-
"github.com/stripe/stripe-go/v72/customer"
17-
"github.com/stripe/stripe-go/v72/usagerecord"
16+
"github.com/stripe/stripe-go/v72/client"
1817
)
1918

19+
type Client struct {
20+
sc *client.API
21+
}
22+
2023
type stripeKeys struct {
2124
PublishableKey string `json:"publishableKey"`
2225
SecretKey string `json:"secretKey"`
2326
}
2427

2528
// Authenticate authenticates the Stripe client using a provided file containing a Stripe secret key.
26-
func Authenticate(apiKeyFile string) error {
29+
func Authenticate(apiKeyFile string) (*Client, error) {
2730
bytes, err := os.ReadFile(apiKeyFile)
2831
if err != nil {
29-
return err
32+
return nil, err
3033
}
3134

3235
var stripeKeys stripeKeys
3336
err = json.Unmarshal(bytes, &stripeKeys)
3437
if err != nil {
35-
return err
38+
return nil, err
3639
}
3740

38-
stripe.Key = stripeKeys.SecretKey
39-
return nil
41+
sc := &client.API{}
42+
sc.Init(stripeKeys.SecretKey, nil)
43+
return &Client{sc: sc}, nil
4044
}
4145

4246
// UpdateUsage updates teams' Stripe subscriptions with usage data
4347
// `usageForTeam` is a map from team name to total workspace seconds used within a billing period.
44-
func UpdateUsage(usageForTeam map[string]int64) error {
48+
func (c *Client) UpdateUsage(usageForTeam map[string]int64) error {
4549
teamIds := make([]string, 0, len(usageForTeam))
4650
for k := range usageForTeam {
4751
teamIds = append(teamIds, k)
@@ -56,7 +60,7 @@ func UpdateUsage(usageForTeam map[string]int64) error {
5660
Expand: []*string{stripe.String("data.subscriptions")},
5761
},
5862
}
59-
iter := customer.Search(params)
63+
iter := c.sc.Customers.Search(params)
6064
for iter.Next() {
6165
customer := iter.Customer()
6266
log.Infof("found customer %q for teamId %q", customer.Name, customer.Metadata["teamId"])
@@ -77,7 +81,7 @@ func UpdateUsage(usageForTeam map[string]int64) error {
7781

7882
subscriptionItemId := subscription.Items.Data[0].ID
7983
log.Infof("registering usage against subscriptionItem %q", subscriptionItemId)
80-
_, err := usagerecord.New(&stripe.UsageRecordParams{
84+
_, err := c.sc.UsageRecords.New(&stripe.UsageRecordParams{
8185
SubscriptionItem: stripe.String(subscriptionItemId),
8286
Quantity: stripe.Int64(creditsUsed),
8387
})

0 commit comments

Comments
 (0)