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.

268 Zeilen
8.7KB

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