forked from stripe-samples/accept-a-payment
-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.go
175 lines (151 loc) · 5.21 KB
/
server.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
package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"log"
"net/http"
"os"
"github.com/joho/godotenv"
"github.com/stripe/stripe-go/v72"
"github.com/stripe/stripe-go/v72/checkout/session"
"github.com/stripe/stripe-go/v72/webhook"
)
func main() {
err := godotenv.Load()
if err != nil {
log.Fatal("Error loading .env file")
}
checkEnv()
stripe.Key = os.Getenv("STRIPE_SECRET_KEY")
// For sample support and debugging, not required for production:
stripe.SetAppInfo(&stripe.AppInfo{
Name: "stripe-samples/accept-a-payment/prebuilt-checkout-page",
Version: "0.0.1",
URL: "https://github.com/stripe-samples",
})
http.Handle("/", http.FileServer(http.Dir(os.Getenv("STATIC_DIR"))))
http.HandleFunc("/checkout-session", handleCheckoutSession)
http.HandleFunc("/create-checkout-session", handleCreateCheckoutSession)
http.HandleFunc("/webhook", handleWebhook)
log.Println("server running at 0.0.0.0:4242")
http.ListenAndServe("0.0.0.0:4242", nil)
}
// ErrorResponseMessage represents the structure of the error
// object sent in failed responses.
type ErrorResponseMessage struct {
Message string `json:"message"`
}
// ErrorResponse represents the structure of the error object sent
// in failed responses.
type ErrorResponse struct {
Error *ErrorResponseMessage `json:"error"`
}
func handleCheckoutSession(w http.ResponseWriter, r *http.Request) {
if r.Method != "GET" {
http.Error(w, http.StatusText(http.StatusMethodNotAllowed), http.StatusMethodNotAllowed)
return
}
sessionID := r.URL.Query().Get("sessionId")
s, _ := session.Get(sessionID, nil)
writeJSON(w, s)
}
func handleCreateCheckoutSession(w http.ResponseWriter, r *http.Request) {
domainURL := os.Getenv("DOMAIN")
// Pulls the list of payment method types from environment variables (`.env`).
// In practice, users often hard code the list of strings.
// Create new Checkout Session for the order
// Other optional params include:
// [billing_address_collection] - to display billing address details on the page
// [customer] - if you have an existing Stripe Customer ID
// [payment_intent_data] - lets capture the payment later
// [customer_email] - lets you prefill the email input in the form
// [automatic_tax] - to automatically calculate sales tax, VAT and GST in the checkout page
// For full details see https://stripe.com/docs/api/checkout/sessions/create
// ?session_id={CHECKOUT_SESSION_ID} means the redirect will have the session ID
// set as a query param
params := &stripe.CheckoutSessionParams{
SuccessURL: stripe.String(domainURL + "/success.html?session_id={CHECKOUT_SESSION_ID}"),
CancelURL: stripe.String(domainURL + "/canceled.html"),
Mode: stripe.String(string(stripe.CheckoutSessionModePayment)),
LineItems: []*stripe.CheckoutSessionLineItemParams{
{
Quantity: stripe.Int64(1),
Price: stripe.String(os.Getenv("PRICE")),
},
},
// AutomaticTax: &stripe.CheckoutSessionAutomaticTaxParams{Enabled: stripe.Bool(true)},
}
s, err := session.New(params)
if err != nil {
http.Error(w, fmt.Sprintf("error while creating session %v", err.Error()), http.StatusInternalServerError)
return
}
http.Redirect(w, r, s.URL, http.StatusSeeOther)
}
func handleWebhook(w http.ResponseWriter, r *http.Request) {
if r.Method != "POST" {
http.Error(w, http.StatusText(http.StatusMethodNotAllowed), http.StatusMethodNotAllowed)
return
}
b, err := ioutil.ReadAll(r.Body)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
log.Printf("ioutil.ReadAll: %v", err)
return
}
event, err := webhook.ConstructEvent(b, r.Header.Get("Stripe-Signature"), os.Getenv("STRIPE_WEBHOOK_SECRET"))
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
log.Printf("webhook.ConstructEvent: %v", err)
return
}
if event.Type == "checkout.session.completed" {
fmt.Println("Checkout Session completed!")
// Note: If you need access to the line items, for instance to
// automate fullfillment based on the the ID of the Price, you'll
// need to refetch the Checkout Session here, and expand the line items:
//
// params := &stripe.CheckoutSessionParams{}
// params.AddExpand("line_items")
// s, _ := session.Get("cs_test_...", params)
// lineItems := s.LineItems
//
// Read more about expand here: https://stripe.com/docs/expand
}
writeJSON(w, nil)
}
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)
log.Printf("json.NewEncoder.Encode: %v", err)
return
}
w.Header().Set("Content-Type", "application/json")
if _, err := io.Copy(w, &buf); err != nil {
log.Printf("io.Copy: %v", err)
return
}
}
func writeJSONError(w http.ResponseWriter, v interface{}, code int) {
w.WriteHeader(code)
writeJSON(w, v)
return
}
func writeJSONErrorMessage(w http.ResponseWriter, message string, code int) {
resp := &ErrorResponse{
Error: &ErrorResponseMessage{
Message: message,
},
}
writeJSONError(w, resp, code)
}
func checkEnv() {
price := os.Getenv("PRICE")
if price == "price_12345" || price == "" {
log.Fatal("You must set a Price ID from your Stripe account. See the README for instructions.")
}
}