Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

213 lines
7.1KB

  1. package main
  2. import (
  3. "bytes"
  4. "fmt"
  5. "log"
  6. "net/http"
  7. "net/http/httptest"
  8. "testing"
  9. "time"
  10. )
  11. //when we setup wechate parameters,we chat will verify us
  12. func TestInitialSetup(t *testing.T) {
  13. expected := `913461463450840893`
  14. req := buildReqWechatAPISetup(expected)
  15. rr, _ := getHTTPResponse(req, answerInitialAuth)
  16. // Check the response body is what we expect.
  17. if rr.Body.String() != expected {
  18. t.Errorf("handler returned unexpected body: got %v want %v",
  19. rr.Body.String(), expected)
  20. }
  21. }
  22. func TestWebRootHandler(t *testing.T) {
  23. req := buildReqWechatWebRoot()
  24. rr, _ := getHTTPResponse(req, webrootHandler)
  25. // Check the response body is what we expect.
  26. expected := `Hi there, I love dummydir!
  27. echostr => [913461463450840893]`
  28. if rr.Body.String() != expected {
  29. t.Errorf("handler returned unexpected body: got %v want %v",
  30. rr.Body.String(), expected)
  31. }
  32. }
  33. //Send encrypted text Message ("test"")to server and get encrypted feedback
  34. //we only check decrypted ToUserName should be the one we sent out.
  35. //as decrypt itself is already a good proof of its working state.
  36. func TestPostTxtMsg(t *testing.T) {
  37. //TODO: as session manager is not auto started in test environment
  38. //it will time out
  39. //uncomment following and only run this particular TestCase it should pass.
  40. // startSessionManager(2048)
  41. return //skip this test case
  42. req := buildReqWechatPostTxtMsg()
  43. rr, _ := getHTTPResponse(req, apiV1Main)
  44. m := ReadEncryptedMsg(rr.Body.String())
  45. xml := Decode(m.Encrypt)
  46. h := ReadCommonHeader(xml)
  47. expected := "oUN420bxqFqlx0ZQHciUOesZO3PE"
  48. if h.ToUserName != expected {
  49. t.Errorf("expect ToUserName: %v \r\nbut got %v",
  50. expected, h.ToUserName)
  51. }
  52. }
  53. func TestGetAccesstoken(t *testing.T) {
  54. req := buildReqGetAccessToken()
  55. rr, _ := getHTTPResponse(req, supplyAccessToken)
  56. errorResponse := "errortoken"
  57. m := rr.Body.String()
  58. expected, _ := GetAccessToken()
  59. log.Printf("TestGetAccesstoken got: [%s] ", m)
  60. AssertEqual(t, m != errorResponse, true, "Signature check failed, error response")
  61. AssertEqual(t, m, expected, "token incorrect")
  62. }
  63. func getHTTPResponse(req *http.Request, handler http.HandlerFunc) (rr *httptest.ResponseRecorder, err error) {
  64. // Our handlers satisfy http.Handler, so we can call their ServeHTTP method
  65. // directly and pass in our Request and ResponseRecorder.
  66. rr = httptest.NewRecorder()
  67. handler.ServeHTTP(rr, req)
  68. // Check the status code is what we expect.
  69. if status := rr.Code; status != http.StatusOK {
  70. err = fmt.Errorf("wrong HTTP status code: got %v want %v",
  71. status, http.StatusOK)
  72. }
  73. return
  74. }
  75. // POST /api?signature=f06bb28c1d3847815d498fc0a343b11b4d03e095&timestamp=1493212928&nonce=1461107899&openid=oUN420bxqFqlx0ZQHciUOesZO3PE&encrypt_type=aes&msg_signature=61a50d4656b13a7bbeecf53a5a85fbf37835762f HTTP/1.1
  76. // Host: wechat.hitxy.org.au
  77. // Accept: */*
  78. // Cache-Control: no-cache
  79. // Connection: Keep-Alive
  80. // Content-Length: 534
  81. // Content-Type: text/xml
  82. // Pragma: no-cache
  83. // User-Agent: Mozilla/4.0
  84. // X-Forwarded-For: 103.7.30.105
  85. // X-Forwarded-Host: wechat.hitxy.org.au
  86. // X-Forwarded-Server: wechat.hitxy.org.au
  87. // <xml>
  88. // <ToUserName><![CDATA[gh_f09231355c68]]></ToUserName>
  89. // <Encrypt><![CDATA[HKILXQjAOV4Zi5Zb8gQ8zt6EPA6cBCRYSq90PZuyMqZSGhtjMESSgveIps74rS2+Q5aZPJhytXIkmuE+dxMTkV06qGNSYuSurXsoJE7bNfrE/Nmxq6GwKH1rwHXk3c50NoHW/h6/jCXu8x0oY1oW/ea1tLRGY4xeoQ9voCuvVYRFSyuU7Zz2QjlbP+AG8mCnGBxUwqrthqWFe7wDEkYa38EoD9DrjrQKRc4Hn2ZIHYN569cn5PDvsif+5FUX4p+3gEkgk/HVxicC7wT9wYzNSk9HH7bET3V7hnhJ+PJa+ZEH7HAPzry61UZ1gghf4dJAGVE9D8R4/0M6DpKGCQBGXmlI/Q3NjN0jx9NAqffPRxsoW4BF7mLV8RmfDbJJEa0W5i0buwyluMyVcrF5KT9Bd2DBvsULCXfuwwp01DmJdfc=]]></Encrypt>
  90. // </xml>
  91. // decrypt as: <xml><ToUserName><![CDATA[gh_f09231355c68]]></ToUserName>
  92. // <FromUserName><![CDATA[oUN420bxqFqlx0ZQHciUOesZO3PE]]></FromUserName>
  93. // <CreateTime>1493212928</CreateTime>
  94. // <MsgType><![CDATA[text]]></MsgType>
  95. // <Content><![CDATA[test]]></Content>
  96. // <MsgId>6413300692136991026</MsgId>
  97. // </xml>
  98. func buildReqWechatPostTxtMsg() *http.Request {
  99. xml := `<xml>
  100. <ToUserName><![CDATA[gh_f09231355c68]]></ToUserName>
  101. <Encrypt><![CDATA[HKILXQjAOV4Zi5Zb8gQ8zt6EPA6cBCRYSq90PZuyMqZSGhtjMESSgveIps74rS2+Q5aZPJhytXIkmuE+dxMTkV06qGNSYuSurXsoJE7bNfrE/Nmxq6GwKH1rwHXk3c50NoHW/h6/jCXu8x0oY1oW/ea1tLRGY4xeoQ9voCuvVYRFSyuU7Zz2QjlbP+AG8mCnGBxUwqrthqWFe7wDEkYa38EoD9DrjrQKRc4Hn2ZIHYN569cn5PDvsif+5FUX4p+3gEkgk/HVxicC7wT9wYzNSk9HH7bET3V7hnhJ+PJa+ZEH7HAPzry61UZ1gghf4dJAGVE9D8R4/0M6DpKGCQBGXmlI/Q3NjN0jx9NAqffPRxsoW4BF7mLV8RmfDbJJEa0W5i0buwyluMyVcrF5KT9Bd2DBvsULCXfuwwp01DmJdfc=]]></Encrypt>
  102. </xml>`
  103. b := bytes.NewBufferString(xml)
  104. req, _ := http.NewRequest("POST", "/api?openid=oUN420bxqFqlx0ZQHciUOesZO3PE&encrypt_type=aes&msg_signature=61a50d4656b13a7bbeecf53a5a85fbf37835762f", b)
  105. buildReqCommonSignature(req, APIConfig.Token)
  106. buildReqCommonHeader(req)
  107. return req
  108. }
  109. func buildReqWechatWebRoot() *http.Request {
  110. req, _ := http.NewRequest("GET", "/dummydir", nil)
  111. buildReqCommonHeader(req)
  112. q := req.URL.Query()
  113. //q.Add("signature", "e39de9f2e28079c01ebb4b803dfc3442b819545c")
  114. q.Add("echostr", "913461463450840893")
  115. req.URL.RawQuery = q.Encode()
  116. return req
  117. }
  118. func buildReqWechatAPISetup(echostr string) *http.Request {
  119. // Create a request to pass to our handler.
  120. //We don't have any query body for now, so we'll
  121. // pass 'nil' as the third parameter.
  122. req, err := http.NewRequest("GET", "/apii", nil)
  123. if err != nil {
  124. log.Fatal(err)
  125. }
  126. buildReqCommonSignature(req, APIConfig.Token)
  127. q := req.URL.Query()
  128. q.Add("echostr", echostr)
  129. req.URL.RawQuery = q.Encode()
  130. buildReqCommonHeader(req)
  131. return req
  132. }
  133. func buildReqGetAccessToken() *http.Request {
  134. req, err := http.NewRequest("GET", "/iapi/getAccessToken", nil)
  135. if err != nil {
  136. log.Fatal(err)
  137. }
  138. buildReqCommonSignature(req, IntraAPIConfig.CRMSecrete)
  139. buildReqCommonHeader(req)
  140. return req
  141. }
  142. func buildSignature(token string) (signature, timestamp, nonce string) {
  143. timestamp = fmt.Sprintf("%d", int32(time.Now().Unix()))
  144. nonce = "1461107899" //a randome string cut from previous wechat request
  145. signature = calculateSignature(timestamp, nonce, token)
  146. return
  147. }
  148. func buildReqCommonSignature(req *http.Request, token string) {
  149. signature, timestamp, nonce := buildSignature(token)
  150. q := req.URL.Query()
  151. q.Add("signature", signature)
  152. q.Add("timestamp", timestamp)
  153. q.Add("nonce", nonce)
  154. req.URL.RawQuery = q.Encode()
  155. }
  156. func buildReqCommonHeader(r *http.Request) {
  157. //
  158. // example request
  159. //
  160. // GET /api?signature=e39de9f2e28079c01ebb4b803dfc3442b819545c&echostr=913461463450840893&timestamp=1492970761&nonce=1850971833 HTTP/1.1
  161. // Host: wechat.hitxy.org.au
  162. // Accept: */*
  163. // Cache-Control: no-cache
  164. // Connection: Keep-Alive
  165. // Pragma: no-cache
  166. // User-Agent: Mozilla/4.0
  167. // X-Forwarded-For: 103.7.30.107
  168. // X-Forwarded-Host: wechat.hitxy.org.au
  169. // X-Forwarded-Server: wechat.hitxy.org.au
  170. r.Header.Set("Host", "wechat.hitxy.org.au")
  171. r.Header.Set("Accept", "*/*")
  172. r.Header.Set("Cache-Control", "no-cache")
  173. r.Header.Set("Connection", "Keep-Alive")
  174. r.Header.Set("Pragma", "no-cache")
  175. r.Header.Set("User-Agent", "Patrick testcase")
  176. r.Header.Set("X-Forwarded-For", "103.7.30.107")
  177. r.Header.Set("X-Forwarded-Host", "wechat.hitxy.org.au")
  178. r.Header.Set("X-Forwarded-Server", "wechat.hitxy.org.au")
  179. }