forked from stripe-samples/accept-a-payment
-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.go
151 lines (130 loc) · 3.9 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
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/paymentintent"
"github.com/stripe/stripe-go/v72/webhook"
)
func main() {
err := godotenv.Load()
if err != nil {
log.Fatal("Error loading .env file")
}
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/payment-element",
Version: "0.0.1",
URL: "https://github.com/stripe-samples",
})
http.Handle("/", http.FileServer(http.Dir(os.Getenv("STATIC_DIR"))))
http.HandleFunc("/config", handleConfig)
http.HandleFunc("/create-payment-intent", handleCreatePaymentIntent)
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 handleConfig(w http.ResponseWriter, r *http.Request) {
if r.Method != "GET" {
http.Error(w, http.StatusText(http.StatusMethodNotAllowed), http.StatusMethodNotAllowed)
return
}
writeJSON(w, struct {
PublishableKey string `json:"publishableKey"`
}{
PublishableKey: os.Getenv("STRIPE_PUBLISHABLE_KEY"),
})
}
func handleCreatePaymentIntent(w http.ResponseWriter, r *http.Request) {
params := &stripe.PaymentIntentParams{
Amount: stripe.Int64(1999),
Currency: stripe.String("EUR"),
AutomaticPaymentMethods: &stripe.PaymentIntentAutomaticPaymentMethodsParams{
Enabled: stripe.Bool(true),
},
}
pi, err := paymentintent.New(params)
if err != nil {
// Try to safely cast a generic error to a stripe.Error so that we can get at
// some additional Stripe-specific information about what went wrong.
if stripeErr, ok := err.(*stripe.Error); ok {
fmt.Printf("Other Stripe error occurred: %v\n", stripeErr.Error())
writeJSONErrorMessage(w, stripeErr.Error(), 400)
} else {
fmt.Printf("Other error occurred: %v\n", err.Error())
writeJSONErrorMessage(w, "Unknown server error", 500)
}
return
}
writeJSON(w, struct {
ClientSecret string `json:"clientSecret"`
}{
ClientSecret: pi.ClientSecret,
})
}
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!")
}
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)
}