conekta 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. data/.gitignore +18 -0
  2. data/CONTRIBUTORS +9 -0
  3. data/Gemfile +2 -0
  4. data/Gemfile.lock +57 -0
  5. data/History.txt +4 -0
  6. data/LICENSE +23 -0
  7. data/README.rdoc +22 -0
  8. data/Rakefile +14 -0
  9. data/VERSION +1 -0
  10. data/bin/conekta-console +7 -0
  11. data/conekta.gemspec +27 -0
  12. data/gemfiles/default-with-activesupport.gemfile +3 -0
  13. data/gemfiles/json.gemfile +4 -0
  14. data/gemfiles/yajl.gemfile +4 -0
  15. data/lib/conekta.rb +292 -0
  16. data/lib/conekta/account.rb +4 -0
  17. data/lib/conekta/api_operations/create.rb +16 -0
  18. data/lib/conekta/api_operations/delete.rb +11 -0
  19. data/lib/conekta/api_operations/list.rb +16 -0
  20. data/lib/conekta/api_operations/update.rb +16 -0
  21. data/lib/conekta/api_resource.rb +33 -0
  22. data/lib/conekta/charge.rb +43 -0
  23. data/lib/conekta/conekta_object.rb +158 -0
  24. data/lib/conekta/errors/api_connection_error.rb +4 -0
  25. data/lib/conekta/errors/api_error.rb +4 -0
  26. data/lib/conekta/errors/authentication_error.rb +4 -0
  27. data/lib/conekta/errors/card_error.rb +11 -0
  28. data/lib/conekta/errors/conekta_error.rb +20 -0
  29. data/lib/conekta/errors/malformed_request_error.rb +10 -0
  30. data/lib/conekta/errors/parameter_validation_error.rb +10 -0
  31. data/lib/conekta/errors/resource_not_found_error.rb +10 -0
  32. data/lib/conekta/event.rb +5 -0
  33. data/lib/conekta/json.rb +21 -0
  34. data/lib/conekta/list_object.rb +35 -0
  35. data/lib/conekta/log.rb +5 -0
  36. data/lib/conekta/singleton_api_resource.rb +20 -0
  37. data/lib/conekta/util.rb +99 -0
  38. data/lib/conekta/version.rb +3 -0
  39. data/lib/data/ca-certificates.crt +3918 -0
  40. data/spec/conekta_spec.rb +743 -0
  41. data/spec/conekta_with_active_support_spec.rb +3 -0
  42. data/spec/test_helper.rb +302 -0
  43. metadata +177 -0
