sdk.go 2.1KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. package invoice
  2. import (
  3. "encoding/base64"
  4. "errors"
  5. "io/ioutil"
  6. "net/http"
  7. "strconv"
  8. "strings"
  9. "time"
  10. "gdyb/common"
  11. )
  12. func NewSdk(algorithm, appkey, appsecret, privateKey, env string) *Client {
  13. return &Client{
  14. env: env,
  15. appkey: appkey,
  16. appsecret: appsecret,
  17. algorithm: algorithm,
  18. privateKey: privateKey,
  19. }
  20. }
  21. type Client struct {
  22. env string
  23. appkey string
  24. appsecret string
  25. privateKey string
  26. algorithm string
  27. }
  28. func (this *Client) HttpPost(baseUrl string, routerAddress string, post map[string]interface{}) ([]byte, error) {
  29. // 获取转换后的post字符串
  30. postData, err := common.GetPostDataWithMap(post)
  31. if err != nil {
  32. return nil, err
  33. }
  34. timestamp := strconv.FormatInt(time.Now().Unix(), 10) //获取时间戳
  35. nonce := common.GetRand(6) //6位随机数
  36. auth, err := this.getAuth(routerAddress, postData, timestamp, nonce) //认证串
  37. if err != nil {
  38. return nil, err
  39. }
  40. client := &http.Client{}
  41. reqest, err := http.NewRequest("POST", baseUrl+routerAddress, strings.NewReader((postData)))
  42. if err != nil {
  43. return nil, err
  44. }
  45. reqest.Header.Add("Authorization", auth)
  46. reqest.Header.Add("Content-Type", "application/json")
  47. r, err := client.Do(reqest)
  48. if err != nil {
  49. return nil, err
  50. }
  51. defer r.Body.Close()
  52. return ioutil.ReadAll(r.Body)
  53. }
  54. // getAuth 获取授权字符串
  55. func (this *Client) getAuth(routerAddress string, postData string, timestamp string, nonce string) (string, error) {
  56. originStr := "algorithm=" + this.algorithm + "|appkey=" + this.appkey + "|nonce=" + nonce + "|timestamp=" + timestamp + "|" + routerAddress + "|" + postData
  57. var signs string
  58. var err error
  59. switch this.algorithm {
  60. case common.HMAC_SHA256:
  61. signs = base64.StdEncoding.EncodeToString(common.HMAC_Sha256(originStr, this.appsecret))
  62. default:
  63. panic(errors.New("algorithm not exists"))
  64. }
  65. if err != nil {
  66. return "", err
  67. }
  68. auth := "algorithm=" + this.algorithm + ",appkey=" + this.appkey + ",nonce=" + nonce + ",timestamp=" + timestamp + ",signature=" + signs
  69. return auth, nil
  70. }