alipay.go 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. // Copyright 2019 Yunion
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package alipay
  15. import (
  16. "context"
  17. "fmt"
  18. "yunion.io/x/jsonutils"
  19. "yunion.io/x/pkg/errors"
  20. "yunion.io/x/onecloud/pkg/keystone/driver/oauth2"
  21. "yunion.io/x/onecloud/pkg/util/alipayclient"
  22. )
  23. type SAlipayOAuth2Driver struct {
  24. oauth2.SOAuth2BaseDriver
  25. }
  26. func NewAlipayOAuth2Driver(appId string, secret string) oauth2.IOAuth2Driver {
  27. drv := &SAlipayOAuth2Driver{
  28. SOAuth2BaseDriver: oauth2.SOAuth2BaseDriver{
  29. AppId: appId,
  30. Secret: secret,
  31. },
  32. }
  33. return drv
  34. }
  35. const (
  36. AuthUrl = "https://openauth.alipay.com/oauth2/publicAppAuthorize.htm"
  37. )
  38. func (drv *SAlipayOAuth2Driver) GetSsoRedirectUri(ctx context.Context, callbackUrl, state string) (string, error) {
  39. req := map[string]string{
  40. "app_id": drv.AppId,
  41. "redirect_uri": callbackUrl,
  42. "scope": "auth_user",
  43. "response_type": "code",
  44. "state": state,
  45. }
  46. urlStr := fmt.Sprintf("%s?%s", AuthUrl, jsonutils.Marshal(req).QueryString())
  47. return urlStr, nil
  48. }
  49. func (drv *SAlipayOAuth2Driver) Authenticate(ctx context.Context, code string) (map[string][]string, error) {
  50. alipayCli, err := alipayclient.NewDefaultAlipayClient(drv.AppId, drv.Secret, "", true)
  51. if err != nil {
  52. return nil, errors.Wrap(err, "alipayclient.NewDefaultAlipayClient")
  53. }
  54. resp, err := alipayCli.GetOAuthToken(ctx, code)
  55. if err != nil {
  56. return nil, errors.Wrap(err, "alipayCli.GetOAuthToken")
  57. }
  58. userInfo, err := alipayCli.GetUserInfo(ctx, resp.AccessToken)
  59. if err != nil {
  60. return nil, errors.Wrap(err, "alipayCli.GetUserInfo")
  61. }
  62. attrs := make(map[string][]string)
  63. for k, v := range userInfo {
  64. attrs[k] = []string{v}
  65. }
  66. attrs["user_name"] = []string{fmt.Sprintf("alipay%s", userInfo["user_id"])}
  67. return attrs, nil
  68. }