ducky/subscriptions

Paddy 2015-07-13 Parent:b240b6123548 Child:1ff031bebf9e

6:c4cfceb2f2fb Go to Latest

ducky/subscriptions/stripe.go

Make it possible to create a user without payment details. We want a new subscription flow, in which the system (not the user) is responsible for creating a subscription when a new profile is created. This is to prevent issues where a user has an account, but no subscription. This is bad because the free trial starts ticking from the day the subscription is created, so we should try to make the subscription and account creation get created as close to each other as possible. Our plan is to instead have the authd service fire off an NSQ event when an auth.Profile is created, which a subscription listener will be listening for. When that happens, the listener will use the subscription API to create a subscription. Then the user will update the subscription with their payment info and the plan they want to use. To accomplish this, we changed the way things were handled. The SubscriptionRequest type, along with its Validate method, were removed. Instead, we get the SubscriptionChange type which handles both the creation of a subscription and the updating of a subscription. We also added an endpoint for patching subscriptions, useful for adding the StripeSubscription or updating the plan. By default, every subscription is created with a "Pending" plan which has a 31 day free trial. This is so we can detect users that haven't actually set up their subscription yet, but their free trial is still timed correctly. We changed the way we handle scopes, creating actual auth.Scope instances instead of just declaring an ID for them. This is useful when we have a client, for example. With this change, we lose all the validation we had on creating a Subscription, and we need to rewrite that validation logic. This is because we no longer have a specific type for "creating a subscription", so we can't just call a validate method. We should have a helper method validateCreateRequest(change SubscriptionChange) that will return the API errors we want, so it's easier to unit test. We should really be restricting the CreateSubscriptionHandler to ScopeSubscriptionAdmin, anyways, since Subscriptions should only ever be created by the system tools or administrators. We created a PatchSubscriptionHandler that exposes an interface to updating properties of a Subscription. It allows users to update their own Subscriptions or requires the ScopeSubscriptionAdmin scope before allowing you to update another user's Subscription. It, likewise, needs validation still. We also added the concept of "system-controlled properties" of the SubscriptionChange type, which only admins or the system tools can update. We updated our planOptions to distinguish between plans that do and do not need administrative credentials to be chosen. Our free and pending plans are available to administrators only. We updated our StripeChange object to be better organised (separating out the system and user-controlled properties), and we added a StripeSource and Email property, so the Stripe part can be better managed, and all our requests can be made using just this type. This required updating our SubscriptionChange.IsEmpty helper, which has been updated (along with its tests) and it passes all tests. To replace our SubscriptionRequest.Validate helper, we created a ChangingSystemProperties helper (which returns the system-controlled properties being changed as a slice of JSON pointers, fit for use in error messages) and an IsAcceptablePlan helper, which returns true if the plan exists and the user has the authority to select it. We also updated our stripe helpers to remove the CreateStripeSubscription (we create one when we create the customer) and create an UpdateStripeSubscription instead. It does what you'd think it does. We also added some comments to New, so it at least has some notes about how it's meant to be used and why. Now it just creates the customer in stripe, then creates a Subscription based on that customer. We also updated our StripeSubscriptionChange helper to detect when the StripeSubscription property changed.

