Skip to content

Commit

Permalink
Merge pull request #18 from seuros/master
Browse files Browse the repository at this point in the history
Some tweaks (thanks to seuros)
  • Loading branch information
Sergiusz Woźnicki committed Aug 26, 2014
2 parents 3537bb4 + 40fe9b5 commit 88583c2
Show file tree
Hide file tree
Showing 47 changed files with 230 additions and 295 deletions.
1 change: 1 addition & 0 deletions .rspec
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
--color
--profile
--r spec_helper
202 changes: 97 additions & 105 deletions lib/mangopay.rb
Original file line number Diff line number Diff line change
Expand Up @@ -4,139 +4,131 @@

# helpers
require 'mangopay/version'
require 'mangopay/json'
require 'mangopay/errors'
require 'mangopay/authorization_token'

# resources
require 'mangopay/http_calls'
require 'mangopay/resource'
require 'mangopay/client'
require 'mangopay/user'
require 'mangopay/natural_user'
require 'mangopay/legal_user'
require 'mangopay/payin'
require 'mangopay/payout'
require 'mangopay/transfer'
require 'mangopay/transaction'
require 'mangopay/wallet'
require 'mangopay/bank_account'
require 'mangopay/card_registration'
require 'mangopay/preauthorization'
require 'mangopay/card'
require 'mangopay/event'
require 'mangopay/kyc_document'
require 'mangopay/hook'
require 'mangopay/refund'


module MangoPay

autoload :HTTPCalls, 'mangopay/http_calls'
autoload :Resource, 'mangopay/resource'
autoload :Client, 'mangopay/client'
autoload :User, 'mangopay/user'
autoload :NaturalUser, 'mangopay/natural_user'
autoload :LegalUser, 'mangopay/legal_user'
autoload :PayIn, 'mangopay/pay_in'
autoload :PayOut, 'mangopay/pay_out'
autoload :Transfer, 'mangopay/transfer'
autoload :Transaction, 'mangopay/transaction'
autoload :Wallet, 'mangopay/wallet'
autoload :BankAccount, 'mangopay/bank_account'
autoload :CardRegistration, 'mangopay/card_registration'
autoload :PreAuthorization, 'mangopay/pre_authorization'
autoload :Card, 'mangopay/card'
autoload :Event, 'mangopay/event'
autoload :KycDocument, 'mangopay/kyc_document'
autoload :Hook, 'mangopay/hook'
autoload :Refund, 'mangopay/refund'
autoload :JSON, 'mangopay/json'
autoload :AuthorizationToken, 'mangopay/authorization_token'

class Configuration
attr_accessor :preproduction, :root_url,
:client_id, :client_passphrase,
:temp_dir
:client_id, :client_passphrase,
:temp_dir

def preproduction
@preproduction || false
end

def root_url
@root_url || (@preproduction == true ? "https://api.sandbox.mangopay.com" : "https://api.mangopay.com")
@root_url || (@preproduction == true ? "https://api.sandbox.mangopay.com" : "https://api.mangopay.com")
end
end

class << self
attr_accessor :configuration
end

def self.configure
self.configuration ||= Configuration.new
yield configuration
end

def self.api_uri(url='')
URI(configuration.root_url + url)
end

#
# - +method+: HTTP method; lowercase symbol, e.g. :get, :post etc.
# - +url+: the part after Configuration#root_url
# - +params+: hash; entity data for creation, update etc.; will dump it by JSON and assign to Net::HTTPRequest#body
# - +filters+: hash; pagination params etc.; will encode it by URI and assign to URI#query
# - +headers+: hash; request_headers by default
# - +before_request_proc+: optional proc; will call it passing the Net::HTTPRequest instance just before Net::HTTPRequest#request
#
# Raises MangoPay::ResponseError if response code != 200.
#
def self.request(method, url, params={}, filters={}, headers = request_headers, before_request_proc = nil)
uri = api_uri(url)
uri.query = URI.encode_www_form(filters) unless filters.empty?

res = Net::HTTP.start(uri.host, uri.port, use_ssl: uri.scheme == 'https') do |http|
req = Net::HTTP::const_get(method.capitalize).new(uri.request_uri, headers)
req.body = MangoPay::JSON.dump(params)
before_request_proc.call(req) if before_request_proc
http.request req
def api_path
"/v2/#{MangoPay.configuration.client_id}"
end

# decode json data
begin
data = MangoPay::JSON.load(res.body.nil? ? '' : res.body)
rescue MultiJson::LoadError
data = {}
def configure
self.configuration ||= Configuration.new
yield configuration
end

############### TEMP!!!! #######################################################
#pp method, uri.request_uri, params #, filters, headers
#pp res, data
#puts

if (!(res.is_a? Net::HTTPOK))
ex = MangoPay::ResponseError.new(uri, res.code, data)
############## TEMP!!!! ########################################################
#pp ex, data
raise ex
def api_uri(url='')
URI(configuration.root_url + url)
end

# copy pagination info if any
['x-number-of-pages', 'x-number-of-items'].each { |k|
filters[k.gsub('x-number-of-', 'total_')] = res[k].to_i if res[k]
}

