atdemo.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. /*
  2. * Copyright 2020. Huawei Technologies Co., Ltd. All rights reserved.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. *
  16. */
  17. package huawei
  18. import (
  19. "encoding/base64"
  20. "encoding/json"
  21. "errors"
  22. "fmt"
  23. "io"
  24. "net/url"
  25. "bet24.com/servers/payment/config"
  26. )
  27. type AtResponse struct {
  28. AccessToken string `json:"access_token"`
  29. }
  30. type AtClient struct {
  31. }
  32. var AtDemo = &AtClient{}
  33. func (atDemo *AtClient) GetAppAt() (string, error) {
  34. urlValue := url.Values{
  35. "grant_type": {"client_credentials"},
  36. "client_secret": {config.Server.ClientSecret},
  37. "client_id": {config.Server.ClientId}}
  38. //log.Debug("urlValue=%v", urlValue)
  39. //log.Debug("TokenUrl=%s", config.Server.TokenUrl)
  40. resp, err := RequestHttpClient.PostForm(config.Server.TokenUrl, urlValue)
  41. //log.Debug("GetAppAt=%v", resp)
  42. if err != nil {
  43. return "", err
  44. }
  45. defer resp.Body.Close()
  46. bodyBytes, err := io.ReadAll(resp.Body)
  47. if err != nil {
  48. return "", err
  49. }
  50. var atResponse AtResponse
  51. json.Unmarshal(bodyBytes, &atResponse)
  52. if atResponse.AccessToken != "" {
  53. return atResponse.AccessToken, nil
  54. } else {
  55. return "", errors.New("Get token fail, " + string(bodyBytes))
  56. }
  57. }
  58. func BuildAuthorization() (string, error) {
  59. appAt, err := AtDemo.GetAppAt()
  60. if err != nil {
  61. return "", err
  62. }
  63. oriString := fmt.Sprintf("APPAT:%s", appAt)
  64. var authString = base64.StdEncoding.EncodeToString([]byte(oriString))
  65. var authHeaderString = fmt.Sprintf("Basic %s", authString)
  66. return authHeaderString, nil
  67. }