package weChat import ( "encoding/json" "errors" "io" "net/http" ) // GetUserInfoResponse 网页授权拉取用户信息返回值 type GetUserInfoResponse struct { OpenId string `json:"openid" form:"openid" label:"openid"` Nickname string `json:"nickname" form:"nickname" label:"用户昵称"` Sex int `json:"sex" form:"sex" label:"性别"` // 用户的性别,值为1时是男性,值为2时是女性,值为0时是未知 Province string `json:"province" form:"province" label:"省份"` City string `json:"city" form:"city" label:"城市"` Country string `json:"country" form:"country" label:"国家"` HeadImgUrl string `json:"headimgurl" form:"headimgurl" label:"头像"` UnionId string `json:"unionid" form:"unionid" label:"unionid"` Errcode *int `json:"errcode" form:"errcode" label:"errcode"` Errmsg string `json:"errmsg" form:"errmsg" label:"errmsg"` } // GetUserInfo 网页授权拉取用户信息 func GetUserInfo(accessToken, openId string) (r *GetUserInfoResponse, err error) { if accessToken == "" { return nil, errors.New("授权失败") } if openId == "" { return nil, errors.New("授权失败") } // 拼接请求数据 requestUrl := "https://api.weixin.qq.com/sns/userinfo?" + "access_token=" + accessToken + "&openid=" + openId + "&lang=zh_CN" // 发送GET请求 resp, err := http.Get(requestUrl) if err != nil { return nil, err } defer func(Body io.ReadCloser) { _ = Body.Close() }(resp.Body) if resp.StatusCode != 200 { return nil, errors.New("请求失败") } // 读取响应体 respBody, err := io.ReadAll(resp.Body) if err != nil { return nil, err } var response GetUserInfoResponse err = json.Unmarshal([]byte(respBody), &response) if err != nil { // json解析失败 return nil, err } if response.Errcode != nil { if response.Errmsg != "" { return nil, errors.New(response.Errmsg) } else { return nil, errors.New("请求失败") } } return &response, nil }