Golang - Check pagarme signature

Identificador: 11574
Autor: Ricardo Bocchi   segunda-feira, Dia 1 de maio de 2023, às 02:53:56 horas
Revisado Por:    quarta-feira, Dia 11 de outubro de 2017, às 02:15:31 horas
Visualização: Todos

Pontos: 0   Acessos: 4974



 import(
  "encoding/json"
  "encoding/hex"
  "crypto/sha1"
  "crypto/hmac"
  "strings"
  "fmt"

)


func (this *PagarmeController) Postback() {



  apiKey := "my api key"
  

  pagarmeSignature := this.Ctx.Request.Header.Get("X-Hub-Signature")

  if !strings.Contains(pagarmeSignature, "="){
    this.Abort("500")
    return
  }

  fmt.Println("************************************************")
  fmt.Println("**  X-Hub-Signature = ", pagarmeSignature)
  fmt.Println("************************************************")    


  cleanedSignature := strings.Split(pagarmeSignature, "=")[1]

  fmt.Println("************************************************")
  fmt.Println("**  cleanedSignature = ", cleanedSignature)
  fmt.Println("************************************************")    

  mac := hmac.New(sha1.New, []byte(apiKey))
  mac.Write(this.Ctx.Input.RequestBody)
  rawBodyMAC := mac.Sum(nil)
  computedHash := hex.EncodeToString(rawBodyMAC)

  fmt.Println("************************************************")
  fmt.Println("**  computedHash = ", computedHash)
  fmt.Println("************************************************")      

  if !hmac.Equal([]byte(cleanedSignature), []byte(computedHash)){
    fmt.Println("************************************************")
    fmt.Println("** Inválid Pagarme Signature: Expected: %v, Received: %v", string(cleanedSignature), string(computedHash))
    fmt.Println("************************************************")    
    this.Abort("500")
    return
  } else {
    fmt.Println("************************************************")
    fmt.Println("** Válido Pagarme Signature: Expected: %v, Received: %v", string(cleanedSignature), string(computedHash))
    fmt.Println("************************************************")        
  }

    this.Ctx.ResponseWriter.WriteHeader(200)
}