-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathoauth_wechat.go
80 lines (68 loc) · 2.19 KB
/
oauth_wechat.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
package simpleoauth
import (
"httplib"
)
const wechat_getaccesstoken_url = "https://api.weixin.qq.com/sns/oauth2/access_token"
const wechat_getuserinfo_url = "https://api.weixin.qq.com/sns/userinfo"
var wechatOAuth = &WechatOAuth{}
type WechatOAuth struct {
appkey string
appsecret string
}
func (oauth *WechatOAuth) GetAccesstoken(code string) map[string]interface{}{
request:= httplib.Get(wechat_getaccesstoken_url)
request.Param("appid",oauth.appkey)
request.Param("secret",oauth.appsecret)
request.Param("code",code)
request.Param("grant_type","authorization_code")
var response map[string]interface{}
err := request.ToJson(&response)
if err != nil {
return nil
}
return response
}
func (oauth *WechatOAuth) GetUserinfo(accesstoken string, openid string) map[string]interface{}{
request:= httplib.Get(wechat_getuserinfo_url)
request.Param("access_token", accesstoken)
request.Param("openid", openid)
var response map[string]interface{}
err := request.ToJson(&response)
if err != nil {
return nil
}
return response
}
func (oauth *WechatOAuth) Authorize(code string) AuthorizeResult{
accesstokenResponse := oauth.GetAccesstoken(code)
if accesstokenResponse == nil{
return AuthorizeResult{false, nil}
}
_, ok := accesstokenResponse["errcode"] //获取accesstoken接口返回错误码
if ok {
return AuthorizeResult{false, nil}
}
openid := accesstokenResponse["openid"].(string)
accesstoken := accesstokenResponse["access_token"].(string)
getuserinfoResult := oauth.GetUserinfo(accesstoken, openid)
if getuserinfoResult == nil {
return AuthorizeResult{false, nil}
}
_, ok = getuserinfoResult["errcode"] //获取用户信息接口返回错误码
if ok {
return AuthorizeResult{false, nil}
}
return AuthorizeResult{true, map[string]interface{}{
"nickname":getuserinfoResult["nickname"].(string),
"openid":getuserinfoResult["openid"].(string),
"sex":getuserinfoResult["sex"].(float64),
"headimgurl":getuserinfoResult["headimgurl"].(string),
"unionid":getuserinfoResult["unionid"].(string)}}
}
func (oauth *WechatOAuth) InitOAuth(){
oauth.appkey = Wechatappkey
oauth.appsecret = Wechatappsecret
}
func init(){
ReisterPlatform("wechat", wechatOAuth)
}