Browse Source

Store price ID in subscriptions

master
Immanuel Onyeka 11 months ago
parent
commit
53ebad02ae
2 changed files with 58 additions and 2 deletions
  1. +2
    -0
      migrations/0_29092022_setup_tables.sql
  2. +56
    -2
      skouter.go

+ 2
- 0
migrations/0_29092022_setup_tables.sql View File

@@ -63,6 +63,8 @@ CREATE TABLE subscription (
stripe_id VARCHAR(255) DEFAULT '', stripe_id VARCHAR(255) DEFAULT '',
user_id INT, user_id INT,
customer_id VARCHAR(255) NOT NULL, customer_id VARCHAR(255) NOT NULL,
price_id VARCHAR(255) NOT NULL,
// Key used by stripejs
client_secret VARCHAR(255) NOT NULL, client_secret VARCHAR(255) NOT NULL,
payment_status VARCHAR(50) NOT NULL, payment_status VARCHAR(50) NOT NULL,
current_period_end INT DEFAULT 0, current_period_end INT DEFAULT 0,


+ 56
- 2
skouter.go View File

@@ -33,6 +33,7 @@ import (
"github.com/stripe/stripe-go/v76/subscription" "github.com/stripe/stripe-go/v76/subscription"
"github.com/stripe/stripe-go/v76/invoice" "github.com/stripe/stripe-go/v76/invoice"
"github.com/stripe/stripe-go/v76/paymentintent" "github.com/stripe/stripe-go/v76/paymentintent"
"github.com/stripe/stripe-go/v76/webhook"
"image" "image"
_ "image/jpeg" _ "image/jpeg"
"image/png" "image/png"
@@ -69,6 +70,7 @@ type Subscription struct {
UserId int `json:"userId"` UserId int `json:"userId"`
StripeId string `json:"stripeId"` StripeId string `json:"stripeId"`
CustomerId string `json:"customerId"` CustomerId string `json:"customerId"`
PriceId string `json:"priceId"`
Start int `json:"start"` Start int `json:"start"`
End int `json:"end"` End int `json:"end"`
ClientSecret string `json:"clientSecret,omitempty"` ClientSecret string `json:"clientSecret,omitempty"`
@@ -273,6 +275,8 @@ var feeTypes = []string{
"Other", "Other",
} }


var standardPriceId = "price_1OZLK9BPMoXn2pf9kuTAf8rs"

// Used to validate claim in JWT token body. Checks if user id is greater than // Used to validate claim in JWT token body. Checks if user id is greater than
// zero and time format is valid // zero and time format is valid
func (c UserClaims) Valid() error { func (c UserClaims) Valid() error {
@@ -1291,6 +1295,7 @@ func (user *User) querySub(db *sql.DB) error {
stripe_id, stripe_id,
user_id, user_id,
customer_id, customer_id,
price_id,
current_period_end, current_period_end,
current_period_start, current_period_start,
client_secret, client_secret,
@@ -1304,6 +1309,7 @@ func (user *User) querySub(db *sql.DB) error {
&user.Sub.StripeId, &user.Sub.StripeId,
&user.Sub.UserId, &user.Sub.UserId,
&user.Sub.CustomerId, &user.Sub.CustomerId,
&user.Sub.PriceId,
&user.Sub.End, &user.Sub.End,
&user.Sub.Start, &user.Sub.Start,
&user.Sub.ClientSecret, &user.Sub.ClientSecret,
@@ -1424,12 +1430,13 @@ func (sub *Subscription) insertSub(db *sql.DB) (error) {
stripe_id, stripe_id,
user_id, user_id,
customer_id, customer_id,
price_id,
current_period_end, current_period_end,
current_period_start, current_period_start,
client_secret, client_secret,
payment_status payment_status
) )
VALUES (?, ?, ?, ?, ?, ?, ?)
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
RETURNING id RETURNING id
` `
@@ -1437,6 +1444,7 @@ func (sub *Subscription) insertSub(db *sql.DB) (error) {
sub.StripeId, sub.StripeId,
sub.UserId, sub.UserId,
sub.CustomerId, sub.CustomerId,
sub.PriceId,
sub.End, sub.End,
sub.Start, sub.Start,
sub.ClientSecret, sub.ClientSecret,
@@ -2946,7 +2954,7 @@ func createSubscription(cid string) (*stripe.Subscription, error) {
Customer: stripe.String(cid), Customer: stripe.String(cid),
Items: []*stripe.SubscriptionItemsParams{ Items: []*stripe.SubscriptionItemsParams{
{ {
Price: stripe.String("price_1OZLK9BPMoXn2pf9kuTAf8rs"),
Price: stripe.String(standardPriceId),
}, },
}, },
PaymentSettings: paymentSettings, PaymentSettings: paymentSettings,
@@ -2994,6 +3002,7 @@ func subscribe(w http.ResponseWriter, db *sql.DB, r *http.Request) {
user.Sub.UserId = user.Id user.Sub.UserId = user.Id
user.Sub.StripeId = s.ID user.Sub.StripeId = s.ID
user.Sub.CustomerId = user.CustomerId user.Sub.CustomerId = user.CustomerId
user.Sub.PriceId = standardPriceId
user.Sub.End = int(s.CurrentPeriodEnd) user.Sub.End = int(s.CurrentPeriodEnd)
user.Sub.Start = int(s.CurrentPeriodStart) user.Sub.Start = int(s.CurrentPeriodStart)
user.Sub.ClientSecret = s.LatestInvoice.PaymentIntent.ClientSecret user.Sub.ClientSecret = s.LatestInvoice.PaymentIntent.ClientSecret
@@ -3019,6 +3028,44 @@ func subscribe(w http.ResponseWriter, db *sql.DB, r *http.Request) {
} }


func invoicePaid(w http.ResponseWriter, db *sql.DB, r *http.Request) {
b, err := io.ReadAll(r.Body)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
log.Printf("io.ReadAll: %v", err)
return
}
event, err := webhook.ConstructEvent(b, r.Header.Get("Stripe-Signature"),
os.Getenv("STRIPE_SECRET_KEY"))
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
log.Printf("webhook.ConstructEvent: %v", err)
return
}

log.Println(event.Data)
}

func invoiceFailed(w http.ResponseWriter, db *sql.DB, r *http.Request) {
b, err := io.ReadAll(r.Body)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
log.Printf("io.ReadAll: %v", err)
return
}
event, err := webhook.ConstructEvent(b, r.Header.Get("Stripe-Signature"),
os.Getenv("STRIPE_SECRET_KEY"))
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
log.Printf("webhook.ConstructEvent: %v", err)
return
}

log.Println(event.Data)
}

func api(w http.ResponseWriter, r *http.Request) { func api(w http.ResponseWriter, r *http.Request) {
var args []string var args []string


@@ -3141,6 +3188,12 @@ func api(w http.ResponseWriter, r *http.Request) {
r.Method == http.MethodPost && r.Method == http.MethodPost &&
guard(r, 1): guard(r, 1):
getPdf(w, db, r) getPdf(w, db, r)
case match(p, "/api/stripe/invoice-paid", &args) &&
r.Method == http.MethodPost:
invoicePaid(w, db, r)
case match(p, "/api/stripe/invoice-payment-failed", &args) &&
r.Method == http.MethodPost:
invoiceFailed(w, db, r)
default: default:
http.Error(w, "Invalid route or token", 404) http.Error(w, "Invalid route or token", 404)
} }
@@ -3469,6 +3522,7 @@ func dev(args []string) {
os.Setenv("DBUser", "tester") os.Setenv("DBUser", "tester")
os.Setenv("DBPass", "test123") os.Setenv("DBPass", "test123")
stripe.Key = os.Getenv("STRIPE_SECRET_KEY") stripe.Key = os.Getenv("STRIPE_SECRET_KEY")
standardPriceId = "price_1OZLK9BPMoXn2pf9kuTAf8rs"


db, err := sql.Open("mysql", db, err := sql.Open("mysql",
fmt.Sprintf("%s:%s@tcp(127.0.0.1:3306)/%s?multiStatements=true", fmt.Sprintf("%s:%s@tcp(127.0.0.1:3306)/%s?multiStatements=true",


Loading…
Cancel
Save