Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Country support and improvements #1

Merged
merged 7 commits into from
Apr 26, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -58,10 +58,11 @@ This is a 2 step process.
First get the link to redirect the user. This is very easy! Just:

```ruby
redirectUrl = meli.auth_url("http://somecallbackurl")
redirect_url = meli.auth_url("http://somecallbackurl", "AR")
```

This will give you the url to redirect the user. You need to specify a callback url which will be the one that the user will redirected after a successfull authrization process.
This will give you the url to redirect the user. You need to specify a callback url which will be the one that the user will redirected after a successfull authrization process.
The country code param (`"AR"`) is optional, it’s set to `"BR"` by default. Take into account that if you don’t specify this, it will only work if your MercadoLibre app is from Brazil.

Once the user is redirected to your callback url, you'll receive in the query string, a parameter named ```code```. You'll need this for the second part of the process.

Expand Down
21 changes: 0 additions & 21 deletions lib/config.yml

This file was deleted.

17 changes: 17 additions & 0 deletions lib/constants.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
SDK_VERSION = "MELI-RUBY-SDK-1.0.1".freeze
API_ROOT_URL = "https://api.mercadolibre.com".freeze
OAUTH_URL = "/oauth/token".freeze

AUTH_URL_AR = "https://auth.mercadolibre.com.ar/authorization".freeze
AUTH_URL_BR = "https://auth.mercadolivre.com.br/authorization".freeze
AUTH_URL_CO = "https://auth.mercadolibre.com.co/authorization".freeze
AUTH_URL_CR = "https://auth.mercadolibre.com.cr/authorization".freeze
AUTH_URL_EC = "https://auth.mercadolibre.com.ec/authorization".freeze
AUTH_URL_CL = "https://auth.mercadolibre.cl/authorization".freeze
AUTH_URL_MX = "https://auth.mercadolibre.com.mx/authorization".freeze
AUTH_URL_UY = "https://auth.mercadolibre.com.uy/authorization".freeze
AUTH_URL_VE = "https://auth.mercadolibre.com.ve/authorization".freeze
AUTH_URL_PA = "https://auth.mercadolibre.com.pa/authorization".freeze
AUTH_URL_PE = "https://auth.mercadolibre.com.pe/authorization".freeze
AUTH_URL_PT = "https://auth.mercadolibre.com.pt/authorization".freeze
AUTH_URL_DO = "https://auth.mercadolibre.com.do/authorization".freeze
272 changes: 135 additions & 137 deletions lib/meli.rb
Original file line number Diff line number Diff line change
Expand Up @@ -5,157 +5,155 @@
require 'net/https'
require 'json'
require 'uri'
require 'yaml'
require 'constants'

class Meli
attr_accessor :access_token, :refresh_token
attr_reader :secret, :app_id, :https

config = YAML.load_file(File.expand_path(File.dirname(__FILE__) + "/config.yml"))
SDK_VERSION = config["config"]["sdk_version"]
API_ROOT_URL = config["config"]["api_root_url"]
AUTH_URL = config["config"]["auth_url"]
OAUTH_URL = config["config"]["oauth_url"]

#constructor
def initialize(app_id = nil, secret = nil, access_token = nil, refresh_token = nil)
@access_token = access_token
@refresh_token = refresh_token
@app_id = app_id
@secret = secret
api_url = URI.parse API_ROOT_URL
@https = Net::HTTP.new(api_url.host, api_url.port)
@https.use_ssl = true
@https.verify_mode = OpenSSL::SSL::VERIFY_PEER
@https.ssl_version = :TLSv1
end

#AUTH METHODS
def auth_url(redirect_URI)
params = {:client_id => @app_id, :response_type => 'code', :redirect_uri => redirect_URI}
url = "#{AUTH_URL}?#{to_url_params(params)}"
end

def authorize(code, redirect_URI)
params = { :grant_type => 'authorization_code', :client_id => @app_id, :client_secret => @secret, :code => code, :redirect_uri => redirect_URI}

uri = make_path(OAUTH_URL, params)

