skip to Main Content

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


  1. try to swap secret and message here

    must be:

    h := hmac.New(sha256.New, []byte("WebAppData"))
        h.Write([]byte(os.Getenv("BOT_TOKEN")))
    
    Login or Signup to reply.
  2. You can verify the integrity of the data (InitData) received by comparing the
    received hash parameter with the hexadecimal representation of the
    HMAC-SHA-256 signature of the data-check-string with the secret key,
    which is the HMAC-SHA-256 signature of the bot’s token with the
    constant string WebAppData used as a key.

    Your secret token will HMAC-SHA-256 signature of the bot’s token with the constant string WebAppData not the other way around. You can replace them to make it work.

    h := hmac.New(sha256.New, []byte("WebAppData"))
        h.Write([]byte(os.Getenv("BOT_TOKEN")))
        secretKey := h.Sum(nil)
    

    Reference: https://core.telegram.org/bots/webapps#validating-data-received-via-the-mini-app

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search