Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

Going to last version

  • Loading branch information...
commit 66b4ced9579f671c47a760f94e3f622c3ec8324a 2 parents 369068d + 050d8b5
@renatoelias renatoelias authored
Showing with 3,315 additions and 620 deletions.
  1. +0 −5 .document
  2. +5 −1 .gitignore
  3. +1 −0  .rspec
  4. +2 −7 Gemfile
  5. +10 −0 Guardfile
  6. +33 −7 README.textile → README.md
  7. +20 −0 RELEASES.md
  8. +4 −52 Rakefile
  9. +0 −41 braspag.gemspec
  10. +17 −0 config/braspag.yml
  11. +0 −32 lib/braspag.rb
  12. +0 −12 lib/braspag/connection.rb
  13. +0 −42 lib/braspag/cryptography.rb
  14. +0 −46 lib/braspag/gateway.rb
  15. +0 −35 lib/braspag/recorrente.rb
  16. +0 −16 lib/braspag/service.rb
  17. +15 −0 lib/generators/braspag/install/install_generator.rb
  18. +17 −0 lib/generators/braspag/install/templates/config/braspag.yml
  19. +45 −0 lib/rbraspag.rb
  20. +160 −0 lib/rbraspag/bill.rb
  21. +37 −0 lib/rbraspag/connection.rb
  22. +181 −0 lib/rbraspag/credit_card.rb
  23. +91 −0 lib/rbraspag/crypto/jar_webservice.rb
  24. +100 −0 lib/rbraspag/crypto/webservice.rb
  25. +90 −0 lib/rbraspag/eft.rb
  26. +39 −0 lib/rbraspag/errors.rb
  27. +43 −0 lib/rbraspag/order.rb
  28. +72 −0 lib/rbraspag/payment_method.rb
  29. +36 −0 lib/rbraspag/poster.rb
  30. +155 −0 lib/rbraspag/protected_credit_card.rb
  31. +32 −0 lib/rbraspag/utils.rb
  32. +3 −0  lib/rbraspag/version.rb
  33. +33 −0 rbraspag.gemspec
  34. +427 −0 spec/bill_spec.rb
  35. +0 −74 spec/braspag/cryptography_spec.rb
  36. +0 −6 spec/braspag/layout_spec.rb
  37. +0 −34 spec/braspag/recorrente_spec.rb
  38. +152 −18 spec/connection_spec.rb
  39. +447 −0 spec/credit_card_spec.rb
  40. +187 −0 spec/crypto/jar_webservice_spec.rb
  41. +143 −0 spec/crypto/webservice_spec.rb
  42. +209 −0 spec/eft_spec.rb
  43. +0 −68 spec/gateway_spec.rb
  44. +118 −0 spec/order_spec.rb
  45. +53 −0 spec/poster_spec.rb
  46. +277 −0 spec/protected_credit_card_spec.rb
  47. +14 −39 spec/spec_helper.rb
  48. +47 −0 spec/utils_spec.rb
  49. +0 −85 tmp/layout
