commit 2ea7d10e53506e1984da716fac3e92d8d2dfd4bf
parent 7f9a5db4aeb2d118bbbc73151146acfa5de1201e
Author: Jacob R. Edwards <jacob@jacobedwards.org>
Date: Sun, 1 Sep 2024 19:11:31 -0700
Make stripe subscription updating more robust
Before, if the subscription didn't already exist, it would not be
updated and no error would be reported. Now if the subscription
doesn't exist just create it.
Diffstat:
1 file changed, 6 insertions(+), 19 deletions(-)
diff --git a/internal/backend/stripe.go b/internal/backend/stripe.go
@@ -42,27 +42,14 @@ func (e *Env) StripeEventHandler(ev *stripe.Event) error {
}
func (e *Env) stripeCreateSub(s *stripe.Subscription) error {
- add, err := e.CacheStmt("create_sub",
- `INSERT INTO spaceplanner.subscriptions (id, customer_id, price_id, product_id, active)
- VALUES ($1, $2, $3, $4, $5)`)
- if err != nil {
- return err
- }
-
- price, err := e.subPrice(s)
- if err != nil {
- return err
- }
-
- log.Printf("stripeHandleCreateSub sub %s for %s (active: %v)\n", s.ID, s.Customer.ID, subIsActive(s))
- _, err = add.Exec(s.ID, s.Customer.ID, price.ID, price.Product.ID, subIsActive(s))
- return err
+ return e.stripeUpdateSub(s)
}
func (e *Env) stripeUpdateSub(s *stripe.Subscription) error {
- update, err := e.CacheStmt("update_sub",
- `UPDATE spaceplanner.subscriptions SET (price_id, product_id, active) = ($2, $3, $4)
- WHERE id = $1`)
+ update, err := e.CacheStmt("create_sub",
+ `INSERT INTO spaceplanner.subscriptions (id, customer_id, price_id, product_id, active)
+ VALUES ($1, $2, $3, $4, $5)
+ ON CONFLICT (id) DO UPDATE SET (price_id, product_id, active) = ($3, $4, $5)`)
if err != nil {
return err
}
@@ -73,7 +60,7 @@ func (e *Env) stripeUpdateSub(s *stripe.Subscription) error {
}
log.Printf("stripeHandleUpdateSub sub %s for %s (active: %v)\n", s.ID, s.Customer.ID, subIsActive(s))
- _, err = update.Exec(s.ID, price.ID, price.Product.ID, subIsActive(s))
+ _, err = update.Exec(s.ID, s.Customer.ID, price.ID, price.Product.ID, subIsActive(s))
return err
}