Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

267 lines
6.7KB

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