weibo.go 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. package dao
  2. import (
  3. "context"
  4. "encoding/json"
  5. "fmt"
  6. "net/http"
  7. "net/url"
  8. "time"
  9. "go-common/app/service/main/passport-sns/model"
  10. "go-common/library/ecode"
  11. "go-common/library/log"
  12. )
  13. const (
  14. _weiboAuthorizeUrl = "https://api.weibo.com/oauth2/authorize"
  15. _weiboAccessTokenUrl = "https://api.weibo.com/oauth2/access_token"
  16. )
  17. // WeiboAuthorize .
  18. func (d *Dao) WeiboAuthorize(c context.Context, appID, redirectURL, display string) (url string) {
  19. return fmt.Sprintf(_weiboAuthorizeUrl+"?client_id=%s&redirect_uri=%s&scope=all", appID, redirectURL)
  20. }
  21. // WeiboOauth2Info .
  22. func (d *Dao) WeiboOauth2Info(c context.Context, code, redirectUrl string, app *model.SnsApps) (res *model.Oauth2Info, err error) {
  23. accessResp, err := d.weiboAccessToken(c, code, app.AppID, app.AppSecret, redirectUrl)
  24. if err != nil {
  25. return nil, err
  26. }
  27. res = &model.Oauth2Info{
  28. Token: accessResp.Token,
  29. Refresh: accessResp.Refresh,
  30. Expires: time.Now().Unix() + accessResp.Expires,
  31. OpenID: accessResp.OpenID,
  32. UnionID: accessResp.OpenID,
  33. }
  34. return
  35. }
  36. // weiboAccessToken .
  37. func (d *Dao) weiboAccessToken(c context.Context, code, appID, appSecret, redirectUrl string) (resp *model.WeiboAccessResp, err error) {
  38. var (
  39. res *http.Response
  40. params = url.Values{}
  41. )
  42. params.Set("client_id", appID)
  43. params.Set("client_secret", appSecret)
  44. params.Set("grant_type", "authorization_code")
  45. params.Set("code", code)
  46. params.Set("redirect_uri", redirectUrl)
  47. res, err = d.client.PostForm(_weiboAccessTokenUrl, params)
  48. if err != nil {
  49. log.Error("d.weiboAccessToken error(%+v) code(%s) appID(%s)", err, code, appID)
  50. return nil, err
  51. }
  52. defer res.Body.Close()
  53. dc := json.NewDecoder(res.Body)
  54. resp = new(model.WeiboAccessResp)
  55. if err = dc.Decode(resp); err != nil {
  56. return
  57. }
  58. if resp.Code == _respCodeSuccess {
  59. return resp, nil
  60. }
  61. log.Error("request weibo failed with code(%d) desc(%s)", resp.Code, resp.Description)
  62. return nil, ecode.PassportSnsRequestErr
  63. }