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.

274 lines
6.6KB

  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. "strconv"
  14. "strings"
  15. "time"
  16. )
  17. //apiV1Main version 1 main entry for all wechat callbacks
  18. //
  19. func apiV1Main(w http.ResponseWriter, r *http.Request) {
  20. logRequestDebug(httputil.DumpRequest(r, true))
  21. if checkSignature(r) == false {
  22. log.Println("signature of URL incorrect")
  23. w.Header().Set("Content-Type", "text/xml; charset=utf-8")
  24. w.WriteHeader(http.StatusUnauthorized)
  25. fmt.Fprintf(w, "") //empty string
  26. return
  27. }
  28. switch r.Method {
  29. case "POST":
  30. //answerWechatPostEcho(w, r)
  31. answerWechatPost(w, r)
  32. case "GET":
  33. answerInitialAuth(w, r)
  34. default:
  35. log.Println(fmt.Sprintf("FATAL: Unhandled HTTP %s", r.Method))
  36. response404Handler(w)
  37. //fmt.Fprintf(w, "Protocol Error: Expect GET or POST only")
  38. }
  39. }
  40. //
  41. //answerInitialAuth, when wechat first verify our URL for API hooks
  42. //
  43. func answerInitialAuth(w http.ResponseWriter, r *http.Request) {
  44. rq := r.URL.RawQuery
  45. m, _ := url.ParseQuery(rq)
  46. echostr, eok := m["echostr"]
  47. if checkSignature(r) && eok {
  48. fmt.Fprintf(w, echostr[0])
  49. } else {
  50. fmt.Fprintf(w, "wtf is wrong with the Internet")
  51. }
  52. }
  53. //
  54. //answerWechatPost distribute PostRequest according to xml body info
  55. func answerWechatPost(w http.ResponseWriter, r *http.Request) {
  56. in, valid := readWechatInput(r)
  57. reply := "" //nothing
  58. w.Header().Set("Content-Type", "text/xml; charset=utf-8")
  59. if !valid {
  60. log.Println("Error: Invalid Input ")
  61. } else {
  62. //put into user session based pipeline
  63. AllInMessage <- in
  64. }
  65. //read instant response
  66. reply = <-in.instantResponse
  67. in.destroy()
  68. //uncomment the followin two lines to enable echo test
  69. // state, _ := echoCommand(in.header.FromUserName, in)
  70. // reply = state.response
  71. fmt.Fprint(w, reply)
  72. }
  73. func readWechatInput(r *http.Request) (result InWechatMsg, valid bool) {
  74. body, err := ioutil.ReadAll(r.Body)
  75. if err != nil {
  76. log.Println(err)
  77. valid = false
  78. return
  79. }
  80. d := decryptToXML(string(body))
  81. if d == "" {
  82. log.Println("Cannot decode Message : \r\n" + string(body))
  83. valid = false
  84. return
  85. }
  86. valid = true
  87. fmt.Printf("decrypt as: %s\n", d)
  88. result.init()
  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. return verifySignature(signature[0], timestamp[0], nonce[0], token)
  135. }
  136. return false
  137. }
  138. func verifySignature(signature, timestamp, nonce, token string) bool {
  139. if timestampTooOldStr(timestamp) {
  140. return false
  141. }
  142. //sort token, timestamp, nonce and join them
  143. strs := []string{token, timestamp, nonce}
  144. sort.Strings(strs)
  145. s := strings.Join(strs, "")
  146. //calculate sha1
  147. h := sha1.New()
  148. h.Write([]byte(s))
  149. calculated := fmt.Sprintf("%x", h.Sum(nil))
  150. return signature == calculated
  151. }
  152. func timestampTooOldStr(timestamp string) bool {
  153. ts, err := strconv.Atoi(timestamp)
  154. if err != nil {
  155. return true
  156. }
  157. return timestampTooOld(int32(ts))
  158. }
  159. func timestampTooOld(ts int32) bool {
  160. //diff > 3min from now
  161. now := int32(time.Now().Unix())
  162. diff := now - ts
  163. if diff < 0 {
  164. diff = -diff
  165. }
  166. return diff > 180 //3 minutes, 180 seconds
  167. }
  168. // func checkSignature1() bool {
  169. // s1 := "e39de9f2e28079c01ebb4b803dfc3442b819545c"
  170. // t1 := "1492970761"
  171. // n1 := "1850971833"
  172. // token := APIConfig.Token
  173. // strs := []string{token, t1, n1}
  174. // sort.Strings(strs)
  175. // s := strings.Join(strs, "")
  176. // h := sha1.New()
  177. // h.Write([]byte(s))
  178. // us := fmt.Sprintf("%x", h.Sum(nil))
  179. // return s1 == us
  180. // }
  181. //webrootHandler sending contents to client when request "/"
  182. // essentially to prove the webserver is still alive
  183. // echo query string to the client
  184. func webrootHandler(w http.ResponseWriter, r *http.Request) {
  185. fmt.Fprintf(w, "Hi there, I love %s!", r.URL.Path[1:])
  186. rq := r.URL.RawQuery
  187. m, _ := url.ParseQuery(rq)
  188. for index, element := range m {
  189. fmt.Fprintf(w, "\n%s => %s", index, element)
  190. }
  191. logRequestDebug(httputil.DumpRequest(r, true))
  192. }
  193. func logRequestDebug(data []byte, err error) {
  194. if err == nil {
  195. fmt.Printf("%s\n\n", string(data))
  196. } else {
  197. log.Fatalf("%s\n\n", err)
  198. }
  199. }
  200. //save uploaded 'file' into temporary location
  201. func uploadHandler(w http.ResponseWriter, r *http.Request) {
  202. r.ParseMultipartForm(32 << 20) //32MB memory
  203. file, handler, err := r.FormFile("file") //form-field 'file'
  204. if err != nil {
  205. fmt.Println(err)
  206. return
  207. }
  208. defer file.Close()
  209. fmt.Fprintf(w, "%v", handler.Header)
  210. f, err := os.OpenFile("/tmp/wechat_hitxy_"+handler.Filename, os.O_WRONLY|os.O_CREATE, 0666)
  211. if err != nil {
  212. fmt.Println(err)
  213. return
  214. }
  215. defer f.Close()
  216. io.Copy(f, file)
  217. }
  218. //when user requst an attachment from our server, we get the file from CRM server and reply it back
  219. //in this way, user has no 'direct-access' to the CRM server.
  220. func crmAttachmentHandler(w http.ResponseWriter, r *http.Request) {
  221. fileID := getCrmFileID(r.URL.Path)
  222. saveAs := CRMConfig.AttachmentCache + "crm_attach_" + fileID //add prefix for easy deleting
  223. if isFileExist(saveAs) {
  224. http.ServeFile(w, r, saveAs)
  225. return
  226. }
  227. if fileID == "" {
  228. log.Println("invalid fileID")
  229. response404Handler(w)
  230. return
  231. }
  232. log.Printf("download %s => %s", fileID, saveAs)
  233. crmDownloadAttachmentAs(fileID, saveAs)
  234. if !isFileExist(saveAs) {
  235. response404Handler(w)
  236. return
  237. }
  238. http.ServeFile(w, r, saveAs)
  239. }
  240. func getCrmFileID(urlPath string) string {
  241. return strings.TrimPrefix(urlPath, "/crmfiles/")
  242. }
  243. func response404Handler(w http.ResponseWriter) {
  244. w.WriteHeader(http.StatusNotFound)
  245. fmt.Fprintf(w, "not found")
  246. }