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.

190 lines
5.1KB

  1. package main
  2. import (
  3. "crypto/sha1"
  4. "fmt"
  5. "io"
  6. "io/ioutil"
  7. "log"
  8. "net/http"
  9. "net/http/httputil"
  10. "net/url"
  11. "os"
  12. "sort"
  13. "strings"
  14. )
  15. //apiV1Main version 1 main entry for all wechat callbacks
  16. //
  17. func apiV1Main(w http.ResponseWriter, r *http.Request) {
  18. logRequestDebug(httputil.DumpRequest(r, true))
  19. if checkSignature(r) == false {
  20. log.Println("signature of URL incorrect")
  21. w.Header().Set("Content-Type", "text/xml; charset=utf-8")
  22. w.WriteHeader(http.StatusUnauthorized)
  23. fmt.Fprintf(w, "") //empty string
  24. return
  25. }
  26. switch r.Method {
  27. case "POST":
  28. //answerWechatPostEcho(w, r)
  29. answerWechatPost(w, r)
  30. case "GET":
  31. answerInitialAuth(w, r)
  32. default:
  33. log.Fatalln(fmt.Sprintf("Unhandled HTTP %s", r.Method))
  34. fmt.Fprintf(w, "Protocol Error: Expect GET or POST only")
  35. }
  36. }
  37. //
  38. //answerInitialAuth, when wechat first verify our URL for API hooks
  39. //
  40. func answerInitialAuth(w http.ResponseWriter, r *http.Request) {
  41. rq := r.URL.RawQuery
  42. m, _ := url.ParseQuery(rq)
  43. echostr, eok := m["echostr"]
  44. if checkSignature(r) && eok {
  45. fmt.Fprintf(w, echostr[0])
  46. } else {
  47. fmt.Fprintf(w, "wtf is wrong with the Internet")
  48. }
  49. }
  50. //answerWechatPost distribute PostRequest according to xml body info
  51. //
  52. func answerWechatPost(w http.ResponseWriter, r *http.Request) {
  53. body, _ := ioutil.ReadAll(r.Body)
  54. d := decryptToXML(string(body))
  55. fmt.Printf("decrypt as: %s\n", d)
  56. h := ReadCommonHeader(d)
  57. reply, _ := BuildTextMsg(h.MsgType, h.FromUserName)
  58. if h.MsgType == "text" {
  59. reply, _ = BuildTextMsg("http://www.hitxy.org.au/", h.FromUserName)
  60. }
  61. if h.MsgType == "voice" {
  62. a := ReadVoiceMsg(d)
  63. reply, _ = BuildTextMsg(a.Recognition, h.FromUserName)
  64. }
  65. if h.MsgType == "event" {
  66. a := ReadEventMsg(d)
  67. if a.Event == "LOCATION" {
  68. reply = BuildLocationMsg(0, 0, 0, h.FromUserName)
  69. fmt.Printf("output %s", reply)
  70. } else {
  71. reply, _ = BuildTextMsg(a.Event+"/"+a.EventKey, h.FromUserName)
  72. }
  73. //mediaID := "cU8BYvAEp3H25V-yGO3WBtMVk2bZcEBgf_kje7V-EPkRA_U4x-OAWb_ONg6Y-Qxt" //video
  74. //mediaID := "e2iNEiSxCX5TV1WbFd0TQPTdMx8WbvpkOs_iNhSVQHY" // 236 second mp3
  75. //mediaID := "e2iNEiSxCX5TV1WbFd0TQDVyk970GxTcBWMnqc2RzF0" //5 sec mp3
  76. //mediaID := "e2iNEiSxCX5TV1WbFd0TQMqvVrqFDbDOacdjgQ-OAuE" //news
  77. //reply = buildVideoMsg(h.FromUserName, mediaID, "标题", a.Event+"/"+a.EventKey)
  78. //reply = buildUploadPicMsg(h.FromUserName, "media_for_test/640x480.jpg")
  79. //reply = buildUploadVoiceMsg(h.FromUserName, "media_for_test/music.mp3")
  80. //reply = buildVoiceMsg(h.FromUserName, mediaID)
  81. reply = buildSampleMusicMsg(h.FromUserName)
  82. //reply = buildSampleArticleMsg(h.FromUserName)
  83. }
  84. w.Header().Set("Content-Type", "text/xml; charset=utf-8")
  85. fmt.Fprint(w, reply)
  86. return
  87. }
  88. func answerWechatPostEcho(w http.ResponseWriter, r *http.Request) {
  89. body, _ := ioutil.ReadAll(r.Body)
  90. //fmt.Printf("get body: %s", string(body))
  91. s := ReadEncryptedMsg(string(body))
  92. //fmt.Printf("to decrypt %s", s.Encrypt)
  93. d := Decode(s.Encrypt)
  94. fmt.Printf("echo as: \n%s", d)
  95. e := strings.Replace(d, "ToUserName", "FDDD20170506xyzunique", 2)
  96. f := strings.Replace(e, "FromUserName", "ToUserName", 2)
  97. g := strings.Replace(f, "FDDD20170506xyzunique", "FromUserName", 2)
  98. fmt.Fprint(w, g)
  99. }
  100. //
  101. func checkSignature(r *http.Request) bool {
  102. rq := r.URL.RawQuery
  103. m, _ := url.ParseQuery(rq)
  104. signature, sok := m["signature"]
  105. timestamp, tok := m["timestamp"]
  106. nonce, nok := m["nonce"]
  107. token := APIConfig.Token
  108. if sok && tok && nok {
  109. //sort token, timestamp, nonce and join them
  110. strs := []string{token, timestamp[0], nonce[0]}
  111. sort.Strings(strs)
  112. s := strings.Join(strs, "")
  113. //calculate sha1
  114. h := sha1.New()
  115. h.Write([]byte(s))
  116. calculated := fmt.Sprintf("%x", h.Sum(nil))
  117. return signature[0] == calculated
  118. }
  119. return false
  120. }
  121. func checkSignature1() bool {
  122. s1 := "e39de9f2e28079c01ebb4b803dfc3442b819545c"
  123. t1 := "1492970761"
  124. n1 := "1850971833"
  125. token := APIConfig.Token
  126. strs := []string{token, t1, n1}
  127. sort.Strings(strs)
  128. s := strings.Join(strs, "")
  129. h := sha1.New()
  130. h.Write([]byte(s))
  131. us := fmt.Sprintf("%x", h.Sum(nil))
  132. return s1 == us
  133. }
  134. //webrootHandler sending contents to client when request "/"
  135. // essentially to prove the webserver is still alive
  136. // echo query string to the client
  137. func webrootHandler(w http.ResponseWriter, r *http.Request) {
  138. fmt.Fprintf(w, "Hi there, I love %s!", r.URL.Path[1:])
  139. rq := r.URL.RawQuery
  140. m, _ := url.ParseQuery(rq)
  141. for index, element := range m {
  142. fmt.Fprintf(w, "\n%s => %s", index, element)
  143. }
  144. logRequestDebug(httputil.DumpRequest(r, true))
  145. }
  146. func logRequestDebug(data []byte, err error) {
  147. if err == nil {
  148. fmt.Printf("%s\n\n", string(data))
  149. } else {
  150. log.Fatalf("%s\n\n", err)
  151. }
  152. }
  153. //save uploaded 'file' into temporary location
  154. func uploadHandler(w http.ResponseWriter, r *http.Request) {
  155. r.ParseMultipartForm(32 << 20) //32MB memory
  156. file, handler, err := r.FormFile("file") //form-field 'file'
  157. if err != nil {
  158. fmt.Println(err)
  159. return
  160. }
  161. defer file.Close()
  162. fmt.Fprintf(w, "%v", handler.Header)
  163. f, err := os.OpenFile("/tmp/wechat_hitxy_"+handler.Filename, os.O_WRONLY|os.O_CREATE, 0666)
  164. if err != nil {
  165. fmt.Println(err)
  166. return
  167. }
  168. defer f.Close()
  169. io.Copy(f, file)
  170. }