I create backend for mini app in telegram. I think, my code is correct, but i get wrong hash. Maybe I create data check string in wrong format:
auth_date=1721732407nquery_id=AAGc5YMWAAAAAJzlgxb_3ABGnuser={"id":377742748,"first_name":"Марк","last_name":"Аникин","username":"corray9","language_code":"en","allows_write_to_pm":true}
Is that correct? I’m not sure about serialization of user object.
My code:
func СheckTelegramAuth(initData string) bool {
data, err := url.ParseQuery(initData)
if err != nil {
fmt.Println("Error parsing initData:", err)
return false
}
var keys []string
for k := range data {
keys = append(keys, k)
}
sort.Strings(keys)
var dataCheckStrings []string
for _, k := range keys {
if k != "hash" {
dataCheckStrings = append(dataCheckStrings, fmt.Sprintf("%s=%s", k, data.Get(k)))
}
}
dataCheckString := strings.Join(dataCheckStrings, "n")
fmt.Println(dataCheckString)
h := hmac.New(sha256.New, []byte(os.Getenv("BOT_TOKEN")))
h.Write([]byte("WebAppData"))
secretKey := h.Sum(nil)
h = hmac.New(sha256.New, secretKey)
h.Write([]byte(dataCheckString))
calculatedHash := hex.EncodeToString(h.Sum(nil))
return calculatedHash == data.Get("hash")
}
2
Answers
try to swap secret and message here
must be:
Your secret token will
HMAC-SHA-256
signature of the bot’s token with the constant stringWebAppData
not the other way around. You can replace them to make it work.Reference: https://core.telegram.org/bots/webapps#validating-data-received-via-the-mini-app