-
Notifications
You must be signed in to change notification settings - Fork 0
/
payment.go
78 lines (66 loc) · 1.88 KB
/
payment.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
package payment
import (
"bytes"
"encoding/json"
"io"
"log"
"net/http"
"github.com/stripe/stripe-go/v72"
"github.com/stripe/stripe-go/v72/paymentintent"
)
type Item struct {
Id string
}
func calculateOrderAmount(items []Item) int64 {
// Replace this constant with a calculation of the order's amount
// Calculate the order total on the server to prevent
// people from directly manipulating the amount on the clientß
return 100
}
func HandleCreatePaymentIntent(w http.ResponseWriter, r *http.Request) {
if r.Method != "POST" {
http.Error(w, http.StatusText(http.StatusMethodNotAllowed), http.StatusMethodNotAllowed)
return
}
var req struct {
Items []Item `json:"items"`
}
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
log.Printf("json.NewDecoder.Decode: %v", err)
return
}
// Create a PaymentIntent with amount and currency
params := &stripe.PaymentIntentParams{
Amount: stripe.Int64(calculateOrderAmount(req.Items)),
Currency: stripe.String(string(stripe.CurrencyUSD)),
AutomaticPaymentMethods: &stripe.PaymentIntentAutomaticPaymentMethodsParams{
Enabled: stripe.Bool(true),
},
}
pi, err := paymentintent.New(params)
log.Printf("pi.New: %v", pi.ClientSecret)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
log.Printf("pi.New: %v", err)
return
}
writeJSON(w, struct {
ClientSecret string `json:"clientSecret"`
}{
ClientSecret: pi.ClientSecret,
})
}
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
}
}