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.

157 líneas
3.9KB

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