~evanj/cms

ref: ed17a2199584ba94d1ca44e9002b52c48b2c02fa cms/internal/s/stripe/stripe.go -rw-r--r-- 3.9 KiB
ed17a219Evan J Feat(context): Thread context throughout data layer. TODO: Update 1 year, 14 days ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
package stripe

import (
	"context"
	"log"

	"git.sr.ht/~evanj/cms/internal/m/org"
	"git.sr.ht/~evanj/cms/internal/m/tier"
	"git.sr.ht/~evanj/cms/internal/m/user"
	"github.com/pkg/errors"
	lib "github.com/stripe/stripe-go/v71"
	"github.com/stripe/stripe-go/v71/checkout/session"
	"github.com/stripe/stripe-go/v71/customer"
	"github.com/stripe/stripe-go/v71/sub"
)

type Stripe struct {
	log                   *log.Logger
	sucesssURL, cancelURL string
	pk, sk                string
	db                    dber
}

type dber interface {
	UserGetFromToken(ctx context.Context, token string) (user.User, error)
	OrgUpdateTier(ctx context.Context, u user.User, o org.Org, t tier.Tier, paymentCustomerID string) error
}

func New(l *log.Logger, sucesssURL, cancelURL, pk, sk string, db dber) Stripe {
	// Stripe sucks.
	lib.Key = sk
	return Stripe{
		l,
		sucesssURL, cancelURL,
		pk, sk,
		db,
	}
}

func (s Stripe) StartCheckout(ctx context.Context, user user.User, t tier.Tier) (string, string, error) {
	customerParams := &lib.CustomerParams{
		Name:        lib.String(user.Name()),
		Description: lib.String(user.Token()),
	}

	c, err := customer.New(customerParams)
	if err != nil {
		return "", "", err
	}

	// Make sure we're on free tier.
	if err := s.db.OrgUpdateTier(ctx, user, user.Org(), tier.Free, c.ID); err != nil {
		return "", "", err
	}

	params := &lib.CheckoutSessionParams{
		Customer: lib.String(c.ID),
		PaymentMethodTypes: lib.StringSlice([]string{
			"card",
		}),
		LineItems: []*lib.CheckoutSessionLineItemParams{
			&lib.CheckoutSessionLineItemParams{
				Price:    lib.String(t.StripePriceID),
				Quantity: lib.Int64(1),
			},
		},
		Mode:       lib.String("subscription"),
		SuccessURL: lib.String(s.sucesssURL),
		CancelURL:  lib.String(s.cancelURL),
	}

	sess, err := session.New(params)
	if err != nil {
		return "", "", err
	}

	return sess.ID, s.pk, nil
}

func (s Stripe) CompleteCheckout(ctx context.Context, sessionID string) error {
	sess, err := session.Get(sessionID, &lib.CheckoutSessionParams{
		PaymentIntentData: &lib.CheckoutSessionPaymentIntentDataParams{},
	})
	if err != nil {
		return errors.Wrap(err, "transaction session not found")
	}

	c, err := customer.Get(sess.Customer.ID, nil)
	if err != nil {
		return errors.Wrap(err, "customer not found")
	}
	if c.Subscriptions == nil {
		return errors.New("corrupted customer object")
	}

	// NOTE: Only one subscription can exist at once per user/org.
	var (
		t   tier.Tier
		def tier.Tier
		ok  bool
	)
	for _, sub := range c.Subscriptions.Data {
		for _, li := range sub.Items.Data {
			t, ok = tier.ByStripePriceID(li.Price.ID)
			if !ok {
				return errors.New("mangled subscription item")
			}
		}
	}

	if t.Name == def.Name {
		return errors.New("subscription could not be found")
	}

	user, err := s.db.UserGetFromToken(ctx, c.Description)
	if err != nil {
		return errors.Wrap(err, "mangled user token")
	}

	return s.db.OrgUpdateTier(ctx, user, user.Org(), t, c.ID)
}

func (s Stripe) CancelSubscription(ctx context.Context, user user.User) error {
	if !user.Org().HasPaymentCustomer() {
		return errors.New("organization has no customer")
	}

	c, err := customer.Get(user.Org().PaymentCustomerID(), nil)
	if err != nil {
		return errors.Wrap(err, "customer not found")
	}
	if c.Subscriptions == nil {
		return errors.New("corrupted customer object")
	}

	currTier := user.Org().Tier()
	if err := s.db.OrgUpdateTier(ctx, user, user.Org(), tier.Free, c.ID); err != nil {
		return err
	}

	for _, subItem := range c.Subscriptions.Data {
		_, err := sub.Cancel(subItem.ID, nil)
		if err != nil {
			if err := s.db.OrgUpdateTier(ctx, user, user.Org(), currTier, c.ID); err != nil {
				// TODO: Better way to report this to ourselves?
				s.log.Println("big error: sub update in DB but not reflected in stripe")
				return errors.Wrap(err, "your subscription has been cancelled within Skipper CMS but not our payment processor: please contact an admin")
			}
			return errors.Wrap(err, "failed to cancel subscription")
		}
	}

	return nil
}