2024-03-27 22:28:01 +02:00
|
|
|
package main
|
|
|
|
|
|
|
|
import (
|
|
|
|
"encoding/json"
|
2024-04-10 23:24:16 +03:00
|
|
|
"gitea.stuzer.link/stuzer05/go-monobank"
|
2024-04-12 13:00:28 +03:00
|
|
|
"io"
|
2024-03-27 22:28:01 +02:00
|
|
|
"net/http"
|
2024-04-12 13:00:28 +03:00
|
|
|
"stuzer.link/monobank-firefly3-bot/app"
|
2024-03-27 22:28:01 +02:00
|
|
|
)
|
|
|
|
|
|
|
|
func handleWebhook(w http.ResponseWriter, r *http.Request) {
|
2024-04-12 13:00:28 +03:00
|
|
|
// read request body bytes
|
|
|
|
body, err := io.ReadAll(r.Body)
|
2024-03-27 22:28:01 +02:00
|
|
|
if err != nil {
|
2024-04-12 13:00:28 +03:00
|
|
|
app.LogString(err.Error())
|
2024-03-27 22:28:01 +02:00
|
|
|
w.WriteHeader(http.StatusOK)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2024-04-12 13:00:28 +03:00
|
|
|
// log body string
|
2024-08-29 16:03:08 +03:00
|
|
|
defer app.LogString(string(body))
|
2024-04-12 13:00:28 +03:00
|
|
|
|
|
|
|
// check request empty body
|
|
|
|
if len(string(body)) == 0 {
|
|
|
|
app.LogString("empty body")
|
2024-03-27 22:28:01 +02:00
|
|
|
w.WriteHeader(http.StatusOK)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2024-04-12 13:00:28 +03:00
|
|
|
// parse request body
|
|
|
|
var monobankTransaction monobank.WebHookResponse
|
|
|
|
err = json.Unmarshal(body, &monobankTransaction)
|
2024-03-27 22:28:01 +02:00
|
|
|
if err != nil {
|
2024-04-12 13:00:28 +03:00
|
|
|
app.LogString(err.Error())
|
2024-03-27 22:28:01 +02:00
|
|
|
w.WriteHeader(http.StatusOK)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2024-09-07 11:38:02 +03:00
|
|
|
// check if transaction hs been logged
|
|
|
|
isTransactionAlreadyLogged, err := app.LogContainsTransactionID(monobankTransaction.Data.StatementItem.Id)
|
|
|
|
if err != nil {
|
|
|
|
app.LogString(err.Error())
|
|
|
|
return
|
|
|
|
}
|
|
|
|
if isTransactionAlreadyLogged {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2024-04-12 13:00:28 +03:00
|
|
|
err = app.ImportTransaction(monobankTransaction)
|
|
|
|
if err != nil {
|
|
|
|
app.LogString(err.Error())
|
2024-03-27 22:28:01 +02:00
|
|
|
w.WriteHeader(http.StatusOK)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
w.WriteHeader(http.StatusOK)
|
|
|
|
}
|