qq.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. package dao
  2. import (
  3. "context"
  4. "encoding/json"
  5. "fmt"
  6. "io/ioutil"
  7. "net/http"
  8. "net/url"
  9. "strings"
  10. "go-common/app/job/main/passport-sns/model"
  11. "go-common/library/log"
  12. )
  13. const (
  14. _qqGetUnionidUrl = "https://graph.qq.com/oauth2.0/get_unionid"
  15. _respCodeSuccess = 0
  16. _respCodeInvalidOpenid = 100050
  17. _respCodeInvalidOpenidLength = 100058
  18. )
  19. // QQUnionID .
  20. func (d *Dao) QQUnionID(c context.Context, openID string) (unionID string, err error) {
  21. var (
  22. res *http.Response
  23. bs []byte
  24. params = url.Values{}
  25. )
  26. params.Set("client_id", model.OldAppID)
  27. params.Set("openid", openID)
  28. if res, err = http.Get(_qqGetUnionidUrl + "?" + params.Encode()); err != nil {
  29. log.Error("d.QQUnionID error(%+v) openID(%s)", err, openID)
  30. return "", err
  31. }
  32. defer res.Body.Close()
  33. if bs, err = ioutil.ReadAll(res.Body); err != nil {
  34. log.Error("ioutil.ReadAll() error(%+v) openID(%s)", err, openID)
  35. return "", err
  36. }
  37. respStr := string(bs)
  38. if strings.HasPrefix(respStr, "callback") {
  39. start := strings.Index(respStr, "{")
  40. end := strings.Index(respStr, "}")
  41. respStr = respStr[start : end+1]
  42. }
  43. unionRes := new(model.QQUnionIDResp)
  44. if err = json.Unmarshal([]byte(respStr), unionRes); err != nil {
  45. log.Error("json.Unmarshal() error(%+v) respStr(%s) openID(%s)", err, respStr, openID)
  46. return "", err
  47. }
  48. if unionRes.Code == _respCodeSuccess && unionRes.UnionID != "" {
  49. return unionRes.UnionID, nil
  50. }
  51. log.Error("request qq get_unionid failed with code(%d) desc(%s) openID(%s)", unionRes.Code, unionRes.Description, openID)
  52. if unionRes.Code == _respCodeInvalidOpenidLength || unionRes.Code == _respCodeInvalidOpenid {
  53. return "", nil
  54. }
  55. return "", fmt.Errorf("request qq get_unionid failed with code(%d) desc(%s) openID(%s)", unionRes.Code, unionRes.Description, openID)
  56. }