webhook.go 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. package webhooks
  2. import (
  3. "github.com/gorilla/schema"
  4. "log"
  5. "net/url"
  6. "strings"
  7. )
  8. type WebhookRequest struct {
  9. Leads Leads `schema:"leads"`
  10. Account Account `schema:"account"`
  11. }
  12. type Leads struct {
  13. Status []Status `schema:"status"`
  14. Add []Status `schema:"add"`
  15. }
  16. type Status struct {
  17. Id string `schema:"id"`
  18. StatusId string `schema:"status_id"`
  19. PipelineId string `schema:"pipeline_id"`
  20. OldStatusId string `schema:"old_status_id"`
  21. OldPipelineId string `schema:"old_pipeline_id"`
  22. }
  23. type Account struct {
  24. Id string `schema:"id"`
  25. SubDomain string `schema:"subdomain"`
  26. }
  27. func NewFromString(body string) (*WebhookRequest, error) {
  28. decodedBody, err := url.QueryUnescape(body)
  29. if err != nil {
  30. log.Fatal(err)
  31. return nil, err
  32. }
  33. replacer := strings.NewReplacer("][", ".", "[", ".", "]", "")
  34. decodedBody = replacer.Replace(decodedBody)
  35. bodyMap := make(map[string][]string)
  36. for _, value := range strings.Split(decodedBody, "&") {
  37. parameter := strings.Split(value, "=")
  38. bodyMap[parameter[0]] = []string{parameter[1]}
  39. }
  40. webhook := new(WebhookRequest)
  41. err = schema.NewDecoder().Decode(webhook, bodyMap)
  42. return webhook, err
  43. }
  44. func (hook *WebhookRequest) GetLeadId() string {
  45. if hook.Leads.Status != nil {
  46. return hook.Leads.Status[0].Id
  47. }
  48. return hook.Leads.Add[0].Id
  49. }