Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

261 line
6.3KB

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