getnet_api 0.1.1

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.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA1:
3
+ metadata.gz: 5aab4ff1ccb3f001c28e65c81e62dd72fa8baa7c
4
+ data.tar.gz: b7bba3dd819473f70285ed51a13ba71bb2e23ed0
5
+ SHA512:
6
+ metadata.gz: aaff9d29f48ccdfd366be7f611a24dff5d693a87eee4f3088309f7633f2ccba1f24e9be6ea7832324a4d86aa7c89027ac646cca5884e9088ef8d76474463bfa3
7
+ data.tar.gz: 8d63931e1fa248e26883488300c54d62838ef7647d11cfa4c1012ca32bbef14dc4b52fcd2d1fb3046e23be4cce2fbddc88c6c9131d2f571e72db94de2cc445fc
data/.gitignore ADDED
@@ -0,0 +1,53 @@
1
+ *.gem
2
+ *.rbc
3
+ /.config
4
+ /coverage/
5
+ /InstalledFiles
6
+ /pkg/
7
+ /spec/reports/
8
+ /spec/examples.txt
9
+ /test/tmp/
10
+ /test/version_tmp/
11
+ /tmp/
12
+
13
+ # Used by dotenv library to load environment variables.
14
+ # .env
15
+
16
+ ## Specific to RubyMotion:
17
+ .dat*
18
+ .repl_history
19
+ build/
20
+ *.bridgesupport
21
+ build-iPhoneOS/
22
+ build-iPhoneSimulator/
23
+
24
+ ## Specific to RubyMotion (use of CocoaPods):
25
+ #
26
+ # We recommend against adding the Pods directory to your .gitignore. However
27
+ # you should judge for yourself, the pros and cons are mentioned at:
28
+ # https://guides.cocoapods.org/using/using-cocoapods.html#should-i-check-the-pods-directory-into-source-control
29
+ #
30
+ # vendor/Pods/
31
+
32
+ ## Documentation cache and generated files:
33
+ /.yardoc/
34
+ /_yardoc/
35
+ /doc/
36
+ /rdoc/
37
+
38
+ ## Environment normalization:
39
+ /.bundle/
40
+ /vendor/bundle
41
+ /lib/bundler/man/
42
+
43
+ # for a library or gem, you might want to ignore these files since the code is
44
+ # intended to run in multiple environments; otherwise, check them in:
45
+ # Gemfile.lock
46
+ # .ruby-version
47
+ # .ruby-gemset
48
+
49
+ # unless supporting rvm < 1.11.0 or doing something fancy, ignore this:
50
+ .rvmrc
51
+
52
+
53
+ to_do
data/Gemfile ADDED
@@ -0,0 +1,2 @@
1
+ source "https://rubygems.org"
2
+ gemspec
data/Gemfile.lock ADDED
@@ -0,0 +1,33 @@
1
+ PATH
2
+ remote: .
3
+ specs:
4
+ getnet_api (0.1.0)
5
+ rest-client
6
+
7
+ GEM
8
+ remote: https://rubygems.org/
9
+ specs:
10
+ domain_name (0.5.20180417)
11
+ unf (>= 0.0.5, < 1.0.0)
12
+ http-cookie (1.0.3)
13
+ domain_name (~> 0.5)
14
+ mime-types (3.2.2)
15
+ mime-types-data (~> 3.2015)
16
+ mime-types-data (3.2018.0812)
17
+ netrc (0.11.0)
18
+ rest-client (2.0.2)
19
+ http-cookie (>= 1.0.2, < 2.0)
20
+ mime-types (>= 1.16, < 4.0)
21
+ netrc (~> 0.8)
22
+ unf (0.1.4)
23
+ unf_ext
24
+ unf_ext (0.0.7.5)
25
+
26
+ PLATFORMS
27
+ ruby
28
+
29
+ DEPENDENCIES
30
+ getnet_api!
31
+
32
+ BUNDLED WITH
33
+ 1.16.4
data/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2018 QW3 - Software, Marketing e Consultoria
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,195 @@
1
+ # Gem Getnet API - Meios de Pagamento
2
+
3
+ ## Versão Beta
4
+
5
+ Gem para utilização dos meios de pagamento [Getnet](https://site.getnet.com.br/) - Uma empresa Santander para integrar sua plataforma de forma segura e eficaz com as principais formas de pagamento disponíveis no mercado.
6
+
7
+ Acesso a documentação de desenvolvimento da [Getnet](https://developers.getnet.com.br/)
8
+
9
+ ## Instalando
10
+
11
+ ### Gemfile
12
+
13
+ Adicione esta linha ao Gemfile do seu aplicativo:
14
+
15
+ ```ruby
16
+ gem 'getnet_api'
17
+ ```
18
+
19
+ - Execute o comando `bundle install`.
20
+
21
+ ### Instalação direta
22
+
23
+ ```ruby
24
+ gem install getnet_api
25
+ ```
26
+
27
+ ## Configuração
28
+
29
+ Para fazer a autenticação, você precisará configurar as credenciais da Getnet. Crie o arquivo `config/initializers/getnet_api.rb` com o conteúdo abaixo.
30
+
31
+ ```ruby
32
+ GetnetApi.configure do |config|
33
+
34
+ #
35
+ # Opções de ambiente
36
+ # [:sandbox, :homologacao, :producao]
37
+ config.ambiente = :producao
38
+
39
+ #
40
+ # Código que identifica o seller_id dentro da Getnet
41
+ # Enviado pela Getnet
42
+ config.seller_id = '5c89ec4a-db89-45a6-8c96-5b0b72907ef5'
43
+
44
+ #
45
+ # Código que identifica o client_id dentro da Getnet
46
+ # Enviado pela Getnet
47
+ config.client_id = 'f43f4b25-fd05-420a-bffc-0dc85428ebd0'
48
+
49
+ #
50
+ # Código que identifica o client_secret dentro da Getnet
51
+ # Enviado pela Getnet
52
+ config.client_secret = '31e285f9-5d97-4370-9553-326310ca8b97'
53
+
54
+ end
55
+ ```
56
+
57
+ ## Pagamentos
58
+
59
+ Nesse endpoint serão recebidos dados para os pagamentos.
60
+
61
+
62
+ ### Montar [Endereço](http://www.rubydoc.info/github/qw3/superpay_api/GetnetApi/Address)
63
+
64
+ ```ruby
65
+ obj_endereco = GetnetApi::Address.new ({
66
+ street: "Rua Dom Pedro II",
67
+ number: "1330",
68
+ district: "Vila Monteiro (Gleba I)",
69
+ complement: "Sala A",
70
+ city: "São Carlos",
71
+ state: "SP",
72
+ postal_code: "13560320",
73
+ })
74
+ ```
75
+
76
+ ### Montar [Cliente](http://www.rubydoc.info/github/qw3/superpay_api/GetnetApi/Customer)
77
+
78
+ ```ruby
79
+ obj_cliente = GetnetApi::Customer.new ({
80
+ customer_id: 1,
81
+ first_name: "Leandro",
82
+ last_name: "Falcão",
83
+ name: "Leandro Falcão",
84
+ document_type: :pessoa_fisica,
85
+ documento: "999.999.999-9",
86
+ email: "contato@qw3.com.br",
87
+ phone_number: "1634166404",
88
+ celphone_number: "16955555555",
89
+ endereco: obj_endereco, # Objeto da classe GetnetApi::Address
90
+ })
91
+ ```
92
+
93
+ ### Montar [Pedido](http://www.rubydoc.info/github/qw3/superpay_api/GetnetApi/Order)
94
+
95
+ ```ruby
96
+ obj_pedido = GetnetApi::Order.new ({
97
+ order_id: "123456",
98
+ sales_tax: 12,
99
+ product_type: "phisical_goods"
100
+ })
101
+ ```
102
+
103
+ ---
104
+
105
+ ### Montar [Pagamento](http://www.rubydoc.info/github/qw3/superpay_api/GetnetApi/Payment)
106
+
107
+ ```ruby
108
+ obj_pagamento = GetnetApi::Payment.new ({
109
+ amount: 100, # Quantidade em centavos
110
+ order: obj_pedido, # Objeto da classe GetnetApi::Order
111
+ customer: obj_cliente, # Objeto da classe GetnetApi::Customer
112
+ billing_address: obj_endereco, # Objeto da classe GetnetApi::Address
113
+ })
114
+ ```
115
+ ## Criando um pagamento na GetNet do tipo Credit
116
+
117
+ ### Montar [Cartão](http://www.rubydoc.info/github/qw3/superpay_api/GetnetApi/Credit)
118
+
119
+ ```ruby
120
+ obj_credit = GetnetApi::Credit.new ({
121
+ delayed: false,
122
+ authenticated: false,
123
+ pre_authorization: false,
124
+ save_card_data: false,
125
+ transaction_type: 'FULL',
126
+ number_installments: 1,
127
+ soft_descriptor: '',
128
+ dynamic_mcc: ''
129
+ })
130
+ ```
131
+
132
+ ```ruby
133
+ # No Caso de pagamento com Cartão de Credito
134
+ # GetnetApi::Payment.create(GetnetApi::Payment, GetnetApi::Credit, tipo)
135
+ novo_pagamento = GetnetApi::Payment.create obj_pagamento, obj_credito, :credit
136
+ ```
137
+
138
+ ---
139
+
140
+ ## Criando um pagamento na GetNet do tipo Boleto
141
+
142
+ ### Montar [Boleto](http://www.rubydoc.info/github/qw3/superpay_api/GetnetApi/Boleto)
143
+
144
+ ```ruby
145
+ obj_boleto = GetnetApi::Boleto.new ({
146
+ our_number: "000001946598",
147
+ document_number: "170500000019763",
148
+ expiration_date: "16/11/2017",
149
+ instructions: "Não receber após o vencimento",
150
+ provider: "santander"
151
+ })
152
+ ```
153
+
154
+ ```ruby
155
+ # No Caso de pagamento de Boleto
156
+ # GetnetApi::Payment.create(GetnetApi::Payment, GetnetApi::Boleto, tipo)
157
+ novo_pagamento = GetnetApi::Payment.create obj_pagamento, obj_boleto, :boleto
158
+ ```
159
+
160
+ ---
161
+
162
+
163
+ ## Autor
164
+
165
+ - [QW3 Software & Marketing](http://qw3.com.br)
166
+ - [Leandro dos Santos Falcão](https://www.linkedin.com/in/lsfalcao)
167
+ - [Victor Barreiros](www.linkedin.com/in/victor-barreiros)
168
+
169
+ ## Copyright
170
+
171
+ [QW3 Software & Marketing](http://qw3.com.br)
172
+
173
+ ![QW3 Logo](http://qw3.com.br/qw3_logo.png)
174
+
175
+ MIT License
176
+
177
+ Copyright (c) 2018 QW3 - Software, Marketing e Consultoria
178
+
179
+ Permission is hereby granted, free of charge, to any person obtaining a copy
180
+ of this software and associated documentation files (the "Software"), to deal
181
+ in the Software without restriction, including without limitation the rights
182
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
183
+ copies of the Software, and to permit persons to whom the Software is
184
+ furnished to do so, subject to the following conditions:
185
+
186
+ The above copyright notice and this permission notice shall be included in all
187
+ copies or substantial portions of the Software.
188
+
189
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
190
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
191
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
192
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
193
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
194
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
195
+ SOFTWARE.
data/Rakefile ADDED
@@ -0,0 +1,2 @@
1
+ require "bundler/gem_tasks"
2
+ task :default => :spec
@@ -0,0 +1,27 @@
1
+ # -*- encoding: utf-8 -*-
2
+ lib = File.expand_path('../lib', __FILE__)
3
+ $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
4
+ require 'getnet_api/version'
5
+
6
+ Gem::Specification.new do |spec|
7
+ spec.name = "getnet_api"
8
+ spec.version = GetnetApi::Version::STRING
9
+ spec.platform = Gem::Platform::RUBY
10
+ spec.authors = ["QW3 Software & Marketing"]
11
+ spec.email = ["contato@qw3.com.br"]
12
+ spec.summary = "Getnet API - Meios de Pagamento"
13
+ spec.description = "Gem para utilização dos meios de pagamento Getnet - Uma empresa Santander para integrar sua plataforma de forma segura e eficaz com as principais formas de pagamento disponíveis no mercado."
14
+ spec.homepage = "https://github.com/qw3/getnet_api"
15
+ spec.license = "MIT"
16
+
17
+ spec.files = `git ls-files`.split($/)
18
+ spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) }
19
+ spec.test_files = spec.files.grep(%r{^(test|spec|features)/})
20
+
21
+ spec.require_paths = ["lib"]
22
+
23
+ spec.required_ruby_version = Gem::Requirement.new(">= 1.9")
24
+
25
+ spec.add_dependency 'rest-client', '~> 0'
26
+
27
+ end
@@ -0,0 +1,79 @@
1
+ # -*- encoding : utf-8 -*-
2
+ module GetnetApi
3
+ class Address
4
+
5
+ # Endereço (Logradouro)
6
+ # Alfa Numérico - Até 60 caracteres
7
+ attr_accessor :street
8
+
9
+ # Número do logradouro
10
+ # Alfa Numérico - Até 10 caracteres
11
+ attr_accessor :number
12
+
13
+ # Complemento do endereço comprador
14
+ # Alfa Numérico - Até 60 caracteres
15
+ attr_accessor :complement
16
+
17
+ # Bairro do logradouro
18
+ # Alfa Numérico - Até 40 caracteres
19
+ attr_accessor :district
20
+
21
+ # Cidade do logradouro
22
+ # Alfa Numérico - Até 40 caracteres
23
+ attr_accessor :city
24
+
25
+ # Estado do logradouro (UF)
26
+ # Alfa Numérico - Até 20 caracteres
27
+ attr_accessor :state
28
+
29
+ # País do logradouro
30
+ # Alfa Numérico - Até 20 caracteres
31
+ attr_accessor :country
32
+
33
+ # Código Postal, CEP no Brasil ou ZIP nos Estados Unidos. (sem máscara)
34
+ # Alfa Numérico - Até 10 caracteres
35
+ attr_accessor :postal_code
36
+
37
+ # Definir country
38
+ def country
39
+ @country ||= "Brasil"
40
+ end
41
+
42
+ # Validações do Rails 3
43
+ include ActiveModel::Validations
44
+
45
+ # Validações
46
+ validates :street, length: { maximum: 60 }
47
+ validates :number, length: { maximum: 10 }
48
+ validates :complement, length: { maximum: 60 }
49
+ validates :district, :city, length: { maximum: 40 }
50
+ validates :state, :country, length: { maximum: 20 }
51
+ validates :postal_code, length: { maximum: 8 }
52
+
53
+ # Nova instancia da classe Endereco
54
+ # @param [Hash] campos
55
+ def initialize(campos = {})
56
+ campos.each do |campo, valor|
57
+ if GetnetApi::Address.public_instance_methods.include? "#{campo}=".to_sym
58
+ send "#{campo}=", valor
59
+ end
60
+ end
61
+ end
62
+
63
+ # Montar o Hash de Endereco no padrão utilizado pela GetnetApi
64
+ def to_request
65
+ address = {
66
+ street: self.street,
67
+ number: self.number,
68
+ complement: self.complement,
69
+ district: self.district,
70
+ city: self.city,
71
+ state: self.state,
72
+ postal_code: self.postal_code,
73
+ country: self.country,
74
+ }
75
+ return address
76
+ end
77
+
78
+ end
79
+ end
@@ -0,0 +1,64 @@
1
+ module GetnetApi
2
+ class Base
3
+ require 'uri'
4
+ require 'net/http'
5
+
6
+ def self.build_request endpoint, metodo, body=nil
7
+
8
+ url = URI("#{GetnetApi.base_uri}/#{endpoint}")
9
+
10
+ http = Net::HTTP.new(url.host, url.port)
11
+ http.use_ssl = true
12
+
13
+ case metodo
14
+ when "delete"
15
+ request = Net::HTTP::Delete.new(url)
16
+ when "get"
17
+ request = Net::HTTP::Get.new(url)
18
+ when "put"
19
+ request = Net::HTTP::Put.new(url)
20
+ when "post"
21
+ request = Net::HTTP::Post.new(url)
22
+ end
23
+ request = GetnetApi::Base.default_headers request
24
+
25
+ request.body = body.to_json
26
+ return http.request(request)
27
+ end
28
+
29
+ def self.default_headers request
30
+ request["authorization"] = "Bearer #{GetnetApi::Base.valid_bearer}"
31
+ request["Content-Type"] = "application/json"
32
+ request["seller_id"] = "#{GetnetApi.seller_id}"
33
+ return request
34
+ end
35
+
36
+ def self.get_token_de_bearer
37
+ url = URI("#{GetnetApi.endpoint}/auth/oauth/v2/token")
38
+ http = Net::HTTP.new(url.host, url.port)
39
+ http.use_ssl = true
40
+ request = Net::HTTP::Post.new(url)
41
+ request.basic_auth "#{GetnetApi.client_id}", "#{GetnetApi.client_secret}"
42
+ request["Content-Type"] = "application/x-www-form-urlencoded"
43
+ hash = {
44
+ "scope" => 'oob',
45
+ "grant_type" => 'client_credentials',
46
+ }
47
+ request.body = hash.to_query
48
+ response = http.request(request)
49
+ result = JSON.parse(response.read_body)
50
+ GetnetApi.access_token = result["access_token"]
51
+ GetnetApi.expires_in = DateTime.now + result["expires_in"].to_i.seconds - 60.seconds
52
+ end
53
+
54
+ def self.valid_bearer
55
+ if GetnetApi.expires_in > DateTime.now
56
+ return GetnetApi.access_token
57
+ else
58
+ GetnetApi::Base.get_token_de_bearer
59
+ return GetnetApi.access_token
60
+ end
61
+ end
62
+
63
+ end
64
+ end
@@ -0,0 +1,62 @@
1
+ # -*- encoding : utf-8 -*-
2
+ module GetnetApi
3
+ class Boleto
4
+
5
+ # string 12 characters
6
+ # Denominado pelos bancos como "Nosso Número". É a identificação única do boleto no sistema de
7
+ # cobrança. É composto por regras que variam em função do banco e do serviço de cobrança.
8
+ # Por exemplo, no caso do Santander existem duas formas de se numerar. 1) Se cliente quem numera, deve informar o dígito verificador (DV); 2) Se o cliente omitir o número, o Banco fica encarregado da geração de um sequêncial, sem um DV. (sem máscara)
9
+ attr_accessor :our_number
10
+
11
+ # string 15 characters
12
+ # Seu Número. Número controlado pelo cliente, geralmente é gerenciado pelo sistema que está gerando o boleto. (sem máscara)
13
+ attr_accessor :document_number
14
+
15
+ # string <dd/mm/yyyy>
16
+ # Data do vencimento do boleto. Caso não seja informado, será considerado o número de dias padrão pré-cadastrado para o vencimento.
17
+ attr_accessor :expiration_date
18
+
19
+ # string
20
+ # Instruções a serem impressas no boleto (colocar quebra de linha a cada 100 caracteres, máximo 10 linhas).
21
+ attr_accessor :instructions
22
+
23
+ # string <= 40 characters
24
+ # Banco provedor. "santander"
25
+ attr_accessor :provider
26
+
27
+ # Validações do Rails 3
28
+ include ActiveModel::Validations
29
+
30
+ # validates :valor_total, length: { maximum: }
31
+ # validates :expiration_date, length: { maximum: }
32
+ validates :moeda, length: { maximum: 3 }
33
+ validates :our_number , length: { maximum: 12 }
34
+ validates :document_number, length: { maximum: 15 }
35
+ validates :instructions, length: { maximum: 1000 }
36
+ validates :provider, length: { maximum: 40 }
37
+
38
+ # Nova instancia da classe Boleto
39
+ # @param [Hash] campos
40
+ def initialize(campos = {})
41
+ campos.each do |campo, valor|
42
+ if GetnetApi::Boleto.public_instance_methods.include? "#{campo}=".to_sym
43
+ send "#{campo}=", valor
44
+ end
45
+ end
46
+ end
47
+
48
+ # Montar o Hash de dados do pagamento no padrão utilizado pela Getnet
49
+ def to_request
50
+ boleto = {
51
+ our_number: self.our_number,
52
+ document_number: self.document_number,
53
+ expiration_date: self.expiration_date,
54
+ instructions: self.instructions,
55
+ provider: self.provider
56
+ }
57
+
58
+ return boleto
59
+ end
60
+
61
+ end
62
+ end
@@ -0,0 +1,65 @@
1
+ # -*- encoding : utf-8 -*-
2
+ module GetnetApi
3
+ class Card
4
+
5
+ # string 128 characters Required
6
+ # Número do cartão tokenizado. Gerado previamente por meio do endpoint /v1/tokens/card.
7
+ attr_accessor :number_token
8
+
9
+ # string <= 26 characters Required
10
+ # Nome do comprador impresso no cartão.
11
+ attr_accessor :cardholder_name
12
+
13
+ # string [ 3 .. 4 ] characters
14
+ # Código de segurança. CVV ou CVC.
15
+ attr_accessor :security_code
16
+
17
+ # string <= 50 characters
18
+ # "Mastercard" "Visa" "Amex" "Elo" "Hipercard"
19
+ # Bandeira do cartão.
20
+ attr_accessor :brand
21
+
22
+ # string 2 characters Required
23
+ # Mês de expiração do cartão com dois dígitos.
24
+ attr_accessor :expiration_month
25
+
26
+ # string 2 characters Required
27
+ # Ano de expiração do cartão com dois dígitos.
28
+ attr_accessor :expiration_year
29
+
30
+ # Validações do Rails 3
31
+ include ActiveModel::Validations
32
+
33
+ validates :number_token, length: { maximum: 128 }
34
+ validates :cardholder_name, length: { maximum: 26 }
35
+ validates :security_code, length: { in: 3..4 }
36
+ validates :brand, length: { maximum: 50 }
37
+ validates :expiration_month, length: { maximum: 2 }
38
+ validates :expiration_year, length: { maximum: 2 }
39
+
40
+ # Nova instancia da classe Card
41
+ # @param [Hash] campos
42
+ def initialize(campos = {})
43
+ campos.each do |campo, valor|
44
+ if GetnetApi::Card.public_instance_methods.include? "#{campo}=".to_sym
45
+ send "#{campo}=", valor
46
+ end
47
+ end
48
+ end
49
+
50
+ # Montar o Hash de dados do pagamento no padrão utilizado pela Getnet
51
+ def to_request
52
+ card = {
53
+ number_token: self.number_token,
54
+ cardholder_name: self.cardholder_name,
55
+ security_code: self.security_code,
56
+ brand: self.brand,
57
+ expiration_month: self.expiration_month,
58
+ expiration_year: self.expiration_year
59
+ }
60
+
61
+ return card
62
+ end
63
+
64
+ end
65
+ end
@@ -0,0 +1,28 @@
1
+ # -*- encoding : utf-8 -*-
2
+ module GetnetApi
3
+ class CardToken < Base
4
+ require 'uri'
5
+ require 'net/http'
6
+
7
+ # Metodo para gerar o token do cartão de credito do cliente, para ser usado no pagamento.
8
+ def self.get card_number
9
+
10
+ hash = {
11
+ "card_number" => card_number.to_s
12
+ }
13
+
14
+ response = self.build_request self.endpoint, "post", hash
15
+
16
+ return JSON.parse(response.read_body)
17
+ end
18
+
19
+ private
20
+
21
+ def self.endpoint
22
+ return "tokens/card"
23
+ end
24
+
25
+ end
26
+ end
27
+
28
+ # GetnetApi::CardToken.get "5155901222280001"
@@ -0,0 +1,32 @@
1
+ # -*- encoding : utf-8 -*-
2
+ module GetnetApi
3
+ class CardVerification < Base
4
+ require 'uri'
5
+ require 'net/http'
6
+
7
+ # Metodo para verificar se o token gerado é valido.
8
+ def self.verify card_token
9
+
10
+ hash = {
11
+ "number_token" => card_token.to_s,
12
+ "cardholder_name": "JOAO DA SILVA",
13
+ "expiration_month": "12",
14
+ "expiration_year": "20",
15
+ "security_code": "123"
16
+ }
17
+
18
+ response = self.build_request self.endpoint, "post", hash
19
+
20
+ return JSON.parse(response.read_body)
21
+ end
22
+
23
+ private
24
+
25
+ def self.endpoint
26
+ return "cards/verification"
27
+ end
28
+
29
+ end
30
+ end
31
+
32
+ # GetnetApi::CardVerification.verify a["number_token"]
@@ -0,0 +1,105 @@
1
+ # -*- encoding : utf-8 -*-
2
+ module GetnetApi
3
+ module Configure
4
+
5
+ # Endereço do wsdl funções:
6
+ # [Criar Transação pagamentoTransacaoCompleta, Capturar operacaoTransacao, Cancelar operacaoTransacao, Consultar consultaTransacaoEspecifica]
7
+ # [Estornar estornaTransacao] - Estorno
8
+ URL = {
9
+ :homologacao => "https://api-homologacao.getnet.com.br",
10
+ :sandbox => "https://api-sandbox.getnet.com.br",
11
+ :producao => "https://api.getnet.com.br",
12
+ }
13
+
14
+ # Parâmetros iniciais
15
+ AMBIENTE = :sandbox # :sandbox ou :homologacao ou :producao
16
+ # Parâmetros iniciais
17
+ API_VERSION = 'v1'
18
+ # Parâmetros iniciais
19
+ SELLER_ID = '5c89ec4a-db89-45a6-8c96-5b0b72907ef5'
20
+ # Parâmetros iniciais
21
+ CLIENT_ID = 'f43f4b25-fd05-420a-bffc-0dc85428ebd0'
22
+ # Parâmetros iniciais
23
+ CLIENT_SECRET = '31e285f9-5d97-4370-9553-326310ca8b97'
24
+
25
+ # Define o ambiente de trabalho
26
+ # Simbolo - Valores pré-definidos [:sandbox, :homologacao, :producao]
27
+ attr_writer :ambiente
28
+
29
+ # Enviado pela Getnet
30
+ attr_writer :api_version
31
+
32
+ # Enviado pela Getnet
33
+ attr_writer :seller_id
34
+
35
+ # Enviado pela Getnet
36
+ attr_writer :client_id
37
+
38
+ # Enviado pela Getnet
39
+ attr_writer :client_secret
40
+
41
+ # Token de acesso utilizado nas demais requisições
42
+ attr_writer :access_token
43
+ attr_writer :expires_in
44
+
45
+ # Comando que recebe as configuracoes
46
+ def configure
47
+ yield self if block_given?
48
+ end
49
+
50
+ # Definir ambiente
51
+ def ambiente
52
+ @ambiente ||= AMBIENTE
53
+ end
54
+
55
+ # Definir Versão da API da Getnet
56
+ def api_version
57
+ @api_version ||= API_VERSION
58
+ end
59
+
60
+ # Definir seller_id
61
+ def seller_id
62
+ @seller_id ||= SELLER_ID
63
+ end
64
+
65
+ # Definir client_id
66
+ def client_id
67
+ @client_id ||= CLIENT_ID
68
+ end
69
+
70
+ # Definir client_secret
71
+ def client_secret
72
+ @client_secret ||= CLIENT_SECRET
73
+ end
74
+
75
+ # Definir endpoint
76
+ def endpoint
77
+ @endpoint ||= set_endpoint
78
+ end
79
+
80
+ # Definir access_token
81
+ def access_token
82
+ @access_token ||= ""
83
+ end
84
+ # Definir Versão da API da Getnet
85
+ def expires_in
86
+ @expires_in ||= DateTime.now - 1.day
87
+ end
88
+
89
+ # Retornar a url conforme o ambiente
90
+ def set_endpoint
91
+ if ambiente == :producao
92
+ return GetnetApi::Configure::URL[:producao]
93
+ elsif ambiente == :homologacao
94
+ return GetnetApi::Configure::URL[:homologacao]
95
+ else
96
+ return GetnetApi::Configure::URL[:sandbox]
97
+ end
98
+ end
99
+
100
+ def base_uri
101
+ return "#{self.endpoint}/#{self.api_version}/"
102
+ end
103
+
104
+ end
105
+ end
@@ -0,0 +1,88 @@
1
+ # -*- encoding : utf-8 -*-
2
+ module GetnetApi
3
+ class Credit < Base
4
+
5
+ # Boolean Required
6
+ # Identifica se o crédito será feito com confirmação tardia.
7
+ attr_accessor :delayed
8
+
9
+ # Boolean
10
+ # Indicativo se transação deve ter o processo de autenticação no emissor, caso authenticated = true, o portador deve ser encaminhado ao site do emissor para autenticação junto ao mesmo.
11
+ attr_accessor :authenticated
12
+
13
+ # Boolean
14
+ # Indicativo se a transação é uma pré autorização de crédito.
15
+ attr_accessor :pre_authorization
16
+
17
+ # Boolean Required
18
+ # Identifica se o cartão deve ser salvo para futuras compras.
19
+ attr_accessor :save_card_data
20
+
21
+ # string Required
22
+ # "FULL" "INSTALL_NO_INTEREST" "INSTALL_WITH_INTEREST"
23
+ # Tipo de transação. Pagamento completo à vista, parcelado sem juros, parcelado com juros.
24
+ attr_accessor :transaction_type
25
+
26
+ # integer Required
27
+ # Número de parcelas.
28
+ attr_accessor :number_installments
29
+
30
+ # string <= 22 characters
31
+ # Texto exibido na fatura do cartão do comprador, Este campo é opcional, não sendo informado nada, será considerado o nome fantasia cadastrado para o estabelecimento.
32
+ attr_accessor :soft_descriptor
33
+
34
+ # integer
35
+ # Campo utilizado para sinalizar a transação com outro Merchant Category Code (Código da Categoria do Estabelecimento) diferente do cadastrado. Caso seja enviado um MCC inválido, será utilizado o padrão. Enviar somente dados numéricos.
36
+ attr_accessor :dynamic_mcc
37
+
38
+ # Cartão
39
+ # GetnetApi::Card
40
+ attr_accessor :card
41
+
42
+ # Validações do Rails 3
43
+ include ActiveModel::Validations
44
+
45
+ validates :transaction_type, length: { maximum: 22 }
46
+ validates :number_installments, presence: true
47
+ validates :soft_descriptor, length: { maximum: 22 }
48
+ validates :dynamic_mcc, length: { maximum: 10 }
49
+
50
+ validates_each [:card] do |record, attr, value|
51
+ if value.is_a? GetnetApi::Card
52
+ if value.invalid?
53
+ value.errors.full_messages.each { |msg| record.errors.add(attr, msg) }
54
+ end
55
+ else
56
+ record.errors.add(attr, 'deve ser um objeto GetnetApi::Card.')
57
+ end
58
+ end
59
+
60
+ # Nova instancia da classe Credit
61
+ # @param [Hash] campos
62
+ def initialize(campos = {})
63
+ campos.each do |campo, valor|
64
+ if GetnetApi::Credit.public_instance_methods.include? "#{campo}=".to_sym
65
+ send "#{campo}=", valor
66
+ end
67
+ end
68
+ end
69
+
70
+ # Montar o Hash de dados do pagamento no padrão utilizado pela Getnet
71
+ def to_request
72
+ credit = {
73
+ delayed: self.delayed,
74
+ authenticated: self.authenticated,
75
+ pre_authorization: self.pre_authorization,
76
+ save_card_data: self.save_card_data,
77
+ transaction_type: self.transaction_type,
78
+ number_installments: self.number_installments.to_i,
79
+ soft_descriptor: self.soft_descriptor,
80
+ dynamic_mcc: self.dynamic_mcc,
81
+ card: self.card.to_request,
82
+ }
83
+
84
+ return credit
85
+ end
86
+
87
+ end
88
+ end
@@ -0,0 +1,135 @@
1
+ # -*- encoding : utf-8 -*-
2
+ module GetnetApi
3
+ class Customer < Base
4
+
5
+ # Opções de Tipo de Cliente
6
+ TIPO_DOCUMENTO = {
7
+ :pessoa_fisica => "CPF",
8
+ :pessoa_juridica => "CNPJ",
9
+ }
10
+
11
+ # Código que identifica o cliente no estabelecimento.
12
+ # Alfa Numérico - Até 20 caracteres
13
+ attr_accessor :customer_id
14
+
15
+ # Nome do comprador
16
+ # Alfa Numérico - Até 40 caracteres
17
+ attr_accessor :first_name
18
+
19
+ # Nome do comprador
20
+ # Alfa Numérico - Até 80 caracteres
21
+ attr_accessor :last_name
22
+
23
+ # Nome do comprador
24
+ # Alfa Numérico - Até 100 caracteres
25
+ attr_accessor :name
26
+
27
+ # E-mail do comprador
28
+ # Alfa Numérico - Até 100 caracteres
29
+ attr_accessor :email
30
+
31
+ # Identifica o tipo de documento informado é pessoa física ou jurídica.
32
+ # Simbolo - Valores pré-definidos [:pessoa_fisica, :pessoa_juridica]
33
+ attr_accessor :document_type
34
+
35
+ # Número do documento do comprador sem pontuação. (sem máscara)
36
+ # Alfa Numérico - Até 15 caracteres
37
+ attr_accessor :document_number
38
+
39
+ # Endereços
40
+ # GetnetApi::Address
41
+ attr_accessor :address
42
+
43
+ # Telefone do comprador. (sem máscara)
44
+ # Alfa Numérico - Até 15 caracteres
45
+ attr_accessor :phone_number
46
+
47
+ # Celular do comprador. (sem máscara)
48
+ # Alfa Numérico - Até 15 caracteres
49
+ attr_accessor :celphone_number
50
+
51
+ attr_accessor :observation
52
+
53
+ # Validações do Rails 3
54
+ include ActiveModel::Validations
55
+
56
+ # Retornar array com os possíveis tipos de cliente
57
+ def self.tipos_document_number_validos
58
+ TIPO_DOCUMENTO.map{ |key, value| key }
59
+ end
60
+
61
+ # Validações
62
+ validates :customer_id, length: { maximum: 100 }
63
+ validates :first_name, length: { maximum: 40 }
64
+ validates :last_name, length: { maximum: 80 }
65
+ validates :name, :email, length: { maximum: 100 }
66
+ validates :document_type, inclusion: { in: GetnetApi::Customer.tipos_document_number_validos }
67
+ validates :document_number, length: { in: 11..15 }
68
+ validates :phone_number, length: { maximum: 15 }
69
+ validates :observation, length: { maximum: 140 }
70
+
71
+ validates_each [:address] do |record, attr, value|
72
+ if value.is_a? GetnetApi::Address
73
+ if value.invalid?
74
+ value.errors.full_messages.each { |msg| record.errors.add(attr, msg) }
75
+ end
76
+ else
77
+ record.errors.add(attr, 'deve ser um objeto GetnetApi::Address.')
78
+ end
79
+ end
80
+
81
+ # Nova instancia da classe Cliente
82
+ # @param [Hash] campos
83
+ def initialize(campos = {})
84
+ campos.each do |campo, valor|
85
+ if GetnetApi::Customer.public_instance_methods.include? "#{campo}=".to_sym
86
+ send "#{campo}=", valor
87
+ end
88
+ end
89
+ end
90
+
91
+ # Retornar o número do tipo de phone_number no padrão utilizado pela Getnet
92
+ def tipos_de_cliente_to_request
93
+ TIPO_DOCUMENTO[self.document_type]
94
+ end
95
+
96
+ # Montar o Hash de dados do usuario no padrão utilizado pela Getnet
97
+ def to_request tipo
98
+ customer = {
99
+ customer_id: self.customer_id.to_s,
100
+ first_name: self.first_name.to_s,
101
+ last_name: self.last_name.to_s,
102
+ email: self.email.to_s,
103
+ document_type: self.tipos_de_cliente_to_request.to_s,
104
+ document_number: self.document_number.to_s,
105
+ phone_number: self.phone_number.to_s,
106
+ }
107
+
108
+ if tipo == :customer
109
+ customer.merge!({"address": address.to_request,})
110
+ elsif tipo == :payment
111
+ customer.merge!({"name": self.name.to_s,})
112
+ customer.merge!({"billing_address": address.to_request,})
113
+ end
114
+
115
+ return customer
116
+ end
117
+
118
+ # a = GetnetApi::Customer.create cliente
119
+ def self.create customer
120
+
121
+ hash = customer.to_request(:customer)
122
+
123
+ response = self.build_request self.endpoint, "post", hash
124
+
125
+ return JSON.parse(response.read_body)
126
+ end
127
+
128
+ private
129
+
130
+ def self.endpoint
131
+ return "/customers"
132
+ end
133
+
134
+ end
135
+ end
@@ -0,0 +1,50 @@
1
+ # -*- encoding : utf-8 -*-
2
+ module GetnetApi
3
+ class Order
4
+
5
+ # Conjunto de dados para identificação da compra
6
+ # order_id
7
+ # string <= 36 characters Required
8
+ attr_accessor :order_id
9
+
10
+ # Código de identificação da compra utilizado pelo e-commerce
11
+ # Valor de impostos
12
+ attr_accessor :sales_tax
13
+
14
+ # string
15
+ # "cash_carry" "digital_content" "digital_goods" "digital_physical" "gift_card" "phisical_goods" "renew_subs" "shareware" "service"
16
+ # Identificador do tipo de produto vendido dentre as opções
17
+ attr_accessor :product_type
18
+
19
+ # Validações do Rails 3
20
+ include ActiveModel::Validations
21
+
22
+ # validates :valor_total, length: { maximum: }
23
+ # validates :expiration_date, length: { maximum: }
24
+ validates :order_id, length: { maximum: 36 }
25
+ # validates :sales_tax , length: { }
26
+ # validates :product_type, length: { }
27
+
28
+ # Nova instancia da classe Boleto
29
+ # @param [Hash] campos
30
+ def initialize(campos = {})
31
+ campos.each do |campo, valor|
32
+ if GetnetApi::Order.public_instance_methods.include? "#{campo}=".to_sym
33
+ send "#{campo}=", valor
34
+ end
35
+ end
36
+ end
37
+
38
+ # Montar o Hash de dados do pagamento no padrão utilizado pela Getnet
39
+ def to_request
40
+ order = {
41
+ order_id: self.order_id.to_s,
42
+ sales_tax: self.sales_tax.to_i,
43
+ product_type: self.product_type.to_s
44
+ }
45
+
46
+ return order
47
+ end
48
+
49
+ end
50
+ end
@@ -0,0 +1,114 @@
1
+ # -*- encoding : utf-8 -*-
2
+ module GetnetApi
3
+ class Payment < Base
4
+ require 'uri'
5
+ require 'net/http'
6
+
7
+ # amount
8
+ # integer Required
9
+ # Valor da compra em centavos.
10
+ attr_accessor :amount
11
+
12
+ # currency
13
+ # string 3 characters
14
+ # Identificação da moeda (Consultar código em "https://www.currency-iso.org/en/home/tables/table-a1.html").
15
+ attr_accessor :currency
16
+
17
+ # Objeto do tipo GetnetApi::Order
18
+ attr_accessor :order
19
+
20
+ # Objeto do tipo GetnetApi::Customer
21
+ attr_accessor :customer
22
+
23
+ # Validações do Rails 3
24
+ include ActiveModel::Validations
25
+
26
+ validates :amount, length: { maximum: 3 }
27
+ validates :currency, length: { maximum: 3 }
28
+
29
+ validates_each [:order] do |record, attr, value|
30
+ if value.is_a? GetnetApi::Order
31
+ if value.invalid?
32
+ value.errors.full_messages.each { |msg| record.errors.add(attr, msg) }
33
+ end
34
+ else
35
+ record.errors.add(attr, 'deve ser um objeto GetnetApi::Order.')
36
+ end
37
+ end
38
+
39
+ validates_each [:boleto] do |record, attr, value|
40
+ if value.is_a? GetnetApi::Boleto
41
+ if value.invalid?
42
+ value.errors.full_messages.each { |msg| record.errors.add(attr, msg) }
43
+ end
44
+ else
45
+ record.errors.add(attr, 'deve ser um objeto GetnetApi::Boleto.')
46
+ end
47
+ end
48
+
49
+ validates_each [:customer] do |record, attr, value|
50
+ if value.is_a? GetnetApi::Customer
51
+ if value.invalid?
52
+ value.errors.full_messages.each { |msg| record.errors.add(attr, msg) }
53
+ end
54
+ else
55
+ record.errors.add(attr, 'deve ser um objeto GetnetApi::Customer.')
56
+ end
57
+ end
58
+
59
+ # Definir moeda usada
60
+ def currency
61
+ @currency ||= "BRL"
62
+ end
63
+
64
+ # Nova instancia da classe Cliente
65
+ # @param [Hash] campos
66
+ def initialize(campos = {})
67
+ campos.each do |campo, valor|
68
+ if GetnetApi::Payment.public_instance_methods.include? "#{campo}=".to_sym
69
+ send "#{campo}=", valor
70
+ end
71
+ end
72
+ end
73
+
74
+ # Montar o Hash de dados do usuario no padrão utilizado pela Getnet
75
+ def to_request obj, type
76
+ payment = {
77
+ seller_id: GetnetApi.seller_id.to_s,
78
+ amount: self.amount.to_i,
79
+ currency: self.currency.to_s,
80
+ order: self.order.to_request,
81
+ customer: self.customer.to_request(:payment),
82
+ }
83
+
84
+ if type == :boleto
85
+ payment.merge!({"boleto": obj.to_request,})
86
+ elsif :credit
87
+ payment.merge!({"credit": obj.to_request,})
88
+ end
89
+
90
+ return payment
91
+ end
92
+
93
+ # a = GetnetApi::Payment.create pagamento, boleto, :boleto
94
+ def self.create(payment, obj, type)
95
+
96
+ hash = payment.to_request(obj, type)
97
+
98
+ response = self.build_request self.endpoint(type), "post", hash
99
+
100
+ return JSON.parse(response.read_body)
101
+ end
102
+
103
+ private
104
+
105
+ def self.endpoint type
106
+ if type == :boleto
107
+ return "payments/boleto"
108
+ elsif :credit
109
+ return "payments/credit"
110
+ end
111
+ end
112
+
113
+ end
114
+ end
@@ -0,0 +1,9 @@
1
+ # -*- encoding : utf-8 -*-
2
+ module GetnetApi
3
+ module Version
4
+ MAJOR = 0
5
+ MINOR = 1
6
+ PATCH = 1
7
+ STRING = "#{MAJOR}.#{MINOR}.#{PATCH}"
8
+ end
9
+ end
data/lib/getnet_api.rb ADDED
@@ -0,0 +1,23 @@
1
+ # -*- encoding : utf-8 -*-
2
+ require 'rubygems'
3
+ require 'active_model'
4
+
5
+ require "getnet_api/version"
6
+ require "getnet_api/configure"
7
+ require "getnet_api/base"
8
+ require "getnet_api/card"
9
+ require "getnet_api/card_token"
10
+ require "getnet_api/card_verification"
11
+ require "getnet_api/customer"
12
+ require "getnet_api/address"
13
+ require "getnet_api/order"
14
+ require "getnet_api/boleto"
15
+ require "getnet_api/credit"
16
+ require "getnet_api/payment"
17
+
18
+
19
+ # -*- encoding : utf-8 -*-
20
+ module GetnetApi
21
+ extend GetnetApi::Configure
22
+
23
+ end
metadata ADDED
@@ -0,0 +1,80 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: getnet_api
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.1
5
+ platform: ruby
6
+ authors:
7
+ - QW3 Software & Marketing
8
+ autorequire:
9
+ bindir: bin
10
+ cert_chain: []
11
+ date: 2018-11-28 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: rest-client
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - "~>"
18
+ - !ruby/object:Gem::Version
19
+ version: '0'
20
+ type: :runtime
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - "~>"
25
+ - !ruby/object:Gem::Version
26
+ version: '0'
27
+ description: Gem para utilização dos meios de pagamento Getnet - Uma empresa Santander
28
+ para integrar sua plataforma de forma segura e eficaz com as principais formas de
29
+ pagamento disponíveis no mercado.
30
+ email:
31
+ - contato@qw3.com.br
32
+ executables: []
33
+ extensions: []
34
+ extra_rdoc_files: []
35
+ files:
36
+ - ".gitignore"
37
+ - Gemfile
38
+ - Gemfile.lock
39
+ - LICENSE
40
+ - README.md
41
+ - Rakefile
42
+ - getnet_api.gemspec
43
+ - lib/getnet_api.rb
44
+ - lib/getnet_api/address.rb
45
+ - lib/getnet_api/base.rb
46
+ - lib/getnet_api/boleto.rb
47
+ - lib/getnet_api/card.rb
48
+ - lib/getnet_api/card_token.rb
49
+ - lib/getnet_api/card_verification.rb
50
+ - lib/getnet_api/configure.rb
51
+ - lib/getnet_api/credit.rb
52
+ - lib/getnet_api/customer.rb
53
+ - lib/getnet_api/order.rb
54
+ - lib/getnet_api/payment.rb
55
+ - lib/getnet_api/version.rb
56
+ homepage: https://github.com/qw3/getnet_api
57
+ licenses:
58
+ - MIT
59
+ metadata: {}
60
+ post_install_message:
61
+ rdoc_options: []
62
+ require_paths:
63
+ - lib
64
+ required_ruby_version: !ruby/object:Gem::Requirement
65
+ requirements:
66
+ - - ">="
67
+ - !ruby/object:Gem::Version
68
+ version: '1.9'
69
+ required_rubygems_version: !ruby/object:Gem::Requirement
70
+ requirements:
71
+ - - ">="
72
+ - !ruby/object:Gem::Version
73
+ version: '0'
74
+ requirements: []
75
+ rubyforge_project:
76
+ rubygems_version: 2.4.8
77
+ signing_key:
78
+ specification_version: 4
79
+ summary: Getnet API - Meios de Pagamento
80
+ test_files: []