-
Notifications
You must be signed in to change notification settings - Fork 1
/
wxlogin.go
299 lines (275 loc) · 7.62 KB
/
wxlogin.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
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
// Copyright (c) 2020.
// ALL Rights reserved.
// @Description mxlogin.go
// @Author moxiao
// @Date 2020/11/22 10:19
package mxlogin
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"github.com/linzengfa/mxtool/mxsha"
"io/ioutil"
"net/http"
"strings"
)
const (
ReturnErrCodeKey = "errcode"
ReturnErrMsgKey = "errmsg"
ReturnOpenIDKey = "openid"
ReturnSessionKey = "session_key"
)
var (
ErrLoginParamError = errors.New("wxLogin param error")
ErrEncryptedDataError = errors.New("encryptedData errors")
)
type WXLogin struct {
AppId string
AppSecret string
}
//微信用户信息
type UserInfo struct {
NickName string `json:"nickName"`
Gender byte `json:"gender"`
City string `json:"city"`
Province string `json:"province"`
Country string `json:"country"`
Language string `json:"language"`
AvatarUrl string `json:"avatarUrl"`
}
//加密数据
type EncryptedData struct {
OpenId string `json:"openId"`
NickName string `json:"nickName"`
Gender byte `json:"gender"`
City string `json:"city"`
Province string `json:"province"`
Country string `json:"country"`
AvatarUrl string `json:"avatarUrl"`
UnionId string `json:"unionId"`
}
type WXUserInfo struct {
Userinfo EncryptedData `json:"userinfo"`
SessionKey string `json:"skey"` //会话密钥
}
type WXAuthorization struct {
Openid string `json:"openid"` //用户唯一标识
SessionKey string `json:"session_key"` //会话密钥
Unionid string `json:"unionid"` //用户在开放平台的唯一标识符。
Errcode int `json:"errcode"` //错误码
ErrMsg string `json:"errmsg"` //错误信息
}
type WXPhoneNumber struct {
PhoneNumber string `json:"phoneNumber"` //用户绑定的手机号(国外手机号会有区号)
PurePhoneNumber string `json:"purePhoneNumber"` //没有区号的手机号
CountryCode string `json:"countryCode"` //区号
}
func New(appId, appSecret string) (wx *WXLogin, err error) {
if appId == "" || appSecret == "" {
err = ErrLoginParamError
return
}
return &WXLogin{appId, appSecret}, nil
}
//微信数据签名校验
func (wx *WXLogin) Check(rawData, signature, session_key string) bool {
var buffer bytes.Buffer
buffer.WriteString(rawData)
buffer.WriteString(session_key)
comresult := strings.Compare(mxsha.Sha1(buffer.Bytes()), signature)
return comresult == 0
}
//临时登录凭证code
func (wx *WXLogin) Code2Session(code string) (wxa *WXAuthorization, err error) {
wxa, err = codeExchangeSessionkey(wx.AppId, wx.AppSecret, code)
return
}
//微信登录
//加密数据( encryptedData )进行解密
func (wx *WXLogin) Login(encryptedData, iv, code string) (wxu *WXUserInfo, err error) {
wxa, err := codeExchangeSessionkey(wx.AppId, wx.AppSecret, code)
if wxa == nil || err != nil {
return
}
if len(encryptedData) != 0 && len(iv) != 0 {
wxDataCrypt := NewWXDataCrypt(wx.AppId, wxa.SessionKey)
wxData, tmperr := wxDataCrypt.decryptUserInfoData(encryptedData, iv)
err = tmperr
if wxData == nil || err != nil {
return
}
if len(wxData.AppID) == 0 || wxData.AppID != wx.AppId {
err = ErrEncryptedDataError
return
}
wxu = &WXUserInfo{
Userinfo: EncryptedData{
wxa.Openid,
wxData.NickName,
wxData.Gender,
wxData.City,
wxData.Province,
wxData.Country,
wxData.AvatarUrl,
wxData.UnionId,
},
SessionKey: wxa.SessionKey,
}
} else {
wxu = &WXUserInfo{
Userinfo: EncryptedData{
wxa.Openid,
"",
0,
"",
"",
"",
"",
wxa.Unionid,
},
SessionKey: wxa.SessionKey,
}
}
return
}
func (wx *WXLogin) GetUserInfo(accessToken, openid string) (wxu *EncryptedData, err error) {
url := fmt.Sprintf("https://api.weixin.qq.com/sns/userinfo?access_token=%s&openid=%s",
accessToken, openid)
resp, err := http.Get(url)
defer resp.Body.Close()
if err != nil {
return
}
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return
}
var resultMap map[string]interface{}
err = json.Unmarshal(body, &resultMap)
if err != nil {
return
}
if _, ok := resultMap[ReturnErrCodeKey]; ok {
errmsg := fmt.Sprintf("GetUserInfo errors,errcode=%v,errmsg=%v", resultMap[ReturnErrCodeKey], resultMap[ReturnErrMsgKey])
err = errors.New(errmsg)
return
}
wxu = new(EncryptedData)
if openid, ok := resultMap["openid"].(string); ok {
wxu.OpenId = openid
}
if nickName, ok := resultMap["nickname"].(string); ok {
wxu.NickName = nickName
}
if sex, ok := resultMap["sex"].(byte); ok {
wxu.Gender = sex
}
if province, ok := resultMap["province"].(string); ok {
wxu.Province = province
}
if city, ok := resultMap["city"].(string); ok {
wxu.City = city
}
if country, ok := resultMap["country"].(string); ok {
wxu.Country = country
}
if headimgurl, ok := resultMap["headimgurl"].(string); ok {
wxu.AvatarUrl = headimgurl
}
if unionid, ok := resultMap["unionid"].(string); ok {
wxu.UnionId = unionid
}
return
}
//code换取session_key
func codeExchangeSessionkey(appId string, appSecret string, code string) (wxa *WXAuthorization, err error) {
url := buildExchangeUrl(appId, appSecret, code)
resp, err := http.Get(url)
defer resp.Body.Close()
if err != nil {
return
}
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return
}
var resultMap map[string]interface{}
err = json.Unmarshal(body, &resultMap)
if err != nil {
return
}
//code换取session_key失败
if _, ok := resultMap[ReturnErrCodeKey]; ok {
errmsg := fmt.Sprintf("codeExchangeSessionkey errors,errcode=%v,errmsg=%v", resultMap[ReturnErrCodeKey], resultMap[ReturnErrMsgKey])
err = errors.New(errmsg)
return
}
if _, ok := resultMap[ReturnSessionKey]; !ok {
err = errors.New("codeExchangeSessionkey errors,session_key does not exist")
return
}
if _, ok := resultMap[ReturnOpenIDKey]; !ok {
err = errors.New("codeExchangeSessionkey errors,openid does not exist")
return
}
err = json.Unmarshal(body, &wxa)
return
}
//组织code换取session_key请求url
func buildExchangeUrl(appId string, appSecret string, code string) string {
return fmt.Sprintf("https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code", appId, appSecret, code)
}
//加密数据( encryptedData )进行解密
func (wx *WXLogin) DecryptPhoneNumber(encryptedData, iv, sessionKey string) (wpn *WXPhoneNumber, err error) {
if len(encryptedData) == 0 || len(iv) == 0 || len(sessionKey) == 0 {
err = ErrLoginParamError
return
}
fmt.Println("DecryptPhoneNumber sessionKey", sessionKey)
wxDataCrypt := NewWXDataCrypt(wx.AppId, sessionKey)
wxData, err := wxDataCrypt.decryptPhoneNumberData(encryptedData, iv)
if err != nil || wxData == nil {
fmt.Println("DecryptPhoneNumber error", err)
return
}
if len(wxData.PhoneNumber) == 0 {
err = ErrEncryptedDataError
return
}
fmt.Println("DecryptPhoneNumber success", wxData)
wpn = &WXPhoneNumber{
wxData.PhoneNumber,
wxData.PurePhoneNumber,
wxData.CountryCode,
}
return
}
//用户信息加密数据( encryptedData )进行解密
func (wx *WXLogin) DecryptUserInfo(encryptedData, iv, sessionKey string) (wxu *EncryptedData, err error) {
if len(encryptedData) == 0 || len(iv) == 0 || len(sessionKey) == 0 {
err = ErrLoginParamError
return
}
wxDataCrypt := NewWXDataCrypt(wx.AppId, sessionKey)
wxData, err := wxDataCrypt.decryptUserInfoData(encryptedData, iv)
if err != nil || wxData == nil {
fmt.Println("decryptUserInfoData error", err)
return
}
if len(wxData.AppID) == 0 || wxData.AppID != wx.AppId {
err = ErrEncryptedDataError
return
}
wxu = &EncryptedData{
wxData.OpenId,
wxData.NickName,
wxData.Gender,
wxData.City,
wxData.Province,
wxData.Country,
wxData.AvatarUrl,
wxData.UnionId,
}
return
}