You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

247 lines
6.0KB

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