-
Notifications
You must be signed in to change notification settings - Fork 0
/
webhooks_payments.go
65 lines (53 loc) · 1.75 KB
/
webhooks_payments.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
package main
import (
"errors"
"fmt"
"net/http"
"reflect"
"github.com/google/uuid"
"github.com/thewerther/webserver/internal/auth"
"github.com/thewerther/webserver/internal/database"
)
type UserPremiumUpgrade struct {
Event string `json:"event"`
Data struct {
UserID uuid.UUID `json:"user_id"`
} `json:"data"`
}
const userUpgradedEvent = "user.upgraded"
func (cfg *ApiConfig) paymentHandler(w http.ResponseWriter, req *http.Request) {
apiKey, err := auth.GetAPIKey(req.Header)
if err != nil {
respondWithError(w, http.StatusUnauthorized, "Error getting api key from request header", err)
return
}
if apiKey != cfg.PolkaKey {
respondWithError(w, http.StatusUnauthorized, "Unauthorization error", errors.New("Wrong polka API Key"))
return
}
webhookReq := UserPremiumUpgrade{}
err = decodeRequestBody(&webhookReq, req)
if err != nil {
respondWithError(w, http.StatusInternalServerError, "Error decoding request", err)
return
}
if webhookReq.Event != userUpgradedEvent {
respondWithError(w, http.StatusNoContent, "Error handling webhook event", errors.New(fmt.Sprintf("%v is not a valid event", webhookReq.Event)))
return
}
userExists, err := cfg.Database.GetUserById(req.Context(), webhookReq.Data.UserID)
if err != nil {
respondWithError(w, http.StatusInternalServerError, "Error querying user by id", err)
return
}
if reflect.DeepEqual(userExists, database.User{}) {
respondWithError(w, http.StatusNotFound, "", errors.New("Invalid user"))
return
}
err = cfg.Database.SetUserPremium(req.Context(), userExists.ID)
if err != nil {
respondWithError(w, http.StatusInternalServerError, "Error updating user to premium", err)
return
}
respondWithJSON(w, http.StatusNoContent, struct{}{})
}