~evanj/cms

ref: 8efa6eb4fd1aad49d40bb3850530c531add998da cms/internal/s/stripe/stripe.go -rw-r--r-- 2.1 KiB
8efa6eb4Evan M Jones WIP(stripe): *. 1 year, 2 months 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
package stripe

import (
	"fmt"

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

const (
	KeyUserToken = "StripeKeyCMSUserID"
)

type Stripe struct {
	sucesssURL, cancelURL string
	pk, sk                string
}

func New(sucesssURL, cancelURL, pk, sk string) Stripe {
	// Stripe sucks.
	lib.Key = sk
	return Stripe{
		sucesssURL, cancelURL,
		pk, sk,
	}
}

func (s Stripe) StartCheckout(user user.User, t tier.Tier) (string, string, error) {
	customerParams := &lib.CustomerParams{
		Params: lib.Params{
			Metadata: map[string]string{
				KeyUserToken: user.Token(),
			},
		},
		Name: lib.String(user.Name()),
	}

	c, err := customer.New(customerParams)
	if 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(fmt.Sprintf("%s?session_id={CHECKOUT_SESSION_ID}", 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(sessionID string) (tier.Tier, error) {
// 	sess, _ := session.Get(sessionID, nil)
// 	userID, ok := sess.Metadata[KeyUserToken]
// 	if !ok {
// 		return tier.Tier{}, errors.New("no user associated with transaction")
// 	}
//
// 	i := session.ListLineItems(sessionID, nil)
// 	for i.Next() {
// 		li := i.LineItem()
// 		if li.Price != nil {
// 			t, ok := tier.ByStripePriceID(li.Price.ID)
// 			if !ok {
// 				return tier.Tier{}, errors.New("invalid stripe response: checkout not complete")
// 			}
// 			return t, nil
// 		}
// 	}
//
// 	return tier.Tier{}, errors.New("tier subscription could not be found")
// }