-
Notifications
You must be signed in to change notification settings - Fork 517
Expand file tree
/
Copy pathstripe.go
More file actions
753 lines (688 loc) · 27.1 KB
/
Copy pathstripe.go
File metadata and controls
753 lines (688 loc) · 27.1 KB
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
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
package handlers
import (
"bytes"
"database/sql"
"encoding/json"
"fmt"
"html/template"
"io"
"net/http"
"time"
"github.com/gobitfly/eth2-beaconchain-explorer/db"
"github.com/gobitfly/eth2-beaconchain-explorer/mail"
"github.com/gobitfly/eth2-beaconchain-explorer/types"
"github.com/gobitfly/eth2-beaconchain-explorer/utils"
"github.com/sirupsen/logrus"
"github.com/stripe/stripe-go/v72"
portalsession "github.com/stripe/stripe-go/v72/billingportal/session"
"github.com/stripe/stripe-go/v72/checkout/session"
"github.com/stripe/stripe-go/v72/price"
"github.com/stripe/stripe-go/v72/promotioncode"
"github.com/stripe/stripe-go/v72/webhook"
)
// StripeCreateCheckoutSession creates a session to checkout api pricing subscription
func StripeCreateCheckoutSession(w http.ResponseWriter, r *http.Request) {
user := getUser(r)
// get the product that the user wants to subscribe to
var req struct {
Price string `json:"priceId"`
AddonQuantity int64 `json:"addonQuantity"`
PromotionCode string `json:"promotionCode"`
}
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
logger.Errorf("error decoding json.NewDecoder.Decode: %v", err)
return
}
rq := "required"
purchaseGroup := utils.GetPurchaseGroup(req.Price)
if purchaseGroup != utils.GROUP_ADDON {
req.AddonQuantity = 1
}
if purchaseGroup == "" {
http.Error(w, "Error invalid price item provided.", http.StatusBadRequest)
logger.Errorf("error invalid stripe price id provided: %v, expected one of [%v, %v, %v]", req.Price, utils.Config.Frontend.Stripe.Sapphire, utils.Config.Frontend.Stripe.Emerald, utils.Config.Frontend.Stripe.Diamond)
return
}
// check if a subscription exists
subscription, err := db.StripeGetUserSubscription(user.UserID, purchaseGroup)
if err != nil {
logger.Errorf("error retrieving user subscriptions %v", err)
http.Error(w, "Internal server error", http.StatusInternalServerError)
return
}
if purchaseGroup != utils.GROUP_ADDON {
// don't let the user checkout another subscription in the same group
if subscription.Active != nil && *subscription.Active {
logger.Errorf("error there is an active subscription cannot create another one %v", err)
w.WriteHeader(http.StatusBadRequest)
writeJSON(w, struct {
ErrorData string `json:"error"`
}{
ErrorData: "could not create a new stripe session",
})
return
}
} else {
addonSubs, err := db.StripeGetUserSubscriptions(user.UserID, utils.GROUP_ADDON)
if err != nil {
logger.Errorf("error retrieving user addon.subscriptions %v", err)
http.Error(w, "Internal server error", http.StatusInternalServerError)
return
}
totalAddonValidators := int64(0)
for _, s := range addonSubs {
p := utils.EffectiveProductId(utils.PriceIdToProductId(*s.PriceID))
switch p {
case "vdb_addon_1k", "vdb_addon_1k.yearly":
totalAddonValidators += 1_000
case "vdb_addon_10k", "vdb_addon_10k.yearly":
totalAddonValidators += 10_000
default:
logger.Warnf("unknown existing addon-product: %v", p)
}
}
p := utils.EffectiveProductId(utils.PriceIdToProductId(req.Price))
switch p {
case "vdb_addon_1k", "vdb_addon_1k.yearly":
totalAddonValidators += (1_000 * req.AddonQuantity)
case "vdb_addon_10k", "vdb_addon_10k.yearly":
totalAddonValidators += (10_000 * req.AddonQuantity)
default:
logger.Warnf("unknown new addon-product: %v", p)
}
if totalAddonValidators > 100_000 {
logger.Errorf("error addon can not be purchased since limit has been reached: %v", totalAddonValidators)
w.WriteHeader(http.StatusBadRequest)
writeJSON(w, struct {
ErrorData string `json:"error"`
}{
ErrorData: "could not create a new stripe session since dasboard-validators-limit has been reached",
})
}
}
// taxRates := utils.StripeDynamicRatesLive
// if strings.HasPrefix(utils.Config.Frontend.Stripe.SecretKey, "sk_test") {
// taxRates = utils.StripeDynamicRatesTest
// }
enabled := true
auto := "auto"
var successUrl = stripe.String("https://" + utils.Config.Frontend.SiteDomain + "/pricing")
var cancelUrl = stripe.String("https://" + utils.Config.Frontend.SiteDomain + "/pricing")
if purchaseGroup == utils.GROUP_MOBILE || purchaseGroup == utils.GROUP_ADDON {
successUrl = stripe.String("https://" + utils.Config.Frontend.SiteDomain + "/premium")
cancelUrl = stripe.String("https://" + utils.Config.Frontend.SiteDomain + "/premium")
}
params := &stripe.CheckoutSessionParams{
SuccessURL: successUrl,
CancelURL: cancelUrl,
// if the customer exists use the existing customer
SubscriptionData: &stripe.CheckoutSessionSubscriptionDataParams{},
BillingAddressCollection: &rq,
CustomerEmail: &subscription.Email,
PaymentMethodTypes: stripe.StringSlice([]string{
"card",
}),
AllowPromotionCodes: &enabled,
Mode: stripe.String(string(stripe.CheckoutSessionModeSubscription)),
LineItems: []*stripe.CheckoutSessionLineItemParams{
{
Price: stripe.String(req.Price),
Quantity: stripe.Int64(req.AddonQuantity),
// DynamicTaxRates: taxRates,
},
},
AutomaticTax: &stripe.CheckoutSessionAutomaticTaxParams{
Enabled: &enabled,
},
TaxIDCollection: &stripe.CheckoutSessionTaxIDCollectionParams{
Enabled: &enabled,
},
}
if subscription.CustomerID != nil {
params.CustomerEmail = nil
params.Customer = subscription.CustomerID
params.CustomerUpdate = &stripe.CheckoutSessionCustomerUpdateParams{
Name: &auto,
Address: &auto,
}
}
if req.PromotionCode != "" {
stripePrice, err := price.Get(req.Price, nil)
if err != nil || stripePrice == nil || stripePrice.Product == nil {
logger.WithError(err).WithField("stripePrice", stripePrice).Error("error retrieving stripe product for promotion code")
w.WriteHeader(http.StatusInternalServerError)
writeJSON(w, struct {
ErrorData string `json:"error"`
}{
ErrorData: "could not create a new stripe session, please try again later",
})
return
}
pcListParams := &stripe.PromotionCodeListParams{
Code: stripe.String(req.PromotionCode),
Active: stripe.Bool(true),
}
pcListParams.AddExpand("data.coupon.applies_to")
it := promotioncode.List(pcListParams)
if it.Err() != nil {
logger.WithError(it.Err()).Error("error retrieving stripe promotion code")
w.WriteHeader(http.StatusInternalServerError)
writeJSON(w, struct {
ErrorData string `json:"error"`
}{
ErrorData: "could not create a new stripe session, please try again later",
})
return
}
var pc *stripe.PromotionCode
for it.Next() {
currPc := it.PromotionCode()
if currPc == nil {
continue
}
// use the latest promotion code
if pc != nil && currPc.Created < pc.Created {
continue
}
if currPc.Coupon == nil || currPc.Coupon.AppliesTo == nil {
continue
}
for _, p := range currPc.Coupon.AppliesTo.Products {
if stripePrice.Product.ID == p {
pc = currPc
break
}
}
}
// if promotion code is not found just ignore it
if pc != nil {
params.AllowPromotionCodes = nil
params.Discounts = []*stripe.CheckoutSessionDiscountParams{
{
PromotionCode: stripe.String(pc.ID),
},
}
}
}
s, err := session.New(params)
if err != nil {
logger.WithError(err).Warn("failed to create a new stripe checkout session")
w.WriteHeader(http.StatusBadRequest)
writeJSON(w, struct {
ErrorData string `json:"error"`
}{
ErrorData: "could not create a new stripe session",
})
return
}
writeJSON(w, struct {
SessionID string `json:"sessionId"`
}{
SessionID: s.ID,
})
}
// StripeCustomerPortal redirects the user to the customer portal
func StripeCustomerPortal(w http.ResponseWriter, r *http.Request) {
user := getUser(r)
var req struct {
ReturnURL string `json:"returnURL"`
}
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
logger.WithError(err).Error("json.NewDecoder.Decode")
return
}
var customerID string
err := db.FrontendWriterDB.Get(&customerID, `
SELECT
stripe_customer_id
FROM
users
WHERE
users.id = $1
`, user.UserID)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
logger.WithError(err).Error("error could not retrieve stripe customer id")
return
}
// The URL to which the user is redirected when they are done managing
// billing in the portal.
params := &stripe.BillingPortalSessionParams{
Customer: stripe.String(customerID),
ReturnURL: stripe.String(req.ReturnURL),
}
ps, _ := portalsession.New(params)
writeJSON(w, struct {
URL string `json:"url"`
}{
URL: ps.URL,
})
}
// StripeWebhook receive events from stripe webhook service
func StripeWebhook(w http.ResponseWriter, r *http.Request) {
if r.Method != "POST" {
http.Error(w, http.StatusText(http.StatusMethodNotAllowed), http.StatusMethodNotAllowed)
return
}
b, err := io.ReadAll(r.Body)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
logger.WithError(err).Error("error failed to read body for StripeWebhook")
return
}
event, err := webhook.ConstructEvent(b, r.Header.Get("Stripe-Signature"), utils.Config.Frontend.Stripe.Webhook)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
logger.WithError(err).Error("error constructing webhook stripe signature event")
return
}
logger.WithFields(logrus.Fields{"type": event.Type}).Infof("received stripe webhook")
switch event.Type {
case "customer.created":
var customer stripe.Customer
err := json.Unmarshal(event.Data.Raw, &customer)
if err != nil {
logger.WithError(err).Error("error parsing stripe webhook JSON")
http.Error(w, "Internal server error", http.StatusInternalServerError)
return
}
if customer.Email == "" {
utils.LogError(nil, fmt.Errorf("error no email provided when creating stripe customer %v", customer.ID), 0)
http.Error(w, "error no email provided when creating stripe customer "+customer.ID, http.StatusBadRequest)
return
}
err = db.StripeUpdateCustomerID(customer.Email, customer.ID)
if err != nil {
logger.WithError(err).Error("error could not update user with a stripe customerID ", customer.ID)
http.Error(w, "error could not update user with a stripe customerID "+customer.ID+" err: "+err.Error(), http.StatusInternalServerError)
return
}
case "customer.deleted":
var customer stripe.Customer
err := json.Unmarshal(event.Data.Raw, &customer)
if err != nil {
logger.WithError(err).Error("error parsing stripe webhook JSON", err)
http.Error(w, "error parsing stripe webhook JSON", http.StatusInternalServerError)
return
}
err = db.DisableAllSubscriptionsFromStripeUser(customer.ID)
if err != nil {
logger.WithError(err).Error("error could not disable stripe mobile subs: " + customer.ID + "err: ")
// log & continue anyway
}
err = db.StripeRemoveCustomer(customer.ID)
if err != nil {
logger.WithError(err).Error("error could not delete user with customer ID: " + customer.ID + "err: ")
http.Error(w, "error could not delete user with customer ID: "+customer.ID+"err: "+err.Error(), http.StatusInternalServerError)
return
}
case "checkout.session.completed":
// Payment is successful and the subscription is created.
// You should provision the subscription.
// inform the user that the payment is being processed
var session stripe.CheckoutSession
err := json.Unmarshal(event.Data.Raw, &session)
if err != nil {
logger.WithError(err).Error("error parsing stripe webhook JSON")
http.Error(w, "error parsing stripe webhook JSON", http.StatusInternalServerError)
return
}
case "customer.subscription.created":
var subscription stripe.Subscription
err := json.Unmarshal(event.Data.Raw, &subscription)
if err != nil {
logger.WithError(err).Error("error parsing stripe webhook JSON")
http.Error(w, "error parsing stripe webhook JSON", http.StatusInternalServerError)
return
}
if subscription.Items == nil {
logger.WithError(err).Error("error creating subscription no items found", subscription)
http.Error(w, "error creating subscription no items found", http.StatusBadRequest)
return
}
if len(subscription.Items.Data) == 0 {
logger.WithError(err).Error("error creating subscription no items found", subscription)
http.Error(w, "error creating subscription no items found", http.StatusBadRequest)
return
}
// to handle race condition errors where subscription.updated is executed before customer.subscription.created, do nothing since it's already processed
_, err = db.StripeGetSubscription(subscription.ID)
if err == sql.ErrNoRows {
err = createNewStripeSubscription(subscription, event)
if err != nil {
logger.WithError(err).Error(err.Error(), event.Data.Object)
http.Error(w, "error "+err.Error()+" customer: "+subscription.Customer.ID, http.StatusInternalServerError)
return
}
}
case "customer.subscription.updated":
var subscription stripe.Subscription
err := json.Unmarshal(event.Data.Raw, &subscription)
if err != nil {
logger.WithError(err).Error("error parsing stripe webhook JSON")
http.Error(w, "error parsing stripe webhook JSON", http.StatusInternalServerError)
return
}
if subscription.Items == nil {
utils.LogError(nil, fmt.Errorf("error updating subscription no items found %v", subscription), 0)
http.Error(w, "error updating subscription no items found", http.StatusBadRequest)
return
}
if len(subscription.Items.Data) == 0 {
utils.LogError(nil, fmt.Errorf("error updating subscription no data found %v", subscription), 0)
http.Error(w, "error updating subscription no items found", http.StatusBadRequest)
return
}
priceID := subscription.Items.Data[0].Price.ID
currSub, err := db.StripeGetSubscription(subscription.ID)
if err != nil {
logger.WithError(err).Error("error getting subscription from database with id ", subscription.ID)
http.Error(w, "error updating subscription could not get current subscription err:"+err.Error(), http.StatusInternalServerError)
return
}
tx, err := db.FrontendWriterDB.Begin()
if err != nil {
logger.WithError(err).Error("error creating transaction ", subscription.ID)
http.Error(w, "error creating transaction :"+err.Error(), http.StatusInternalServerError)
}
defer tx.Rollback()
err = db.StripeUpdateSubscription(tx, priceID, subscription.ID, event.Data.Raw)
if err != nil {
logger.WithError(err).WithField("subscription.ID", subscription.ID).Error("error updating user subscription")
http.Error(w, "error updating user subscription, customer: "+subscription.Customer.ID, http.StatusInternalServerError)
return
}
if utils.GetPurchaseGroup(priceID) == utils.GROUP_MOBILE || utils.GetPurchaseGroup(priceID) == utils.GROUP_ADDON {
appSubID, err := db.GetUserSubscriptionIDByStripe(subscription.ID)
if err != nil {
if err == sql.ErrNoRows {
// subscription changed from nonmobile to mobile, insert mobile subscription
err = insertMobileSubscription(tx, subscription)
if err != nil {
logger.WithError(err).WithField("subscription.ID", subscription.ID).Error("error updating stripe mobile subscription, no users_app_subs id found for subscription id")
http.Error(w, "error updating stripe mobile subscription, no users_app_subs id found for subscription id, customer: "+subscription.Customer.ID, http.StatusInternalServerError)
return
}
} else {
logger.WithError(err).WithField("subscription.ID", subscription.ID).Error("error updating user subscription, calling db.GetUserSubscriptionIDByStripe")
http.Error(w, "error updating user subscription, customer: "+subscription.Customer.ID, http.StatusInternalServerError)
return
}
}
err = db.ChangeProductIDFromStripe(tx, subscription.ID, utils.PriceIdToProductId(priceID))
if err != nil {
logger.WithError(err).Error("error updating stripe mobile subscription", subscription.ID)
http.Error(w, "error updating stripe mobile subscription customer: "+subscription.Customer.ID, http.StatusInternalServerError)
return
}
err = db.UpdateUserSubscription(tx, appSubID, true, 0, "")
if err != nil {
logger.WithError(err).Error("error updating stripe mobile subscription (sub updated)", subscription.ID)
http.Error(w, "error updating subscription", http.StatusInternalServerError)
return
}
} else {
// make sure to delete all mobile subscriptions with the same subID
err = db.DeleteMobileSubscriptionBySubscriptionID(tx, subscription.ID)
if err != nil {
logger.WithError(err).Error("error updating stripe mobile subscription (sub updated)", subscription.ID)
http.Error(w, "error updating subscription", http.StatusInternalServerError)
return
}
}
err = tx.Commit()
if err != nil {
logger.WithError(err).Error("error committing transaction ", subscription.ID)
http.Error(w, "error committing transaction :"+err.Error(), http.StatusInternalServerError)
}
if currSub.PriceID != nil && *currSub.PriceID != priceID && utils.GetPurchaseGroup(*currSub.PriceID) == utils.GetPurchaseGroup(priceID) {
email, err := db.StripeGetCustomerEmail(subscription.Customer.ID)
if err != nil {
logger.WithError(err).Error("error retrieving customer email for subscription ", subscription.ID)
http.Error(w, "error retrieving customer email for subscription err:"+err.Error(), http.StatusInternalServerError)
}
emailCustomerAboutPlanChange(email, priceID)
}
case "customer.subscription.deleted":
// delete customer token
var subscription stripe.Subscription
err := json.Unmarshal(event.Data.Raw, &subscription)
if err != nil {
logger.WithError(err).Error("error parsing stripe webhook JSON")
http.Error(w, "error parsing stripe webhook JSON", http.StatusInternalServerError)
return
}
tx, err := db.FrontendWriterDB.Begin()
if err != nil {
logger.WithError(err).Error("error creating transaction ", subscription.ID)
http.Error(w, "error creating transaction :"+err.Error(), http.StatusInternalServerError)
}
defer tx.Rollback()
err = db.StripeUpdateSubscriptionStatus(tx, subscription.ID, false, &event.Data.Raw)
if err != nil {
logger.WithError(err).Error("error while deactivating subscription", event.Data.Object)
http.Error(w, "error while deactivating subscription, customer:"+subscription.Customer.ID, http.StatusInternalServerError)
return
}
if utils.GetPurchaseGroup(subscription.Items.Data[0].Price.ID) == utils.GROUP_MOBILE || utils.GetPurchaseGroup(subscription.Items.Data[0].Price.ID) == utils.GROUP_ADDON {
appSubID, err := db.GetUserSubscriptionIDByStripe(subscription.ID)
if err != nil {
logger.WithError(err).Error("error updating stripe mobile subscription, no users_app_subs id found for subscription id", subscription.ID)
http.Error(w, "error updating stripe mobile subscription, no users_app_subs id found for subscription id, customer: "+subscription.Customer.ID, http.StatusInternalServerError)
return
}
now := time.Now()
nowTs := now.Unix()
err = db.UpdateUserSubscription(tx, appSubID, false, nowTs, "user_canceled")
if err != nil {
logger.WithError(err).Error("error updating stripe mobile subscription (sub deleted)", subscription.ID)
http.Error(w, "error updating stripe mobile subscription customer: "+subscription.Customer.ID, http.StatusInternalServerError)
return
}
}
err = tx.Commit()
if err != nil {
logger.WithError(err).Error("error committing transaction ", subscription.ID)
http.Error(w, "error committing transaction :"+err.Error(), http.StatusInternalServerError)
}
// inform the user when the subscription will expire
case "invoice.paid":
// Continue to provision the subscription as payments continue to be made.
// Store the status in your database and check when a user accesses your service.
// This approach helps you avoid hitting rate limits.
var invoice stripe.Invoice
err := json.Unmarshal(event.Data.Raw, &invoice)
if err != nil {
logger.WithError(err).Error("error parsing stripe webhook JSON")
http.Error(w, "Internal server error", http.StatusInternalServerError)
return
}
if invoice.Lines == nil {
logger.Warn("warning processing invoice and updating subscription no items found", invoice.ID)
return
}
if len(invoice.Lines.Data) == 0 {
logger.Warn("warning processing invoice and updating subscription no items found", invoice.ID)
return
}
if len(invoice.Lines.Data[0].Subscription) == 0 {
logger.Warn("error processing invoice and updating subscription no items found", invoice.ID)
return
}
tx, err := db.FrontendWriterDB.Begin()
if err != nil {
logger.WithError(err).Error("error creating transaction ")
http.Error(w, "error creating transaction :"+err.Error(), http.StatusInternalServerError)
}
defer tx.Rollback()
err = db.StripeUpdateSubscriptionStatus(tx, invoice.Lines.Data[0].Subscription, true, nil)
if err != nil {
logger.WithError(err).Error("error processing invoice failed to activate subscription for customer", invoice.Customer.ID)
http.Error(w, "error processing invoice failed to activate subscription for customer", http.StatusInternalServerError)
return
}
if utils.GetPurchaseGroup(invoice.Lines.Data[0].Price.ID) == utils.GROUP_MOBILE || utils.GetPurchaseGroup(invoice.Lines.Data[0].Price.ID) == utils.GROUP_ADDON {
appSubID, err := db.GetUserSubscriptionIDByStripe(invoice.Lines.Data[0].Subscription)
if err != nil {
logger.WithError(err).Error("error updating stripe mobile subscription (paid), no users_app_subs id found for subscription id", invoice.Lines.Data[0].Subscription)
http.Error(w, "error updating stripe mobile subscription, no users_app_subs id found for subscription id, customer: "+invoice.Customer.ID, http.StatusInternalServerError)
return
}
err = db.UpdateUserSubscription(tx, appSubID, true, 0, "")
if err != nil {
logger.WithError(err).Error("error updating stripe mobile subscription (paid)", invoice.Lines.Data[0].Subscription)
http.Error(w, "error updating stripe mobile subscription customer: "+invoice.Customer.ID, http.StatusInternalServerError)
return
}
}
err = tx.Commit()
if err != nil {
logger.WithError(err).Error("error committing transaction ")
http.Error(w, "error committing transaction :"+err.Error(), http.StatusInternalServerError)
}
case "invoice.payment_failed":
// The payment failed or the customer does not have a valid payment method.
// The subscription becomes past_due. Notify your customer and send them to the
// customer portal to update their payment information.
var invoice stripe.Invoice
err := json.Unmarshal(event.Data.Raw, &invoice)
if err != nil {
logger.WithError(err).Error("error parsing stripe webhook JSON")
http.Error(w, "error parsing stripe webhook JSON", http.StatusInternalServerError)
return
}
emailCustomerAboutFailedPayment(invoice.CustomerEmail)
default:
return
// unhandled event type
}
}
func createNewStripeSubscription(subscription stripe.Subscription, event stripe.Event) error {
tx, err := db.FrontendWriterDB.Begin()
if err != nil {
return err
}
defer tx.Rollback()
err = db.StripeCreateSubscription(tx, subscription.Customer.ID, subscription.Items.Data[0].Price.ID, subscription.ID, event.Data.Raw)
if err != nil {
return err
}
if utils.GetPurchaseGroup(subscription.Items.Data[0].Price.ID) == utils.GROUP_MOBILE || utils.GetPurchaseGroup(subscription.Items.Data[0].Price.ID) == utils.GROUP_ADDON {
err = insertMobileSubscription(tx, subscription)
if err != nil {
return err
}
}
err = tx.Commit()
if err != nil {
return err
}
return nil
}
func insertMobileSubscription(tx *sql.Tx, subscription stripe.Subscription) error {
userID, err := db.StripeGetCustomerUserId(subscription.Customer.ID)
if err != nil {
return err
}
details := types.MobileSubscription{
ProductID: utils.PriceIdToProductId(subscription.Items.Data[0].Price.ID),
PriceMicros: uint64(subscription.Items.Data[0].Price.UnitAmount),
Currency: string(subscription.Items.Data[0].Price.Currency),
Transaction: types.MobileSubscriptionTransactionGeneric{
Type: "stripe",
Receipt: subscription.ID,
ID: subscription.Items.Data[0].Price.ID,
},
Valid: false,
}
err = db.InsertMobileSubscription(tx, userID, details, details.Transaction.Type, details.Transaction.Receipt, 0, "", subscription.ID)
if err != nil {
return err
}
return nil
}
func emailCustomerAboutFailedPayment(email string) {
msg := fmt.Sprintf("Payment processing failed. Could not activate your subscription. Please contact support at " + utils.Config.Frontend.Mail.Contact.SupportEmail + ". Manage Subscription: https://" + utils.Config.Frontend.SiteDomain + "/user/settings")
// escape html
msg = template.HTMLEscapeString(msg)
err := mail.SendTextMail(email, "Failed Payment", msg, []types.EmailAttachment{})
if err != nil {
logger.Errorf("error sending failed payment mail: %v", err)
return
}
}
func emailCustomerAboutPlanChange(email, plan string) {
p := "Sapphire"
isApi := false
if plan == utils.Config.Frontend.Stripe.Emerald {
p = "Emerald"
isApi = true
} else if plan == utils.Config.Frontend.Stripe.Diamond {
p = "Diamond"
isApi = true
} else if plan == utils.Config.Frontend.Stripe.Plankton {
p = "Plankton"
isApi = true
} else if plan == utils.Config.Frontend.Stripe.Goldfish {
p = "Goldfish"
} else if plan == utils.Config.Frontend.Stripe.Whale {
p = "Whale"
} else if plan == utils.Config.Frontend.Stripe.Iron {
p = "Iron"
isApi = true
} else if plan == utils.Config.Frontend.Stripe.Silver {
p = "Silver"
isApi = true
} else if plan == utils.Config.Frontend.Stripe.Gold {
p = "Gold"
isApi = true
} else if plan == utils.Config.Frontend.Stripe.Guppy {
p = "Guppy"
} else if plan == utils.Config.Frontend.Stripe.Dolphin {
p = "Dolphin"
} else if plan == utils.Config.Frontend.Stripe.Orca {
p = "Orca"
} else if plan == utils.Config.Frontend.Stripe.IronYearly {
p = "Iron (yearly)"
isApi = true
} else if plan == utils.Config.Frontend.Stripe.SilverYearly {
p = "Silver (yearly)"
isApi = true
} else if plan == utils.Config.Frontend.Stripe.GoldYearly {
p = "Gold (yearly)"
isApi = true
} else if plan == utils.Config.Frontend.Stripe.GuppyYearly {
p = "Guppy (yearly)"
} else if plan == utils.Config.Frontend.Stripe.DolphinYearly {
p = "Dolphin (yearly)"
} else if plan == utils.Config.Frontend.Stripe.OrcaYearly {
p = "Orca (yearly)"
}
page := "/user/settings#api"
if !isApi {
page = "/premium"
}
msg := fmt.Sprintf("You have successfully changed your payment plan to " + p + " to manage your subscription go to https://" + utils.Config.Frontend.SiteDomain + page)
// escape html
msg = template.HTMLEscapeString(msg)
err := mail.SendTextMail(email, "Payment Plan Change", msg, []types.EmailAttachment{})
if err != nil {
logger.Errorf("error sending order fulfillment email: %v", err)
return
}
}
func writeJSON(w http.ResponseWriter, v interface{}) {
var buf bytes.Buffer
if err := json.NewEncoder(&buf).Encode(v); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
logger.WithError(err).Error("error failed to writeJSON NewEncoder")
return
}
w.Header().Set("Content-Type", "application/json")
if _, err := io.Copy(w, &buf); err != nil {
logger.WithError(err).Error("error failed to writeJSON io.Copy")
return
}
}