Class: CDEKApiClient::Client

Inherits:
Object
  • Object
show all
Defined in:
lib/cdek_api_client/client.rb

Overview

Client class for interacting with the CDEK API.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(client_id, client_secret, environment: nil, base_url: nil, logger: Logger.new($stdout)) ⇒ Client

Initializes the client with API credentials and configuration.

Parameters:

  • client_id (String)

    the client ID.

  • client_secret (String)

    the client secret.

  • environment (Symbol, String) (defaults to: nil)

    the API environment (:production or :demo). Defaults to :demo or value from CDEK_API_ENV environment variable.

  • base_url (String) (defaults to: nil)

    custom API base URL (overrides environment). Defaults to value from CDEK_API_URL environment variable or environment default.

  • logger (Logger) (defaults to: Logger.new($stdout))

    the logger instance.



51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
# File 'lib/cdek_api_client/client.rb', line 51

def initialize(client_id, client_secret, environment: nil, base_url: nil, logger: Logger.new($stdout))
  @client_id = client_id
  @client_secret = client_secret
  @base_url = Config.base_url(environment: environment, custom_url: base_url)
  @logger = logger
  @token = authenticate

  @courier = CDEKApiClient::API::Courier.new(self)
  @location = CDEKApiClient::API::Location.new(self)
  @order = CDEKApiClient::API::Order.new(self)
  @payment = CDEKApiClient::API::Payment.new(self)
  @print = CDEKApiClient::API::Print.new(self)
  @tariff = CDEKApiClient::API::Tariff.new(self)
  @webhook = CDEKApiClient::API::Webhook.new(self)
end

Instance Attribute Details

#base_urlString (readonly)

Returns the base API URL.

Returns:

  • (String)

    the base API URL



22
23
24
# File 'lib/cdek_api_client/client.rb', line 22

def base_url
  @base_url
end

#courierCDEKApiClient::Courier (readonly)

Returns the courier API interface.

Returns:

  • (CDEKApiClient::Courier)

    the courier API interface.



28
29
30
# File 'lib/cdek_api_client/client.rb', line 28

def courier
  @courier
end

#locationCDEKApiClient::Location (readonly)

Returns the location API interface.

Returns:

  • (CDEKApiClient::Location)

    the location API interface.



30
31
32
# File 'lib/cdek_api_client/client.rb', line 30

def location
  @location
end

#loggerLogger (readonly)

Returns the logger instance.

Returns:

  • (Logger)

    the logger instance.



26
27
28
# File 'lib/cdek_api_client/client.rb', line 26

def logger
  @logger
end

#orderCDEKApiClient::Order (readonly)

Returns the order API interface.

Returns:

  • (CDEKApiClient::Order)

    the order API interface.



32
33
34
# File 'lib/cdek_api_client/client.rb', line 32

def order
  @order
end

#paymentCDEKApiClient::Payment (readonly)

Returns the payment API interface.

Returns:

  • (CDEKApiClient::Payment)

    the payment API interface.



34
35
36
# File 'lib/cdek_api_client/client.rb', line 34

def payment
  @payment
end

Returns the print API interface.

Returns:

  • (CDEKApiClient::Print)

    the print API interface.



36
37
38
# File 'lib/cdek_api_client/client.rb', line 36

def print
  @print
end

#tariffCDEKApiClient::Tariff (readonly)

Returns the tariff API interface.

Returns:

  • (CDEKApiClient::Tariff)

    the tariff API interface.



38
39
40
# File 'lib/cdek_api_client/client.rb', line 38

def tariff
  @tariff
end

#tokenString (readonly)

Returns the access token for API authentication.

Returns:

  • (String)

    the access token for API authentication.



24
25
26
# File 'lib/cdek_api_client/client.rb', line 24

def token
  @token
end

#webhookCDEKApiClient::Webhook (readonly)

Returns the webhook API interface.

Returns:

  • (CDEKApiClient::Webhook)

    the webhook API interface.



40
41
42
# File 'lib/cdek_api_client/client.rb', line 40

def webhook
  @webhook
end

Instance Method Details

#authenticateString

Authenticates with the API and retrieves an access token.

Returns:

  • (String)

    the access token.

Raises:

  • (StandardError)

    if authentication fails.



71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
# File 'lib/cdek_api_client/client.rb', line 71

def authenticate
  uri = URI(Config.token_url(custom_url: @base_url))
  http = Net::HTTP.new(uri.host, uri.port)
  http.use_ssl = true

  request = Net::HTTP::Post.new(uri)
  request.set_form_data(
    'grant_type' => 'client_credentials',
    'client_id' => @client_id,
    'client_secret' => @client_secret
  )

  response = http.request(request)

  case response
  when Net::HTTPSuccess
    begin
      data = JSON.parse(response.body)
      auth_response = CDEKApiClient::Entities::AuthResponse.new(
        access_token: data['access_token'],
        token_type: data['token_type'],
        expires_in: data['expires_in'],
        scope: data['scope'],
        jti: data['jti']
      )
      @logger.info("Successfully authenticated, token expires in #{auth_response.expires_in} seconds")
      auth_response.access_token
    rescue JSON::ParserError => e
      raise "Failed to parse authentication response: #{e.message}"
    rescue ArgumentError => e
      raise "Invalid authentication response format: #{e.message}"
    end
  else
    begin
      error_data = JSON.parse(response.body)
      error_response = CDEKApiClient::Entities::AuthErrorResponse.new(
        error: error_data['error'],
        error_description: error_data['error_description']
      )
      raise "Authentication failed: #{error_response.error} - #{error_response.error_description}"
    rescue JSON::ParserError, ArgumentError
      raise "Authentication failed with HTTP #{response.code}: #{response.body}"
    end
  end
end

#request(method, path, body: nil, query: nil) ⇒ Hash, Array

Makes an HTTP request to the API.

Parameters:

  • method (String)

    the HTTP method (e.g., ‘get’, ‘post’).

  • path (String)

    the API endpoint path.

  • body (Hash, nil) (defaults to: nil)

    the request body.

  • query (Hash, nil) (defaults to: nil)

    the query parameters.

Returns:

  • (Hash, Array)

    the parsed response.



124
125
126
127
128
129
130
131
132
133
134
135
# File 'lib/cdek_api_client/client.rb', line 124

def request(method, path, body: nil, query: nil)
  uri = URI("#{@base_url}/#{path}")
  uri.query = URI.encode_www_form(query) if query
  http = Net::HTTP.new(uri.host, uri.port)
  http.use_ssl = true
  request = build_request(method, uri, body)
  response = http.request(request)
  handle_response(response)
rescue StandardError => e
  @logger.error("HTTP request failed: #{e.message}")
  { 'error' => e.message }
end

#validate_uuid(uuid) ⇒ Object

Raises:

  • (ArgumentError)


137
138
139
# File 'lib/cdek_api_client/client.rb', line 137

def validate_uuid(uuid)
  raise ArgumentError, 'Invalid UUID format' unless uuid&.match?(/\A[\da-f]{8}-([\da-f]{4}-){3}[\da-f]{12}\z/i)
end