Du kannst nicht mehr als 25 Themen auswählen Themen müssen entweder mit einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

270 Zeilen
6.8KB

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