-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathoauth_weibo.go
92 lines (81 loc) · 2.44 KB
/
oauth_weibo.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
package simpleoauth
import (
"fmt"
"httplib"
)
const weibo_getaccesstoken_url = "https://api.weibo.com/oauth2/access_token"
const weibo_getuserinfo_url = "https://api.weibo.com/2/users/show.json"
var weiboOAuth = &WeiboOAuth{}
type WeiboOAuth struct {
appkey string
appsecret string
redirect_url string
}
func (oauth *WeiboOAuth) GetAccesstoken(code string) map[string]interface{}{
request:= httplib.Post(weibo_getaccesstoken_url)
request.Param("client_id", oauth.appkey)
request.Param("client_secret", oauth.appsecret)
request.Param("grant_type", "authorization_code")
request.Param("code", code)
request.Param("redirect_uri", oauth.redirect_url)
var response map[string]interface{}
err := request.ToJson(&response)
if err != nil {
return nil
}
return response
}
func (oauth *WeiboOAuth) GetUserinfo(accesstoken string, openid string) map[string]interface{}{
request:= httplib.Get(weibo_getuserinfo_url)
request.Param("access_token", accesstoken)
request.Param("uid", openid)
var response map[string]interface{}
err := request.ToJson(&response)
if err != nil {
return nil
}
return response
}
func (oauth *WeiboOAuth) Authorize(code string) AuthorizeResult{
accesstokenResponse := oauth.GetAccesstoken(code)
if accesstokenResponse == nil{
return AuthorizeResult{false, nil}
}
_, ok := accesstokenResponse["error_code"] //获取accesstoken接口返回错误码
if ok {
return AuthorizeResult{false, nil}
}
openid := accesstokenResponse["uid"].(string)
accesstoken := accesstokenResponse["access_token"].(string)
getuserinfoResult := oauth.GetUserinfo(accesstoken, openid)
fmt.Println(getuserinfoResult)
if getuserinfoResult == nil {
return AuthorizeResult{false, nil}
}
_, ok = getuserinfoResult["error_code"] //获取用户信息接口返回错误码
if ok {
return AuthorizeResult{false, nil}
}
var sex int
if getuserinfoResult["gender"].(string) == "m"{
sex = 1
}else if getuserinfoResult["gender"].(string) == "f"{
sex = 2
}else if getuserinfoResult["gender"].(string) == "n"{
sex = 0
}
return AuthorizeResult{true, map[string]interface{}{
"nickname":getuserinfoResult["screen_name"].(string),
"openid":openid,
"sex":sex,
"headimgurl":getuserinfoResult["profile_image_url"].(string),
"unionid":""}}
}
func (oauth *WeiboOAuth) InitOAuth(){
oauth.appkey = Weiboappkey
oauth.appsecret = Weiboappsecret
oauth.redirect_url = WeiboRedirectUrl
}
func init(){
ReisterPlatform("weibo", weiboOAuth)
}