server.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. package server
  2. import (
  3. "encoding/xml"
  4. "fmt"
  5. "io/ioutil"
  6. "github.com/silenceper/wechat/context"
  7. "github.com/silenceper/wechat/message"
  8. "github.com/silenceper/wechat/util"
  9. )
  10. //Server struct
  11. type Server struct {
  12. *context.Context
  13. isSafeMode bool
  14. rawXMLMsg string
  15. }
  16. //NewServer init
  17. func NewServer(context *context.Context) *Server {
  18. srv := new(Server)
  19. srv.Context = context
  20. return srv
  21. }
  22. //Serve 处理微信的请求消息
  23. func (srv *Server) Serve() error {
  24. if !srv.Validate() {
  25. return fmt.Errorf("请求校验失败")
  26. }
  27. echostr, exists := srv.GetQuery("echostr")
  28. if exists {
  29. return srv.String(echostr)
  30. }
  31. srv.handleRequest()
  32. return nil
  33. }
  34. //Validate 校验请求是否合法
  35. func (srv *Server) Validate() bool {
  36. timestamp := srv.Query("timestamp")
  37. nonce := srv.Query("nonce")
  38. signature := srv.Query("signature")
  39. return signature == util.Signature(srv.Token, timestamp, nonce)
  40. }
  41. //HandleRequest 处理微信的请求
  42. func (srv *Server) handleRequest() {
  43. srv.isSafeMode = false
  44. encryptType := srv.Query("encrypt_type")
  45. if encryptType == "aes" {
  46. srv.isSafeMode = true
  47. }
  48. _, err := srv.getMessage()
  49. if err != nil {
  50. fmt.Printf("%v", err)
  51. }
  52. }
  53. func (srv *Server) getMessage() (interface{}, error) {
  54. var rawXMLMsgBytes []byte
  55. var err error
  56. if srv.isSafeMode {
  57. var encryptedXMLMsg message.EncryptedXMLMsg
  58. if err := xml.NewDecoder(srv.Request.Body).Decode(&encryptedXMLMsg); err != nil {
  59. return nil, fmt.Errorf("从body中解析xml失败,err=%v", err)
  60. }
  61. //验证消息签名
  62. timestamp := srv.Query("timestamp")
  63. nonce := srv.Query("nonce")
  64. msgSignature := srv.Query("msg_signature")
  65. msgSignatureCreate := util.Signature(srv.Token, timestamp, nonce, encryptedXMLMsg.EncryptedMsg)
  66. if msgSignature != msgSignatureCreate {
  67. return nil, fmt.Errorf("消息不合法,验证签名失败")
  68. }
  69. //解密
  70. rawXMLMsgBytes, err = util.DecryptMsg(srv.AppID, encryptedXMLMsg.EncryptedMsg, srv.EncodingAESKey)
  71. if err != nil {
  72. return nil, fmt.Errorf("消息解密失败,err=%v", err)
  73. }
  74. } else {
  75. rawXMLMsgBytes, err = ioutil.ReadAll(srv.Request.Body)
  76. if err != nil {
  77. return nil, fmt.Errorf("从body中解析xml失败,err=%v", err)
  78. }
  79. }
  80. srv.rawXMLMsg = string(rawXMLMsgBytes)
  81. fmt.Println(srv.rawXMLMsg)
  82. return nil, nil
  83. }