Class: Whmcs::Api

Inherits:
Object
  • Object
show all
Includes:
ActiveModel::Validations
Defined in:
lib/whmcs/api.rb

Instance Method Summary collapse

Instance Method Details

#execute_command(command, options = {}) ⇒ Object

Method provides the same functionality as #execute_command! except it does not raises exceptions. When error occurs, it just returns false. So if method returns false, errors message should be in #errors

Example

@api = Whmcs::Api.new
@api.execute_command('some command', some_param: 'some value')   # => false
@api.errors.messages # => {:command=>["'some command' is invalid command"]}


66
67
68
69
70
71
72
# File 'lib/whmcs/api.rb', line 66

def execute_command(command, options={})
  begin
    return execute_command!(command, options)
  rescue
    return false
  end
end

#execute_command!(command, params = {}) ⇒ Object



6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
# File 'lib/whmcs/api.rb', line 6

def execute_command!(command, params={})
  # Clear errors from previous request
  errors.clear

  # Set local variables
  @command = command.to_s
  @params = process_params(params)


  # Assemble request_options
  request_options = {
      action: @command,
      username: Whmcs.config.api_user,
      password: Digest::MD5.hexdigest(Whmcs.config.api_password),
      responsetype: 'json'
  }
  request_options.merge! @params

  begin
    # send curl request to the Whmcs server
    curl = Curl::Easy.new(Whmcs.config.api_url)
    curl.ssl_verify_peer = false
    curl.ssl_verify_host=0
    if Whmcs.config.http_auth_user.present?
      curl.http_auth_types = :basic
      curl.username = Whmcs.config.http_auth_user
      curl.password = Whmcs.config.http_auth_password
    end
    curl.http_post(request_options.to_query)
    curl.perform

    # handle response
    result = JSON.parse(curl.body_str, symbolize_names: true)
  rescue Exception => e
    # If error occurs, it adds to instance errors
    errors.add(:base, e.message)
    raise e
  end

  # check if error occurred
  if result[:result] == 'error'
    errors.add(:base, result[:message])
    raise StandardError, result[:message]
  end

  # If all pass success, returns a result hash
  result
end