forked from magicshui/wechat-1
/
client.debug.go
206 lines (172 loc) · 5.38 KB
/
client.debug.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
// @description wechat 是腾讯微信公众平台 api 的 golang 语言封装
// @link https://github.com/chanxuehong/wechat for the canonical source repository
// @license https://github.com/chanxuehong/wechat/blob/master/LICENSE
// @authors chanxuehong(chanxuehong@gmail.com)
// +build wechatdebug
package mp
import (
"bytes"
"fmt"
"io/ioutil"
"net/http"
"net/url"
"reflect"
"github.com/chanxuehong/wechat/json"
)
type Client struct {
AccessTokenServer
HttpClient *http.Client
}
// 创建一个新的 Client.
// 如果 clt == nil 则默认用 http.DefaultClient
func NewClient(srv AccessTokenServer, clt *http.Client) *Client {
if srv == nil {
panic("nil AccessTokenServer")
}
if clt == nil {
clt = http.DefaultClient
}
return &Client{
AccessTokenServer: srv,
HttpClient: clt,
}
}
// 用 encoding/json 把 request marshal 为 JSON, 放入 http 请求的 body 中,
// POST 到微信服务器, 然后将微信服务器返回的 JSON 用 encoding/json 解析到 response.
//
// NOTE:
// 1. 一般不用调用这个方法, 请直接调用高层次的封装方法;
// 2. 最终的 URL == incompleteURL + access_token;
// 3. response 格式有要求, 要么是 *Error, 要么是下面结构体的指针(注意 Error 必须是第一个 Field):
// struct {
// Error
// ...
// }
func (clt *Client) PostJSON(incompleteURL string, request interface{}, response interface{}) (err error) {
buf := textBufferPool.Get().(*bytes.Buffer)
buf.Reset()
defer textBufferPool.Put(buf)
if err = json.NewEncoder(buf).Encode(request); err != nil {
return
}
requestBytes := buf.Bytes()
token, err := clt.Token()
if err != nil {
return
}
hasRetried := false
RETRY:
finalURL := incompleteURL + url.QueryEscape(token)
LogInfoln("[WECHAT_DEBUG] request url:", finalURL)
LogInfoln("[WECHAT_DEBUG] request json:", string(requestBytes))
httpResp, err := clt.HttpClient.Post(finalURL, "application/json; charset=utf-8", bytes.NewReader(requestBytes))
if err != nil {
return
}
defer httpResp.Body.Close()
if httpResp.StatusCode != http.StatusOK {
return fmt.Errorf("http.Status: %s", httpResp.Status)
}
respBody, err := ioutil.ReadAll(httpResp.Body)
if err != nil {
return
}
LogInfoln("[WECHAT_DEBUG] response json:", string(respBody))
if err = json.Unmarshal(respBody, response); err != nil {
return
}
var ErrorStructValue reflect.Value // Error
// 下面的代码对 response 有特定要求, 见此函数 NOTE
responseStructValue := reflect.ValueOf(response).Elem()
if v := responseStructValue.Field(0); v.Kind() == reflect.Struct {
ErrorStructValue = v
} else {
ErrorStructValue = responseStructValue
}
switch ErrCode := ErrorStructValue.Field(0).Int(); ErrCode {
case ErrCodeOK:
return
case ErrCodeInvalidCredential, ErrCodeAccessTokenExpired:
ErrMsg := ErrorStructValue.Field(1).String()
LogInfoln("[WECHAT_RETRY] err_code:", ErrCode, ", err_msg:", ErrMsg)
LogInfoln("[WECHAT_RETRY] current token:", token)
if !hasRetried {
hasRetried = true
if token, err = clt.TokenRefresh(); err != nil {
return
}
LogInfoln("[WECHAT_RETRY] new token:", token)
responseStructValue.Set(reflect.New(responseStructValue.Type()).Elem())
goto RETRY
}
LogInfoln("[WECHAT_RETRY] fallthrough, current token:", token)
fallthrough
default:
return
}
}
// GET 微信资源, 然后将微信服务器返回的 JSON 用 encoding/json 解析到 response.
//
// NOTE:
// 1. 一般不用调用这个方法, 请直接调用高层次的封装方法;
// 2. 最终的 URL == incompleteURL + access_token;
// 3. response 格式有要求, 要么是 *Error, 要么是下面结构体的指针(注意 Error 必须是第一个 Field):
// struct {
// Error
// ...
// }
func (clt *Client) GetJSON(incompleteURL string, response interface{}) (err error) {
token, err := clt.Token()
if err != nil {
return
}
hasRetried := false
RETRY:
finalURL := incompleteURL + url.QueryEscape(token)
httpResp, err := clt.HttpClient.Get(finalURL)
if err != nil {
return
}
defer httpResp.Body.Close()
if httpResp.StatusCode != http.StatusOK {
return fmt.Errorf("http.Status: %s", httpResp.Status)
}
respBody, err := ioutil.ReadAll(httpResp.Body)
if err != nil {
return
}
LogInfoln("[WECHAT_DEBUG] request url:", finalURL)
LogInfoln("[WECHAT_DEBUG] response json:", string(respBody))
if err = json.Unmarshal(respBody, response); err != nil {
return
}
var ErrorStructValue reflect.Value // Error
// 下面的代码对 response 有特定要求, 见此函数 NOTE
responseStructValue := reflect.ValueOf(response).Elem()
if v := responseStructValue.Field(0); v.Kind() == reflect.Struct {
ErrorStructValue = v
} else {
ErrorStructValue = responseStructValue
}
switch ErrCode := ErrorStructValue.Field(0).Int(); ErrCode {
case ErrCodeOK:
return
case ErrCodeInvalidCredential, ErrCodeAccessTokenExpired:
ErrMsg := ErrorStructValue.Field(1).String()
LogInfoln("[WECHAT_RETRY] err_code:", ErrCode, ", err_msg:", ErrMsg)
LogInfoln("[WECHAT_RETRY] current token:", token)
if !hasRetried {
hasRetried = true
if token, err = clt.TokenRefresh(); err != nil {
return
}
LogInfoln("[WECHAT_RETRY] new token:", token)
responseStructValue.Set(reflect.New(responseStructValue.Type()).Elem())
goto RETRY
}
LogInfoln("[WECHAT_RETRY] fallthrough, current token:", token)
fallthrough
default:
return
}
}