No puede seleccionar más de 25 temas Los temas deben comenzar con una letra o número, pueden incluir guiones ('-') y pueden tener hasta 35 caracteres de largo.

155 líneas
3.8KB

  1. package main
  2. import (
  3. "crypto/sha1"
  4. "fmt"
  5. "io/ioutil"
  6. "log"
  7. "net/http"
  8. "net/http/httputil"
  9. "net/url"
  10. "sort"
  11. "strings"
  12. )
  13. //apiV1Main version 1 main entry for all wechat callbacks
  14. //
  15. func apiV1Main(w http.ResponseWriter, r *http.Request) {
  16. logRequestDebug(httputil.DumpRequest(r, true))
  17. if checkSignature(r) == false {
  18. log.Println("signature of URL incorrect")
  19. w.Header().Set("Content-Type", "text/xml; charset=utf-8")
  20. w.WriteHeader(http.StatusUnauthorized)
  21. fmt.Fprintf(w, "") //empty string
  22. return
  23. }
  24. switch r.Method {
  25. case "POST":
  26. //answerWechatPostEcho(w, r)
  27. answerWechatPost(w, r)
  28. case "GET":
  29. answerInitialAuth(w, r)
  30. default:
  31. log.Fatalln(fmt.Sprintf("Unhandled HTTP %s", r.Method))
  32. fmt.Fprintf(w, "Protocol Error: Expect GET or POST only")
  33. }
  34. }
  35. //
  36. //answerInitialAuth, when wechat first verify our URL for API hooks
  37. //
  38. func answerInitialAuth(w http.ResponseWriter, r *http.Request) {
  39. rq := r.URL.RawQuery
  40. m, _ := url.ParseQuery(rq)
  41. echostr, eok := m["echostr"]
  42. if checkSignature(r) && eok {
  43. fmt.Fprintf(w, echostr[0])
  44. } else {
  45. fmt.Fprintf(w, "wtf is wrong with the Internet")
  46. }
  47. }
  48. //answerWechatPost distribute PostRequest according to xml body info
  49. //
  50. func answerWechatPost(w http.ResponseWriter, r *http.Request) {
  51. body, _ := ioutil.ReadAll(r.Body)
  52. d := decryptToXML(string(body))
  53. fmt.Printf("decrypt as: %s\n", d)
  54. h := ReadCommonHeader(d)
  55. reply, _ := BuildTextMsg(h.MsgType, h.FromUserName)
  56. if h.MsgType == "voice" {
  57. a := ReadVoiceMsg(d)
  58. reply, _ = BuildTextMsg(a.Recognition, h.FromUserName)
  59. }
  60. if h.MsgType == "event" {
  61. a := ReadEventMsg(d)
  62. if a.Event == "LOCATION" {
  63. reply = BuildLocationMsg(0, 0, 0, h.FromUserName)
  64. fmt.Printf("output %s", reply)
  65. } else {
  66. reply, _ = BuildTextMsg(a.Event+"/"+a.EventKey, h.FromUserName)
  67. }
  68. }
  69. w.Header().Set("Content-Type", "text/xml; charset=utf-8")
  70. fmt.Fprint(w, reply)
  71. return
  72. }
  73. func answerWechatPostEcho(w http.ResponseWriter, r *http.Request) {
  74. body, _ := ioutil.ReadAll(r.Body)
  75. //fmt.Printf("get body: %s", string(body))
  76. s := ReadEncryptedMsg(string(body))
  77. //fmt.Printf("to decrypt %s", s.Encrypt)
  78. d := Decode(s.Encrypt)
  79. fmt.Printf("echo as: \n%s", d)
  80. e := strings.Replace(d, "ToUserName", "FDDD20170506xyzunique", 2)
  81. f := strings.Replace(e, "FromUserName", "ToUserName", 2)
  82. g := strings.Replace(f, "FDDD20170506xyzunique", "FromUserName", 2)
  83. fmt.Fprint(w, g)
  84. }
  85. //
  86. func checkSignature(r *http.Request) bool {
  87. rq := r.URL.RawQuery
  88. m, _ := url.ParseQuery(rq)
  89. signature, sok := m["signature"]
  90. timestamp, tok := m["timestamp"]
  91. nonce, nok := m["nonce"]
  92. token := APIConfig.Token
  93. if sok && tok && nok {
  94. //sort token, timestamp, nonce and join them
  95. strs := []string{token, timestamp[0], nonce[0]}
  96. sort.Strings(strs)
  97. s := strings.Join(strs, "")
  98. //calculate sha1
  99. h := sha1.New()
  100. h.Write([]byte(s))
  101. calculated := fmt.Sprintf("%x", h.Sum(nil))
  102. return signature[0] == calculated
  103. }
  104. return false
  105. }
  106. func checkSignature1() bool {
  107. s1 := "e39de9f2e28079c01ebb4b803dfc3442b819545c"
  108. t1 := "1492970761"
  109. n1 := "1850971833"
  110. token := APIConfig.Token
  111. strs := []string{token, t1, n1}
  112. sort.Strings(strs)
  113. s := strings.Join(strs, "")
  114. h := sha1.New()
  115. h.Write([]byte(s))
  116. us := fmt.Sprintf("%x", h.Sum(nil))
  117. return s1 == us
  118. }
  119. //webrootHandler sending contents to client when request "/"
  120. // essentially to prove the webserver is still alive
  121. // echo query string to the client
  122. func webrootHandler(w http.ResponseWriter, r *http.Request) {
  123. fmt.Fprintf(w, "Hi there, I love %s!", r.URL.Path[1:])
  124. rq := r.URL.RawQuery
  125. m, _ := url.ParseQuery(rq)
  126. for index, element := range m {
  127. fmt.Fprintf(w, "\n%s => %s", index, element)
  128. }
  129. logRequestDebug(httputil.DumpRequest(r, true))
  130. }
  131. func logRequestDebug(data []byte, err error) {
  132. if err == nil {
  133. fmt.Printf("%s\n\n", data)
  134. } else {
  135. log.Fatalf("%s\n\n", err)
  136. }
  137. }