Nie możesz wybrać więcej, niż 25 tematów Tematy muszą się zaczynać od litery lub cyfry, mogą zawierać myślniki ('-') i mogą mieć do 35 znaków.

150 lines
3.7KB

  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. reply, _ = BuildTextMsg(a.Event+"/"+a.EventKey, h.FromUserName)
  63. }
  64. w.Header().Set("Content-Type", "text/xml; charset=utf-8")
  65. fmt.Fprint(w, reply)
  66. return
  67. }
  68. func answerWechatPostEcho(w http.ResponseWriter, r *http.Request) {
  69. body, _ := ioutil.ReadAll(r.Body)
  70. //fmt.Printf("get body: %s", string(body))
  71. s := ReadEncryptedMsg(string(body))
  72. //fmt.Printf("to decrypt %s", s.Encrypt)
  73. d := Decode(s.Encrypt)
  74. fmt.Printf("echo as: \n%s", d)
  75. e := strings.Replace(d, "ToUserName", "FDDD20170506xyzunique", 2)
  76. f := strings.Replace(e, "FromUserName", "ToUserName", 2)
  77. g := strings.Replace(f, "FDDD20170506xyzunique", "FromUserName", 2)
  78. fmt.Fprint(w, g)
  79. }
  80. //
  81. func checkSignature(r *http.Request) bool {
  82. rq := r.URL.RawQuery
  83. m, _ := url.ParseQuery(rq)
  84. signature, sok := m["signature"]
  85. timestamp, tok := m["timestamp"]
  86. nonce, nok := m["nonce"]
  87. token := APIConfig.Token
  88. if sok && tok && nok {
  89. //sort token, timestamp, nonce and join them
  90. strs := []string{token, timestamp[0], nonce[0]}
  91. sort.Strings(strs)
  92. s := strings.Join(strs, "")
  93. //calculate sha1
  94. h := sha1.New()
  95. h.Write([]byte(s))
  96. calculated := fmt.Sprintf("%x", h.Sum(nil))
  97. return signature[0] == calculated
  98. }
  99. return false
  100. }
  101. func checkSignature1() bool {
  102. s1 := "e39de9f2e28079c01ebb4b803dfc3442b819545c"
  103. t1 := "1492970761"
  104. n1 := "1850971833"
  105. token := APIConfig.Token
  106. strs := []string{token, t1, n1}
  107. sort.Strings(strs)
  108. s := strings.Join(strs, "")
  109. h := sha1.New()
  110. h.Write([]byte(s))
  111. us := fmt.Sprintf("%x", h.Sum(nil))
  112. return s1 == us
  113. }
  114. //webrootHandler sending contents to client when request "/"
  115. // essentially to prove the webserver is still alive
  116. // echo query string to the client
  117. func webrootHandler(w http.ResponseWriter, r *http.Request) {
  118. fmt.Fprintf(w, "Hi there, I love %s!", r.URL.Path[1:])
  119. rq := r.URL.RawQuery
  120. m, _ := url.ParseQuery(rq)
  121. for index, element := range m {
  122. fmt.Fprintf(w, "\n%s => %s", index, element)
  123. }
  124. logRequestDebug(httputil.DumpRequest(r, true))
  125. }
  126. func logRequestDebug(data []byte, err error) {
  127. if err == nil {
  128. fmt.Printf("%s\n\n", data)
  129. } else {
  130. log.Fatalf("%s\n\n", err)
  131. }
  132. }