-
Notifications
You must be signed in to change notification settings - Fork 3
/
stripe.go
260 lines (231 loc) · 6.89 KB
/
stripe.go
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
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
package main
import (
"crypto/rand"
"encoding/base64"
"errors"
"fmt"
"log"
"net/http"
"net/url"
"strings"
"sync"
"time"
"github.com/stripe/stripe-go/v74"
"github.com/stripe/stripe-go/v74/checkout/session"
"github.com/stripe/stripe-go/v74/subscription"
)
const STRIPE_SESSION_CACHE = "stripe_sessions.gob"
type StripeClient struct {
URLSuccess string
URLCancel string
URLPageManage string
RoutePageManage string
RoutePageThankYou string
RouteAPIIncoming string
RouteAPISuccess string
RouteAPICancel string
sync.Mutex
}
func NewStripeClient(domain *url.URL, apiPrefix string, pagePrefix string) *StripeClient {
auth, ok := providerAuth["stripe"]
if !ok {
return nil
}
stripe.Key = auth.Secret
routeAPISuccess := apiPrefix + "/success"
routePageManage := pagePrefix
urlSuccess := domain.JoinPath(routeAPISuccess)
urlCancel := domain.JoinPath("/order")
urlPageManage := domain.JoinPath(routePageManage)
urlSuccess.RawQuery = "session_id={CHECKOUT_SESSION_ID}"
log.Println("Using Stripe auth", auth.Secret)
return &StripeClient{
URLSuccess: urlSuccess.String(),
URLCancel: urlCancel.String(),
URLPageManage: urlPageManage.String(),
RoutePageManage: pagePrefix,
RoutePageThankYou: (pagePrefix + "/thankyou"),
RouteAPIIncoming: (apiPrefix + "/incoming"),
RouteAPISuccess: routeAPISuccess,
RouteAPICancel: (apiPrefix + "/cancel"),
}
}
func stripeSaltedSubID(salt string, subID string) string {
hash := CryptHashOfSlice([]byte(subID + salt))
ret := base64.StdEncoding.EncodeToString(hash[:])
return ret
}
// Sub accesses encrypted subscription data.
func (c *StripeClient) Sub(salt string) (string, error) {
saltedSubID, ok := stripeSubs.data[salt]
if !ok {
return "", errors.New("unknown subscription")
}
return saltedSubID, nil
}
func (c *StripeClient) subIDVerify(salt string, subID string) error {
expected, err := c.Sub(salt)
if err != nil {
return err
}
if expected != stripeSaltedSubID(salt, subID) {
return errors.New("unknown combination of salt and subscription ID")
}
return nil
}
func (c *StripeClient) subDataFromForm(req *http.Request) (salt string, subID string, err error) {
if err := req.ParseForm(); err != nil {
return "", "", err
}
salt = strings.TrimSpace(req.PostForm.Get("salt"))
subID = strings.TrimSpace(req.PostForm.Get("sub_id"))
if (len(salt) == 0) || (len(subID) == 0) {
return "", "", errors.New("missing form data")
}
return salt, subID, c.subIDVerify(salt, subID)
}
type stripeSessionView struct {
SubID string
URLPageManage string
Unpaid bool
}
func (c *StripeClient) Session(sessionID string, salt string) (*stripeSessionView, error) {
s, err := session.Get(sessionID, nil)
if err != nil {
return nil, err
}
if err := c.subIDVerify(salt, s.Subscription.ID); err != nil {
return nil, err
}
unpaid := (s.PaymentStatus == stripe.CheckoutSessionPaymentStatusUnpaid)
return &stripeSessionView{
SubID: s.Subscription.ID,
URLPageManage: (c.URLPageManage + "/" + salt),
Unpaid: unpaid,
}, nil
}
func (c *StripeClient) HandleIncoming(wr http.ResponseWriter, req *http.Request, in *Incoming) {
str := stripe.String
i64 := stripe.Int64
params := &stripe.CheckoutSessionParams{
SuccessURL: &c.URLSuccess,
CancelURL: &c.URLCancel,
LineItems: []*stripe.CheckoutSessionLineItemParams{{
PriceData: &stripe.CheckoutSessionLineItemPriceDataParams{
Currency: str(string(stripe.CurrencyEUR)),
Product: str("prod_NiZac7KHxgcQul"),
UnitAmount: i64(int64(in.Cents)),
TaxBehavior: str(string(stripe.PriceTaxBehaviorInclusive)),
},
Quantity: i64(1),
}},
}
if in.Cycle == "monthly" {
params.Mode = str(string(stripe.CheckoutSessionModeSubscription))
params.LineItems[0].PriceData.Recurring = &stripe.CheckoutSessionLineItemPriceDataRecurringParams{
Interval: str("month"),
IntervalCount: i64(1),
}
} else {
params.Mode = str(string(stripe.CheckoutSessionModePayment))
}
// Just in case the server crashes between here and the success handler…
log.Println("Incoming Stripe payment request:", *in)
s, err := session.New(params)
if err != nil {
respondWithError(wr, err)
return
}
time := time.Unix(s.Created, 0)
in.ProviderSession = s.ID
in.Time = &time
c.Lock()
defer c.Unlock()
sessions, err := CacheLoad[map[string]*Incoming](STRIPE_SESSION_CACHE)
if err != nil {
sessions = make(map[string]*Incoming)
}
sessions[s.ID] = in
CacheSave(STRIPE_SESSION_CACHE, sessions)
// https://github.com/whatwg/fetch/issues/763#issuecomment-1430650132
wr.Header().Add("Location", s.URL)
wr.WriteHeader(http.StatusNoContent)
}
func (c *StripeClient) HandleSuccess(wr http.ResponseWriter, req *http.Request) {
sessionID := req.URL.Query().Get("session_id")
c.Lock()
defer c.Unlock()
sessions, err := CacheLoad[map[string]*Incoming](STRIPE_SESSION_CACHE)
if err != nil {
//lint:ignore ST1005 People might read this one.
respondWithError(wr, fmt.Errorf(
"Failed to load Stripe session cache?! I should have received your order though. If I did, you will soon receive a confirmation email.",
))
return
}
in, ok := sessions[sessionID]
if !ok {
respondWithError(wr, fmt.Errorf(
"invalid Stripe session ID: %v", sessionID,
))
return
}
s, err := session.Get(sessionID, nil)
if err != nil {
respondWithError(wr, err)
return
}
// Note that we don't check the PaymentStatus here, as certain payment
// providers take days or even weeks to confirm subscription transactions.
if s.Status != stripe.CheckoutSessionStatusComplete {
wr.WriteHeader(http.StatusPaymentRequired)
fmt.Fprintln(wr, "Nice try.")
return
}
if err := incoming.Insert(in); err != nil {
respondWithError(wr, err)
return
}
redirect := "/thankyou"
if s.Subscription != nil {
saltBytes := make([]byte, 8)
salt := ""
ok = true
for ok {
_, err := rand.Read(saltBytes)
if err != nil {
respondWithError(wr, fmt.Errorf(
"error generating cancellation key for subscription: %v",
err,
))
return
}
salt = base64.URLEncoding.EncodeToString(saltBytes)
_, ok = stripeSubs.data[salt]
}
stripeSubs.Insert(salt, stripeSaltedSubID(salt, s.Subscription.ID))
redirect = (c.RoutePageThankYou + "/" + sessionID + "/" + salt)
}
delete(sessions, sessionID)
CacheSave(STRIPE_SESSION_CACHE, sessions)
http.Redirect(wr, req, redirect, http.StatusSeeOther)
}
func (c *StripeClient) HandleCancel(wr http.ResponseWriter, req *http.Request) {
salt, subID, err := c.subDataFromForm(req)
if err != nil {
respondWithError(wr, err)
return
}
if _, err := subscription.Cancel(subID, nil); err != nil {
respondWithError(wr, err)
return
}
if err := stripeSubs.Delete(salt); err != nil {
//lint:ignore ST1005 People might read this one.
respondWithError(wr, fmt.Errorf(
"Failed to remove the subscription from the server: %v. It was properly canceled though.",
err,
))
}
wr.WriteHeader(http.StatusNoContent)
}