-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtelegramParser.go
89 lines (65 loc) · 1.76 KB
/
telegramParser.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
package telegramparser
import (
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"errors"
"net/url"
"sort"
"strconv"
"strings"
)
type TelegramParser struct {
secret []byte
}
func CreateParser(token string) TelegramParser {
sha := hmac.New(sha256.New, []byte("WebAppData"))
sha.Write([]byte(token))
return TelegramParser{secret: sha.Sum(nil)}
}
func (parser *TelegramParser) Parse(query string) (WebAppInitData, error) {
result := WebAppInitData{}
values, err := url.ParseQuery(query)
if err != nil {
return result, err
}
var hash string
keys := make([]string, 0, len(values))
for key := range values {
if key == "hash" {
hash = values.Get(key)
continue
}
keys = append(keys, key)
}
sort.Strings(keys)
var stringBuilder strings.Builder
for index, key := range keys {
stringBuilder.WriteString(key)
stringBuilder.WriteString("=")
stringBuilder.WriteString(values.Get(key))
if index < len(keys)-1 {
stringBuilder.WriteString("\n")
}
}
sha := hmac.New(sha256.New, parser.secret)
sha.Write([]byte(stringBuilder.String()))
if hex.EncodeToString(sha.Sum(nil)) != hash {
return result, errors.New("hash does not match")
}
result.Hash = hash
result.Signature = values.Get("signature")
result.AuthDate, err = strconv.ParseInt(values.Get("auth_date"), 10, 64)
if err != nil {
return result, err
}
result.QueryId = values.Get("query_id")
result.ChatType = values.Get("chat_type")
result.ChatInstance = values.Get("chat_instance")
result.StartParam = values.Get("start_param")
result.CanSendAfter, _ = strconv.ParseInt(values.Get("can_send_after"), 10, 64)
_ = json.Unmarshal([]byte(values.Get("user")), &result.User)
_ = json.Unmarshal([]byte(values.Get("receiver")), &result.Receiver)
return result, nil
}