History
     1.1 --- a/stripe.go	Tue Jun 30 01:13:16 2015 -0400
     1.2 +++ b/stripe.go	Mon Jul 13 23:30:49 2015 -0400
     1.3 @@ -1,7 +1,7 @@
     1.4  package subscriptions
     1.5  
     1.6  import (
     1.7 -	"log"
     1.8 +	"errors"
     1.9  	"time"
    1.10  
    1.11  	"code.secondbit.org/uuid.hg"
    1.12 @@ -11,6 +11,17 @@
    1.13  	"github.com/stripe/stripe-go/sub"
    1.14  )
    1.15  
    1.16 +const (
    1.17 +	PendingPlan = "pending"
    1.18 +)
    1.19 +
    1.20 +var (
    1.21 +	ErrNilCustomer               = errors.New("nil customer passed")
    1.22 +	ErrNilCustomerSubs           = errors.New("customer with nil subscriptions list passed")
    1.23 +	ErrWrongNumberOfCustomerSubs = errors.New("customer with wrong number of subscriptions passed")
    1.24 +	ErrNilSubscription           = errors.New("nil subscription passed")
    1.25 +)
    1.26 +
    1.27  type Stripe struct {
    1.28  	apiKey        string
    1.29  	customers     customer.Client
    1.30 @@ -31,13 +42,13 @@
    1.31  	}
    1.32  }
    1.33  
    1.34 -func CreateStripeCustomer(token, email string, userID uuid.ID, s Stripe) (*stripe.Customer, error) {
    1.35 +func CreateStripeCustomer(plan, email string, userID uuid.ID, s Stripe) (*stripe.Customer, error) {
    1.36  	customerParams := &stripe.CustomerParams{
    1.37  		Desc:  "Customer for user " + userID.String(),
    1.38  		Email: email,
    1.39 +		Plan:  plan,
    1.40  	}
    1.41  	customerParams.AddMeta("UserID", userID.String())
    1.42 -	customerParams.SetSource(token)
    1.43  	c, err := s.customers.New(customerParams)
    1.44  	if err != nil {
    1.45  		return nil, err
    1.46 @@ -45,57 +56,65 @@
    1.47  	return c, nil
    1.48  }
    1.49  
    1.50 -func CreateStripeSubscription(customer, plan string, userID uuid.ID, s Stripe) (*stripe.Sub, error) {
    1.51 -	subParams := &stripe.SubParams{
    1.52 -		Plan:     plan,
    1.53 -		Customer: customer,
    1.54 +func UpdateStripeSubscription(customerID string, plan, token *string, s Stripe) (*stripe.Sub, error) {
    1.55 +	params := &stripe.SubParams{}
    1.56 +	if plan != nil {
    1.57 +		params.Plan = *plan
    1.58  	}
    1.59 -	subParams.AddMeta("UserID", userID.String())
    1.60 -
    1.61 -	resp, err := s.subscriptions.New(subParams)
    1.62 +	if token != nil {
    1.63 +		params.Token = *token
    1.64 +	}
    1.65 +	subscription, err := s.subscriptions.Update(customerID, params)
    1.66  	if err != nil {
    1.67  		return nil, err
    1.68  	}
    1.69 -	return resp, nil
    1.70 +	return subscription, nil
    1.71  }
    1.72  
    1.73 -func New(req SubscriptionRequest, s Stripe, store SubscriptionStore) (Subscription, error) {
    1.74 -	subscription := SubscriptionFromRequest(req)
    1.75 -	// create the subscription in our datastore
    1.76 -	// this will fail if they already have a subscription, which prevents duplicate/orphaned Stripe customers being created
    1.77 -	err := store.CreateSubscription(subscription)
    1.78 +// New should be called when a user's profile is created. At this point, we know nothing about the subscription
    1.79 +// they actually _want_. We just sign them up for the dedicated "pending" plan. This is to make their free trial begin
    1.80 +// immediately and not have to worry about automatically locking them out until they actually create a subscription.
    1.81 +// Basically, we want everyone to have a subscription at all times, but some users will have placeholders until they
    1.82 +// actually update their subscription with a desired plan and payment method.
    1.83 +func New(req SubscriptionChange, s Stripe, store SubscriptionStore) (Subscription, error) {
    1.84 +	subscription := Subscription{}
    1.85 +	subscription.ApplyChange(req)
    1.86 +	// BUG(paddy): need to validate the change
    1.87 +
    1.88 +	// create the customer in Stripe, storing the token for reuse
    1.89 +	customer, err := CreateStripeCustomer(PendingPlan, *req.Email, req.UserID, s)
    1.90 +	if err != nil {
    1.91 +		return subscription, err
    1.92 +	}
    1.93 +	if customer == nil {
    1.94 +		return subscription, ErrNilCustomer
    1.95 +	}
    1.96 +	if customer.Subs == nil {
    1.97 +		return subscription, ErrNilCustomerSubs
    1.98 +	}
    1.99 +	if len(customer.Subs.Values) != 1 {
   1.100 +		return subscription, ErrWrongNumberOfCustomerSubs
   1.101 +	}
   1.102 +	if customer.Subs.Values[0] == nil {
   1.103 +		return subscription, ErrNilSubscription
   1.104 +	}
   1.105 +
   1.106 +	change := StripeSubscriptionChange(subscription, *customer.Subs.Values[0])
   1.107 +	subscription.ApplyChange(change)
   1.108 +
   1.109 +	err = store.CreateSubscription(subscription)
   1.110  	if err != nil {
   1.111  		return subscription, err
   1.112  	}
   1.113  
   1.114 -	// create the customer in Stripe, storing the token for reuse
   1.115 -	customer, err := CreateStripeCustomer(req.StripeToken, req.Email, req.UserID, s)
   1.116 -	if err != nil {
   1.117 -		// TODO: delete subscription object
   1.118 -		return subscription, err
   1.119 -	}
   1.120 -
   1.121 -	// create the subscription in Stripe, storing the ID for tracking and associating purposes
   1.122 -	stripeSub, err := CreateStripeSubscription(customer.ID, subscription.Plan, subscription.UserID, s)
   1.123 -	if err != nil {
   1.124 -		// TODO: delete customer
   1.125 -		// TODO: delete subscription object
   1.126 -		return subscription, err
   1.127 -	}
   1.128 -
   1.129 -	// update our subscription in the datastore with the latest information from Stripe
   1.130 -	change := StripeSubscriptionChange(subscription, *stripeSub)
   1.131 -	err = store.UpdateSubscription(subscription.UserID, change)
   1.132 -	if err != nil {
   1.133 -		log.Printf("Error pairing Stripe subscription %s to user %s: %+v\nUser needs to have their subscription updated manually.", change.StripeSubscription, req.UserID, err)
   1.134 -		return subscription, nil
   1.135 -	}
   1.136 -	subscription.ApplyChange(change)
   1.137  	return subscription, nil
   1.138  }
   1.139  
   1.140  func StripeSubscriptionChange(orig Subscription, subscription stripe.Sub) SubscriptionChange {
   1.141  	var change SubscriptionChange
   1.142 +	if subscription.ID != orig.StripeSubscription {
   1.143 +		change.StripeSubscription = &subscription.ID
   1.144 +	}
   1.145  	if subscription.Plan != nil && orig.Plan != subscription.Plan.ID {
   1.146  		change.Plan = &subscription.Plan.ID
   1.147  	}