|
| 1 | +package billing |
| 2 | + |
| 3 | +import ( |
| 4 | + "encoding/json" |
| 5 | + "fmt" |
| 6 | + "net/http" |
| 7 | + "net/url" |
| 8 | + "os" |
| 9 | + "strings" |
| 10 | + |
| 11 | + Stripe "github.com/stripe/stripe-go/v72" |
| 12 | + "github.com/stripe/stripe-go/v72/client" |
| 13 | +<%- if eq (index .Params `userAuth`) "yes" %> |
| 14 | + "<% .Files.Repository %>/internal/auth" |
| 15 | +<%- end %> |
| 16 | +) |
| 17 | + |
| 18 | +var backendHost = os.Getenv("BACKEND_HOST") |
| 19 | +var frontendHost = os.Getenv("FRONTEND_HOST") |
| 20 | + |
| 21 | +var Handler = getHandler() |
| 22 | +var stripe *client.API |
| 23 | + |
| 24 | +// Subscriptions for frontend to display available plans available for checkout |
| 25 | +type Subscriptions struct { |
| 26 | + Nickname string `json:"nickname"` |
| 27 | + Interval string `json:"interval"` |
| 28 | + Type string `json:"type"` |
| 29 | + ID string `json:"id"` |
| 30 | + Price string `json:"price"` |
| 31 | +} |
| 32 | + |
| 33 | +func getHandler() http.Handler { |
| 34 | + setupStripe() |
| 35 | + mux := http.NewServeMux() |
| 36 | + mux.HandleFunc("/billing/products", getProducts) |
| 37 | + mux.HandleFunc("/billing/checkout", checkout) |
| 38 | + mux.HandleFunc("/billing/success", success) |
| 39 | + mux.HandleFunc("/billing/cancel", cancel) |
| 40 | + mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { |
| 41 | + w.Write([]byte("Not found")) |
| 42 | + }) |
| 43 | + return mux |
| 44 | +} |
| 45 | + |
| 46 | +func setupStripe() { |
| 47 | + stripe = &client.API{} |
| 48 | + apiKey := os.Getenv("STRIPE_API_SECRET_KEY") |
| 49 | + stripe.Init(apiKey, nil) |
| 50 | +} |
| 51 | + |
| 52 | +func getProducts(w http.ResponseWriter, r *http.Request) { |
| 53 | + active := true |
| 54 | + listParams := &Stripe.PriceListParams{Active: &active} |
| 55 | + stripePriceIterator := stripe.Prices.List(listParams).Iter |
| 56 | + |
| 57 | + subs := []Subscriptions{} |
| 58 | + // Data to display subscriptions for the frontend example |
| 59 | + for stripePriceIterator.Next() { |
| 60 | + stripePrice := stripePriceIterator.Current().(*Stripe.Price) |
| 61 | + amount := float64(stripePrice.UnitAmount) / 100 |
| 62 | + displayPrice := fmt.Sprintf("%s $%.2f/%s", strings.ToUpper(string(stripePrice.Currency)), amount, string(stripePrice.Recurring.Interval)) |
| 63 | + sub := Subscriptions{ |
| 64 | + Nickname: stripePrice.Nickname, |
| 65 | + Interval: string(stripePrice.Recurring.Interval), |
| 66 | + Type: string(stripePrice.Type), |
| 67 | + ID: stripePrice.ID, |
| 68 | + Price: displayPrice, |
| 69 | + } |
| 70 | + subs = append(subs, sub) |
| 71 | + } |
| 72 | + output, err := json.Marshal(&subs) |
| 73 | + if err != nil { |
| 74 | + http.Error(w, err.Error(), http.StatusInternalServerError) |
| 75 | + } |
| 76 | + w.Write(output) |
| 77 | +} |
| 78 | + |
| 79 | +func checkout(w http.ResponseWriter, r *http.Request) { |
| 80 | + if r.Method != "POST" { |
| 81 | + http.Error(w, "Incorrect method", http.StatusBadRequest) |
| 82 | + return |
| 83 | + } |
| 84 | + |
| 85 | + price := struct { |
| 86 | + ID string `json:"price_id"` |
| 87 | + }{} |
| 88 | + err := json.NewDecoder(r.Body).Decode(&price) |
| 89 | + if err != nil { |
| 90 | + http.Error(w, err.Error(), http.StatusBadRequest) |
| 91 | + return |
| 92 | + } |
| 93 | + |
| 94 | + paymentMethod := "card" |
| 95 | + paymentMode := "subscription" |
| 96 | + checkoutQuantity := int64(1) |
| 97 | + lineItem := &Stripe.CheckoutSessionLineItemParams{ |
| 98 | + Price: &price.ID, |
| 99 | + Quantity: &checkoutQuantity, |
| 100 | + } |
| 101 | + successURL := "https://" + backendHost + "/billing/success?session_id={CHECKOUT_SESSION_ID}" |
| 102 | + cancelURL := "https://" + backendHost + "/billing/cancel?session_id={CHECKOUT_SESSION_ID}" |
| 103 | +<% if eq (index .Params `userAuth`) "yes" %> |
| 104 | + authErr, userInfo := auth.GetUserInfoFromHeaders(r) |
| 105 | + clientReferenceID := userInfo.ID |
| 106 | + if authErr != nil { |
| 107 | + http.Error(w, authErr.Error(), http.StatusUnauthorized) |
| 108 | + return |
| 109 | + } |
| 110 | + <%- else %> |
| 111 | + clientReferenceID := "internal-app-reference-id" |
| 112 | + <%- end %> |
| 113 | + |
| 114 | + checkoutParams := &Stripe.CheckoutSessionParams{ |
| 115 | + Mode: &paymentMode, |
| 116 | + PaymentMethodTypes: []*string{&paymentMethod}, |
| 117 | + ClientReferenceID: &clientReferenceID, |
| 118 | + LineItems: []*Stripe.CheckoutSessionLineItemParams{lineItem}, |
| 119 | + SuccessURL: &successURL, |
| 120 | + CancelURL: &cancelURL, |
| 121 | + } |
| 122 | + session, err := stripe.CheckoutSessions.New(checkoutParams) |
| 123 | + if err != nil { |
| 124 | + http.Error(w, err.Error(), http.StatusInternalServerError) |
| 125 | + return |
| 126 | + } |
| 127 | + fmt.Fprintf(w, `{"sessionId": "%s"}`, session.ID) |
| 128 | +} |
| 129 | + |
| 130 | +func success(w http.ResponseWriter, r *http.Request) { |
| 131 | + sessionId := string(r.URL.Query().Get("session_id")) |
| 132 | + |
| 133 | + session, err := stripe.CheckoutSessions.Get(sessionId, &Stripe.CheckoutSessionParams{}) |
| 134 | + if err != nil { |
| 135 | + http.Error(w, err.Error(), http.StatusInternalServerError) |
| 136 | + return |
| 137 | + } |
| 138 | + data := map[string]string{ |
| 139 | + "payment_status": string(session.PaymentStatus), |
| 140 | + "amount": fmt.Sprintf("%d", session.AmountSubtotal), |
| 141 | + "currency": string(session.Currency), |
| 142 | + "customer": string(session.CustomerDetails.Email), |
| 143 | + "reference": string(session.ClientReferenceID), |
| 144 | + } |
| 145 | + |
| 146 | + baseUrl := url.URL{ |
| 147 | + Scheme: "https", |
| 148 | + Host: frontendHost, |
| 149 | + Path: "/billing/confirmation", |
| 150 | + } |
| 151 | + redirectURL := fmt.Sprintf("%s?%s", baseUrl.String(), mapToQueryString(data)) |
| 152 | + http.Redirect(w, r, redirectURL, 302) |
| 153 | +} |
| 154 | + |
| 155 | +func cancel(w http.ResponseWriter, r *http.Request) { |
| 156 | + sessionId := string(r.URL.Query().Get("session_id")) |
| 157 | + |
| 158 | + session, err := stripe.CheckoutSessions.Get(sessionId, &Stripe.CheckoutSessionParams{}) |
| 159 | + if err != nil { |
| 160 | + http.Error(w, err.Error(), http.StatusInternalServerError) |
| 161 | + return |
| 162 | + } |
| 163 | + data := map[string]string{ |
| 164 | + "payment_status": string(session.PaymentStatus), |
| 165 | + "amount": fmt.Sprintf("%d", session.AmountSubtotal), |
| 166 | + "currency": string(session.Currency), |
| 167 | + "reference": string(session.ClientReferenceID), |
| 168 | + } |
| 169 | + baseUrl := url.URL{ |
| 170 | + Scheme: "https", |
| 171 | + Host: frontendHost, |
| 172 | + Path: "/billing/confirmation", |
| 173 | + } |
| 174 | + redirectURL := fmt.Sprintf("%s?%s", baseUrl.String(), mapToQueryString(data)) |
| 175 | + http.Redirect(w, r, redirectURL, 302) |
| 176 | +} |
| 177 | + |
| 178 | +func mapToQueryString(data map[string]string) string { |
| 179 | + queryString := url.Values{} |
| 180 | + for k, v := range data { |
| 181 | + queryString.Add(k, v) |
| 182 | + } |
| 183 | + return queryString.Encode() |
| 184 | +} |
0 commit comments