蛋蛋星球-制度模式
Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

94 rader
2.2 KiB

  1. package paypal
  2. import (
  3. "context"
  4. "github.com/go-pay/xlog"
  5. "github.com/go-pay/gopay"
  6. "github.com/go-pay/gopay/pkg/xhttp"
  7. )
  8. // Client PayPal支付客户端
  9. type Client struct {
  10. Clientid string
  11. Secret string
  12. Appid string
  13. AccessToken string
  14. ExpiresIn int
  15. IsProd bool
  16. ctx context.Context
  17. DebugSwitch gopay.DebugSwitch
  18. logger xlog.XLogger
  19. hc *xhttp.Client
  20. baseUrlProd string
  21. baseUrlSandbox string
  22. }
  23. type Option func(*Client)
  24. // NewClient 初始化PayPal支付客户端
  25. func NewClient(clientid, secret string, isProd bool, options ...Option) (client *Client, err error) {
  26. if clientid == gopay.NULL || secret == gopay.NULL {
  27. return nil, gopay.MissPayPalInitParamErr
  28. }
  29. logger := xlog.NewLogger()
  30. logger.SetLevel(xlog.DebugLevel)
  31. client = &Client{
  32. Clientid: clientid,
  33. Secret: secret,
  34. IsProd: isProd,
  35. ctx: context.Background(),
  36. DebugSwitch: gopay.DebugOff,
  37. logger: logger,
  38. hc: xhttp.NewClient(),
  39. baseUrlProd: baseUrlProd,
  40. baseUrlSandbox: baseUrlSandbox,
  41. }
  42. for _, option := range options {
  43. option(client)
  44. }
  45. _, err = client.GetAccessToken()
  46. if err != nil {
  47. return nil, err
  48. }
  49. // 自动刷新Token
  50. go client.goAuthRefreshToken()
  51. return client, nil
  52. }
  53. // WithProxyUrl 设置代理 Url
  54. func WithProxyUrl(proxyUrlProd, proxyUrlSandbox string) Option {
  55. return func(c *Client) {
  56. c.baseUrlProd = proxyUrlProd
  57. c.baseUrlSandbox = proxyUrlSandbox
  58. }
  59. }
  60. // SetBodySize 设置http response body size(MB)
  61. func (c *Client) SetBodySize(sizeMB int) {
  62. if sizeMB > 0 {
  63. c.hc.SetBodySize(sizeMB)
  64. }
  65. }
  66. // SetHttpClient 设置自定义的xhttp.Client
  67. func (c *Client) SetHttpClient(client *xhttp.Client) {
  68. if client != nil {
  69. c.hc = client
  70. }
  71. }
  72. func (c *Client) SetLogger(logger xlog.XLogger) {
  73. if logger != nil {
  74. c.logger = logger
  75. }
  76. }
  77. // SetProxyUrl 设置代理 Url
  78. // 使用场景:
  79. // 1. 大陆直接调用 PayPal 接口响应较慢,可以在第三地例如硅谷部署代理服务器来加速请求
  80. func (c *Client) SetProxyUrl(proxyUrlProd, proxyUrlSandbox string) {
  81. c.baseUrlProd = proxyUrlProd
  82. c.baseUrlSandbox = proxyUrlSandbox
  83. }