package weixin import ( "bytes" "encoding/json" "fmt" "github.com/tidwall/gjson" "io" "net/http" ) type OaSdk struct { BaseSdk } func NewOaSdk(appid, secret string) *OaSdk { return &OaSdk{ BaseSdk{ appid: appid, secret: secret, }, } } func (o *OaSdk) GetQrCode(sceneStr string) (string, error) { params := make(map[string]interface{}) params["expire_seconds"] = 1728000 //20天 params["action_name"] = "QR_STR_SCENE" params["action_info"] = map[string]interface{}{ "scene": map[string]interface{}{ "scene_str": sceneStr, // sceneStr不超过64个字符 }, } marshal, _ := json.Marshal(params) accessToken, err := o.getAccessToken() if err != nil { return "", err } url := fmt.Sprintf("%s?access_token=%s", oaQrCodeCreateUrl, accessToken) res, err := http.Post(url, "application/json", bytes.NewBuffer(marshal)) if err != nil { return "", err } defer res.Body.Close() body, err := io.ReadAll(res.Body) if err != nil { return "", err } g := gjson.ParseBytes(body) qrcodeUrl := g.Get("url").String() if qrcodeUrl == "" { return "", fmt.Errorf("%d:%s", g.Get("errcode").Int(), g.Get("errmsg").String()) } return qrcodeUrl, nil } func (o *BaseSdk) GetUserInfoByCode(code string) (*UserInfo, error) { return o.getUserInfoByCode(code) } func (o *OaSdk) GetUserInfoByOpenid(openid string) (*UserInfo, error) { accessToken, err := o.getAccessToken() if err != nil { return nil, err } url := fmt.Sprintf("%s?access_token=%s&openid=%s&lang=zh_CN", userInfoByOpenid, accessToken, openid) res, err := http.Get(url) if err != nil { return nil, err } defer res.Body.Close() body, err := io.ReadAll(res.Body) if err != nil { return nil, err } g := gjson.ParseBytes(body) errcode := g.Get("errcode").Int() if errcode != 0 { return nil, fmt.Errorf("%d:%s", errcode, g.Get("errmsg").String()) } user := new(UserInfo) user.Unionid = g.Get("unionid").String() user.Nickname = g.Get("nickname").String() user.Province = g.Get("province").String() user.City = g.Get("city").String() user.Country = g.Get("country").String() user.HeadUrl = g.Get("headimgurl").String() user.Sex = int(g.Get("sex").Int()) user.Openid = openid return user, nil }