Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

134 lines
3.1KB

  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. answerWechatPost(w, r)
  27. case "GET":
  28. answerInitialAuth(w, r)
  29. default:
  30. log.Fatalln(fmt.Sprintf("Unhandled HTTP %s", r.Method))
  31. fmt.Fprintf(w, "Protocol Error: Expect GET or POST only")
  32. }
  33. }
  34. //
  35. //answerInitialAuth, when wechat first verify our URL for API hooks
  36. //
  37. func answerInitialAuth(w http.ResponseWriter, r *http.Request) {
  38. rq := r.URL.RawQuery
  39. m, _ := url.ParseQuery(rq)
  40. echostr, eok := m["echostr"]
  41. if checkSignature(r) && eok {
  42. fmt.Fprintf(w, echostr[0])
  43. } else {
  44. fmt.Fprintf(w, "wtf is wrong with the Internet")
  45. }
  46. }
  47. //answerWechatPost distribute PostRequest according to xml body info
  48. //
  49. func answerWechatPost(w http.ResponseWriter, r *http.Request) {
  50. body, _ := ioutil.ReadAll(r.Body)
  51. //fmt.Printf("get body: %s", string(body))
  52. s := ReadEncryptedMsg(string(body))
  53. //fmt.Printf("to decrypt %s", s.Encrypt)
  54. d := Decode(s.Encrypt)
  55. fmt.Printf("decrypt as: %s", d)
  56. h := ReadCommonHeader(d)
  57. reply, _ := BuildTextMsg(h.MsgType, h.FromUserName)
  58. if h.MsgType == "voice" {
  59. a := ReadVoiceMsg(d)
  60. reply, _ = BuildTextMsg(a.Recognition, h.FromUserName)
  61. }
  62. w.Header().Set("Content-Type", "text/xml; charset=utf-8")
  63. fmt.Fprint(w, reply)
  64. return
  65. }
  66. //
  67. func checkSignature(r *http.Request) bool {
  68. rq := r.URL.RawQuery
  69. m, _ := url.ParseQuery(rq)
  70. signature, sok := m["signature"]
  71. timestamp, tok := m["timestamp"]
  72. nonce, nok := m["nonce"]
  73. token := APIConfig.Token
  74. if sok && tok && nok {
  75. //sort token, timestamp, nonce and join them
  76. strs := []string{token, timestamp[0], nonce[0]}
  77. sort.Strings(strs)
  78. s := strings.Join(strs, "")
  79. //calculate sha1
  80. h := sha1.New()
  81. h.Write([]byte(s))
  82. calculated := fmt.Sprintf("%x", h.Sum(nil))
  83. return signature[0] == calculated
  84. }
  85. return false
  86. }
  87. func checkSignature1() bool {
  88. s1 := "e39de9f2e28079c01ebb4b803dfc3442b819545c"
  89. t1 := "1492970761"
  90. n1 := "1850971833"
  91. token := APIConfig.Token
  92. strs := []string{token, t1, n1}
  93. sort.Strings(strs)
  94. s := strings.Join(strs, "")
  95. h := sha1.New()
  96. h.Write([]byte(s))
  97. us := fmt.Sprintf("%x", h.Sum(nil))
  98. return s1 == us
  99. }
  100. //webrootHandler sending contents to client when request "/"
  101. // essentially to prove the webserver is still alive
  102. // echo query string to the client
  103. func webrootHandler(w http.ResponseWriter, r *http.Request) {
  104. fmt.Fprintf(w, "Hi there, I love %s!", r.URL.Path[1:])
  105. rq := r.URL.RawQuery
  106. m, _ := url.ParseQuery(rq)
  107. for index, element := range m {
  108. fmt.Fprintf(w, "\n%s => %s", index, element)
  109. }
  110. logRequestDebug(httputil.DumpRequest(r, true))
  111. }
  112. func logRequestDebug(data []byte, err error) {
  113. if err == nil {
  114. fmt.Printf("%s\n\n", data)
  115. } else {
  116. log.Fatalf("%s\n\n", err)
  117. }
  118. }