您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

205 行
6.9KB

  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. req := buildReqWechatPostTxtMsg()
  38. rr, _ := getHTTPResponse(req, apiV1Main)
  39. m := ReadEncryptedMsg(rr.Body.String())
  40. xml := Decode(m.Encrypt)
  41. h := ReadCommonHeader(xml)
  42. expected := "oUN420bxqFqlx0ZQHciUOesZO3PE"
  43. if h.ToUserName != expected {
  44. t.Errorf("expect ToUserName: %v \r\nbut got %v",
  45. expected, h.ToUserName)
  46. }
  47. }
  48. func TestGetAccesstoken(t *testing.T) {
  49. req := buildReqGetAccessToken()
  50. rr, _ := getHTTPResponse(req, supplyAccessToken)
  51. errorResponse := "errortoken"
  52. m := rr.Body.String()
  53. expected, _ := GetAccessToken()
  54. log.Printf("TestGetAccesstoken got: [%s] ", m)
  55. AssertEqual(t, m != errorResponse, true, "Signature check failed, error response")
  56. AssertEqual(t, m, expected, "token incorrect")
  57. }
  58. func getHTTPResponse(req *http.Request, handler http.HandlerFunc) (rr *httptest.ResponseRecorder, err error) {
  59. // Our handlers satisfy http.Handler, so we can call their ServeHTTP method
  60. // directly and pass in our Request and ResponseRecorder.
  61. rr = httptest.NewRecorder()
  62. handler.ServeHTTP(rr, req)
  63. // Check the status code is what we expect.
  64. if status := rr.Code; status != http.StatusOK {
  65. err = fmt.Errorf("wrong HTTP status code: got %v want %v",
  66. status, http.StatusOK)
  67. }
  68. return
  69. }
  70. // POST /api?signature=f06bb28c1d3847815d498fc0a343b11b4d03e095&timestamp=1493212928&nonce=1461107899&openid=oUN420bxqFqlx0ZQHciUOesZO3PE&encrypt_type=aes&msg_signature=61a50d4656b13a7bbeecf53a5a85fbf37835762f HTTP/1.1
  71. // Host: wechat.hitxy.org.au
  72. // Accept: */*
  73. // Cache-Control: no-cache
  74. // Connection: Keep-Alive
  75. // Content-Length: 534
  76. // Content-Type: text/xml
  77. // Pragma: no-cache
  78. // User-Agent: Mozilla/4.0
  79. // X-Forwarded-For: 103.7.30.105
  80. // X-Forwarded-Host: wechat.hitxy.org.au
  81. // X-Forwarded-Server: wechat.hitxy.org.au
  82. // <xml>
  83. // <ToUserName><![CDATA[gh_f09231355c68]]></ToUserName>
  84. // <Encrypt><![CDATA[HKILXQjAOV4Zi5Zb8gQ8zt6EPA6cBCRYSq90PZuyMqZSGhtjMESSgveIps74rS2+Q5aZPJhytXIkmuE+dxMTkV06qGNSYuSurXsoJE7bNfrE/Nmxq6GwKH1rwHXk3c50NoHW/h6/jCXu8x0oY1oW/ea1tLRGY4xeoQ9voCuvVYRFSyuU7Zz2QjlbP+AG8mCnGBxUwqrthqWFe7wDEkYa38EoD9DrjrQKRc4Hn2ZIHYN569cn5PDvsif+5FUX4p+3gEkgk/HVxicC7wT9wYzNSk9HH7bET3V7hnhJ+PJa+ZEH7HAPzry61UZ1gghf4dJAGVE9D8R4/0M6DpKGCQBGXmlI/Q3NjN0jx9NAqffPRxsoW4BF7mLV8RmfDbJJEa0W5i0buwyluMyVcrF5KT9Bd2DBvsULCXfuwwp01DmJdfc=]]></Encrypt>
  85. // </xml>
  86. // decrypt as: <xml><ToUserName><![CDATA[gh_f09231355c68]]></ToUserName>
  87. // <FromUserName><![CDATA[oUN420bxqFqlx0ZQHciUOesZO3PE]]></FromUserName>
  88. // <CreateTime>1493212928</CreateTime>
  89. // <MsgType><![CDATA[text]]></MsgType>
  90. // <Content><![CDATA[test]]></Content>
  91. // <MsgId>6413300692136991026</MsgId>
  92. // </xml>
  93. func buildReqWechatPostTxtMsg() *http.Request {
  94. xml := `<xml>
  95. <ToUserName><![CDATA[gh_f09231355c68]]></ToUserName>
  96. <Encrypt><![CDATA[HKILXQjAOV4Zi5Zb8gQ8zt6EPA6cBCRYSq90PZuyMqZSGhtjMESSgveIps74rS2+Q5aZPJhytXIkmuE+dxMTkV06qGNSYuSurXsoJE7bNfrE/Nmxq6GwKH1rwHXk3c50NoHW/h6/jCXu8x0oY1oW/ea1tLRGY4xeoQ9voCuvVYRFSyuU7Zz2QjlbP+AG8mCnGBxUwqrthqWFe7wDEkYa38EoD9DrjrQKRc4Hn2ZIHYN569cn5PDvsif+5FUX4p+3gEkgk/HVxicC7wT9wYzNSk9HH7bET3V7hnhJ+PJa+ZEH7HAPzry61UZ1gghf4dJAGVE9D8R4/0M6DpKGCQBGXmlI/Q3NjN0jx9NAqffPRxsoW4BF7mLV8RmfDbJJEa0W5i0buwyluMyVcrF5KT9Bd2DBvsULCXfuwwp01DmJdfc=]]></Encrypt>
  97. </xml>`
  98. b := bytes.NewBufferString(xml)
  99. req, _ := http.NewRequest("POST", "/api?openid=oUN420bxqFqlx0ZQHciUOesZO3PE&encrypt_type=aes&msg_signature=61a50d4656b13a7bbeecf53a5a85fbf37835762f", b)
  100. buildReqCommonSignature(req, APIConfig.Token)
  101. buildReqCommonHeader(req)
  102. return req
  103. }
  104. func buildReqWechatWebRoot() *http.Request {
  105. req, _ := http.NewRequest("GET", "/dummydir", nil)
  106. buildReqCommonHeader(req)
  107. q := req.URL.Query()
  108. //q.Add("signature", "e39de9f2e28079c01ebb4b803dfc3442b819545c")
  109. q.Add("echostr", "913461463450840893")
  110. req.URL.RawQuery = q.Encode()
  111. return req
  112. }
  113. func buildReqWechatAPISetup(echostr string) *http.Request {
  114. // Create a request to pass to our handler.
  115. //We don't have any query body for now, so we'll
  116. // pass 'nil' as the third parameter.
  117. req, err := http.NewRequest("GET", "/apii", nil)
  118. if err != nil {
  119. log.Fatal(err)
  120. }
  121. buildReqCommonSignature(req, APIConfig.Token)
  122. q := req.URL.Query()
  123. q.Add("echostr", echostr)
  124. req.URL.RawQuery = q.Encode()
  125. buildReqCommonHeader(req)
  126. return req
  127. }
  128. func buildReqGetAccessToken() *http.Request {
  129. req, err := http.NewRequest("GET", "/iapi/getAccessToken", nil)
  130. if err != nil {
  131. log.Fatal(err)
  132. }
  133. buildReqCommonSignature(req, IntraAPIConfig.CRMSecrete)
  134. buildReqCommonHeader(req)
  135. return req
  136. }
  137. func buildSignature(token string) (signature, timestamp, nonce string) {
  138. timestamp = fmt.Sprintf("%d", int32(time.Now().Unix()))
  139. nonce = "1461107899" //a randome string cut from previous wechat request
  140. signature = calculateSignature(timestamp, nonce, token)
  141. return
  142. }
  143. func buildReqCommonSignature(req *http.Request, token string) {
  144. signature, timestamp, nonce := buildSignature(token)
  145. q := req.URL.Query()
  146. q.Add("signature", signature)
  147. q.Add("timestamp", timestamp)
  148. q.Add("nonce", nonce)
  149. req.URL.RawQuery = q.Encode()
  150. }
  151. func buildReqCommonHeader(r *http.Request) {
  152. //
  153. // example request
  154. //
  155. // GET /api?signature=e39de9f2e28079c01ebb4b803dfc3442b819545c&echostr=913461463450840893&timestamp=1492970761&nonce=1850971833 HTTP/1.1
  156. // Host: wechat.hitxy.org.au
  157. // Accept: */*
  158. // Cache-Control: no-cache
  159. // Connection: Keep-Alive
  160. // Pragma: no-cache
  161. // User-Agent: Mozilla/4.0
  162. // X-Forwarded-For: 103.7.30.107
  163. // X-Forwarded-Host: wechat.hitxy.org.au
  164. // X-Forwarded-Server: wechat.hitxy.org.au
  165. r.Header.Set("Host", "wechat.hitxy.org.au")
  166. r.Header.Set("Accept", "*/*")
  167. r.Header.Set("Cache-Control", "no-cache")
  168. r.Header.Set("Connection", "Keep-Alive")
  169. r.Header.Set("Pragma", "no-cache")
  170. r.Header.Set("User-Agent", "Patrick testcase")
  171. r.Header.Set("X-Forwarded-For", "103.7.30.107")
  172. r.Header.Set("X-Forwarded-Host", "wechat.hitxy.org.au")
  173. r.Header.Set("X-Forwarded-Server", "wechat.hitxy.org.au")
  174. }