data
end

private
#
# - +method+: HTTP method; lowercase symbol, e.g. :get, :post etc.
# - +url+: the part after Configuration#root_url
# - +params+: hash; entity data for creation, update etc.; will dump it by JSON and assign to Net::HTTPRequest#body
# - +filters+: hash; pagination params etc.; will encode it by URI and assign to URI#query
# - +headers+: hash; request_headers by default
# - +before_request_proc+: optional proc; will call it passing the Net::HTTPRequest instance just before Net::HTTPRequest#request
#
# Raises MangoPay::ResponseError if response code != 200.
#
def request(method, url, params={}, filters={}, headers = request_headers, before_request_proc = nil)
uri = api_uri(url)
uri.query = URI.encode_www_form(filters) unless filters.empty?

res = Net::HTTP.start(uri.host, uri.port, use_ssl: true) do |http|
req = Net::HTTP::const_get(method.capitalize).new(uri.request_uri, headers)
req.body = JSON.dump(params)
before_request_proc.call(req) if before_request_proc
http.request req
end

# decode json data
data = JSON.load(res.body.to_s) rescue {}


unless res.is_a?(Net::HTTPOK)
fail MangoPay::ResponseError.new(uri, res.code, data)
end

# copy pagination info if any
['x-number-of-pages', 'x-number-of-items'].each { |k|
filters[k.gsub('x-number-of-', 'total_')] = res[k].to_i if res[k]
}

data
end

def self.user_agent
@uname ||= get_uname
private

{
bindings_version: MangoPay::VERSION,
lang: 'ruby',
lang_version: "#{RUBY_VERSION} p#{RUBY_PATCHLEVEL} (#{RUBY_RELEASE_DATE})",
platform: RUBY_PLATFORM,
uname: @uname
}
end
def user_agent
{
bindings_version: VERSION,
lang: 'ruby',
lang_version: "#{RUBY_VERSION} p#{RUBY_PATCHLEVEL} (#{RUBY_RELEASE_DATE})",
platform: RUBY_PLATFORM,
uname: get_uname
}
end

def self.get_uname
`uname -a 2>/dev/null`.strip if RUBY_PLATFORM =~ /linux|darwin/i
rescue Errno::ENOMEM
'uname lookup failed'
end
def get_uname
`uname -a 2>/dev/null`.strip if RUBY_PLATFORM =~ /linux|darwin/i
rescue Errno::ENOMEM
'uname lookup failed'
end

def self.request_headers
auth_token = MangoPay::AuthorizationToken::Manager.get_token
headers = {
'user_agent' => "MangoPay V2 RubyBindings/#{MangoPay::VERSION}",
'Authorization' => "#{auth_token['token_type']} #{auth_token['access_token']}",
'Content-Type' => 'application/json'
}
begin
headers.update('x_mangopay_client_user_agent' => MangoPay::JSON.dump(user_agent))
rescue => e
headers.update('x_mangopay_client_raw_user_agent' => user_agent.inspect, error: "#{e} (#{e.class})")
def request_headers
auth_token = AuthorizationToken::Manager.get_token
headers = {
'user_agent' => "MangoPay V2 RubyBindings/#{VERSION}",
'Authorization' => "#{auth_token['token_type']} #{auth_token['access_token']}",
'Content-Type' => 'application/json'
}
begin
headers.update('x_mangopay_client_user_agent' => JSON.dump(user_agent))
rescue => e
headers.update('x_mangopay_client_raw_user_agent' => user_agent.inspect, error: "#{e} (#{e.class})")
end
end

end
end
8 changes: 4 additions & 4 deletions lib/mangopay/bank_account.rb
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
module MangoPay
class BankAccount < Resource
include MangoPay::HTTPCalls::Fetch
include HTTPCalls::Fetch
class << self
def create(user_id, params)
type = params.fetch(:Type) { |no_symbol_key| params.fetch('Type') }
Expand All @@ -15,15 +15,15 @@ def create(user_id, params)
# (+page+, +per_page+; see MangoPay::HTTPCalls::Fetch::ClassMethods#fetch)
#
def fetch(user_id, bank_account_id_or_filters={})
bank_account_id, filters = MangoPay::HTTPCalls::Fetch.parse_id_or_filters(bank_account_id_or_filters)
bank_account_id, filters = HTTPCalls::Fetch.parse_id_or_filters(bank_account_id_or_filters)
MangoPay.request(:get, url(user_id, bank_account_id), {}, filters)
end

