2024-08-04 14:26:02 +00:00
|
|
|
package main
|
|
|
|
|
|
|
|
import (
|
|
|
|
"encoding/json"
|
2024-08-04 14:52:03 +00:00
|
|
|
"myapp/internal/cards"
|
2024-08-04 14:26:02 +00:00
|
|
|
"net/http"
|
2024-08-04 14:52:03 +00:00
|
|
|
"strconv"
|
2024-08-04 14:26:02 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
type stripePayload struct {
|
|
|
|
Currency string `json:"currency"`
|
|
|
|
Amount string `json:"amount"`
|
|
|
|
}
|
|
|
|
|
|
|
|
type jsonResponse struct {
|
|
|
|
OK bool `json:"ok"`
|
2024-08-04 14:52:03 +00:00
|
|
|
Message string `json:"message,omitempty"`
|
|
|
|
Content string `json:"content,omitempty"`
|
|
|
|
ID int `json:"id,omitempty"`
|
2024-08-04 14:26:02 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func (app *application) GetPaymentIntent(w http.ResponseWriter, r *http.Request) {
|
2024-08-04 14:52:03 +00:00
|
|
|
var payload stripePayload
|
|
|
|
|
|
|
|
err := json.NewDecoder(r.Body).Decode(&payload)
|
|
|
|
if err != nil {
|
|
|
|
app.errorLog.Println(err)
|
|
|
|
return // TODO: return a valid json
|
2024-08-04 14:26:02 +00:00
|
|
|
}
|
|
|
|
|
2024-08-04 14:52:03 +00:00
|
|
|
amount, err := strconv.Atoi(payload.Amount)
|
2024-08-04 14:26:02 +00:00
|
|
|
if err != nil {
|
|
|
|
app.errorLog.Println(err)
|
2024-08-04 14:52:03 +00:00
|
|
|
return // TODO: return a valid json
|
|
|
|
}
|
|
|
|
|
|
|
|
card := cards.Card{
|
|
|
|
Secret: app.config.stripe.secret,
|
|
|
|
Key: app.config.stripe.key,
|
|
|
|
Currency: payload.Currency,
|
|
|
|
}
|
|
|
|
|
|
|
|
pi, msg, err := card.Charge(payload.Currency, amount)
|
|
|
|
if err != nil {
|
|
|
|
j := jsonResponse{
|
|
|
|
OK: false,
|
|
|
|
Message: msg,
|
|
|
|
Content: "",
|
|
|
|
}
|
|
|
|
|
|
|
|
out, err := json.MarshalIndent(j, "", " ")
|
|
|
|
if err != nil {
|
|
|
|
app.errorLog.Println(err)
|
|
|
|
}
|
|
|
|
w.Header().Set("Content-Type", "application/json")
|
|
|
|
w.Write(out)
|
|
|
|
return
|
2024-08-04 14:26:02 +00:00
|
|
|
}
|
|
|
|
|
2024-08-04 14:52:03 +00:00
|
|
|
out, err := json.MarshalIndent(pi, "", " ")
|
|
|
|
if err != nil {
|
|
|
|
app.errorLog.Println(err)
|
|
|
|
return // TODO: return a valid json
|
|
|
|
}
|
2024-08-04 14:26:02 +00:00
|
|
|
w.Header().Set("Content-Type", "application/json")
|
|
|
|
w.Write(out)
|
|
|
|
}
|