View
5 .document
@@ -1,5 +0,0 @@
-README.rdoc
-lib/**/*.rb
-bin/*
-features/**/*.feature
-LICENSE
View
6 .gitignore
@@ -1,5 +1,9 @@
+nbproject
pkg
doc
tags
-*.swp
+*.sw*
.bundle
+.rvmrc
+Gemfile.lock
+
View
1  .rspec
@@ -0,0 +1 @@
+--colour
View
9 Gemfile
@@ -1,9 +1,4 @@
source "http://rubygems.org"
-gem "handsoap"
-gem "curb"
-
-group :test do
- gem "rspec"
- gem "nokogiri"
-end
+# Specify your gem's dependencies in rbraspag.gemspec
+gemspec
View
10 Guardfile
@@ -0,0 +1,10 @@
+guard 'bundler' do
+ watch('Gemfile')
+end
+
+guard 'rspec', :version => 2, :bundler => false do
+ watch(%r{^spec/(.*)_spec\.rb$})
+ watch(%r{^lib/rbraspag.rb$}) { "spec" }
+ watch(%r{^lib/rbraspag/(.*)\.rb$}) { |m| "spec/#{m[1]}_spec.rb" }
+ watch('spec/spec_helper.rb') { "spec" }
+end
View
40 README.textile → README.md
@@ -1,14 +1,39 @@
-h2. INSTALLATION
+# rBraspag
-<pre><code>sudo gem install braspag</code></pre>
+rbraspag gem to use Braspag gateway
-h2. USAGE
+* This gem need RACK_ENV environment variable to identify the environment
-<pre><code>connection = Braspag::Connection.new '{84BE7E7F-698A-6C74-F820-AE359C2A07C2}'
-gateway = Braspag::Gateway.new connection
-gateway.authorize! :orderId => 'test001', :customerName => 'Walter Bishop', :amount => '1000000,00', ...</code></pre>
+# How to install
-h2. LICENSE:
+## for Rails 3 app
+
+### Add on your Gemfile
+
+ gem "rbraspag"
+
+### Create a config/braspag.yml file
+
+ $ rails generate braspag:install
+
+### Set RACK_ENV (our suggest)
+
+ # add last line in config/environment.rb
+ # ...
+ # ENV["RACK_ENV"] ||= ENV["RAILS_ENV"]
+
+### Edit config/braspag.yml with your Braspag merchant_id
+
+# Examples
+
+## to create a Bill (Boleto/Bloqueto for brazilian guys)
+ @bill = Braspag::Bill.generate({
+ :order_id => 1,
+ :amount => 3,
+ :payment_method => 10
+ })
+
+# License
(The MIT License)
@@ -32,3 +57,4 @@ 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.
+
View
20 RELEASES.md
@@ -0,0 +1,20 @@
+# RELEASES
+
+## For next release
+
+d2b9a7a Voltando a usar o HTTPI
+
+## 0.1.1 - 09/01/2012
+
+9ffbcbd adicionando novos códigos de métodos de pagamento
+
+
+## 0.1.0 - 09/01/2012
+
+5cf697e adicionando Gemfile.lock ao .gitignore
+a6b1f54 removendo Gemfile.lock; modificando verificação do argumento has_interest
+a663e0a baixando a versão mínima requerida do nokogiri
+628d108 refatorando testes e implementação
+087549a moving Connection exceptions to errors.rb; tests for Utils class
+9a727eb bump up version
+6e5b1c3 refatorando para suportar o ambiente de produção da Braspag
View
56 Rakefile
@@ -1,54 +1,6 @@
-require 'rubygems'
-require 'rubygems/specification'
-require 'rake'
-require 'rake/gempackagetask'
-require 'spec/rake/spectask'
+require 'bundler/gem_tasks'
+require 'rspec/core/rake_task'
-GEM = "braspag"
-GEM_VERSION = "0.4.0"
-SUMMARY = "Access the Braspag webservices using Ruby"
-AUTHOR = "Gonow"
-EMAIL = "labs@gonow.com.br"
-HOMEPAGE = "http://www.gonow.com.br"
+RSpec::Core::RakeTask.new(:spec)
-spec = Gem::Specification.new do |s|
- s.name = GEM
- s.version = GEM_VERSION
- s.platform = Gem::Platform::RUBY
- s.summary = SUMMARY
- s.require_paths = ['lib']
- s.files = FileList['lib/**/*.rb', '[A-Z]*'].to_a
-
- s.add_dependency 'handsoap', '=1.1.7'
-
- s.add_development_dependency 'rspec'
- s.add_development_dependency 'nokogiri'
-
- s.author = AUTHOR
- s.email = EMAIL
- s.homepage = HOMEPAGE
-end
-
-Spec::Rake::SpecTask.new do |t|
- t.spec_files = FileList['spec/**/*_spec.rb']
- t.spec_opts = %w(-fs -fh:doc/specs.html --color)
-end
-
-Rake::GemPackageTask.new(spec) do |pkg|
- pkg.gem_spec = spec
-end
-
-desc "Install the gem locally"
-task :install => [:package] do
- sh %{sudo gem install pkg/#{GEM}-#{GEM_VERSION}}
-end
-
-desc "Create a gemspec file"
-task :make_spec do
- File.open("#{GEM}.gemspec", "w") do |file|
- file.puts spec.to_ruby
- end
-end
-
-desc "Builds the project"
-task :build => :spec
+task :default => :spec
View
41 braspag.gemspec
@@ -1,41 +0,0 @@
-# -*- encoding: utf-8 -*-
-
-Gem::Specification.new do |s|
- s.name = %q{braspag}
- s.version = "0.4.0"
-
- s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version=
- s.authors = ["Gonow"]
- s.date = %q{2010-09-10}
- s.email = %q{labs@gonow.com.br}
- s.files = ["lib/braspag/connection.rb", "lib/braspag/cryptography.rb", "lib/braspag/gateway.rb", "lib/braspag/recorrente.rb", "lib/braspag/service.rb", "lib/braspag.rb", "Rakefile", "README.textile"]
- s.homepage = %q{http://www.gonow.com.br}
- s.require_paths = ["lib"]
- s.rubygems_version = %q{1.3.7}
- s.summary = %q{Access the Braspag webservices using Ruby}
-
- if s.respond_to? :specification_version then
- current_version = Gem::Specification::CURRENT_SPECIFICATION_VERSION
- s.specification_version = 3
-
- if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then
- s.add_runtime_dependency(%q<rubigen>, [">= 1.3.4"])
- s.add_runtime_dependency(%q<handsoap>, ["= 1.1.7"])
- s.add_runtime_dependency(%q<curb>, ["= 0.7.6"])
- s.add_development_dependency(%q<rspec>, [">= 0"])
- s.add_development_dependency(%q<nokogiri>, [">= 0"])
- else
- s.add_dependency(%q<rubigen>, [">= 1.3.4"])
- s.add_dependency(%q<handsoap>, ["= 1.1.7"])
- s.add_dependency(%q<curb>, ["= 0.7.6"])
- s.add_dependency(%q<rspec>, [">= 0"])
- s.add_dependency(%q<nokogiri>, [">= 0"])
- end
- else
- s.add_dependency(%q<rubigen>, [">= 1.3.4"])
- s.add_dependency(%q<handsoap>, ["= 1.1.7"])
- s.add_dependency(%q<curb>, ["= 0.7.6"])
- s.add_dependency(%q<rspec>, [">= 0"])
- s.add_dependency(%q<nokogiri>, [">= 0"])
- end
-end
View
17 config/braspag.yml
@@ -0,0 +1,17 @@
+development:
+ environment: "homologation"
+ merchant_id: "{84BE7E7F-698A-6C74-F820-AE359C2A07C2}"
+ crypto_url: "http://localhost:9292"
+ crypto_key: "1234561246"
+
+test:
+ environment: "homologation"
+ merchant_id: "{84BE7E7F-698A-6C74-F820-AE359C2A07C2}"
+ crypto_url: "http://localhost:9292"
+ crypto_key: "1234561246"
+
+production:
+ environment: "production"
+ merchant_id: "{84BE7E7F-698A-6C74-F820-AE359C2A07C2}"
+ crypto_url: "http://localhost:9292"
+ crypto_key: "1234561246"
View
32 lib/braspag.rb
@@ -1,32 +0,0 @@
-require 'rubygems'
-require 'bundler/setup'
-
-require 'handsoap'
-require 'braspag/service'
-require 'braspag/cryptography'
-require 'braspag/connection'
-require 'braspag/gateway'
-require 'braspag/recorrente'
-
-module Braspag
- class Production
- BASE_URL = 'https://transaction.pagador.com.br'
- end
-
- class Test
- BASE_URL = 'https://homologacao.pagador.com.br'
- end
-end
-
-module Handsoap
- class Service
- private
- def invoke_and_parse(method_name, soap_action, &block)
- response = invoke("tns:#{method_name}", soap_action) do |message|
- message.add("tns:merchantId", @connection.merchant_id)
- block.call(message)
- end
- response.document.xpath("//ns:#{method_name}Result").first
- end
- end
-end
View
12 lib/braspag/connection.rb
@@ -1,12 +0,0 @@
-module Braspag
- class Connection
- attr_reader :base_url, :environment, :merchant_id
-
- def initialize(merchant_id, environment = :production)
- environment = :test unless environment.eql? :production
- @environment = eval(environment.to_s.capitalize)
- @base_url = @environment::BASE_URL
- @merchant_id = merchant_id
- end
- end
-end
View
42 lib/braspag/cryptography.rb
@@ -1,42 +0,0 @@
-module Braspag
- class Cryptography < Handsoap::Service
- include Braspag::Service
-
- def encrypt(map)
- soap_action = "#{base_action_url}/EncryptRequest"
- invoke_and_parse('EncryptRequest', soap_action) do |message|
- message.add("tns:request") do |sub_message|
- map.each do |key, value|
- sub_message.add("tns:string", "#{key}=#{value}")
- end
- end
- end.to_s
- end
-
- def decrypt(encripted_text)
- soap_action = "#{base_action_url}/DecryptRequest"
- document = invoke_and_parse('DecryptRequest', soap_action) do |message|
- message.add("tns:cryptString", encripted_text)
- end
- convert_request_to_map document
- end
-
- def base_action_url
- "https://www.pagador.com.br/webservice/BraspagGeneralService"
- end
-
- def uri
- "#{@connection.base_url}/BraspagGeneralService/BraspagGeneralService.asmx"
- end
-
- private
- def convert_request_to_map(document)
- map = {}
- document.xpath("//ns:string").each do |text|
- values = text.to_s.split("=")
- map[values[0].downcase.to_sym] = values[1]
- end
- map
- end
- end
-end
View
46 lib/braspag/gateway.rb
@@ -1,46 +0,0 @@
-module Braspag
- class Gateway < Handsoap::Service
- include Braspag::Service
-
- %w(authorize capture).each do |method|
- eval <<-METHOD
- def #{method}!(map)
- invoke! "#{method.capitalize}", map
- end
- METHOD
- end
-
- def void_transaction!(map)
- invoke! "VoidTransaction", map
- end
-
- protected
-
- def invoke!(method, map)
- document = invoke_and_parse(method, "#{uri}/#{method}") do |message|
- map.each do |key, value|
- message.add("tns:#{key}", "#{value}")
- end
- end
- convert_to_map document
- end
-
- def base_action_url
- "https://www.pagador.com.br/webservice/pagador"
- end
-
- def uri
- "#{@connection.base_url}/webservices/pagador/Pagador.asmx"
- end
-
- def convert_to_map(document)
- map = { "amount" => "", "authorisationNumber" => "", "message" => "", "returnCode" => "", "status" => "", "transactionId" => "" }
- map.each_key do |key|
- document.xpath("//ns:#{key}").each do |text|
- map[key] = text.to_s
- end
- end
- map
- end
- end
-end
View
35 lib/braspag/recorrente.rb
@@ -1,35 +0,0 @@
-module Braspag
- class Recorrente < Handsoap::Service
- include Braspag::Service
-
- def create_creditcard_order(map)
- soap_action = "#{base_action_url}/CreateCreditCardOrder"
- document = invoke_and_parse('CreateCreditCardOrder', soap_action) do |message|
- map.each do |key, value|
- message.add("tns:#{key}", "#{value}")
- end
- end
- convert_to_map document
- end
-
- def base_action_url
- "https://www.pagador.com.br/webservice/recorrente"
- end
-
- def uri
- "#{@connection.base_url}/webservice/recorrente.asmx"
- end
-
- private
- def convert_to_map(document)
- map = {"code" => "", "description" => ""}
- map.each_key do |key|
- document.xpath("//ns:#{key}").each do |text|
- map[key] = text.to_s
- end
- end
- map
- end
-
- end
-end
View
16 lib/braspag/service.rb
@@ -1,16 +0,0 @@
-module Braspag
- module Service
- def initialize(connection)
- @connection = connection
- self.class.endpoint :uri => uri, :version => 2
- end
-
- def on_create_document(doc)
- doc.alias 'tns', base_action_url
- end
-
- def on_response_document(doc)
- doc.add_namespace 'ns', base_action_url
- end
- end
-end
View
15 lib/generators/braspag/install/install_generator.rb
@@ -0,0 +1,15 @@
+module Braspag
+ module Generators
+ class InstallGenerator < ::Rails::Generators::Base
+ desc "Copy braspag.yml file to your application config directory."
+
+ def self.source_root
+ @source_root ||= File.expand_path(File.join(File.dirname(__FILE__), 'templates'))
+ end
+
+ def copy_config_file
+ template "config/braspag.yml"
+ end
+ end
+ end
+end
View
17 lib/generators/braspag/install/templates/config/braspag.yml
@@ -0,0 +1,17 @@
+development:
+ environment: "homologation"
+ merchant_id: "{YOUR_MERCHANT_ID_ON_BRASPAG}"
+ crypto_url: "http://localhost:9292"
+ crypto_key: "1234561246"
+
+test:
+ environment: "homologation"
+ merchant_id: "{YOUR_MERCHANT_ID_ON_BRASPAG}"
+ crypto_url: "http://localhost:9292"
+ crypto_key: "1234561246"
+
+production:
+ environment: "production"
+ merchant_id: "{YOUR_MERCHANT_ID_ON_BRASPAG}"
+ crypto_url: "http://localhost:9292"
+ crypto_key: "1234561246"
View
45 lib/rbraspag.rb
@@ -0,0 +1,45 @@
+require 'singleton'
+require 'httpi'
+require 'nokogiri'
+require 'json'
+require 'savon'
+
+require "rbraspag/version"
+require 'rbraspag/connection'
+require 'rbraspag/payment_method'
+require 'rbraspag/crypto/jar_webservice'
+require 'rbraspag/crypto/webservice'
+require 'rbraspag/bill'
+require 'rbraspag/poster'
+require 'rbraspag/credit_card'
+require 'rbraspag/protected_credit_card'
+require 'rbraspag/eft'
+require 'rbraspag/errors'
+require 'rbraspag/utils'
+require 'rbraspag/order'
+
+module Braspag
+ def self.logger=(value)
+ @logger = value
+ end
+
+ def self.logger
+ @logger
+ end
+
+ def self.config_file_path=(path)
+ @config_path = path
+ end
+
+ def self.config_file_path
+ @config_path || 'config/braspag.yml'
+ end
+
+ def self.proxy_address=(value)
+ @proxy_address = value
+ end
+
+ def self.proxy_address
+ @proxy_address
+ end
+end
View
160 lib/rbraspag/bill.rb
@@ -0,0 +1,160 @@
+require "bigdecimal"
+
+module Braspag
+ class Bill < PaymentMethod
+
+ PAYMENT_METHODS = {
+ :bradesco => "06",
+ :cef => "07",
+ :hsbc => "08",
+ :bb => "09",
+ :real => "10",
+ :citibank => "13",
+ :itau => "14",
+ :unibanco => "26"
+ }
+
+ MAPPING = {
+ :merchant_id => "merchantId",
+ :order_id => "orderId",
+ :customer_name => "customerName",
+ :customer_id => "customerIdNumber",
+ :amount => "amount",
+ :payment_method => "paymentMethod",
+ :number => "boletoNumber",
+ :instructions => "instructions",
+ :expiration_date => "expirationDate",
+ :emails => "emails"
+ }
+
+ PRODUCTION_INFO_URI = "/webservices/pagador/pedido.asmx/GetDadosBoleto"
+ HOMOLOGATION_INFO_URI = "/pagador/webservice/pedido.asmx/GetDadosBoleto"
+ CREATION_URI = "/webservices/pagador/Boleto.asmx/CreateBoleto"
+
+ def self.generate(params)
+ connection = Braspag::Connection.instance
+ params[:merchant_id] = connection.merchant_id
+
+ params = self.normalize_params(params)
+ self.check_params(params)
+
+ data = {}
+
+ MAPPING.each do |k, v|
+ case k
+ when :payment_method
+ data[v] = PAYMENT_METHODS[params[:payment_method]]
+ when :amount
+ data[v] = Utils.convert_decimal_to_string(params[:amount])
+ else
+ data[v] = params[k] || ""
+ end
+ end
+
+ request = ::HTTPI::Request.new(self.creation_url)
+ request.body = data
+
+ response = Utils::convert_to_map(::HTTPI.post(request).body,
+ {
+ :url => nil,
+ :amount => nil,
+ :number => "boletoNumber",
+ :expiration_date => Proc.new { |document|
+ begin
+ Date.parse(document.search("expirationDate").first.to_s)
+ rescue
+ nil
+ end
+ },
+ :return_code => "returnCode",
+ :status => nil,
+ :message => nil
+ })
+
+ raise InvalidMerchantId if response[:message] == "Invalid merchantId"
+ raise InvalidAmount if response[:message] == "Invalid purchase amount"
+ raise InvalidPaymentMethod if response[:message] == "Invalid payment method"
+ raise InvalidStringFormat if response[:message] == "Input string was not in a correct format."
+ raise UnknownError if response[:status].nil?
+
+ response[:amount] = BigDecimal.new(response[:amount])
+
+ response
+ end
+
+ def self.normalize_params(params)
+ params = super
+
+ if params[:expiration_date].respond_to?(:strftime)
+ params[:expiration_date] = params[:expiration_date].strftime("%d/%m/%y")
+ end
+
+ params
+ end
+
+ def self.check_params(params)
+ super
+
+ if params[:number]
+ raise InvalidNumber unless (1..255).include?(params[:number].to_s.size)
+ end
+
+ if params[:instructions]
+ raise InvalidInstructions unless (1..512).include?(params[:instructions].to_s.size)
+ end
+
+ if params[:expiration_date]
+ matches = params[:expiration_date].to_s.match /(\d{2})\/(\d{2})\/(\d{2})/
+ raise InvalidExpirationDate unless matches
+ begin
+ Date.new(matches[3].to_i, matches[2].to_i, matches[1].to_i)
+ rescue ArgumentError
+ raise InvalidExpirationDate
+ end
+ end
+ end
+
+ def self.info_url
+ connection = Braspag::Connection.instance
+ connection.braspag_url + (connection.production? ? PRODUCTION_INFO_URI : HOMOLOGATION_INFO_URI)
+ end
+
+ def self.creation_url
+ Braspag::Connection.instance.braspag_url + CREATION_URI
+ end
+
+ def self.info(order_id)
+ connection = Braspag::Connection.instance
+
+ raise InvalidOrderId unless self.valid_order_id?(order_id)
+
+ request = ::HTTPI::Request.new(self.info_url)
+ request.body = {
+ :loja => connection.merchant_id,
+ :numeroPedido => order_id.to_s
+ }
+
+ response = ::HTTPI.post(request)
+
+ response = Utils::convert_to_map(response.body, {
+ :document_number => "NumeroDocumento",
+ :payer => "Sacado",
+ :our_number => "NossoNumero",
+ :bill_line => "LinhaDigitavel",
+ :document_date => "DataDocumento",
+ :expiration_date => "DataVencimento",
+ :receiver => "Cedente",
+ :bank => "Banco",
+ :agency => "Agencia",
+ :account => "Conta",
+ :wallet => "Carteira",
+ :amount => "ValorDocumento",
+ :amount_invoice => "ValorPago",
+ :invoice_date => "DataCredito"
+ })
+
+ raise UnknownError if response[:document_number].nil?
+ response
+ end
+ end
+end
View
37 lib/rbraspag/connection.rb
@@ -0,0 +1,37 @@
+module Braspag
+ class Connection
+ include Singleton
+
+ PRODUCTION_URL = "https://transaction.pagador.com.br"
+ HOMOLOGATION_URL = "https://homologacao.pagador.com.br"
+
+ PROTECTED_CARD_PRODUCTION_URL = "https://cartaoprotegido.braspag.com.br/Services"
+ PROTECTED_CARD_HOMOLOGATION_URL = "https://homologacao.braspag.com.br/services/testenvironment"
+
+ attr_reader :braspag_url, :protected_card_url, :merchant_id, :crypto_url, :crypto_key, :options, :environment
+
+ def initialize
+ raise InvalidEnv if ENV["BRASPAG_ENV"].nil? || ENV["BRASPAG_ENV"].empty?
+
+ @options = YAML.load_file(Braspag.config_file_path)[ ENV['BRASPAG_ENV'] ]
+ @merchant_id = @options['merchant_id']
+
+ raise InvalidMerchantId unless @merchant_id =~ /\{[a-z0-9]{8}-([a-z0-9]{4}-){3}[a-z0-9]{12}\}/i
+
+ @crypto_key = @options["crypto_key"]
+ @crypto_url = @options["crypto_url"]
+ @environment = @options["environment"] == 'production' ? 'production' : 'homologation'
+
+ @braspag_url = self.production? ? PRODUCTION_URL : HOMOLOGATION_URL
+ @protected_card_url = self.production? ? PROTECTED_CARD_PRODUCTION_URL : PROTECTED_CARD_HOMOLOGATION_URL
+ end
+
+ def production?
+ @environment == 'production'
+ end
+
+ def homologation?
+ @environment == 'homologation'
+ end
+ end
+end
View
181 lib/rbraspag/credit_card.rb
@@ -0,0 +1,181 @@
+module Braspag
+ class CreditCard < PaymentMethod
+
+ MAPPING = {
+ :merchant_id => "merchantId",
+ :order => 'order',
+ :order_id => "orderId",
+ :customer_name => "customerName",
+ :amount => "amount",
+ :payment_method => "paymentMethod",
+ :holder => "holder",
+ :card_number => "cardNumber",
+ :expiration => "expiration",
+ :security_code => "securityCode",
+ :number_payments => "numberPayments",
+ :type => "typePayment",
+ }
+
+ AUTHORIZE_URI = "/webservices/pagador/Pagador.asmx/Authorize"
+ CAPTURE_URI = "/webservices/pagador/Pagador.asmx/Capture"
+ CANCELLATION_URI = "/webservices/pagador/Pagador.asmx/VoidTransaction"
+ PRODUCTION_INFO_URI = "/webservices/pagador/pedido.asmx/GetDadosCartao"
+ HOMOLOGATION_INFO_URI = "/pagador/webservice/pedido.asmx/GetDadosCartao"
+
+ def self.authorize(params = {})
+ connection = Braspag::Connection.instance
+ params[:merchant_id] = connection.merchant_id
+
+ self.check_params(params)
+
+ data = {}
+ MAPPING.each do |k, v|
+ case k
+ when :payment_method
+ data[v] = Braspag::Connection.instance.homologation? ? PAYMENT_METHODS[:braspag] : PAYMENT_METHODS[params[:payment_method]]
+ when :amount
+ data[v] = Utils.convert_decimal_to_string(params[:amount])
+ else
+ data[v] = params[k] || ""
+ end
+ end
+
+ response = Braspag::Poster.new(self.authorize_url).do_post(:authorize, data)
+
+ Utils::convert_to_map(response.body, {
+ :amount => nil,
+ :number => "authorisationNumber",
+ :message => 'message',
+ :return_code => 'returnCode',
+ :status => 'status',
+ :transaction_id => "transactionId"
+ })
+ end
+
+ def self.capture(order_id)
+ connection = Braspag::Connection.instance
+ merchant_id = connection.merchant_id
+
+ raise InvalidOrderId unless self.valid_order_id?(order_id)
+
+ data = {
+ MAPPING[:order_id] => order_id,
+ MAPPING[:merchant_id] => merchant_id
+ }
+
+ response = Braspag::Poster.new(self.capture_url).do_post(:capture, data)
+
+ Utils::convert_to_map(response.body, {
+ :amount => nil,
+ :number => "authorisationNumber",
+ :message => 'message',
+ :return_code => 'returnCode',
+ :status => 'status',
+ :transaction_id => "transactionId"
+ })
+ end
+
+ def self.void(order_id)
+ connection = Braspag::Connection.instance
+ merchant_id = connection.merchant_id
+
+ raise InvalidOrderId unless self.valid_order_id?(order_id)
+
+ data = {
+ MAPPING[:order] => order_id,
+ MAPPING[:merchant_id] => merchant_id
+ }
+
+ response = Braspag::Poster.new(self.cancellation_url).do_post(:void, data)
+
+ Utils::convert_to_map(response.body, {
+ :amount => nil,
+ :number => "authorisationNumber",
+ :message => 'message',
+ :return_code => 'returnCode',
+ :status => 'status',
+ :transaction_id => "transactionId"
+ })
+ end
+
+ def self.info(order_id)
+ connection = Braspag::Connection.instance
+
+ raise InvalidOrderId unless self.valid_order_id?(order_id)
+
+ data = {:loja => connection.merchant_id, :numeroPedido => order_id.to_s}
+ response = Braspag::Poster.new(self.info_url).do_post(:info_credit_card, data)
+
+ response = Utils::convert_to_map(response.body, {
+ :checking_number => "NumeroComprovante",
+ :certified => "Autenticada",
+ :autorization_number => "NumeroAutorizacao",
+ :card_number => "NumeroCartao",
+ :transaction_number => "NumeroTransacao"
+ })
+
+ raise UnknownError if response[:checking_number].nil?
+ response
+ end
+
+ def self.check_params(params)
+ super
+
+ [:customer_name, :holder, :card_number, :expiration, :security_code, :number_payments, :type].each do |param|
+ raise IncompleteParams if params[param].nil?
+ end
+
+ raise InvalidHolder if params[:holder].to_s.size < 1 || params[:holder].to_s.size > 100
+
+ matches = params[:expiration].to_s.match /^(\d{2})\/(\d{2,4})$/
+ raise InvalidExpirationDate unless matches
+ begin
+ year = matches[2].to_i
+ year = "20#{year}" if year.size == 2
+
+ Date.new(year.to_i, matches[1].to_i)
+ rescue ArgumentError
+ raise InvalidExpirationDate
+ end
+
+ raise InvalidSecurityCode if params[:security_code].to_s.size < 1 || params[:security_code].to_s.size > 4
+
+ raise InvalidNumberPayments if params[:number_payments].to_i < 1 || params[:number_payments].to_i > 99
+ end
+
+ # <b>DEPRECATED:</b> Please use <tt>ProtectedCreditCard.save</tt> instead.
+ def self.save(params)
+ warn "[DEPRECATION] `CreditCard.save` is deprecated. Please use `ProtectedCreditCard.save` instead."
+ ProtectedCreditCard.save(params)
+ end
+
+ # <b>DEPRECATED:</b> Please use <tt>ProtectedCreditCard.get</tt> instead.
+ def self.get(just_click_key)
+ warn "[DEPRECATION] `CreditCard.get` is deprecated. Please use `ProtectedCreditCard.get` instead."
+ ProtectedCreditCard.get(just_click_key)
+ end
+
+ # <b>DEPRECATED:</b> Please use <tt>ProtectedCreditCard.just_click_shop</tt> instead.
+ def self.just_click_shop(params = {})
+ warn "[DEPRECATION] `CreditCard.just_click_shop` is deprecated. Please use `ProtectedCreditCard.just_click_shop` instead."
+ ProtectedCreditCard.just_click_shop(params)
+ end
+
+ def self.info_url
+ connection = Braspag::Connection.instance
+ connection.braspag_url + (connection.production? ? PRODUCTION_INFO_URI : HOMOLOGATION_INFO_URI)
+ end
+
+ def self.authorize_url
+ Braspag::Connection.instance.braspag_url + AUTHORIZE_URI
+ end
+
+ def self.capture_url
+ Braspag::Connection.instance.braspag_url + CAPTURE_URI
+ end
+
+ def self.cancellation_url
+ Braspag::Connection.instance.braspag_url + CANCELLATION_URI
+ end
+ end
+end
View
91 lib/rbraspag/crypto/jar_webservice.rb
@@ -0,0 +1,91 @@
+module Braspag
+ module Crypto
+ class JarWebservice
+ def self.encrypt(map)
+ crypto_key = Braspag::Connection.instance.crypto_key
+ raise Braspag::IncompleteParams if map.nil?
+ raise Braspag::IncompleteParams unless map.is_a?(Hash)
+
+ request = ::HTTPI::Request.new encrypt_uri
+
+ data = {:key => crypto_key, :fields => map}
+
+ request.headers["Content-Type"] = "application/json"
+
+ request.body = data.to_json
+
+ response = ::HTTPI.post request
+
+ begin
+ response = JSON.parse(response.body)
+ rescue Exception => e
+ raise UnknownError
+ end
+
+ raise IncompleteParams if (
+ response["msg"] == "INVALID FORMAT" ||
+ response["msg"] == "INVALID FIELDS"
+ )
+
+ raise InvalidEncryptedKey if response["msg"] == "INVALID ENCRYPTED STRING"
+ raise InvalidCryptKey if response["msg"] == "INVALID KEY"
+
+ response["encrypt"]
+ end
+
+ def self.decrypt(encrypted, fields)
+ crypto_key = Braspag::Connection.instance.crypto_key
+ raise Braspag::InvalidEncryptedKey if encrypted.nil?
+ raise Braspag::InvalidEncryptedKey unless encrypted.is_a?(String)
+
+ raise Braspag::IncompleteParams if fields.nil?
+ raise Braspag::IncompleteParams unless fields.is_a?(Array)
+
+
+ request = ::HTTPI::Request.new decrypt_uri
+ request.body = {
+ "key" => crypto_key,
+ "encrypted" => encrypted,
+ "fields" => fields
+ }.to_json
+
+ request.headers["Content-Type"] = "application/json"
+
+ response = ::HTTPI.post request
+
+ begin
+ response = JSON.parse(response.body)
+ rescue Exception => e
+ raise UnknownError
+ end
+
+ raise IncompleteParams if (
+ response["msg"] == "INVALID FORMAT" ||
+ response["msg"] == "INVALID FIELDS"
+ )
+
+ raise InvalidEncryptedKey if response["msg"] == "INVALID ENCRYPTED STRING"
+
+ raise InvalidCryptKey if response["msg"] == "INVALID KEY"
+
+ map = {}
+ response["fields"].each do |key,value|
+ map[key.downcase.to_sym] = value
+ end
+ map
+ end
+
+ protected
+ def self.encrypt_uri
+ connection_uri = Braspag::Connection.instance.crypto_url
+ "#{connection_uri}/v1/encrypt.json"
+ end
+
+ def self.decrypt_uri
+ connection_uri = Braspag::Connection.instance.crypto_url
+ "#{connection_uri}/v1/decrypt.json"
+ end
+
+ end
+ end
+end
View
100 lib/rbraspag/crypto/webservice.rb
@@ -0,0 +1,100 @@
+module Braspag
+ module Crypto
+ class Webservice
+ def self.encrypt(map)
+ connection = Braspag::Connection.instance
+ raise Braspag::IncompleteParams if map.nil?
+ raise Braspag::IncompleteParams unless map.is_a?(Hash)
+
+ request = ::HTTPI::Request.new self.uri
+
+ fields = "\n"
+ map.each do |key, value|
+ fields.concat(" <tns:string>#{key}=#{value}</tns:string>\n")
+ end
+
+ request.body = <<-STRING
+<?xml version="1.0" encoding="utf-8"?>
+<env:Envelope xmlns:env="http://www.w3.org/2003/05/soap-envelope">
+ <env:Header />
+ <env:Body>
+ <tns:EncryptRequest xmlns:tns="https://www.pagador.com.br/webservice/BraspagGeneralService">
+ <tns:merchantId>#{connection.merchant_id}</tns:merchantId>
+ <tns:request>
+ #{fields}
+ </tns:request>
+ </tns:EncryptRequest>
+ </env:Body>
+</env:Envelope>
+STRING
+
+ request.headers["Content-Type"] = "text/xml"
+
+ response = ::HTTPI.post request
+
+ document = Nokogiri::XML(response.body)
+
+ raise Braspag::UnknownError if document.children.empty?
+
+ #melhorar este parser cof cof
+ response = document.children.children.children.children.children.to_s
+
+ raise Braspag::InvalidMerchantId if (response == 'Erro BP 011' || response == 'Erro BP 012')
+ raise Braspag::InvalidIP if (response == 'Erro BP 067' || response == 'Erro BP 068')
+
+ response
+ end
+
+ def self.decrypt(encripted_text)
+ connection = Braspag::Connection.instance
+
+ raise Braspag::IncompleteParams if encripted_text.nil?
+ raise Braspag::IncompleteParams unless encripted_text.is_a?(String)
+
+ request = ::HTTPI::Request.new self.uri
+
+ request.body = <<-STRING
+<?xml version="1.0" encoding="utf-8"?>
+<env:Envelope xmlns:env="http://www.w3.org/2003/05/soap-envelope">
+ <env:Header />
+ <env:Body>
+ <tns:DecryptRequest xmlns:tns="https://www.pagador.com.br/webservice/BraspagGeneralService">
+ <tns:merchantId>#{connection.merchant_id}</tns:merchantId>
+ <tns:cryptString>#{encripted_text}</tns:cryptString>
+ </tns:DecryptRequest>
+ </env:Body>
+</env:Envelope>
+STRING
+
+ request.headers["Content-Type"] = "text/xml"
+
+ response = ::HTTPI.post request
+
+ document = Nokogiri::XML(response.body)
+ raise Braspag::UnknownError if document.children.empty?
+
+ result_error = document.children.children.children.children.children.first.content.to_s
+
+ raise Braspag::InvalidMerchantId if (result_error == 'Erro BP 011' || result_error == 'Erro BP 012')
+ raise Braspag::InvalidIP if (result_error == 'Erro BP 067' || result_error == 'Erro BP 068')
+
+ self.convert_request_to_map document
+ end
+
+ protected
+ def self.uri
+ connection = Braspag::Connection.instance
+ "#{connection.braspag_url}/BraspagGeneralService/BraspagGeneralService.asmx"
+ end
+
+ def self.convert_request_to_map(document)
+ map = {}
+ document.children.children.children.children.children.each do |n|
+ values = n.content.to_s.split("=")
+ map[values[0].downcase.to_sym] = values[1]
+ end
+ map
+ end
+ end
+ end
+end
View
90 lib/rbraspag/eft.rb
@@ -0,0 +1,90 @@
+module Braspag
+ class Eft < PaymentMethod
+
+ PAYMENT_METHODS = {
+ :bradesco => 11,
+ :itau => 12,
+ :banco_do_brasil => 15,
+ :banco_real => 16,
+ :banrisul => 30,
+ :unibanco => 31
+ }
+
+ MAPPING = {
+ :merchant_id => "Id_Loja",
+ :order_id => "VENDAID",
+ :customer_name => "nome",
+ :customer_id => "CPF",
+ :amount => "VALOR",
+ :payment_method => "CODPAGAMENTO",
+ :installments => "PARCELAS",
+ :has_interest => "TIPOPARCELADO"
+ }
+
+ ACTION_URI = "/pagador/passthru.asp"
+
+ def self.generate(params, crypto_strategy = nil)
+ connection = Braspag::Connection.instance
+ params[:merchant_id] = connection.merchant_id
+
+ params = self.normalize_params(params)
+ self.check_params(params)
+
+ data = {}
+
+ MAPPING.each do |k, v|
+ case k
+ when :payment_method
+ data[v] = PAYMENT_METHODS[params[:payment_method]]
+ when :amount
+ data[v] = Utils.convert_decimal_to_string(params[:amount])
+ else
+ data[v] = params[k] || ""
+ end
+ end
+
+ html = "<form id=\"form_tef_#{params[:order_id]}\" name=\"form_tef_#{params[:order_id]}\" action=\"#{self.action_url}\" method=\"post\">"
+
+ if crypto_strategy.nil?
+ data.each do |key, value|
+ html << "<input type=\"text\" name=\"#{key}\" value=\"#{value}\" />"
+ end
+ else
+ data.delete("Id_Loja")
+ html << "<input type=\"text\" name=\"Id_Loja\" value=\"#{params[:merchant_id]}\" />"
+ html << "<input type=\"text\" name=\"crypt\" value=\"#{crypto_strategy.encrypt(data)}\" />"
+ end
+
+ html << "</form><script type=\"text/javascript\" charset=\"utf-8\">document.forms[\"form_tef_#{params[:order_id]}\"].submit();</script>"
+
+ html
+ end
+
+ def self.normalize_params(params)
+ params = super
+
+ params[:installments] = params[:installments].to_i unless params[:installments].nil?
+ params[:installments] ||= 1
+
+ params[:has_interest] = params[:has_interest] == true ? "1" : "0"
+
+ params
+ end
+
+ def self.check_params(params)
+ super
+
+ if params[:installments]
+ raise InvalidInstallments if params[:installments].to_i < 1 || params[:installments].to_i > 99
+ end
+
+ if params[:has_interest]
+ raise InvalidHasInterest if params[:has_interest] != "1" && params[:has_interest] != "0"
+ end
+ end
+
+ def self.action_url
+ Braspag::Connection.instance.braspag_url + ACTION_URI
+ end
+ end
+end
View
39 lib/rbraspag/errors.rb
@@ -0,0 +1,39 @@
+module Braspag
+ class InvalidConnection < Exception ; end
+ class InvalidMerchantId < Exception ; end
+ class InvalidConnection < Exception ; end
+ class IncompleteParams < Exception ; end
+ class InvalidOrderId < Exception ; end
+ class InvalidCustomerName < Exception ; end
+ class InvalidCustomerId < Exception ; end
+ class InvalidNumber < Exception ; end
+ class InvalidInstructions < Exception ; end
+ class InvalidExpirationDate < Exception ; end
+ class InvalidStringFormat < Exception ; end
+ class InvalidPost < Exception ; end
+ class InvalidPaymentMethod < Exception ; end
+ class InvalidAmount < Exception ; end
+ class InvalidInstallments < Exception ; end
+ class InvalidHasInterest < Exception ; end
+ class InvalidIP < Exception; end
+ class InvalidCryptKey < Exception; end
+ class InvalidEncryptedKey < Exception; end
+ class InvalidHolder < Exception ; end
+ class InvalidExpirationDate < Exception ; end
+ class InvalidSecurityCode < Exception ; end
+ class InvalidType < Exception ; end
+ class InvalidNumberPayments < Exception ; end
+ class InvalidNumberInstallments < Exception ; end
+ class InvalidJustClickKey < Exception ; end
+ class UnknownError < Exception ; end
+
+ class Connection
+ class InvalidMerchantId < Exception ; end
+ class InvalidEnv < Exception ; end
+ class InvalidBraspagUrl < Exception ; end
+ end
+
+ class Order
+ class InvalidData < Exception; end
+ end
+end
View
43 lib/rbraspag/order.rb
@@ -0,0 +1,43 @@
+module Braspag
+ class Order
+ PRODUCTION_INFO_URI = "/webservices/pagador/pedido.asmx/GetDadosPedido"
+ HOMOLOGATION_INFO_URI = "/pagador/webservice/pedido.asmx/GetDadosPedido"
+
+ def self.status(order_id)
+ connection = Braspag::Connection.instance
+
+ raise InvalidOrderId unless Braspag::PaymentMethod.valid_order_id?(order_id)
+
+ request = ::HTTPI::Request.new(self.status_url)
+ request.body = {
+ :loja => connection.merchant_id, :numeroPedido => order_id.to_s
+ }
+
+ response = ::HTTPI.post(request)
+
+ response = Utils::convert_to_map(response.body, {
+ :authorization => "CodigoAutorizacao",
+ :error_code => "CodigoErro",
+ :error_message => "MensagemErro",
+ :payment_method => "CodigoPagamento",
+ :payment_method_name => "FormaPagamento",
+ :installments => "NumeroParcelas",
+ :status => "Status",
+ :amount => "Valor",
+ :cancelled_at => "DataCancelamento",
+ :paid_at => "DataPagamento",
+ :order_date => "DataPedido",
+ :transaction_id => "TransId",
+ :tid => "BraspagTid"
+ })
+
+ raise InvalidData if response[:authorization].nil?
+ response
+ end
+
+ def self.status_url
+ connection = Braspag::Connection.instance
+ connection.braspag_url + (connection.production? ? PRODUCTION_INFO_URI : HOMOLOGATION_INFO_URI)
+ end
+ end
+end
View
72 lib/rbraspag/payment_method.rb
@@ -0,0 +1,72 @@
+module Braspag
+ class PaymentMethod
+ PAYMENT_METHODS = {
+ # BRASIL
+ :amex_2p => 18, # American Express 2 Party
+ :cielo_noauth_visa => 71, # Cielo webservice captura automática sem autenticação - Visa
+ :cielo_preauth_visa => 73, # Cielo webservice preauth sem autenticação - Visa
+ :cielo_noauth_mastercard => 120, # Cielo webservice captura automática sem autenticação - Mastercard
+ :cielo_preauth_mastercard => 122, # Cielo webservice preauth sem autenticação - Mastercard
+ :cielo_noauth_elo => 126, # Cielo webservice captura automática sem autenticação - ELO
+ :cielo_noauth_diners => 130, # Cielo webservice captura automática sem autenticação - Diners
+ :redecard => 20, # Redecard Mastercard/Diners/Visa
+ :redecard_preauth => 42, # Redecard preauth Mastercard/Diners/Visa
+ :cielo_sitef => 57, # Cielo SITEF
+ :hipercard_sitef => 62, # Hipercard SITEF
+ :hipercard_moip => 90, # Hipercard MOIP
+ :oi_paggo => 55, # OiPaggo
+ :amex_sitef => 58, # Amex SITEF
+ :aura_dtef => 37, # Aura DTEF
+ :redecard_sitef => 44, # Redecard SITEF - Mastercard/Diners
+ # MÉXICO
+ :mex_amex_2p => 45, # American Express 2 Party
+ :mex_banorte_visa => 50, # Banorte Visa
+ :mex_banorte_diners => 52, # Banorte Diners
+ :mex_banorte_mastercard => 53, # Banorte Mastercard
+ # COLÔMBIA
+ :col_visa => 63, # Visa
+ :col_amex => 65, # Amex
+ :col_diners => 66, # Diners
+ # INTERNACIONAL
+ :paypal_express => 35, # PayPal Express Checkout
+ # HOMOLOGATION
+ :braspag => 997
+ }
+
+ def self.payment_method_from_id(code)
+ self::PAYMENT_METHODS.invert.values_at(code).first
+ end
+
+ def self.normalize_params(params)
+ if params[:amount] && !params[:amount].is_a?(BigDecimal)
+ params[:amount] = BigDecimal.new(params[:amount].to_s)
+ end
+
+ params
+ end
+
+ def self.check_params(params)
+ [:order_id, :amount, :payment_method].each do |param|
+ raise IncompleteParams if params[param].nil?
+ end
+
+ raise InvalidOrderId unless self.valid_order_id?(params[:order_id])
+
+ if params[:customer_name]
+ raise InvalidCustomerName unless (1..255).include?(params[:customer_name].to_s.size)
+ end
+
+ if params[:customer_id]
+ raise InvalidCustomerId unless (11..18).include?(params[:customer_id].to_s.size)
+ end
+
+ unless params[:payment_method].is_a?(Symbol) && self::PAYMENT_METHODS[params[:payment_method]]
+ raise InvalidPaymentMethod
+ end
+ end
+
+ def self.valid_order_id?(order_id)
+ (order_id.is_a?(String) || order_id.is_a?(Fixnum)) && (1..50).include?(order_id.to_s.size)
+ end
+ end
+end
View
36 lib/rbraspag/poster.rb
@@ -0,0 +1,36 @@
+module Braspag
+ class Poster
+ def initialize(url)
+ @request = ::HTTPI::Request.new(url)
+ end
+
+ def do_post(method, data)
+ @request.body = data
+ @request.proxy = Braspag.proxy_address if Braspag.proxy_address
+
+ with_logger(method) do
+ ::HTTPI.post @request
+ end
+ end
+
+ private
+
+ def with_logger(method)
+ if Braspag::logger
+ Braspag::logger.info("[Braspag] ##{method}: #{@request.url}, data: #{mask_data(@request.body).inspect}")
+ response = yield
+ Braspag::logger.info("[Braspag] ##{method} returns: #{response.body.inspect}")
+ else
+ response = yield
+ end
+ response
+ end
+
+ def mask_data(data)
+ copy_data = data.dup
+ copy_data['cardNumber'] = "************%s" % copy_data['cardNumber'][-4..-1] if copy_data['cardNumber']
+ copy_data['securityCode'] = "***" if copy_data['securityCode']
+ copy_data
+ end
+ end
+end
View
155 lib/rbraspag/protected_credit_card.rb
@@ -0,0 +1,155 @@
+module Braspag
+ class ProtectedCreditCard < PaymentMethod
+
+ PROTECTED_CARD_MAPPING = {
+ :request_id => "RequestId",
+ :merchant_id => "MerchantKey",
+ :customer_name => "CustomerName",
+ :holder => "CardHolder",
+ :card_number => "CardNumber",
+ :expiration => "CardExpiration"
+ }
+
+ JUST_CLICK_MAPPING = {
+ :request_id => "RequestId",
+ :merchant_id => "MerchantKey",
+ :customer_name => "CustomerName",
+ :order_id => "OrderId",
+ :amount => "Amount",
+ :payment_method => "PaymentMethod",
+ :number_installments => "NumberInstallments",
+ :payment_type => "PaymentType",
+ :just_click_key => "JustClickKey",
+ :security_code => "SecurityCode"
+ }
+
+ SAVE_PROTECTED_CARD_URI = "/CartaoProtegido.asmx?wsdl"
+ GET_PROTECTED_CARD_URI = "/CartaoProtegido.asmx/GetCreditCard"
+ JUST_CLICK_SHOP_URI = "/CartaoProtegido.asmx?wsdl"
+
+ # saves credit card in Braspag PCI Compliant
+ def self.save(params = {})
+ connection = Braspag::Connection.instance
+ params[:merchant_id] = connection.merchant_id
+
+ self.check_protected_card_params(params)
+
+ data = { 'saveCreditCardRequestWS' => {} }
+
+ PROTECTED_CARD_MAPPING.each do |k, v|
+ data['saveCreditCardRequestWS'][v] = params[k] || ""
+ end
+
+
+ client = Savon::Client.new(self.save_protected_card_url)
+ response = client.request(:web, :save_credit_card) do
+ soap.body = data
+ end
+
+ response.to_hash[:save_credit_card_response][:save_credit_card_result]
+
+ end
+
+ # request the credit card info in Braspag PCI Compliant
+ def self.get(just_click_key)
+ connection = Braspag::Connection.instance
+
+ raise InvalidJustClickKey unless valid_just_click_key?(just_click_key)
+
+ data = { 'getCreditCardRequestWS' => {:loja => connection.merchant_id, :justClickKey => just_click_key} }
+
+ request = ::HTTPI::Request.new(self.get_protected_card_url)
+ request.body = { 'getCreditCardRequestWS' => {:loja => connection.merchant_id, :justClickKey => just_click_key} }
+
+ response = ::HTTPI.post(request)
+
+ response = Utils::convert_to_map(response.body, {
+ :holder => "CardHolder",
+ :card_number => "CardNumber",
+ :expiration => "CardExpiration",
+ :masked_card_number => "MaskedCardNumber"
+ })
+
+ raise UnknownError if response[:card_number].nil?
+ response
+ end
+
+ def self.just_click_shop(params = {})
+ connection = Braspag::Connection.instance
+ params[:merchant_id] = connection.merchant_id
+
+ self.check_just_click_shop_params(params)
+
+ order_id = params[:order_id]
+ raise InvalidOrderId unless self.valid_order_id?(order_id)
+
+ data = { 'justClickShopRequestWS' => {} }
+
+ JUST_CLICK_MAPPING.each do |k, v|
+ case k
+ when :payment_method
+ data['justClickShopRequestWS'][v] = Braspag::Connection.instance.homologation? ? PAYMENT_METHODS[:braspag] : PAYMENT_METHODS[params[:payment_method]]
+ else
+ data['justClickShopRequestWS'][v] = params[k] || ""
+ end
+ end
+
+ client = Savon::Client.new(self.just_click_shop_url)
+ response = client.request(:web, :just_click_shop) do
+ soap.body = data
+ end
+
+ response.to_hash[:just_click_shop_response][:just_click_shop_result]
+
+ end
+
+ def self.check_protected_card_params(params)
+ [:request_id, :customer_name, :holder, :card_number, :expiration].each do |param|
+ raise IncompleteParams if params[param].nil?
+ end
+
+ raise InvalidHolder if params[:holder].to_s.size < 1 || params[:holder].to_s.size > 100
+
+ matches = params[:expiration].to_s.match /^(\d{2})\/(\d{2,4})$/
+ raise InvalidExpirationDate unless matches
+ begin
+ year = matches[2].to_i
+ year = "20#{year}" if year.size == 2
+
+ Date.new(year.to_i, matches[1].to_i)
+ rescue ArgumentError
+ raise InvalidExpirationDate
+ end
+ end
+
+ def self.check_just_click_shop_params(params)
+ just_click_shop_attributes = [:request_id, :customer_name, :order_id, :amount, :payment_method,
+ :number_installments, :payment_type, :just_click_key, :security_code]
+
+ just_click_shop_attributes.each do |param|
+ raise IncompleteParams if params[param].nil?
+ end
+
+ raise InvalidSecurityCode if params[:security_code].to_s.size < 1 || params[:security_code].to_s.size > 4
+
+ raise InvalidNumberInstallments if params[:number_installments].to_i < 1 || params[:number_installments].to_i > 99
+
+ end
+
+ def self.valid_just_click_key?(just_click_key)
+ (just_click_key.is_a?(String) && just_click_key.size == 36)
+ end
+
+ def self.save_protected_card_url
+ Braspag::Connection.instance.protected_card_url + SAVE_PROTECTED_CARD_URI
+ end
+
+ def self.get_protected_card_url
+ Braspag::Connection.instance.protected_card_url + GET_PROTECTED_CARD_URI
+ end
+
+ def self.just_click_shop_url
+ Braspag::Connection.instance.protected_card_url + JUST_CLICK_SHOP_URI
+ end
+ end
+end
View
32 lib/rbraspag/utils.rb
@@ -0,0 +1,32 @@
+module Braspag
+ class Utils
+ def self.convert_decimal_to_string(value)
+ ("%.2f" % value.to_f).gsub('.', ',')
+ end
+
+ def self.convert_to_map(document, map = {})
+ document = Nokogiri::XML(document)
+
+ map.each do |key, value|
+ if value.is_a?(String) || value.nil?
+ value = key if value.nil?
+
+ new_value = document.search(value).first
+
+ if new_value.nil?
+ map[key] = nil
+ else
+ new_value = new_value.content.to_s
+ map[key] = new_value unless new_value == ""
+ map[key] = nil if new_value == ""
+ end
+
+ elsif value.is_a?(Proc)
+ map[key] = value.call(document)
+ end
+ end
+
+ map
+ end
+ end
+end
View
3  lib/rbraspag/version.rb
@@ -0,0 +1,3 @@
+module Braspag
+ VERSION = "0.1.2"
+end
View
33 rbraspag.gemspec
@@ -0,0 +1,33 @@
+# -*- encoding: utf-8 -*-
+$:.push File.expand_path("../lib", __FILE__)
+require "rbraspag/version"
+
+Gem::Specification.new do |s|
+ s.name = "rbraspag"
+ s.version = Braspag::VERSION
+ s.authors = ["Celestino Gomes", "Renato Elias", "Luca Bastos", "Lenon Marcel", "Madson Cardoso", "Marcelo Linhares"]
+ s.email = %w[tinorj@gmail.com renato.elias@gmail.com lucabastos@gmail.com lenon.marcel@gmail.com madsonmac@gmail.com marcelolinhares@gmail.com]
+ s.homepage = "http://github.com/concretesolutions/rbraspag"
+ s.summary = "rbraspag gem to use Braspag gateway"
+ s.description = "rbraspag gem to use Braspag gateway"
+
+ s.rubyforge_project = "rbraspag"
+
+ s.files = `git ls-files`.split("\n")
+ s.test_files = `git ls-files -- {test,spec,features}/*`.split("\n")
+ s.executables = `git ls-files -- bin/*`.split("\n").map{ |f| File.basename(f) }
+ s.require_paths = ["lib"]
+
+ s.add_dependency 'httpi', '>= 0.9.6'
+ s.add_dependency 'json', '>= 1.6.1'
+ s.add_dependency 'nokogiri', '>= 1.4.7'
+ s.add_dependency 'savon', '>= 0.9.9'
+
+ s.add_development_dependency "rake"
+ s.add_development_dependency "rspec"
+ s.add_development_dependency "fakeweb"
+ s.add_development_dependency "shoulda-matchers"
+ s.add_development_dependency "guard-rspec"
+ s.add_development_dependency "guard-bundler"
+ s.add_development_dependency "debugger"
+end
View
427 spec/bill_spec.rb
@@ -0,0 +1,427 @@
+# encoding: utf-8
+require File.expand_path(File.dirname(__FILE__) + '/spec_helper')
+
+describe Braspag::Bill do
+ let(:braspag_homologation_url) { "https://homologacao.pagador.com.br" }
+ let(:braspag_production_url) { "https://transaction.pagador.com.br" }
+ let(:merchant_id) { "um id qualquer" }
+
+ before do
+ @connection = mock(:merchant_id => merchant_id)
+ Braspag::Connection.stub(:instance => @connection)
+ end
+
+ describe ".generate" do
+ let(:params) do
+ {
+ :order_id => 11,
+ :amount => 3,
+ :payment_method => :hsbc
+ }
+ end
+
+ let(:params_with_merchant_id) do
+ params.merge!(:merchant_id => merchant_id)
+ end
+
+ let(:creation_url) { "https://bla.com/foo/bar/baz" }
+
+ before do
+ @connection.should_receive(:merchant_id)
+
+ Braspag::Bill.should_receive(:creation_url)
+ .and_return(creation_url)
+
+ Braspag::Bill.should_receive(:normalize_params)
+ .with(params_with_merchant_id)
+ .and_return(params_with_merchant_id)
+
+ Braspag::Bill.should_receive(:check_params)
+ .and_return(true)
+ end
+
+ context "with invalid params" do
+ it "should raise an error when Braspag returns 'Invalid merchantId' as response" do
+ xml = <<-EOXML
+ <?xml version="1.0" encoding="utf-8"?>
+ <PagadorBoletoReturn xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xmlns:xsd="http://www.w3.org/2001/XMLSchema"
+ xmlns="https://www.pagador.com.br/webservice/pagador">
+ <amount xsi:nil="true" />
+ <expirationDate xsi:nil="true" />
+ <returnCode>1</returnCode>
+ <message>Invalid merchantId</message>
+ <status xsi:nil="true" />
+ </PagadorBoletoReturn>
+ EOXML
+
+ FakeWeb.register_uri(:post, creation_url, :body => xml)
+
+ expect {
+ Braspag::Bill.generate(params)
+ }.to raise_error(Braspag::InvalidMerchantId)
+ end
+
+ it "should raise an error when Braspag returns 'Input string was not in a correct format' as response" do
+ xml = <<-EOXML
+ <?xml version="1.0" encoding="utf-8"?>
+ <PagadorBoletoReturn xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xmlns:xsd="http://www.w3.org/2001/XMLSchema"
+ xmlns="https://www.pagador.com.br/webservice/pagador">
+ <amount xsi:nil="true" />
+ <expirationDate xsi:nil="true" />
+ <returnCode>1</returnCode>
+ <message>Input string was not in a correct format.</message>
+ <status xsi:nil="true" />
+ </PagadorBoletoReturn>
+ EOXML
+
+ FakeWeb.register_uri(:post, creation_url, :body => xml)
+
+ expect {
+ Braspag::Bill.generate(params)
+ }.to raise_error(Braspag::InvalidStringFormat)
+ end
+
+ it "should raise an error when Braspag returns 'Invalid payment method' as response" do
+ xml = <<-EOXML
+ <?xml version="1.0" encoding="utf-8"?>
+ <PagadorBoletoReturn xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xmlns:xsd="http://www.w3.org/2001/XMLSchema"
+ xmlns="https://www.pagador.com.br/webservice/pagador">
+ <amount xsi:nil="true" />
+ <expirationDate xsi:nil="true" />
+ <returnCode>3</returnCode>
+ <message>Invalid payment method</message>
+ <status xsi:nil="true" />
+ </PagadorBoletoReturn>
+ EOXML
+
+ FakeWeb.register_uri(:post, creation_url, :body => xml)
+
+ expect {
+ Braspag::Bill.generate(params)
+ }.to raise_error(Braspag::InvalidPaymentMethod)
+ end
+
+ it "should raise an error when Braspag returns 'Invalid purchase amount' as response" do
+ xml = <<-EOXML
+ <?xml version="1.0" encoding="utf-8"?>
+ <PagadorBoletoReturn xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xmlns:xsd="http://www.w3.org/2001/XMLSchema"
+ xmlns="https://www.pagador.com.br/webservice/pagador">
+ <amount xsi:nil="true" />
+ <expirationDate xsi:nil="true" />
+ <returnCode>1</returnCode>
+ <message>Invalid purchase amount</message>
+ <status xsi:nil="true" />
+ </PagadorBoletoReturn>
+ EOXML
+
+ FakeWeb.register_uri(:post, creation_url, :body => xml)
+
+ expect {
+ Braspag::Bill.generate(params)
+ }.to raise_error(Braspag::InvalidAmount)
+ end
+
+ it "should raise an error when Braspag returns any other error as response" do
+ xml = <<-EOXML
+ <?xml version="1.0" encoding="utf-8"?>
+ <PagadorBoletoReturn xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xmlns:xsd="http://www.w3.org/2001/XMLSchema"
+ xmlns="https://www.pagador.com.br/webservice/pagador">
+ <amount xsi:nil="true" />
+ <expirationDate xsi:nil="true" />
+ <returnCode>1</returnCode>
+ <message>Invalid server</message>
+ <status xsi:nil="true" />
+ </PagadorBoletoReturn>
+ EOXML
+
+ FakeWeb.register_uri(:post, creation_url, :body => xml)
+
+ expect {
+ Braspag::Bill.generate(params)
+ }.to raise_error(Braspag::UnknownError)
+ end
+ end
+
+ context "with valid params" do
+ let(:valid_xml) do
+ <<-EOXML
+ <?xml version="1.0" encoding="utf-8"?>
+ <PagadorBoletoReturn xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xmlns:xsd="http://www.w3.org/2001/XMLSchema"
+ xmlns="https://www.pagador.com.br/webservice/pagador">
+ <amount>3.00</amount>
+ <boletoNumber>123123</boletoNumber>
+ <expirationDate>2012-01-08T00:00:00</expirationDate>
+ <url>https://homologacao.pagador.com.br/pagador/reenvia.asp?Id_Transacao=722934be-6756-477a-87ab-42115ee1424d</url>
+ <returnCode>0</returnCode>
+ <status>0</status>
+ </PagadorBoletoReturn>
+ EOXML
+ end
+
+ let(:params) do
+ {
+ :order_id => 2901,
+ :amount => 3,
+ :payment_method => :real,
+ :number => "123123",
+ :expiration_date => Date.today.strftime("%d/%m/%y")
+ }
+ end
+
+ before do
+ FakeWeb.register_uri(:post, creation_url, :body => valid_xml)
+ @response = Braspag::Bill.generate(params)
+ end
+
+ it "should return a Hash" do
+ @response.should be_kind_of Hash
+ @response.should == {
+ :url => "https://homologacao.pagador.com.br/pagador/reenvia.asp?Id_Transacao=722934be-6756-477a-87ab-42115ee1424d",
+ :amount => BigDecimal.new("3.00"),
+ :number => "123123",
+ :expiration_date => Date.new(2012, 1, 8),
+ :return_code => "0",
+ :status => "0",
+ :message => nil
+ }
+ end
+ end
+ end
+
+ describe ".normalize_params" do
+ it "should format the expiration_date param" do
+ params = { :expiration_date => Date.new(2011, 12, 10) }
+
+ result = Braspag::Bill.normalize_params(params)
+ result.should be_kind_of Hash
+
+ result[:expiration_date].should =~ /10\/12\/11/
+ end
+
+ it "should convert amount to BigDecimal" do
+ params = { :amount => "100.2" }
+
+ result = Braspag::Bill.normalize_params(params)
+ result.should be_kind_of Hash
+
+ result[:amount].should be_kind_of BigDecimal
+ end
+ end
+
+ describe ".check_params" do
+ let(:params) do
+ {
+ :order_id => "111",
+ :amount => 100.0,
+ :payment_method => :bradesco
+ }
+ end
+
+ [:order_id, :amount, :payment_method].each do |param|
+ it "should raise an error when #{param} is not present" do
+ expect {
+ params[param] = nil
+ Braspag::Bill.check_params(params)
+ }.to raise_error Braspag::IncompleteParams
+ end
+ end
+
+ it "should raise an error when order_id is not valid" do
+ Braspag::Bill.should_receive(:valid_order_id?)
+ .with(params[:order_id])
+ .and_return(false)
+
+ expect {
+ Braspag::Bill.check_params(params)
+ }.to raise_error Braspag::InvalidOrderId
+ end
+
+ it "should raise an error when customer_name is present and is greater than 255 chars" do
+ expect {
+ params[:customer_name] = "b" * 256
+ Braspag::Bill.check_params(params)
+ }.to raise_error Braspag::InvalidCustomerName
+ end
+
+ it "should raise an error when customer_id is present and is greater than 18 chars" do
+ expect {
+ params[:customer_id] = "1" * 19
+ Braspag::Bill.check_params(params)
+ }.to raise_error Braspag::InvalidCustomerId
+ end
+
+ it "should raise an error when customer_id is present and is less than 11 chars" do
+ expect {
+ params[:customer_id] = "1" * 10
+ Braspag::Bill.check_params(params)
+ }.to raise_error Braspag::InvalidCustomerId
+ end
+
+ it "should raise an error when number is present and is greater than 255 chars" do
+ expect {
+ params[:number] = "1" * 256
+ Braspag::Bill.check_params(params)
+ }.to raise_error Braspag::InvalidNumber
+ end
+
+ it "should raise an error when instructions is present and is greater than 512 chars" do
+ expect {
+ params[:instructions] = "A" * 513
+ Braspag::Bill.check_params(params)
+ }.to raise_error Braspag::InvalidInstructions
+ end
+
+ it "should raise an error when expiration_date is present and is not in a valid format" do
+ expect {
+ params[:expiration_date] = "2011/19/19"
+ Braspag::Bill.check_params(params)
+ }.to raise_error Braspag::InvalidExpirationDate
+
+ expect {
+ params[:expiration_date] = "29/10/1991"
+ Braspag::Bill.check_params(params)
+ }.to_not raise_error Braspag::InvalidExpirationDate
+ end
+
+ it "should raise an error when payment_method is not invalid" do
+ expect {
+ params[:payment_method] = "non ecziste"
+ Braspag::Bill.check_params(params)
+ }.to raise_error Braspag::InvalidPaymentMethod
+ end
+ end
+
+ describe ".valid_order_id?" do
+ it "should return false when order id is greater than 50 chars" do
+ Braspag::Bill.valid_order_id?("A"*51).should be_false
+ end
+
+ it "should return false when order id is not a String or Fixnum" do
+ Braspag::Bill.valid_order_id?(nil).should be_false
+ end
+
+ it "should return true" do
+ Braspag::Bill.valid_order_id?("A"*50).should be_true
+ Braspag::Bill.valid_order_id?(100).should be_true
+ end
+ end
+
+ describe ".info" do
+ let(:info_url) { "http://braspag/bla" }
+ let(:invalid_xml) do
+ <<-EOXML
+ <?xml version="1.0" encoding="utf-8"?>
+ <DadosBoleto xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xmlns:xsd="http://www.w3.org/2001/XMLSchema"
+ xsi:nil="true"
+ xmlns="http://www.pagador.com.br/" />
+ EOXML
+ end
+
+ let(:valid_xml) do
+ <<-EOXML
+ <?xml version="1.0" encoding="utf-8"?>
+ <DadosBoleto xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xmlns:xsd="http://www.w3.org/2001/XMLSchema"
+ xmlns="http://www.pagador.com.br/">
+ <NumeroDocumento>999</NumeroDocumento>
+ <Sacado/>
+ <NossoNumero>999</NossoNumero>
+ <LinhaDigitavel>35690.00361 03962.070003 00000.009993 4 50160000001000</LinhaDigitavel>
+ <DataDocumento>22/6/2011</DataDocumento>
+ <DataVencimento>2/7/2011</DataVencimento>
+ <Cedente>Gonow Tecnologia e Acessoria Empresarial Ltda</Cedente>
+ <Banco>356-5</Banco>
+ <Agencia>0003</Agencia>
+ <Conta>6039620</Conta>
+ <Carteira>57</Carteira>
+ <ValorDocumento>10,00</ValorDocumento>
+ </DadosBoleto>
+ EOXML
+ end
+
+ it "should raise an error when order id is not valid" do
+ Braspag::Bill.should_receive(:valid_order_id?)
+ .with("bla")
+ .and_return(false)
+
+ expect {
+ Braspag::Bill.info "bla"
+ }.to raise_error(Braspag::InvalidOrderId)
+ end
+
+ it "should raise an error when Braspag returned an invalid xml as response" do
+ FakeWeb.register_uri(:post, info_url, :body => invalid_xml)
+
+ Braspag::Bill.should_receive(:info_url)
+ .and_return(info_url)
+
+ expect {
+ Braspag::Bill.info("orderid")
+ }.to raise_error(Braspag::UnknownError)
+ end
+
+ it "should return a Hash when Braspag returned a valid xml as response" do
+ FakeWeb.register_uri(:post, info_url, :body => valid_xml)
+
+ Braspag::Bill.should_receive(:info_url)
+ .and_return(info_url)
+
+ response = Braspag::Bill.info("orderid")
+ response.should be_kind_of Hash
+
+ response.should == {
+ :document_number => "999",
+ :payer => nil,
+ :our_number => "999",
+ :bill_line => "35690.00361 03962.070003 00000.009993 4 50160000001000",
+ :document_date => "22/6/2011",
+ :expiration_date => "2/7/2011",
+ :receiver => "Gonow Tecnologia e Acessoria Empresarial Ltda",
+ :bank => "356-5",
+ :agency => "0003",
+ :account => "6039620",
+ :wallet => "57",
+ :amount => "10,00",
+ :amount_invoice => nil,
+ :invoice_date => nil
+ }
+ end
+ end
+
+ describe ".creation_url" do
+ it "should return the correct bill creation url when connection environment is homologation" do
+ @connection.stub(:braspag_url => braspag_homologation_url)
+ Braspag::Bill.creation_url.should == "#{braspag_homologation_url}/webservices/pagador/Boleto.asmx/CreateBoleto"
+ end
+
+ it "should return the correct bill creation url when connection environment is production" do
+ @connection.stub(:braspag_url => braspag_production_url)
+ Braspag::Bill.creation_url.should == "#{braspag_production_url}/webservices/pagador/Boleto.asmx/CreateBoleto"
+ end
+ end
+
+ describe ".info_url" do
+ it "should return the correct info url when connection environment is homologation" do
+ @connection.stub(:braspag_url => braspag_homologation_url)
+ @connection.should_receive(:production?)
+ .and_return(false)
+
+ Braspag::Bill.info_url.should == "#{braspag_homologation_url}/pagador/webservice/pedido.asmx/GetDadosBoleto"
+ end
+
+ it "should return the correct info url when connection environment is production" do
+ @connection.stub(:braspag_url => braspag_production_url)
+ @connection.should_receive(:production?)
+ .and_return(true)
+
+ Braspag::Bill.info_url.should == "#{braspag_production_url}/webservices/pagador/pedido.asmx/GetDadosBoleto"
+ end
+ end
+end
View
74 spec/braspag/cryptography_spec.rb
@@ -1,74 +0,0 @@
-# encoding: utf-8
-
-require File.expand_path(File.dirname(__FILE__) + '/../spec_helper')
-
-describe Braspag::Cryptography do
- before do
- @merchant_id = "{84BE9T9T-75FC-6C74-7K4B-AE469C2A07C3}"
- @connection = Braspag::Connection.new(@merchant_id, :test)
- @cryptography = Braspag::Cryptography.new(@connection)
- end
-
- it "deve reconhecer a base_url da conexão" do
- @cryptography.class.uri.should be_start_with(@connection.base_url)
- end
-
- context "ao encriptar dados" do
- before :each do
- @key = "j23hn34jkb34n"
- respond_with "<?xml version='1.0' encoding='utf-8'?><soap:Envelope xmlns:soap='http://www.w3.org/2003/05/soap-envelope' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns:xsd='http://www.w3.org/2001/XMLSchema'><soap:Body><EncryptRequestResponse xmlns='https://www.pagador.com.br/webservice/BraspagGeneralService'><EncryptRequestResult>#{@key}</EncryptRequestResult></EncryptRequestResponse></soap:Body></soap:Envelope>"
- end
-
- it "deve realiza-lo a partir de um mapa de chaves e valores" do
- expected = <<STRING
-<?xml version='1.0' ?>
-<env:Envelope xmlns:env="http://www.w3.org/2003/05/soap-envelope">
- <env:Header />
- <env:Body>
- <tns:EncryptRequest xmlns:tns="https://www.pagador.com.br/webservice/BraspagGeneralService">
- <tns:merchantId>#{@merchant_id}</tns:merchantId>
- <tns:request>
- <tns:string>nome=Chapulin</tns:string>
- <tns:string>sobrenome=Colorado</tns:string>
- </tns:request>
- </tns:EncryptRequest>
- </env:Body>
-</env:Envelope>
-STRING
- request_should_contain(expected)
- @cryptography.encrypt(:nome => "Chapulin", :sobrenome => "Colorado")
- end
-
- it "deve devolver o resultado como uma string" do
- @cryptography.encrypt(:key => "value").should eql(@key)
- end
- end
-
- context "ao decriptar os dados" do
- before :each do
- respond_with "<?xml version='1.0' encoding='utf-8'?><soap:Envelope xmlns:soap='http://www.w3.org/2003/05/soap-envelope' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns:xsd='http://www.w3.org/2001/XMLSchema'><soap:Body><DecryptRequestResponse xmlns='https://www.pagador.com.br/webservice/BraspagGeneralService'><DecryptRequestResult><string>CODPAGAMENTO=18</string><string>VENDAID=teste123</string><string>VALOR=100</string><string>PARCELAS=1</string><string>NOME=comprador</string></DecryptRequestResult></DecryptRequestResponse></soap:Body></soap:Envelope>"
- end
-
-
- it "deve realiza-lo a partir de uma string criptografada" do
- expected = <<STRING
-<?xml version='1.0' ?>
-<env:Envelope xmlns:env="http://www.w3.org/2003/05/soap-envelope">
- <env:Header />
- <env:Body>
- <tns:DecryptRequest xmlns:tns="https://www.pagador.com.br/webservice/BraspagGeneralService">
- <tns:merchantId>{84BE9T9T-75FC-6C74-7K4B-AE469C2A07C3}</tns:merchantId>
- <tns:cryptString>{sdfsdf}</tns:cryptString>
- </tns:DecryptRequest>
- </env:Body>
-</env:Envelope>
-STRING
- request_should_contain(expected)
- @cryptography.decrypt("{sdfsdf}")
- end
-
- it "deve retornar o resultado como um mapa de valores" do
- @cryptography.decrypt("{sdfsdf34543534}")[:parcelas].should eql("1")
- end
- end
-end
View
6 spec/braspag/layout_spec.rb
@@ -1,6 +0,0 @@
-require File.expand_path(File.dirname(__FILE__) + '/../spec_helper')
-
-module Braspag
- describe "Layout" do
- end
-end
View
34 spec/braspag/recorrente_spec.rb
@@ -1,34 +0,0 @@
-require File.expand_path(File.dirname(__FILE__) + '/../spec_helper')
-
-describe Braspag::Recorrente do
- before do
- @merchant_id = "{234234-234234-234234}"
- @connection = Braspag::Connection.new(@merchant_id, :test)
- @recorrente = Braspag::Recorrente.new(@connection)
- respond_with "<?xml version='1.0' encoding='utf-8'?><soap:Envelope xmlns:soap='http://www.w3.org/2003/05/soap-envelope' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns:xsd='http://www.w3.org/2001/XMLSchema'><soap:Body><CreateCreditCardOrderResponse xmlns='https://www.pagador.com.br/webservice/recorrente'><CreateCreditCardOrderResult><code>1</code><description>teste</description></CreateCreditCardOrderResult></CreateCreditCardOrderResponse></soap:Body></soap:Envelope>"
- end
-
- it "deve enviar dados para o webservice de cartao de credito" do
- expected = <<STRING
-<?xml version='1.0' ?>
-<env:Envelope xmlns:env="http://www.w3.org/2003/05/soap-envelope">
- <env:Header />
- <env:Body>
- <tns:CreateCreditCardOrder xmlns:tns="https://www.pagador.com.br/webservice/recorrente">
- <tns:merchantId>#{@merchant_id}</tns:merchantId>
- <tns:orderId>123</tns:orderId>
- <tns:startDate>12/11/2009</tns:startDate>
- <tns:endDate>12/12/2009</tns:endDate>
- </tns:CreateCreditCardOrder>
- </env:Body>
-</env:Envelope>
-STRING
- request_should_contain expected
- @recorrente.create_creditcard_order(:orderId => "123", :startDate => "12/11/2009", :endDate => "12/12/2009")
- end
-
- it "deve devolver dados em um mapa" do
- map = { "code" =>"1", "description" => "teste"}
- @recorrente.create_creditcard_order(:orderId => "123", :startDate => "12/11/2009", :endDate => "12/12/2009").should == map
- end
-end
View
170 spec/connection_spec.rb
@@ -1,38 +1,172 @@
# encoding: utf-8
-
require File.expand_path(File.dirname(__FILE__) + '/spec_helper')
describe Braspag::Connection do
- before :each do
- @clazz = Braspag::Connection
+ let(:merchant_id) { "{12345678-1234-1234-1234-123456789000}" }
+ let(:crypto_key) { "{84BE7E7F-698A-6C74-F820-AE359C2A07C2}" }
+ let(:crypto_url) { "http://localhost:9292" }
+
+ let(:braspag_environment) { "homologation" }
+
+ let(:braspag_homologation_url) { "https://homologacao.pagador.com.br" }
+ let(:braspag_production_url) { "https://transaction.pagador.com.br" }
+
+ let(:braspag_config) do
+ config = {}
+ config[ENV["BRASPAG_ENV"]] = {
+ "environment" => braspag_environment,
+ "merchant_id" => merchant_id,
+ "crypto_key" => crypto_key,
+ "crypto_url" => crypto_url
+ }
+ config
+ end
+
+ before(:all) do
+ @connection = Braspag::Connection.clone
+ end