req = Net::HTTP::Post.new(uri.path)
req['Accept'] = 'application/json'
req['User-Agent'] = SDK_VERSION
req['Content-Type'] = "application/x-www-form-urlencoded"
req.set_form_data(params)
response = @https.request(req)

case response
when Net::HTTPSuccess
response_info = JSON.parse response.body
#convert hash keys to symbol
response_info = Hash[response_info.map{ |k, v| [k.to_sym, v] }]

@access_token = response_info[:access_token]
if response_info.has_key?(:refresh_token)
@refresh_token = response_info[:refresh_token]
else
@refresh_token = '' # offline_access not set up
end
@access_token
else
# response code isn't a 200; raise an exception
response.error!
end

end

def get_refresh_token()
if !@refresh_token.nil? and !@refresh_token.empty?
params = {:grant_type => 'refresh_token', :client_id => @app_id, :client_secret => @secret, :refresh_token => @refresh_token}

uri = make_path(OAUTH_URL, params)

req = Net::HTTP::Post.new(uri.path)
req['Accept'] = 'application/json'
req['User-Agent'] = SDK_VERSION
req['Content-Type'] = "application/x-www-form-urlencoded"
req.set_form_data(params)
response = @https.request(req)

case response
when Net::HTTPSuccess
response_info = JSON.parse response.body

#convert hash keys to symbol
response_info = Hash[response_info.map{ |k, v| [k.to_sym, v] }]

@access_token = response_info[:access_token]
@refresh_token = response_info[:refresh_token]
else
# response code isn't a 200; raise an exception
response.error!
end
else
raise "Offline-Access is not allowed."
end
attr_accessor :access_token, :refresh_token
attr_reader :secret, :app_id, :https

#constructor
def initialize(app_id = nil, secret = nil, access_token = nil, refresh_token = nil)
@access_token = access_token
@refresh_token = refresh_token
@app_id = app_id
@secret = secret
api_url = URI.parse API_ROOT_URL
@https = Net::HTTP.new(api_url.host, api_url.port)
@https.use_ssl = true
@https.verify_mode = OpenSSL::SSL::VERIFY_PEER
@https.ssl_version = :TLSv1
end

def self.auth_url_country(iso_country_code)
const_get "AUTH_URL_#{iso_country_code}"
end

#AUTH METHODS
def auth_url(redirect_URI, iso_country_code = "BR")
params = {:client_id => @app_id, :response_type => 'code', :redirect_uri => redirect_URI}
url = "#{Meli.auth_url_country(iso_country_code)}?#{to_url_params(params)}"
end

def authorize(code, redirect_URI)
params = { :grant_type => 'authorization_code', :client_id => @app_id, :client_secret => @secret, :code => code, :redirect_uri => redirect_URI}

uri = make_path(OAUTH_URL, params)

req = Net::HTTP::Post.new(uri.path)
req['Accept'] = 'application/json'
req['User-Agent'] = SDK_VERSION
req['Content-Type'] = "application/x-www-form-urlencoded"
req.set_form_data(params)
response = @https.request(req)

case response
when Net::HTTPSuccess
response_info = JSON.parse response.body
#convert hash keys to symbol
response_info = Hash[response_info.map{ |k, v| [k.to_sym, v] }]

@access_token = response_info[:access_token]
if response_info.has_key?(:refresh_token)
@refresh_token = response_info[:refresh_token]
else
@refresh_token = '' # offline_access not set up
end
@access_token
else
# response code isn't a 200; raise an exception
response.error!
end

end

#REQUEST METHODS
def execute(req)
req['Accept'] = 'application/json'
req['User-Agent'] = SDK_VERSION
req['Content-Type'] = 'application/json'
response = @https.request(req)
end
def get_refresh_token()
if !@refresh_token.nil? and !@refresh_token.empty?
params = {:grant_type => 'refresh_token', :client_id => @app_id, :client_secret => @secret, :refresh_token => @refresh_token}

def get(path, params = {})
uri = make_path(path, params)
req = Net::HTTP::Get.new("#{uri.path}?#{uri.query}")
execute req
end
uri = make_path(OAUTH_URL, params)