@@ -0,0 +1,18 @@
1
+ *.gem
2
+ *.rbc
3
+ .bundle
4
+ .config
5
+ coverage
6
+ InstalledFiles
7
+ lib/bundler/man
8
+ pkg
9
+ rdoc
10
+ spec/reports
11
+ test/tmp
12
+ test/version_tmp
13
+ tmp
14
+
15
+ # YARD artifacts
16
+ .yardoc
17
+ _yardoc
18
+ doc/
@@ -0,0 +1,9 @@
1
+ Copyright (C) 2013 Conekta
2
+ Leo Fischer
3
+ Mauricio Murga
4
+
5
+ Copyright (C) 2013 Stripe
6
+
7
+ Greg Brockman <gdb@gregbrockman.com>
8
+ Ross Boucher <rboucher@gmail.com>
9
+ Bradley Grzesiak <brad@bendyworks.com>
data/Gemfile ADDED
@@ -0,0 +1,2 @@
1
+ source "https://rubygems.org"
2
+ gemspec
@@ -0,0 +1,57 @@
1
+ PATH
2
+ remote: .
3
+ specs:
4
+ conekta (0.2.0)
5
+ multi_json (>= 1.0.4, < 2)
6
+ rest-client (~> 1.4)
7
+
8
+ GEM
9
+ remote: https://rubygems.org/
10
+ specs:
11
+ activesupport (4.0.0)
12
+ i18n (~> 0.6, >= 0.6.4)
13
+ minitest (~> 4.2)
14
+ multi_json (~> 1.3)
15
+ thread_safe (~> 0.1)
16
+ tzinfo (~> 0.3.37)
17
+ atomic (1.1.10)
18
+ bourne (1.5.0)
19
+ mocha (>= 0.13.2, < 0.15)
20
+ diff-lcs (1.2.4)
21
+ i18n (0.6.4)
22
+ metaclass (0.0.1)
23
+ mime-types (2.0)
24
+ minitest (4.7.5)
25
+ mocha (0.13.3)
26
+ metaclass (~> 0.0.1)
27
+ multi_json (1.7.7)
28
+ rake (10.1.0)
29
+ rest-client (1.6.7)
30
+ mime-types (>= 1.16)
31
+ rspec (2.14.1)
32
+ rspec-core (~> 2.14.0)
33
+ rspec-expectations (~> 2.14.0)
34
+ rspec-mocks (~> 2.14.0)
35
+ rspec-core (2.14.2)
36
+ rspec-expectations (2.14.0)
37
+ diff-lcs (>= 1.1.3, < 2.0)
38
+ rspec-mocks (2.14.1)
39
+ shoulda (3.4.0)
40
+ shoulda-context (~> 1.0, >= 1.0.1)
41
+ shoulda-matchers (~> 1.0, >= 1.4.1)
42
+ shoulda-context (1.1.4)
43
+ shoulda-matchers (1.5.6)
44
+ activesupport (>= 3.0.0)
45
+ bourne (~> 1.3)
46
+ thread_safe (0.1.1)
47
+ atomic
48
+ tzinfo (0.3.37)
49
+
50
+ PLATFORMS
51
+ ruby
52
+
53
+ DEPENDENCIES
54
+ conekta!
55
+ rake
56
+ rspec
57
+ shoulda (~> 3.4.0)
@@ -0,0 +1,4 @@
1
+ === 0.1.0 2013-07-29
2
+
3
+ * 1 major enhancement:
4
+ * Initial release
data/LICENSE ADDED
@@ -0,0 +1,23 @@
1
+ The MIT License
2
+
3
+ Copyright (c) 2013- Conekta (http://conekta.mx)
4
+
5
+ Copyright (c) 2011-2013 Stripe, Inc. (https://stripe.com)
6
+
7
+ Permission is hereby granted, free of charge, to any person obtaining a copy
8
+ of this software and associated documentation files (the "Software"), to deal
9
+ in the Software without restriction, including without limitation the rights
10
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11
+ copies of the Software, and to permit persons to whom the Software is
12
+ furnished to do so, subject to the following conditions:
13
+
14
+ The above copyright notice and this permission notice shall be included in
15
+ all copies or substantial portions of the Software.
16
+
17
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
23
+ THE SOFTWARE.
@@ -0,0 +1,22 @@
1
+ = Conekta Ruby bindings
2
+
3
+ == Installation
4
+
5
+ You don't need this source code unless you want to modify the gem. If
6
+ you want to install the gem via bundler you should add this line to your gemfile:
7
+
8
+ gem 'conekta', :git => 'git://github.com/conekta/conekta-ruby.git'
9
+
10
+ If you want to build the gem from source:
11
+
12
+ gem build conekta.gemspec
13
+
14
+ == Requirements
15
+
16
+ * Ruby 1.8.7 or above. (Ruby 1.8.6 may work if you load
17
+ ActiveSupport.)
18
+ * rest-client, multi_json
19
+
20
+ == Development
21
+
22
+ Test cases can be run with: `bundle exec rake test`
@@ -0,0 +1,14 @@
1
+ require 'rspec/core/rake_task'
2
+ task :default => [:spec]
3
+
4
+
5
+ RSpec::Core::RakeTask.new(:spec)
6
+
7
+
8
+ #task :test do
9
+ # ret = true
10
+ # Dir["test/**/*.rb"].each do |f|
11
+ # ret = ret && ruby(f, '')
12
+ # end
13
+ # exit(ret)
14
+ # end
data/VERSION ADDED
@@ -0,0 +1 @@
1
+ 0.3.0
@@ -0,0 +1,7 @@
1
+ #!/usr/bin/env ruby
2
+ irb = RUBY_PLATFORM =~ /(:?mswin|mingw)/ ? 'irb.bat' : 'irb'
3
+
4
+ libs = " -r irb/completion"
5
+ libs << " -r #{File.dirname(__FILE__) + '/../lib/conekta.rb'}"
6
+ puts "Loading conekta gem"
7
+ exec "#{irb} #{libs} --simple-prompt"
@@ -0,0 +1,27 @@
1
+ $:.unshift(File.join(File.dirname(__FILE__), 'lib'))
2
+
3
+ require 'conekta/version'
4
+
5
+ spec = Gem::Specification.new do |s|
6
+ s.name = 'conekta'
7
+ s.version = Conekta::VERSION
8
+ s.summary = 'Ruby bindings for the Conekta API'
9
+ s.description = 'Easy payments and shipping, see http://conekta.mx for details.'
10
+ s.authors = ['Leo Fischer', 'Mauricio Murga']
11
+ s.email = %w(leo@conekta.mx mauricio@conekta.com)
12
+ s.homepage = 'http://conekta.mx/doc'
13
+
14
+ s.add_dependency('rest-client', '~> 1.4')
15
+ s.add_dependency('multi_json', '>= 1.0.4', '< 2')
16
+
17
+ # s.add_development_dependency('mocha', '~> 0.13.2')
18
+ s.add_development_dependency('shoulda', '~> 3.4.0')
19
+ # s.add_development_dependency('test-unit')
20
+ s.add_development_dependency('rspec')
21
+ s.add_development_dependency('rake')
22
+
23
+ s.files = `git ls-files`.split("\n")
24
+ s.test_files = `git ls-files -- test/*`.split("\n")
25
+ s.executables = `git ls-files -- bin/*`.split("\n").map{ |f| File.basename(f) }
26
+ s.require_paths = ['lib']
27
+ end
@@ -0,0 +1,3 @@
1
+ source "https://rubygems.org"
2
+ gemspec :path => File.join(File.dirname(__FILE__), "..")
3
+ gem "activesupport", "~> 3.0"
@@ -0,0 +1,4 @@
1
+ source "https://rubygems.org"
2
+ gemspec :path => File.join(File.dirname(__FILE__), "..")
3
+ gem "json"
4
+ gem "activesupport", "~> 3.0"
@@ -0,0 +1,4 @@
1
+ source "https://rubygems.org"
2
+ gemspec :path => File.join(File.dirname(__FILE__), "..")
3
+ gem "yajl-ruby"
4
+ gem "activesupport", "~> 3.0"
@@ -0,0 +1,292 @@
1
+ # Conekta Ruby bindings
2
+ # API spec at https://conekta.io/docs/api
3
+ require 'cgi'
4
+ require 'set'
5
+ require 'openssl'
6
+ require 'rest_client'
7
+ require 'multi_json'
8
+ require 'base64'
9
+
10
+ # Version
11
+ require 'conekta/version'
12
+
13
+ # API operations
14
+ require 'conekta/api_operations/create'
15
+ require 'conekta/api_operations/update'
16
+ require 'conekta/api_operations/delete'
17
+ require 'conekta/api_operations/list'
18
+
19
+ # Resources
20
+ require 'conekta/util'
21
+ require 'conekta/json'
22
+ require 'conekta/conekta_object'
23
+ require 'conekta/api_resource'
24
+ require 'conekta/singleton_api_resource'
25
+ require 'conekta/account'
26
+ require 'conekta/list_object'
27
+ require 'conekta/charge'
28
+ require 'conekta/event'
29
+ require 'conekta/log'
30
+
31
+ # Errors
32
+ require 'conekta/errors/conekta_error'
33
+ require 'conekta/errors/api_error'
34
+ require 'conekta/errors/api_connection_error'
35
+ require 'conekta/errors/card_error'
36
+ require 'conekta/errors/resource_not_found_error'
37
+ require 'conekta/errors/malformed_request_error'
38
+ require 'conekta/errors/parameter_validation_error'
39
+ require 'conekta/errors/authentication_error'
40
+
41
+ module Conekta
42
+ @api_base = 'https://api.conekta.io'
43
+
44
+ @ssl_bundle_path = File.dirname(__FILE__) + '/data/ca-certificates.crt'
45
+ @verify_ssl_certs = true
46
+
47
+ class << self
48
+ attr_accessor :api_key, :api_base, :verify_ssl_certs, :api_version
49
+ end
50
+
51
+ def self.api_url(url='')
52
+ url = @api_base + url
53
+ if not url.match(/\.json/)
54
+ url = url + '.json'
55
+ end
56
+ url
57
+ end
58
+
59
+ def self.request(method, url, api_key, params={}, headers={})
60
+ unless api_key ||= @api_key
61
+ raise AuthenticationError.new('No API key provided. ' +
62
+ 'Set your API key using "Conekta.api_key = <API-KEY>". ' +
63
+ 'You can generate API keys from the Conekta web interface. ' +
64
+ 'See https://conekta.io/api for details, or email support@conekta.io ' +
65
+ 'if you have any questions.')
66
+ end
67
+
68
+ if api_key =~ /\s/
69
+ raise AuthenticationError.new('Your API key is invalid, as it contains ' +
70
+ 'whitespace. (HINT: You can double-check your API key from the ' +
71
+ 'Conekta web interface. See https://conekta.io/api for details, or ' +
72
+ 'email support@conekta.io if you have any questions.)')
73
+ end
74
+
75
+ request_opts = { :verify_ssl => false }
76
+
77
+ if ssl_preflight_passed?
78
+ request_opts.update(:verify_ssl => OpenSSL::SSL::VERIFY_PEER,
79
+ :ssl_ca_file => @ssl_bundle_path)
80
+ end
81
+
82
+ params = Util.objects_to_ids(params)
83
+ url = api_url(url)
84
+
85
+ case method.to_s.downcase.to_sym
86
+ when :get, :head, :delete
87
+ # Make params into GET parameters
88
+ url += "#{URI.parse(url).query ? '&' : '?'}#{uri_encode(params)}" if params && params.any?
89
+ payload = nil
90
+ else
91
+ payload = params.to_json#uri_encode(params)
92
+ headers[:content_type] = 'application/json'
93
+ end
94
+
95
+ request_opts.update(:headers => request_headers(api_key).update(headers),
96
+ :method => method, :open_timeout => 30,
97
+ :payload => payload, :url => url, :timeout => 80)
98
+
99
+ begin
100
+ response = execute_request(request_opts)
101
+ rescue SocketError => e
102
+ handle_restclient_error(e)
103
+ rescue NoMethodError => e
104
+ # Work around RestClient bug
105
+ if e.message =~ /\WRequestFailed\W/
106
+ e = APIConnectionError.new('Unexpected HTTP response code')
107
+ handle_restclient_error(e)
108
+ else
109
+ raise
110
+ end
111
+ rescue RestClient::ExceptionWithResponse => e
112
+ if rcode = e.http_code and rbody = e.http_body
113
+ handle_api_error(rcode, rbody)
114
+ else
115
+ handle_restclient_error(e)
116
+ end
117
+ rescue RestClient::Exception, Errno::ECONNREFUSED => e
118
+ handle_restclient_error(e)
119
+ end
120
+
121
+ [parse(response), api_key]
122
+ end
123
+
124
+ private
125
+
126
+ def self.ssl_preflight_passed?
127
+ if !verify_ssl_certs && !@no_verify
128
+ $stderr.puts "WARNING: Running without SSL cert verification. " +
129
+ "Execute 'Conekta.verify_ssl_certs = true' to enable verification."
130
+
131
+ @no_verify = true
132
+
133
+ elsif !Util.file_readable(@ssl_bundle_path) && !@no_bundle
134
+ $stderr.puts "WARNING: Running without SSL cert verification " +
135
+ "because #{@ssl_bundle_path} isn't readable"
136
+
137
+ @no_bundle = true
138
+ end
139
+
140
+ !(@no_verify || @no_bundle)
141
+ end
142
+
143
+ def self.user_agent
144
+ @uname ||= get_uname
145
+ lang_version = "#{RUBY_VERSION} p#{RUBY_PATCHLEVEL} (#{RUBY_RELEASE_DATE})"
146
+
147
+ {
148
+ :bindings_version => Conekta::VERSION,
149
+ :lang => 'ruby',
150
+ :lang_version => lang_version,
151
+ :platform => RUBY_PLATFORM,
152
+ :publisher => 'conekta',
153
+ :uname => @uname
154
+ }
155
+
156
+ end
157
+
158
+ def self.get_uname
159
+ `uname -a 2>/dev/null`.strip if RUBY_PLATFORM =~ /linux|darwin/i
160
+ rescue Errno::ENOMEM => ex # couldn't create subprocess
161
+ "uname lookup failed"
162
+ end
163
+
164
+ def self.uri_encode(params)
165
+ Util.flatten_params(params).
166
+ map { |k,v| "#{k}=#{Util.url_encode(v)}" }.join('&')
167
+ end
168
+
169
+ def self.request_headers(api_key)
170
+ headers = {
171
+ :user_agent => "Conekta RubyBindings/#{Conekta::VERSION}",
172
+ :authorization => "Basic #{Base64.encode64(api_key+':')}"
173
+ }
174
+
175
+ if api_version
176
+ headers.update(:accept=>"application/vnd.conekta-v#{api_version}+json")
177
+ else
178
+ headers.update(:accept=>"application/vnd.conekta-v0.3.0+json")
179
+ end
180
+
181
+ begin
182
+ headers.update(:conekta_client_user_agent => Conekta::JSON.dump(user_agent))
183
+ rescue => e
184
+ headers.update(:conekta_client_raw_user_agent => user_agent.inspect,
185
+ :error => "#{e} (#{e.class})")
186
+ end
187
+ end
188
+
189
+ def self.execute_request(opts)
190
+ RestClient::Request.execute(opts)
191
+ end
192
+
193
+ def self.parse(response)
194
+ begin
195
+ # Would use :symbolize_names => true, but apparently there is
196
+ # some library out there that makes symbolize_names not work.
197
+ response = Conekta::JSON.load(response.body)
198
+ rescue MultiJson::DecodeError
199
+ raise general_api_error(response.code, response.body)
200
+ end
201
+
202
+ Util.symbolize_names(response)
203
+ end
204
+
205
+ def self.general_api_error(rcode, rbody)
206
+ APIError.new("Invalid response object from API: #{rbody.inspect} " +
207
+ "(HTTP response code was #{rcode})", rcode, rbody)
208
+ end
209
+
210
+ def self.handle_api_error(rcode, rbody)
211
+ begin
212
+ error_obj = Conekta::JSON.load(rbody)
213
+ error_obj = Util.symbolize_names(error_obj)
214
+ error = error_obj or raise ConektaError.new # escape from parsing
215
+
216
+ rescue MultiJson::DecodeError, ConektaError
217
+ raise general_api_error(rcode, rbody)
218
+ end
219
+
220
+ case rcode
221
+ when 400
222
+ raise malformed_request_error error, rcode, rbody, error_obj
223
+ when 401
224
+ raise authentication_error error, rcode, rbody, error_obj
225
+ when 402
226
+ raise card_error error, rcode, rbody, error_obj
227
+ when 404
228
+ raise resource_not_found_error error, rcode, rbody, error_obj
229
+ when 422
230
+ raise parameter_validation_error error, rcode, rbody, error_obj
231
+ else
232
+ raise api_error error, rcode, rbody, error_obj
233
+ end
234
+
235
+ end
236
+
237
+ def self.resource_not_found_error(error, rcode, rbody, error_obj)
238
+ ResourceNotFoundError.new(error[:message], error[:param], rcode,
239
+ rbody, error_obj)
240
+ end
241
+
242
+ def self.malformed_request_error(error, rcode, rbody, error_obj)
243
+ MalformedRequestError.new(error[:message], error[:param], rcode,
244
+ rbody, error_obj)
245
+ end
246
+
247
+ def self.parameter_validation_error(error, rcode, rbody, error_obj)
248
+ ParameterValidationError.new(error[:message], error[:param], rcode,
249
+ rbody, error_obj)
250
+ end
251
+
252
+ def self.authentication_error(error, rcode, rbody, error_obj)
253
+ AuthenticationError.new(error[:message], rcode, rbody, error_obj)
254
+ end
255
+
256
+ def self.card_error(error, rcode, rbody, error_obj)
257
+ CardError.new(error[:message], error[:param], error[:code],
258
+ rcode, rbody, error_obj)
259
+ end
260
+
261
+ def self.api_error(error, rcode, rbody, error_obj)
262
+ APIError.new(error[:message], rcode, rbody, error_obj)
263
+ end
264
+
265
+ def self.handle_restclient_error(e)
266
+ case e
267
+ when RestClient::ServerBrokeConnection, RestClient::RequestTimeout
268
+ message = "Could not connect to Conekta (#{@api_base}). " +
269
+ "Please check your internet connection and try again. " +
270
+ "If this problem persists, you should check Conekta's service status at " +
271
+ "https://twitter.com/conektastatus, or let us know at support@conekta.io."
272
+
273
+ when RestClient::SSLCertificateNotVerified
274
+ message = "Could not verify Conekta's SSL certificate. " +
275
+ "Please make sure that your network is not intercepting certificates. " +
276
+ "(Try going to https://api.conekta.io/ in your browser.) " +
277
+ "If this problem persists, let us know at support@conekta.io."
278
+
279
+ when SocketError
280
+ message = "Unexpected error communicating when trying to connect to Conekta. " +
281
+ "You may be seeing this message because your DNS is not working. " +
282
+ "To check, try running 'host conekta.io' from the command line."
283
+
284
+ else
285
+ message = "Unexpected error communicating with Conekta. " +
286
+ "If this problem persists, let us know at support@conekta.io."
287
+
288
+ end
289
+
290
+ raise APIConnectionError.new(message + "\n\n(Network error: #{e.message})")
291
+ end
292
+ end