product.go (1566B)
1 package backend 2 3 import ( 4 "github.com/stripe/stripe-go/v72" 5 ) 6 7 /* 8 * NOTE: For now I'm not caching anything in the database, and each call 9 * to these functions retrieves the information anew from Stripe's servers. 10 * 11 * TODO: Implement a cache 12 */ 13 type Service struct { 14 ID string `json:"id"` 15 Name string `json:"name"` 16 Description string `json:"description"` 17 Prices []Price `json:"prices"` 18 } 19 20 type Price struct { 21 ID string `json:"id"` 22 ServiceID string `json:"service"` 23 Amount int64 `json:"amount"` 24 Interval string `json:"interval"` 25 IntervalCount int64 `json:"intervalCount"` 26 } 27 28 func (e *Env) Services() ([]Service, error) { 29 p := &stripe.ProductListParams{ 30 Active: stripe.Bool(true), 31 } 32 p.AddExpand("data.default_price") 33 34 services := make([]Service, 0, 8) 35 products := e.Stripe.Products.List(p) 36 for products.Next() { 37 services = append(services, toService(products.Product())) 38 } 39 40 if err := products.Err(); err != nil { 41 return nil, err 42 } 43 return services, nil 44 } 45 46 func (e *Env) Price(id string) (Price, error) { 47 p, err := e.Stripe.Prices.Get(id, nil) 48 if err != nil { 49 return Price{}, err 50 } 51 return toPrice(p), nil 52 } 53 54 func toService(p *stripe.Product) Service { 55 s := Service{ 56 ID: p.ID, 57 Name: p.Name, 58 Description: p.Description, 59 } 60 if p.DefaultPrice != nil { 61 a := []Price{toPrice(p.DefaultPrice)} 62 s.Prices = a 63 } 64 return s 65 } 66 67 func toPrice(p *stripe.Price) Price { 68 return Price{ 69 ID: p.ID, 70 ServiceID: p.Product.ID, 71 Amount: p.UnitAmount, 72 Interval: string(p.Recurring.Interval), 73 IntervalCount: p.Recurring.IntervalCount, 74 } 75 }