package wechat import ( "encoding/json" "fmt" ) var Wechat = &wechat{} type wechat struct { appid string secret string } type AuthAccessToken struct { AccessToken string `json:"access_token"` ExpiresIn int64 `json:"expires_in"` Openid string `json:"openid"` RefreshToken string `json:"refresh_token"` Scope string `json:"scope"` } // InitWechat @Title 初始化 func InitWechat(appid, secret string) *wechat { Wechat.appid = appid Wechat.secret = secret return Wechat } // GetOpenId @Title 获取openId func (w *wechat) GetOpenId(code string) string { accessToken, err := w.GetAccessToken(code) if err != nil { return "" } return accessToken.Openid } // GetAccessToken @Title 获取微信验证结构体 func (w *wechat) GetAccessToken(code string) (*AuthAccessToken, error) { res, err := request(get, fmt.Sprintf("https://api.weixin.qq.com/sns/oauth2/access_token?appid=%v&secret=%v&code=%v&grant_type=authorization_code", w.appid, w.secret, code), "") if err != nil { return nil, err } result := AuthAccessToken{} if err := json.Unmarshal(res, &result); err != nil { return nil, err } return &result, nil } type UserInfo struct { City string `json:"city"` Country string `json:"country"` Headimgurl string `json:"headimgurl"` Nickname string `json:"nickname"` Openid string `json:"openid"` Privilege []string `json:"privilege"` Province string `json:"province"` Sex uint `json:"sex"` Unionid string `json:"unionid"` } // GetUserInfo @Title 获取微信登录会员信息 func (w *wechat) GetUserInfo(accessToken, openId string) (*UserInfo, error) { res, err := request(get, fmt.Sprintf("https://api.weixin.qq.com/sns/userinfo?access_token=%s&openid=%s&lang=zh_CN", accessToken, openId), "") if err != nil { return nil, err } result := UserInfo{} if err := json.Unmarshal(res, &result); err != nil { return nil, err } return &result, nil }