def url(user_id, bank_account_id = nil)
if bank_account_id
"/v2/#{MangoPay.configuration.client_id}/users/#{CGI.escape(user_id.to_s)}/bankaccounts/#{CGI.escape(bank_account_id.to_s)}"
"#{MangoPay.api_path}/users/#{CGI.escape(user_id.to_s)}/bankaccounts/#{CGI.escape(bank_account_id.to_s)}"
else
"/v2/#{MangoPay.configuration.client_id}/users/#{CGI.escape(user_id.to_s)}/bankaccounts"
"#{MangoPay.api_path}/users/#{CGI.escape(user_id.to_s)}/bankaccounts"
end
end
end
Expand Down
4 changes: 2 additions & 2 deletions lib/mangopay/card.rb
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
module MangoPay
class Card < Resource
include MangoPay::HTTPCalls::Fetch
include MangoPay::HTTPCalls::Update
include HTTPCalls::Fetch
include HTTPCalls::Update
end
end
6 changes: 3 additions & 3 deletions lib/mangopay/card_registration.rb
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
module MangoPay
class CardRegistration < Resource
include MangoPay::HTTPCalls::Create
include MangoPay::HTTPCalls::Update
include MangoPay::HTTPCalls::Fetch
include HTTPCalls::Create
include HTTPCalls::Update
include HTTPCalls::Fetch
end
end
2 changes: 1 addition & 1 deletion lib/mangopay/client.rb
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ class Client < Resource

def self.create(params)
MangoPay.request(:post, '/api/clients/', params, {}, {
'user_agent' => "MangoPay V2 RubyBindings/#{MangoPay::VERSION}",
'user_agent' => "MangoPay V2 RubyBindings/#{VERSION}",
'Content-Type' => 'application/json'
})
end
Expand Down
6 changes: 3 additions & 3 deletions lib/mangopay/hook.rb
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
module MangoPay
class Hook < Resource
include MangoPay::HTTPCalls::Create
include MangoPay::HTTPCalls::Update
include MangoPay::HTTPCalls::Fetch
include HTTPCalls::Create
include HTTPCalls::Update
include HTTPCalls::Fetch
end
end
2 changes: 1 addition & 1 deletion lib/mangopay/http_calls.rb
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ module ClassMethods
# filter # => {"page"=>2, "per_page"=>3, "total_pages"=>1969, "total_items"=>5905}
#
def fetch(id_or_filters = nil)
id, filters = MangoPay::HTTPCalls::Fetch.parse_id_or_filters(id_or_filters)
id, filters = HTTPCalls::Fetch.parse_id_or_filters(id_or_filters)
response = MangoPay.request(:get, url(id), {}, filters)
end
end
Expand Down
21 changes: 6 additions & 15 deletions lib/mangopay/json.rb
Original file line number Diff line number Diff line change
@@ -1,22 +1,13 @@
# We can use MultiJson directly , why do we even have this module ?
module MangoPay
module JSON
class << self
if MultiJson.respond_to?(:dump)
def dump(*args)
MultiJson.dump(*args)
end

def load(*args)
MultiJson.load(*args)
end
else
def dump(*args)
MultiJson.encode(*args)
end
def dump(*args)
MultiJson.dump(*args)
end

def load(*args)
MultiJson.decode(*args)
end
def load(*args)
MultiJson.load(*args)
end
end
end
Expand Down
6 changes: 3 additions & 3 deletions lib/mangopay/kyc_document.rb
Original file line number Diff line number Diff line change
Expand Up @@ -31,16 +31,16 @@ def create_page(user_id, document_id, file_or_base64)
# normally it returns 204 HTTP code on success
begin
MangoPay.request(:post, url(user_id, document_id) + '/pages', {'File' => base64})
rescue MangoPay::ResponseError => ex
rescue ResponseError => ex
raise ex unless ex.code == '204'
end
end

def url(user_id, document_id = nil)
if document_id
"/v2/#{MangoPay.configuration.client_id}/users/#{CGI.escape(user_id.to_s)}/KYC/documents/#{CGI.escape(document_id.to_s)}"
"#{MangoPay.api_path}/users/#{CGI.escape(user_id.to_s)}/KYC/documents/#{CGI.escape(document_id.to_s)}"
else
"/v2/#{MangoPay.configuration.client_id}/users/#{CGI.escape(user_id.to_s)}/KYC/documents"
"#{MangoPay.api_path}/users/#{CGI.escape(user_id.to_s)}/KYC/documents"
end
end
end
Expand Down
4 changes: 2 additions & 2 deletions lib/mangopay/legal_user.rb
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,9 @@ class LegalUser < User

def self.url(id = nil)
if id
"/v2/#{MangoPay.configuration.client_id}/users/legal/#{CGI.escape(id.to_s)}"
"#{MangoPay.api_path}/users/legal/#{CGI.escape(id.to_s)}"
else
"/v2/#{MangoPay.configuration.client_id}/users/legal"
"#{MangoPay.api_path}/users/legal"
end
end
end
Expand Down
4 changes: 2 additions & 2 deletions lib/mangopay/natural_user.rb
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,9 @@ class NaturalUser < User

def self.url(id = nil)
if id
"/v2/#{MangoPay.configuration.client_id}/users/natural/#{CGI.escape(id.to_s)}"
"#{MangoPay.api_path}/users/natural/#{CGI.escape(id.to_s)}"
else
"/v2/#{MangoPay.configuration.client_id}/users/natural"
"#{MangoPay.api_path}/users/natural"
end
end
end
Expand Down
Loading

0 comments on commit 88583c2

Please sign in to comment.