locaweb-gateway 0.1.6

Sign up to get free protection for your applications and to get access to all the features.
data/Gemfile ADDED
@@ -0,0 +1,4 @@
1
+ source "http://rubygems.org"
2
+
3
+ # Specify your gem's dependencies in locaweb-gateway.gemspec
4
+ gemspec
data/LICENSE ADDED
@@ -0,0 +1,7 @@
1
+ Copyright (C) 2012 LOCAWEB SERVIÇOS DE INTERNET S.A.
2
+
3
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
4
+
5
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
6
+
7
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
@@ -0,0 +1,49 @@
1
+ # Locaweb Gateway
2
+
3
+ ## Install
4
+
5
+ gem install locaweb-gateway
6
+
7
+ ## Usage
8
+
9
+ Locaweb::Gateway.configure do |config|
10
+ config.token = '3a5bbed0-50d4-012f-8d73-0026bb5a6240'
11
+ config.environment = 'sandbox' # se não for passado irá utilizar production por default.
12
+ end
13
+
14
+ transaction = Locaweb::Gateway.criar(
15
+ :url_retorno => 'http://foo.com/url_retorno',
16
+ :capturar => true,
17
+ :pedido => {
18
+ :numero => "989012",
19
+ :total => "100.00",
20
+ :moeda => :real,
21
+ :descricao => "cylon toaster!"
22
+ },
23
+ :pagamento => {
24
+ :meio_pagamento => :cielo,
25
+ :bandeira => :visa,
26
+ :numero_cartao => "4012001037141112",
27
+ :cartao_codigo_verificacao => "973",
28
+ :parcelas => "1",
29
+ :tipo_operacao => "credito_a_vista",
30
+ :vencimento_cartao => "082015"
31
+ },
32
+ :comprador => {
33
+ :nome => "Bruna da Silva",
34
+ :documento => "12345678900",
35
+ :endereco => "Rua da Casa",
36
+ :numero => "23",
37
+ :cep => "09710240",
38
+ :bairro => "Centro",
39
+ :cidade => "São Paulo",
40
+ :estado => "SP"
41
+ }
42
+ )
43
+ Locaweb::Gateway.consultar(transaction.id)
44
+ Locaweb::Gateway.cancelar(transaction.id)
45
+ Locaweb::Gateway.capturar(transaction.id)
46
+
47
+ ## Docs
48
+
49
+ [Documentação do Gateway de Pagamentos Locaweb](http://docs.gatewaylocaweb.com.br)
@@ -0,0 +1 @@
1
+ require "bundler/gem_tasks"
@@ -0,0 +1,19 @@
1
+ require 'rest-client'
2
+ require 'active_support/core_ext/class'
3
+ require 'active_support/core_ext/object'
4
+ require 'ostruct'
5
+ require 'locaweb-gateway/actions'
6
+ require 'locaweb-gateway/config'
7
+ require 'locaweb-gateway/transaction'
8
+ require 'locaweb-gateway/request'
9
+ require 'locaweb-gateway/response'
10
+
11
+ module Locaweb
12
+ module Gateway
13
+ extend Locaweb::Gateway::Actions
14
+
15
+ def self.configure(&block)
16
+ Locaweb::Gateway::Config.configure(&block)
17
+ end
18
+ end
19
+ end
@@ -0,0 +1,34 @@
1
+ module Locaweb
2
+ module Gateway
3
+ module Actions
4
+ def create(params)
5
+ request = ::Locaweb::Gateway::Request.new(:action => "/")
6
+ Response.new(request.post(gateway_params(params))).parse
7
+ end
8
+ alias :criar :create
9
+
10
+ def cancel(id)
11
+ request = ::Locaweb::Gateway::Request.new(:action => "/#{id}/estornar")
12
+ Response.new(request.post(gateway_params)).parse
13
+ end
14
+ alias :cancelar :cancel
15
+
16
+ def capture(id)
17
+ request = ::Locaweb::Gateway::Request.new(:action => "/#{id}/capturar")
18
+ Response.new(request.post(gateway_params)).parse
19
+ end
20
+ alias :capturar :capture
21
+
22
+ def show(id)
23
+ request = ::Locaweb::Gateway::Request.new(:action => "/#{id}")
24
+ Response.new(request.get(gateway_params)).parse
25
+ end
26
+ alias :consultar :show
27
+
28
+ def gateway_params(params={})
29
+ attributes = params.empty? ? {} : { :transacao => params }
30
+ attributes.merge(:token => Locaweb::Gateway::Config.token)
31
+ end
32
+ end
33
+ end
34
+ end
@@ -0,0 +1,36 @@
1
+ module Locaweb
2
+ module Gateway
3
+ class Config
4
+ # The class variable that represents the user token.
5
+ #
6
+ cattr_accessor :token
7
+ self.token = ''
8
+
9
+ # The class variable that represents the environment that the transaction will be processed
10
+ # <b>OBS.:</b>: Defaults to production
11
+ #
12
+ cattr_accessor :environment
13
+ self.environment = :production
14
+
15
+ # TODO: put ssl and the request object should read from this.
16
+ #
17
+ # cattr_accessor :ssl, :ssl_client_cert, :ssl_client_key, :ssl_ca_file
18
+ # self.ssl = false
19
+ #
20
+
21
+ # Returns the base endpoint for the Locaweb Payment Gateway.
22
+ #
23
+ def self.base_uri
24
+ if environment.equal?(:production)
25
+ 'https://api.gatewaylocaweb.com.br/v1/transacao'
26
+ else
27
+ 'https://api-sandbox.gatewaylocaweb.com.br/v1/transacao'
28
+ end
29
+ end
30
+
31
+ def self.configure(&block)
32
+ block.call(self)
33
+ end
34
+ end
35
+ end
36
+ end
@@ -0,0 +1,35 @@
1
+ module Locaweb
2
+ module Gateway
3
+ class Request
4
+ attr_reader :engine, :action
5
+ delegate :base_uri, :to => Locaweb::Gateway::Config
6
+
7
+ def initialize(options={})
8
+ @action = options[:action]
9
+ @engine = RestClient
10
+ end
11
+
12
+ def request_uri
13
+ "#{base_uri}#{action}"
14
+ end
15
+
16
+ def post(params)
17
+ http_request(:method => :post, :params => params.to_json)
18
+ end
19
+
20
+ def get(params)
21
+ http_request(:method => :get, :params => { :params => params })
22
+ end
23
+
24
+ private
25
+
26
+ def http_request(options={})
27
+ response = begin
28
+ engine.send(options[:method], request_uri, options[:params])
29
+ rescue RestClient::Exception => bad_request
30
+ OpenStruct.new(:body => bad_request.http_body, :to_i => bad_request.http_code)
31
+ end
32
+ end
33
+ end
34
+ end
35
+ end
@@ -0,0 +1,32 @@
1
+ module Locaweb
2
+ module Gateway
3
+ class Response
4
+ attr_reader :raw_response, :body, :http_status
5
+
6
+ def initialize(raw_response)
7
+ @raw_response = raw_response
8
+ @body = JSON.parse(raw_response.body.to_s)
9
+ @http_status = raw_response.to_i
10
+ end
11
+
12
+ def parse
13
+ transaction = Locaweb::Gateway::Transaction.new
14
+ transaction.response = self
15
+ transaction_node = @body['transacao'] || {}
16
+ error_node = transaction_node['erro'] || {}
17
+
18
+ transaction.id = transaction_node['id']
19
+ transaction.status = transaction_node['status']
20
+ transaction.url_acesso = transaction_node['url_acesso']
21
+ transaction.meio_pagamento = transaction_node['meio_pagamento']
22
+ transaction.numero_pedido = transaction_node['numero_pedido']
23
+ transaction.detalhes = transaction_node['detalhes']
24
+ transaction.erro = error_node.symbolize_keys
25
+ transaction.erro_codigo = error_node['codigo']
26
+ transaction.erro_mensagem = error_node['mensagem']
27
+
28
+ transaction
29
+ end
30
+ end
31
+ end
32
+ end
@@ -0,0 +1,16 @@
1
+ require 'locaweb-gateway/actions'
2
+
3
+ module Locaweb
4
+ module Gateway
5
+ class Transaction
6
+ extend ::Locaweb::Gateway::Actions
7
+
8
+ attr_accessor :response, :id, :status, :url_acesso, :meio_pagamento, :numero_pedido, :detalhes
9
+ attr_accessor :erro, :erro_codigo, :erro_mensagem
10
+
11
+ def initialize
12
+ @detalhes = {}
13
+ end
14
+ end
15
+ end
16
+ end
@@ -0,0 +1,5 @@
1
+ module Locaweb
2
+ module Gateway
3
+ VERSION = "0.1.6"
4
+ end
5
+ end
@@ -0,0 +1 @@
1
+ require 'locaweb-gateway'
@@ -0,0 +1,26 @@
1
+ # -*- encoding: utf-8 -*-
2
+ $:.push File.expand_path("../lib", __FILE__)
3
+ require "locaweb-gateway/version"
4
+
5
+ Gem::Specification.new do |s|
6
+ s.name = "locaweb-gateway"
7
+ s.version = Locaweb::Gateway::VERSION
8
+ s.authors = ["Locaweb - Saas"]
9
+ s.email = ["atendimento@locaweb.com.br"]
10
+ s.homepage = "http://github.com/locaweb/locaweb-gateway-ruby"
11
+ s.summary = %q{Locaweb Payment Gateway Gem}
12
+ s.description = %q{This gem was designed to help you to access the locaweb payment gateway.}
13
+
14
+ s.rubyforge_project = "locaweb-gateway"
15
+
16
+ s.files = `git ls-files`.split("\n")
17
+ s.test_files = `git ls-files -- {test,spec,features}/*`.split("\n")
18
+ s.executables = `git ls-files -- bin/*`.split("\n").map{ |f| File.basename(f) }
19
+ s.require_paths = ["lib"]
20
+
21
+ s.add_dependency 'rest-client'
22
+ s.add_dependency 'activesupport'
23
+ s.add_dependency 'json'
24
+
25
+ s.add_development_dependency 'rspec'
26
+ end
@@ -0,0 +1,31 @@
1
+ require 'spec_helper'
2
+
3
+ module Locaweb
4
+ module Gateway
5
+ describe Config do
6
+ describe ".token" do
7
+ it "should return an empty string if dont pass a token" do
8
+ Config.token.should == ''
9
+ end
10
+ end
11
+
12
+ describe ".environment" do
13
+ it "should have production as default" do
14
+ Config.environment.should be :production
15
+ end
16
+ end
17
+
18
+ describe ".base_uri" do
19
+ it "should return the production base uri" do
20
+ Config.stub(:environment).and_return(:production)
21
+ Config.base_uri.should == 'https://api.gatewaylocaweb.com.br/v1/transacao'
22
+ end
23
+
24
+ it "should return the sandbox base uri" do
25
+ Config.stub(:environment).and_return(:sandbox)
26
+ Config.base_uri.should == 'https://api-sandbox.gatewaylocaweb.com.br/v1/transacao'
27
+ end
28
+ end
29
+ end
30
+ end
31
+ end
@@ -0,0 +1,54 @@
1
+ require 'spec_helper'
2
+
3
+ module Locaweb
4
+ module Gateway
5
+ describe Request do
6
+ subject { Request.new(:action => '/') }
7
+
8
+ describe "#action" do
9
+ it "should read the action instance variable" do
10
+ subject.action.should == '/'
11
+ end
12
+ end
13
+
14
+ describe "#request_uri" do
15
+ subject { Request.new(:action => '/foo') }
16
+
17
+ it "should join the base endpoint with the requested action" do
18
+ subject.stub(:base_uri).and_return('https://api.gatewaylocaweb.com.br/v1/transacao')
19
+ subject.request_uri.should == 'https://api.gatewaylocaweb.com.br/v1/transacao/foo'
20
+ end
21
+ end
22
+
23
+ describe "#engine" do
24
+ it "should have RestClient as default" do
25
+ subject.engine.should be RestClient
26
+ end
27
+ end
28
+
29
+ describe "#post" do
30
+ it "should pass post to the base endpoint and return the response" do
31
+ subject.engine.should_receive(:post).with(subject.request_uri, "{\"foo\":\"bar\"}").and_return(invalid_credentials)
32
+ subject.post(:foo => :bar)
33
+ end
34
+
35
+ it "should not raise an exception when rest raise exception" do
36
+ subject.engine.should_receive(:post).and_raise(RestClient::ResourceNotFound)
37
+ expect { subject.post(:foo => :bar) }.to_not raise_error
38
+ end
39
+ end
40
+
41
+ describe "#get" do
42
+ it "should pass the get to the engine and return an response" do
43
+ subject.engine.should_receive(:get).with(subject.request_uri, { :params => { :foo => :bar }}).and_return(invalid_credentials)
44
+ subject.get(:foo => :bar)
45
+ end
46
+
47
+ it "should not raise an exception when the engine raise exception" do
48
+ subject.engine.should_receive(:get).and_raise(RestClient::ResourceNotFound)
49
+ expect { subject.get(:foo => :bar) }.to_not raise_error
50
+ end
51
+ end
52
+ end
53
+ end
54
+ end
@@ -0,0 +1,59 @@
1
+ # encoding: utf-8
2
+ require 'spec_helper'
3
+
4
+ module Locaweb
5
+ module Gateway
6
+ describe Response do
7
+ describe "#parse" do
8
+ context 'on invalid credentital' do
9
+ subject { Response.new(ResponseFixture.new(:body => invalid_credentials, :status => 403)) }
10
+
11
+ it "should parse the transaction in error node with code and message" do
12
+ transaction = subject.parse
13
+ transaction.erro.should == { :codigo => '001', :mensagem => 'Credenciais inválidas' }
14
+ transaction.erro_codigo.should == '001'
15
+ transaction.erro_mensagem.should == 'Credenciais inválidas'
16
+ end
17
+ end
18
+
19
+ context 'on transaction not found' do
20
+ subject { Response.new(ResponseFixture.new(:body => transaction_not_found, :status => 404))}
21
+
22
+ it "should parse the transaction in error node with code and message" do
23
+ transaction = subject.parse
24
+ transaction.erro.should == { :codigo => '006', :mensagem => 'Recurso não encontrado' }
25
+ transaction.erro_codigo.should == '006'
26
+ transaction.erro_mensagem.should == 'Recurso não encontrado'
27
+ end
28
+ end
29
+
30
+ context 'on cielo success response' do
31
+ subject { Response.new(ResponseFixture.new(:body => cielo_success_response, :status => 201))}
32
+
33
+ it "should parse the transaction and return the id, status, url_acesso and meio_pagamento" do
34
+ transaction = subject.parse
35
+ transaction.id.should == '152'
36
+ transaction.status.should == 'pago'
37
+ transaction.url_acesso.should == 'http://api.gatewaylocaweb.com.br/v1/transacao/foobar'
38
+ transaction.meio_pagamento.should == 'cielo'
39
+ transaction.numero_pedido.should == '876'
40
+ transaction.detalhes.should == { "tid" => "10017", "nsu" => "998877", "pan" => "887766", "arp" => "776655", "lr" => nil }
41
+ end
42
+ end
43
+
44
+ context 'on itau shopline success response' do
45
+ subject { Response.new(ResponseFixture.new(:body => itau_shopline_success_response, :status => 201))}
46
+
47
+ it "should parse the transaction and return the id, status, meio_pagamento, url_acesso and detalhes" do
48
+ transaction = subject.parse
49
+ transaction.id.should == '159'
50
+ transaction.status.should == 'aguardando pagamento'
51
+ transaction.url_acesso.should == 'https://api-gateway.devintegration.locaweb.com.br/v1/itau_shopline/fd350d45-0b26-4dcf-8455-3f755bd71826'
52
+ transaction.numero_pedido.should == '654'
53
+ transaction.detalhes.should == { "nsu" => nil, "tipo_pagamento" => nil, "data_pagamento" => nil, "numero_autorizacao" => nil, "tipo_cartao" => nil }
54
+ end
55
+ end
56
+ end
57
+ end
58
+ end
59
+ end
@@ -0,0 +1,6 @@
1
+ require 'spec_helper'
2
+
3
+ module Locaweb
4
+ describe Gateway do
5
+ end
6
+ end
@@ -0,0 +1,7 @@
1
+ require "locaweb-gateway"
2
+
3
+ Dir['spec/support/*.rb'].each { |file| require File.expand_path(file) }
4
+
5
+ RSpec.configure do |config|
6
+ config.include GatewayJSONResponse
7
+ end
@@ -0,0 +1,54 @@
1
+ # encoding: utf-8
2
+ module GatewayJSONResponse
3
+ def invalid_credentials
4
+ "{\"transacao\":{\"erro\":{\"codigo\":\"001\",\"mensagem\":\"Credenciais inválidas\"}}}"
5
+ end
6
+
7
+ def transaction_not_found
8
+ "{\"transacao\":{\"erro\":{\"codigo\":\"006\",\"mensagem\":\"Recurso não encontrado\"}}}"
9
+ end
10
+
11
+ def payment_way_not_valid
12
+ "{\"transacao\":{\"erro\":{\"codigo\":\"004\",\"mensagem\":\"Meio de pagamento não é válido\"}}}"
13
+ end
14
+
15
+ def cielo_success_response
16
+ {
17
+ "transacao" => {
18
+ "id" => "152",
19
+ "status" => "pago",
20
+ "url_acesso" => "http://api.gatewaylocaweb.com.br/v1/transacao/foobar",
21
+ "meio_pagamento" => "cielo",
22
+ "numero_pedido" => "876",
23
+ "erro" => nil,
24
+ "detalhes" => {
25
+ "tid" => "10017",
26
+ "nsu" => "998877",
27
+ "pan" => "887766",
28
+ "arp" => "776655",
29
+ "lr" => nil
30
+ }
31
+ }
32
+ }.to_json
33
+ end
34
+
35
+ def itau_shopline_success_response
36
+ {
37
+ "transacao" => {
38
+ "id" => "159",
39
+ "status" => "aguardando pagamento",
40
+ "meio_pagamento" => "itau_shopline",
41
+ "numero_pedido" => "654",
42
+ "url_acesso" => "https://api-gateway.devintegration.locaweb.com.br/v1/itau_shopline/fd350d45-0b26-4dcf-8455-3f755bd71826",
43
+ "erro" => nil,
44
+ "detalhes" => {
45
+ "nsu" => nil,
46
+ "tipo_pagamento" => nil,
47
+ "data_pagamento" => nil,
48
+ "numero_autorizacao" => nil,
49
+ "tipo_cartao" => nil
50
+ }
51
+ }
52
+ }.to_json
53
+ end
54
+ end
@@ -0,0 +1,9 @@
1
+ class ResponseFixture
2
+ attr_reader :body, :to_i, :headers
3
+
4
+ def initialize(options={})
5
+ @body = options[:body]
6
+ @to_i = options[:status] # RestClient Response Status code is #to_i :S
7
+ @headers = []
8
+ end
9
+ end
metadata ADDED
@@ -0,0 +1,132 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: locaweb-gateway
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.6
5
+ prerelease:
6
+ platform: ruby
7
+ authors:
8
+ - Locaweb - Saas
9
+ autorequire:
10
+ bindir: bin
11
+ cert_chain: []
12
+ date: 2012-05-21 00:00:00.000000000 Z
13
+ dependencies:
14
+ - !ruby/object:Gem::Dependency
15
+ name: rest-client
16
+ requirement: !ruby/object:Gem::Requirement
17
+ none: false
18
+ requirements:
19
+ - - ! '>='
20
+ - !ruby/object:Gem::Version
21
+ version: '0'
22
+ type: :runtime
23
+ prerelease: false
24
+ version_requirements: !ruby/object:Gem::Requirement
25
+ none: false
26
+ requirements:
27
+ - - ! '>='
28
+ - !ruby/object:Gem::Version
29
+ version: '0'
30
+ - !ruby/object:Gem::Dependency
31
+ name: activesupport
32
+ requirement: !ruby/object:Gem::Requirement
33
+ none: false
34
+ requirements:
35
+ - - ! '>='
36
+ - !ruby/object:Gem::Version
37
+ version: '0'
38
+ type: :runtime
39
+ prerelease: false
40
+ version_requirements: !ruby/object:Gem::Requirement
41
+ none: false
42
+ requirements:
43
+ - - ! '>='
44
+ - !ruby/object:Gem::Version
45
+ version: '0'
46
+ - !ruby/object:Gem::Dependency
47
+ name: json
48
+ requirement: !ruby/object:Gem::Requirement
49
+ none: false
50
+ requirements:
51
+ - - ! '>='
52
+ - !ruby/object:Gem::Version
53
+ version: '0'
54
+ type: :runtime
55
+ prerelease: false
56
+ version_requirements: !ruby/object:Gem::Requirement
57
+ none: false
58
+ requirements:
59
+ - - ! '>='
60
+ - !ruby/object:Gem::Version
61
+ version: '0'
62
+ - !ruby/object:Gem::Dependency
63
+ name: rspec
64
+ requirement: !ruby/object:Gem::Requirement
65
+ none: false
66
+ requirements:
67
+ - - ! '>='
68
+ - !ruby/object:Gem::Version
69
+ version: '0'
70
+ type: :development
71
+ prerelease: false
72
+ version_requirements: !ruby/object:Gem::Requirement
73
+ none: false
74
+ requirements:
75
+ - - ! '>='
76
+ - !ruby/object:Gem::Version
77
+ version: '0'
78
+ description: This gem was designed to help you to access the locaweb payment gateway.
79
+ email:
80
+ - atendimento@locaweb.com.br
81
+ executables: []
82
+ extensions: []
83
+ extra_rdoc_files: []
84
+ files:
85
+ - Gemfile
86
+ - LICENSE
87
+ - README.md
88
+ - Rakefile
89
+ - builds/locaweb-gateway-0.1.0.gem
90
+ - builds/locaweb-gateway-0.1.1.gem
91
+ - builds/locaweb-gateway-0.1.4.gem
92
+ - lib/locaweb-gateway.rb
93
+ - lib/locaweb-gateway/actions.rb
94
+ - lib/locaweb-gateway/config.rb
95
+ - lib/locaweb-gateway/request.rb
96
+ - lib/locaweb-gateway/response.rb
97
+ - lib/locaweb-gateway/transaction.rb
98
+ - lib/locaweb-gateway/version.rb
99
+ - lib/locaweb_gateway.rb
100
+ - locaweb-gateway.gemspec
101
+ - spec/locaweb-gateway/config_spec.rb
102
+ - spec/locaweb-gateway/request_spec.rb
103
+ - spec/locaweb-gateway/response_spec.rb
104
+ - spec/locaweb-gateway_spec.rb
105
+ - spec/spec_helper.rb
106
+ - spec/support/gateway_json_response.rb
107
+ - spec/support/response_fixture.rb
108
+ homepage: http://github.com/locaweb/locaweb-gateway-ruby
109
+ licenses: []
110
+ post_install_message:
111
+ rdoc_options: []
112
+ require_paths:
113
+ - lib
114
+ required_ruby_version: !ruby/object:Gem::Requirement
115
+ none: false
116
+ requirements:
117
+ - - ! '>='
118
+ - !ruby/object:Gem::Version
119
+ version: '0'
120
+ required_rubygems_version: !ruby/object:Gem::Requirement
121
+ none: false
122
+ requirements:
123
+ - - ! '>='
124
+ - !ruby/object:Gem::Version
125
+ version: '0'
126
+ requirements: []
127
+ rubyforge_project: locaweb-gateway
128
+ rubygems_version: 1.8.24
129
+ signing_key:
130
+ specification_version: 3
131
+ summary: Locaweb Payment Gateway Gem
132
+ test_files: []