forked from maddyblue/goread
-
Notifications
You must be signed in to change notification settings - Fork 0
/
charge.go
249 lines (234 loc) · 6.43 KB
/
charge.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
/*
* Copyright (c) 2013 Matt Jibson <[email protected]>
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
package goread
import (
"context"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"net/url"
"strings"
"time"
"github.com/mjibson/goon"
"google.golang.org/appengine/datastore"
"google.golang.org/appengine/log"
"google.golang.org/appengine/urlfetch"
"google.golang.org/appengine/user"
)
type Plan struct {
Id, Name, Desc string
Amount int
}
// parent: User, key: 1
type UserCharge struct {
_kind string `goon:"kind,UC"`
Id int64 `datastore:"-" goon:"id"`
Parent *datastore.Key `datastore:"-" goon:"parent"`
Customer string `datastore:"c,noindex" json:"-"`
Created time.Time `datastore:"r,noindex"`
Last4 string `datastore:"l,noindex" json:"-"`
Next time.Time `datastore:"n,noindex"`
Amount int `datastore:"a,noindex"`
Interval string `datastore:"i,noindex"`
Plan string `datastore:"p,noindex"`
}
type StripeCustomer struct {
Id string `json:"id"`
Created int64 `json:"created"`
Card struct {
Last4 string `json:"last4"`
} `json:"active_card"`
Subscription struct {
Plan struct {
Interval string `json:"interval"`
Id string `json:"id"`
Amount int `json:"amount"`
} `json:"plan"`
End int64 `json:"current_period_end"`
} `json:"subscription"`
}
type StripeError struct {
Error struct {
Message string `json:"message"`
} `json:"error"`
}
func Charge(w http.ResponseWriter, r *http.Request) {
c := r.Context()
cu := user.Current(c)
gn := goon.FromContext(c)
u := User{Id: cu.ID}
uc := &UserCharge{Id: 1, Parent: gn.Key(&u)}
if err := gn.Get(&u); err != nil {
serveError(w, err)
return
} else if u.Account != AFree {
serveError(w, fmt.Errorf("You're already subscribed."))
return
}
if err := gn.Get(uc); err == nil && len(uc.Customer) > 0 {
serveError(w, fmt.Errorf("You're already subscribed."))
return
} else if err != datastore.ErrNoSuchEntity {
serveError(w, err)
return
}
resp, err := stripe(c, "POST", "customers", url.Values{
"email": {u.Email},
"description": {u.Id},
"card": {r.FormValue("token")},
"plan": {r.FormValue("plan")},
}.Encode())
if err != nil {
serveError(w, err)
return
} else if resp.StatusCode != http.StatusOK {
var se StripeError
defer resp.Body.Close()
b, _ := ioutil.ReadAll(resp.Body)
if err := json.Unmarshal(b, &se); err == nil {
serveError(w, fmt.Errorf(se.Error.Message))
} else {
serveError(w, fmt.Errorf("Error"))
}
log.Errorf(c, "status: %v, %s", resp.StatusCode, b)
return
}
uc, err = setCharge(c, resp)
if err != nil {
serveError(w, err)
return
}
b, _ := json.Marshal(&uc)
w.Write(b)
}
func setCharge(c context.Context, r *http.Response) (*UserCharge, error) {
var sc StripeCustomer
defer r.Body.Close()
b, err := ioutil.ReadAll(r.Body)
if err != nil {
return nil, err
}
if err := json.Unmarshal(b, &sc); err != nil {
return nil, err
}
cu := user.Current(c)
gn := goon.FromContext(c)
u := User{Id: cu.ID}
uc := UserCharge{Id: 1, Parent: gn.Key(&u)}
if err := gn.RunInTransaction(func(gn *goon.Goon) error {
if err := gn.Get(&u); err != nil && err != datastore.ErrNoSuchEntity {
return err
}
if err := gn.Get(&uc); err != nil && err != datastore.ErrNoSuchEntity {
return err
}
u.Account = APaid
uc.Customer = sc.Id
uc.Last4 = sc.Card.Last4
uc.Created = time.Unix(sc.Created, 0)
uc.Next = time.Unix(sc.Subscription.End, 0)
uc.Amount = sc.Subscription.Plan.Amount
uc.Interval = sc.Subscription.Plan.Interval
uc.Plan = sc.Subscription.Plan.Id
_, err := gn.PutMulti([]interface{}{&u, &uc})
return err
}, nil); err != nil {
return nil, err
}
return &uc, nil
}
func Account(w http.ResponseWriter, r *http.Request) {
c := r.Context()
cu := user.Current(c)
gn := goon.FromContext(c)
u := User{Id: cu.ID}
uc := &UserCharge{Id: 1, Parent: gn.Key(&u)}
if err := gn.Get(uc); err == nil {
if uc.Next.Before(time.Now()) {
if resp, err := stripe(c, "GET", "customers/"+uc.Customer, ""); err == nil {
if nuc, err := setCharge(c, resp); err == nil {
uc = nuc
log.Infof(c, "updated user charge %v", cu.ID)
}
}
}
b, _ := json.Marshal(&uc)
w.Write(b)
} else if err != datastore.ErrNoSuchEntity {
serveError(w, err)
return
}
}
func Uncheckout(w http.ResponseWriter, r *http.Request) {
c := r.Context()
uc, err := doUncheckout(c)
if err != nil {
serveError(w, err)
return
}
b, _ := json.Marshal(uc)
w.Write(b)
}
func doUncheckout(c context.Context) (*UserCharge, error) {
cu := user.Current(c)
gn := goon.FromContext(c)
u := User{Id: cu.ID}
uc := UserCharge{Id: 1, Parent: gn.Key(&u)}
if err := gn.Get(&u); err != nil {
return nil, err
}
if err := gn.Get(&uc); err != nil || len(uc.Customer) == 0 {
return nil, err
}
resp, err := stripe(c, "DELETE", "customers/"+uc.Customer, "")
if err != nil {
return nil, err
} else if resp.StatusCode != http.StatusOK {
log.Errorf(c, "%s", resp.Body)
log.Errorf(c, "stripe delete error, but proceeding")
}
if err := gn.RunInTransaction(func(gn *goon.Goon) error {
if err := gn.Get(&u); err != nil && err != datastore.ErrNoSuchEntity {
return err
}
u.Account = AFree
if uc.Next.After(u.Until) {
u.Until = uc.Next
}
if err := gn.Delete(gn.Key(&uc)); err != nil {
return err
}
_, err := gn.Put(&u)
return err
}, nil); err != nil {
return nil, err
}
return &uc, nil
}
func stripe(c context.Context, method, urlStr, body string) (*http.Response, error) {
cl := &http.Client{
Transport: &urlfetch.Transport{
Context: c,
},
}
req, err := http.NewRequest(method, fmt.Sprintf("https://api.stripe.com/v1/%s", urlStr), strings.NewReader(body))
if err != nil {
return nil, err
}
req.SetBasicAuth(STRIPE_SECRET, "")
return cl.Do(req)
}