選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

250 行
6.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.Println(fmt.Sprintf("FATAL: Unhandled HTTP %s", r.Method))
  34. response404Handler(w)
  35. //fmt.Fprintf(w, "Protocol Error: Expect GET or POST only")
  36. }
  37. }
  38. //
  39. //answerInitialAuth, when wechat first verify our URL for API hooks
  40. //
  41. func answerInitialAuth(w http.ResponseWriter, r *http.Request) {
  42. rq := r.URL.RawQuery
  43. m, _ := url.ParseQuery(rq)
  44. echostr, eok := m["echostr"]
  45. if checkSignature(r) && eok {
  46. fmt.Fprintf(w, echostr[0])
  47. } else {
  48. fmt.Fprintf(w, "wtf is wrong with the Internet")
  49. }
  50. }
  51. //
  52. //InWechatMsg what we received currently from wechat
  53. type InWechatMsg struct {
  54. header CommonHeader
  55. body interface{} //dynamic type
  56. }
  57. //
  58. //answerWechatPost distribute PostRequest according to xml body info
  59. func answerWechatPost(w http.ResponseWriter, r *http.Request) {
  60. in, valid := readWechatInput(r)
  61. reply := "" //nothing
  62. w.Header().Set("Content-Type", "text/xml; charset=utf-8")
  63. if !valid {
  64. log.Println("Error: Invalid Input ")
  65. } else {
  66. //put into user session based pipeline
  67. AllInMessage <- in
  68. }
  69. //uncomment the followin two lines to enable echo test
  70. // state, _ := echoCommand(in.header.FromUserName, in)
  71. // reply = state.response
  72. fmt.Fprint(w, reply)
  73. }
  74. func readWechatInput(r *http.Request) (result InWechatMsg, valid bool) {
  75. body, err := ioutil.ReadAll(r.Body)
  76. if err != nil {
  77. log.Println(err)
  78. valid = false
  79. return
  80. }
  81. d := decryptToXML(string(body))
  82. if d == "" {
  83. log.Println("Cannot decode Message : \r\n" + string(body))
  84. valid = false
  85. return
  86. }
  87. valid = true
  88. fmt.Printf("decrypt as: %s\n", d)
  89. result.header = ReadCommonHeader(d)
  90. switch result.header.MsgType {
  91. case "text":
  92. result.body = ReadTextMsg(d)
  93. case "image":
  94. result.body = ReadPicMsg(d)
  95. case "voice":
  96. result.body = ReadVoiceMsg(d)
  97. case "video":
  98. result.body = ReadVideoMsg(d)
  99. case "shortvideo":
  100. result.body = ReadShortVideoMsg(d)
  101. case "location":
  102. result.body = ReadLocationMsg(d)
  103. case "link":
  104. result.body = ReadLinkMsg(d)
  105. case "event":
  106. result.body = ReadEventMsg(d)
  107. default:
  108. log.Println("Fatal: unknown incoming message type" + result.header.MsgType)
  109. valid = false
  110. }
  111. return
  112. }
  113. func answerWechatPostEcho(w http.ResponseWriter, r *http.Request) {
  114. body, _ := ioutil.ReadAll(r.Body)
  115. //fmt.Printf("get body: %s", string(body))
  116. s := ReadEncryptedMsg(string(body))
  117. //fmt.Printf("to decrypt %s", s.Encrypt)
  118. d := Decode(s.Encrypt)
  119. fmt.Printf("echo as: \r\n%s", d)
  120. e := strings.Replace(d, "ToUserName", "FDDD20170506xyzunique", 2)
  121. f := strings.Replace(e, "FromUserName", "ToUserName", 2)
  122. g := strings.Replace(f, "FDDD20170506xyzunique", "FromUserName", 2)
  123. fmt.Fprint(w, g)
  124. }
  125. //
  126. func checkSignature(r *http.Request) bool {
  127. rq := r.URL.RawQuery
  128. m, _ := url.ParseQuery(rq)
  129. signature, sok := m["signature"]
  130. timestamp, tok := m["timestamp"]
  131. nonce, nok := m["nonce"]
  132. token := APIConfig.Token
  133. if sok && tok && nok {
  134. //sort token, timestamp, nonce and join them
  135. strs := []string{token, timestamp[0], nonce[0]}
  136. sort.Strings(strs)
  137. s := strings.Join(strs, "")
  138. //calculate sha1
  139. h := sha1.New()
  140. h.Write([]byte(s))
  141. calculated := fmt.Sprintf("%x", h.Sum(nil))
  142. return signature[0] == calculated
  143. }
  144. return false
  145. }
  146. func checkSignature1() bool {
  147. s1 := "e39de9f2e28079c01ebb4b803dfc3442b819545c"
  148. t1 := "1492970761"
  149. n1 := "1850971833"
  150. token := APIConfig.Token
  151. strs := []string{token, t1, n1}
  152. sort.Strings(strs)
  153. s := strings.Join(strs, "")
  154. h := sha1.New()
  155. h.Write([]byte(s))
  156. us := fmt.Sprintf("%x", h.Sum(nil))
  157. return s1 == us
  158. }
  159. //webrootHandler sending contents to client when request "/"
  160. // essentially to prove the webserver is still alive
  161. // echo query string to the client
  162. func webrootHandler(w http.ResponseWriter, r *http.Request) {
  163. fmt.Fprintf(w, "Hi there, I love %s!", r.URL.Path[1:])
  164. rq := r.URL.RawQuery
  165. m, _ := url.ParseQuery(rq)
  166. for index, element := range m {
  167. fmt.Fprintf(w, "\n%s => %s", index, element)
  168. }
  169. logRequestDebug(httputil.DumpRequest(r, true))
  170. }
  171. func logRequestDebug(data []byte, err error) {
  172. if err == nil {
  173. fmt.Printf("%s\n\n", string(data))
  174. } else {
  175. log.Fatalf("%s\n\n", err)
  176. }
  177. }
  178. //save uploaded 'file' into temporary location
  179. func uploadHandler(w http.ResponseWriter, r *http.Request) {
  180. r.ParseMultipartForm(32 << 20) //32MB memory
  181. file, handler, err := r.FormFile("file") //form-field 'file'
  182. if err != nil {
  183. fmt.Println(err)
  184. return
  185. }
  186. defer file.Close()
  187. fmt.Fprintf(w, "%v", handler.Header)
  188. f, err := os.OpenFile("/tmp/wechat_hitxy_"+handler.Filename, os.O_WRONLY|os.O_CREATE, 0666)
  189. if err != nil {
  190. fmt.Println(err)
  191. return
  192. }
  193. defer f.Close()
  194. io.Copy(f, file)
  195. }
  196. //when user requst an attachment from our server, we get the file from CRM server and reply it back
  197. //in this way, user has no 'direct-access' to the CRM server.
  198. func crmAttachmentHandler(w http.ResponseWriter, r *http.Request) {
  199. fileID := getCrmFileID(r.URL.Path)
  200. saveAs := GlobalPath.CRMAttachment + "crm_attach_" + fileID //add prefix for easy deleting
  201. if isFileExist(saveAs) {
  202. http.ServeFile(w, r, saveAs)
  203. return
  204. }
  205. if fileID == "" {
  206. log.Println("invalid fileID")
  207. response404Handler(w)
  208. return
  209. }
  210. log.Printf("download %s => %s", fileID, saveAs)
  211. crmDownloadAttachmentAs(fileID, saveAs)
  212. if !isFileExist(saveAs) {
  213. response404Handler(w)
  214. return
  215. }
  216. http.ServeFile(w, r, saveAs)
  217. }
  218. func getCrmFileID(urlPath string) string {
  219. return strings.TrimPrefix(urlPath, "/crmfiles/")
  220. }
  221. func response404Handler(w http.ResponseWriter) {
  222. w.WriteHeader(http.StatusNotFound)
  223. fmt.Fprintf(w, "not found")
  224. }