def post(path, body, params = {})
uri = make_path(path, params)
req = Net::HTTP::Post.new("#{uri.path}?#{uri.query}")
req.set_form_data(params)
req.body = body.to_json unless body.nil?
execute req
end
req = Net::HTTP::Post.new(uri.path)
req['Accept'] = 'application/json'
req['User-Agent'] = SDK_VERSION
req['Content-Type'] = "application/x-www-form-urlencoded"
req.set_form_data(params)
response = @https.request(req)

def put(path, body, params = {})
uri = make_path(path, params)
req = Net::HTTP::Put.new("#{uri.path}?#{uri.query}")
req.set_form_data(params)
req.body = body.to_json unless body.nil?
execute req
end
case response
when Net::HTTPSuccess
response_info = JSON.parse response.body

def delete(path, params = {})
uri = make_path(path, params)
req = Net::HTTP::Delete.new("#{uri.path}?#{uri.query}")
execute req
end
#convert hash keys to symbol
response_info = Hash[response_info.map{ |k, v| [k.to_sym, v] }]

def options(path, params = {})
uri = make_path(path, params)
req = Net::HTTP::Options.new("#{uri.path}?#{uri.query}")
execute req
@access_token = response_info[:access_token]
@refresh_token = response_info[:refresh_token]
else
# response code isn't a 200; raise an exception
response.error!
end
else
raise "Offline-Access is not allowed."
end
end


#REQUEST METHODS
def execute(req)
req['Accept'] = 'application/json'
req['User-Agent'] = SDK_VERSION
req['Content-Type'] = 'application/json'
response = @https.request(req)
end

def get(path, params = {})
uri = make_path(path, params)
req = Net::HTTP::Get.new("#{uri.path}?#{uri.query}")
execute req
end

def post(path, body, params = {})
uri = make_path(path, params)
req = Net::HTTP::Post.new("#{uri.path}?#{uri.query}")
req.set_form_data(params)
req.body = body.to_json unless body.nil?
execute req
end

def put(path, body, params = {})
uri = make_path(path, params)
req = Net::HTTP::Put.new("#{uri.path}?#{uri.query}")
req.set_form_data(params)
req.body = body.to_json unless body.nil?
execute req
end

def delete(path, params = {})
uri = make_path(path, params)
req = Net::HTTP::Delete.new("#{uri.path}?#{uri.query}")
execute req
end

def options(path, params = {})
uri = make_path(path, params)
req = Net::HTTP::Options.new("#{uri.path}?#{uri.query}")
execute req
end

private
def to_url_params(params)
URI.escape(params.collect{|k,v| "#{k}=#{v}"}.join('&'))
end

def make_path(path, params = {})
# Making Path and add a leading / if not exist
unless path =~ /^http/
path = "/#{path}" unless path =~ /^\//
path = "#{API_ROOT_URL}#{path}"
end
path = "#{path}?#{to_url_params(params)}" if params.keys.size > 0
uri = URI.parse path
def to_url_params(params)
URI.escape(params.collect{|k,v| "#{k}=#{v}"}.join('&'))
end

def make_path(path, params = {})
# Making Path and add a leading / if not exist
unless path =~ /^http/
path = "/#{path}" unless path =~ /^\//
path = "#{API_ROOT_URL}#{path}"
end
path = "#{path}?#{to_url_params(params)}" if params.keys.size > 0
uri = URI.parse path
end


end #class
4 changes: 3 additions & 1 deletion meli.gemspec
Original file line number Diff line number Diff line change
Expand Up @@ -19,11 +19,13 @@ Gem::Specification.new do |spec|
spec.homepage = "http://developers.mercadolibre.com"
spec.license = "MIT"

spec.files = `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) }
spec.files = `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features|examples)/}) }
spec.bindir = "exe"
spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
spec.require_paths = ["lib"]

spec.add_development_dependency "bundler", "~> 1.8"
spec.add_development_dependency "rake", "~> 10.0"
spec.add_development_dependency "rspec", "~> 2.99.0"
spec.add_development_dependency "json", "~> 1.8"
end
Loading