Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

161 lines
4.2KB

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