Skip to content
Browse files

Merge pull request #1 from brazilian-payment/master

Merge From Baby
  • Loading branch information...
2 parents 9913d34 + b0b8e57 commit 050d8b5ec8dda8e9892d729158ce43973e816e68 @renatoelias renatoelias committed
View
2 .gitignore
@@ -2,7 +2,7 @@ nbproject
pkg
doc
tags
-*.swp
+*.sw*
.bundle
.rvmrc
Gemfile.lock
View
15 lib/rbraspag.rb
@@ -2,6 +2,7 @@
require 'httpi'
require 'nokogiri'
require 'json'
+require 'savon'
require "rbraspag/version"
require 'rbraspag/connection'
@@ -9,15 +10,17 @@
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=(logger)
- @logger = logger
+ def self.logger=(value)
+ @logger = value
end
def self.logger
@@ -31,4 +34,12 @@ def self.config_file_path=(path)
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
10 lib/rbraspag/connection.rb
@@ -4,13 +4,16 @@ class Connection
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, :merchant_id, :crypto_url, :crypto_key, :options, :environment
+ attr_reader :braspag_url, :protected_card_url, :merchant_id, :crypto_url, :crypto_key, :options, :environment
def initialize
- raise InvalidEnv if ENV["RACK_ENV"].nil? || ENV["RACK_ENV"].empty?
+ raise InvalidEnv if ENV["BRASPAG_ENV"].nil? || ENV["BRASPAG_ENV"].empty?
- @options = YAML.load_file(Braspag.config_file_path)[ ENV['RACK_ENV'] ]
+ @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
@@ -20,6 +23,7 @@ def initialize
@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?
View
75 lib/rbraspag/credit_card.rb
@@ -1,37 +1,6 @@
module Braspag
class CreditCard < 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
- }
-
MAPPING = {
:merchant_id => "merchantId",
:order => 'order',
@@ -50,7 +19,6 @@ class CreditCard < PaymentMethod
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"
@@ -64,7 +32,7 @@ def self.authorize(params = {})
MAPPING.each do |k, v|
case k
when :payment_method
- data[v] = PAYMENT_METHODS[params[: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
@@ -72,13 +40,8 @@ def self.authorize(params = {})
end
end
- request = ::HTTPI::Request.new self.authorize_url
- request.body = data
+ response = Braspag::Poster.new(self.authorize_url).do_post(:authorize, data)
- ::Braspag.logger.info("[Braspag] #authorize: #{self.authorize_url}, data: #{data.inspect}")
-
- response = ::HTTPI.post request
- ::Braspag.logger.info("[Braspag] #authorize return: #{response.body.inspect}")
Utils::convert_to_map(response.body, {
:amount => nil,
:number => "authorisationNumber",
@@ -100,10 +63,8 @@ def self.capture(order_id)
MAPPING[:merchant_id] => merchant_id
}
- request = ::HTTPI::Request.new(self.capture_url)
- request.body = data
+ response = Braspag::Poster.new(self.capture_url).do_post(:capture, data)
- response = ::HTTPI.post(request)
Utils::convert_to_map(response.body, {
:amount => nil,
:number => "authorisationNumber",
@@ -125,10 +86,8 @@ def self.void(order_id)
MAPPING[:merchant_id] => merchant_id
}
- request = ::HTTPI::Request.new(self.cancellation_url)
- request.body = data
+ response = Braspag::Poster.new(self.cancellation_url).do_post(:void, data)
- response = ::HTTPI.post(request)
Utils::convert_to_map(response.body, {
:amount => nil,
:number => "authorisationNumber",
@@ -144,10 +103,8 @@ def self.info(order_id)
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)
+ 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",
@@ -170,7 +127,7 @@ def self.check_params(params)
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}|\d{4})$/
+ matches = params[:expiration].to_s.match /^(\d{2})\/(\d{2,4})$/
raise InvalidExpirationDate unless matches
begin
year = matches[2].to_i
@@ -186,6 +143,24 @@ def self.check_params(params)
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)
View
2 lib/rbraspag/errors.rb
@@ -23,6 +23,8 @@ 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
View
33 lib/rbraspag/payment_method.rb
@@ -1,5 +1,38 @@
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
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
2 lib/rbraspag/version.rb
@@ -1,3 +1,3 @@
module Braspag
- VERSION = "0.1.1"
+ VERSION = "0.1.2"
end
View
3 rbraspag.gemspec
@@ -21,6 +21,7 @@ Gem::Specification.new do |s|
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"
@@ -28,5 +29,5 @@ Gem::Specification.new do |s|
s.add_development_dependency "shoulda-matchers"
s.add_development_dependency "guard-rspec"
s.add_development_dependency "guard-bundler"
- s.add_development_dependency "ruby-debug19"
+ s.add_development_dependency "debugger"
end
View
24 spec/connection_spec.rb
@@ -13,7 +13,7 @@
let(:braspag_config) do
config = {}
- config[ENV["RACK_ENV"]] = {
+ config[ENV["BRASPAG_ENV"]] = {
"environment" => braspag_environment,
"merchant_id" => merchant_id,
"crypto_key" => crypto_key,
@@ -60,9 +60,9 @@
@connection.instance
end
- it "should generate an exception when RACK_ENV is nil" do
+ it "should generate an exception when BRASPAG_ENV is nil" do
ENV.should_receive(:[])
- .with("RACK_ENV")
+ .with("BRASPAG_ENV")
.and_return(nil)
expect {
@@ -70,10 +70,10 @@
}.to raise_error Braspag::Connection::InvalidEnv
end
- it "should generate an exception when RACK_ENV is empty" do
+ it "should generate an exception when BRASPAG_ENV is empty" do
ENV.should_receive(:[])
.twice
- .with("RACK_ENV")
+ .with("BRASPAG_ENV")
.and_return("")
expect {
@@ -82,7 +82,7 @@
end
it "should generate an exception when merchant_id is not in a correct format" do
- braspag_config[ENV["RACK_ENV"]]["merchant_id"] = "A" * 38
+ braspag_config[ENV["BRASPAG_ENV"]]["merchant_id"] = "A" * 38
YAML.should_receive(:load_file)
.with("config/braspag.yml")
@@ -106,7 +106,7 @@
describe "#production?" do
it "should return true when environment is production" do
- braspag_config[ENV["RACK_ENV"]]["environment"] = "production"
+ braspag_config[ENV["BRASPAG_ENV"]]["environment"] = "production"
YAML.should_receive(:load_file)
.and_return(braspag_config)
@@ -115,7 +115,7 @@
end
it "should return false when environment is not production" do
- braspag_config[ENV["RACK_ENV"]]["environment"] = "homologation"
+ braspag_config[ENV["BRASPAG_ENV"]]["environment"] = "homologation"
YAML.should_receive(:load_file)
.and_return(braspag_config)
@@ -126,7 +126,7 @@
describe "#homologation?" do
it "should return true when environment is homologation" do
- braspag_config[ENV["RACK_ENV"]]["environment"] = "homologation"
+ braspag_config[ENV["BRASPAG_ENV"]]["environment"] = "homologation"
YAML.should_receive(:load_file)
.and_return(braspag_config)
@@ -135,7 +135,7 @@
end
it "should return false when environment is not homologation" do
- braspag_config[ENV["RACK_ENV"]]["environment"] = "production"
+ braspag_config[ENV["BRASPAG_ENV"]]["environment"] = "production"
YAML.should_receive(:load_file)
.and_return(braspag_config)
@@ -147,7 +147,7 @@
describe "#braspag_url" do
context "when environment is homologation" do
it "should return the Braspag homologation url" do
- braspag_config[ENV["RACK_ENV"]]["environment"] = "homologation"
+ braspag_config[ENV["BRASPAG_ENV"]]["environment"] = "homologation"
YAML.should_receive(:load_file)
.and_return(braspag_config)
@@ -159,7 +159,7 @@
context "when environment is production" do
it "should return the Braspag production url" do
- braspag_config[ENV["RACK_ENV"]]["environment"] = "production"
+ braspag_config[ENV["BRASPAG_ENV"]]["environment"] = "production"
YAML.should_receive(:load_file)
.and_return(braspag_config)
View
73 spec/credit_card_spec.rb
@@ -1,12 +1,14 @@
require File.expand_path(File.dirname(__FILE__) + '/spec_helper')
+require 'ostruct'
describe Braspag::CreditCard 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" }
+ let(:logger) { mock(:info => nil) }
before do
- @connection = mock(:merchant_id => merchant_id)
+ @connection = mock(:merchant_id => merchant_id, :protected_card_url => 'https://www.cartaoprotegido.com.br/Services/TestEnvironment', :homologation? => false)
Braspag::Connection.stub(:instance => @connection)
end
@@ -61,14 +63,18 @@
EOXML
end
+ let(:request) { OpenStruct.new :url => authorize_url }
+
before do
- FakeWeb.register_uri(:post, authorize_url, :body => valid_xml)
- @response = Braspag::CreditCard.authorize(params)
+ Braspag::Connection.instance.should_receive(:homologation?)
+ ::HTTPI::Request.should_receive(:new).with(authorize_url).and_return(request)
+ ::HTTPI.should_receive(:post).with(request).and_return(mock(:body => valid_xml))
end
it "should return a Hash" do
- @response.should be_kind_of Hash
- @response.should == {
+ response = Braspag::CreditCard.authorize(params)
+ response.should be_kind_of Hash
+ response.should == {
:amount => "5",
:message => "Transaction Successful",
:number => "733610",
@@ -77,6 +83,11 @@
:transaction_id => "0"
}
end
+
+ it "should post transation info" do
+ Braspag::CreditCard.authorize(params)
+ request.body.should == {"merchantId"=>"um id qualquer", "order"=>"", "orderId"=>"um order id", "customerName"=>"WWWWWWWWWWWWWWWWWWWWW", "amount"=>"100,00", "paymentMethod"=>20, "holder"=>"Joao Maria Souza", "cardNumber"=>"9999999999", "expiration"=>"10/12", "securityCode"=>"123", "numberPayments"=>1, "typePayment"=>0}
+ end
end
end
@@ -115,17 +126,25 @@
EOXML
end
+ let(:request) { OpenStruct.new :url => capture_url }
+
before do
Braspag::CreditCard.should_receive(:capture_url)
.and_return(capture_url)
- FakeWeb.register_uri(:post, capture_url, :body => valid_xml)
- @response = Braspag::CreditCard.capture("order id qualquer")
+ ::HTTPI::Request.should_receive(:new)
+ .with(capture_url)
+ .and_return(request)
+
+ ::HTTPI.should_receive(:post)
+ .with(request)
+ .and_return(mock(:body => valid_xml))
end
it "should return a Hash" do
- @response.should be_kind_of Hash
- @response.should == {
+ response = Braspag::CreditCard.capture("order id qualquer")
+ response.should be_kind_of Hash
+ response.should == {
:amount => "2",
:number => nil,
:message => "Approved",
@@ -134,6 +153,11 @@
:transaction_id => nil
}
end
+
+ it "should post capture info" do
+ Braspag::CreditCard.capture("order id qualquer")
+ request.body.should == {"orderId"=>"order id qualquer", "merchantId"=>"um id qualquer"}
+ end
end
end
@@ -172,17 +196,20 @@
EOXML
end
+ let(:request) { OpenStruct.new :url => cancellation_url }
+
before do
Braspag::CreditCard.should_receive(:cancellation_url)
.and_return(cancellation_url)
- FakeWeb.register_uri(:post, cancellation_url, :body => valid_xml)
- @response = Braspag::CreditCard.void("order id qualquer")
+ ::HTTPI::Request.should_receive(:new).with(cancellation_url).and_return(request)
+ ::HTTPI.should_receive(:post).with(request).and_return(mock(:body => valid_xml))
end
it "should return a Hash" do
- @response.should be_kind_of Hash
- @response.should == {
+ response = Braspag::CreditCard.void("order id qualquer")
+ response.should be_kind_of Hash
+ response.should == {
:amount => "2",
:number => nil,
:message => "Approved",
@@ -191,6 +218,11 @@
:transaction_id => nil
}
end
+
+ it "should post void info" do
+ Braspag::CreditCard.void("order id qualquer")
+ request.body.should == {"order"=>"order id qualquer", "merchantId"=>"um id qualquer"}
+ end
end
end
@@ -385,6 +417,7 @@
describe ".authorize_url .capture_url .cancellation_url" do
it "should return the correct credit card creation url when connection environment is homologation" do
@connection.stub(:braspag_url => braspag_homologation_url)
+
Braspag::CreditCard.authorize_url.should == "#{braspag_homologation_url}/webservices/pagador/Pagador.asmx/Authorize"
Braspag::CreditCard.capture_url.should == "#{braspag_homologation_url}/webservices/pagador/Pagador.asmx/Capture"
Braspag::CreditCard.cancellation_url.should == "#{braspag_homologation_url}/webservices/pagador/Pagador.asmx/VoidTransaction"
@@ -392,9 +425,23 @@
it "should return the correct credit card creation url when connection environment is production" do
@connection.stub(:braspag_url => braspag_production_url)
+
Braspag::CreditCard.authorize_url.should == "#{braspag_production_url}/webservices/pagador/Pagador.asmx/Authorize"
Braspag::CreditCard.capture_url.should == "#{braspag_production_url}/webservices/pagador/Pagador.asmx/Capture"
Braspag::CreditCard.cancellation_url.should == "#{braspag_production_url}/webservices/pagador/Pagador.asmx/VoidTransaction"
end
end
+
+ describe ".save .get .just_click_shop" do
+ it "should delegate to ProtectedCreditCard class" do
+ Braspag::ProtectedCreditCard.should_receive(:save).with({})
+ Braspag::CreditCard.save({})
+
+ Braspag::ProtectedCreditCard.should_receive(:get).with('just_click_key')
+ Braspag::CreditCard.get('just_click_key')
+
+ Braspag::ProtectedCreditCard.should_receive(:just_click_shop).with({})
+ Braspag::CreditCard.just_click_shop({})
+ end
+ end
end
View
53 spec/poster_spec.rb
@@ -0,0 +1,53 @@
+require 'spec_helper'
+require 'ostruct'
+
+describe Braspag::Poster do
+ let(:request) { OpenStruct.new(:url => 'http://foo/bar') }
+ let(:response) { mock(:body => 'success') }
+ let(:logger) { mock(:info => nil) }
+ subject { described_class.new('http://foo/bar') }
+ before { Braspag.logger = logger }
+
+ describe "#do_post" do
+ before do
+ ::HTTPI::Request.should_receive(:new).with('http://foo/bar').and_return(request)
+ ::HTTPI.should_receive(:post).with(request).and_return(response)
+ end
+
+ it "should log the request info" do
+ logger.should_receive(:info).with('[Braspag] #doe: http://foo/bar, data: {:foo=>:bar, :egg=>:span}')
+ subject.do_post(:doe, { :foo => :bar, :egg => :span })
+ end
+
+ it "should log the request info removing the credit card sensitive info" do
+ logger.should_receive(:info).with('[Braspag] #doe: http://foo/bar, data: {"cardNumber"=>"************", "securityCode"=>"***"}')
+ subject.do_post(:doe, { 'cardNumber' => '123', 'securityCode' => '456' })
+ end
+
+ it "should log response info" do
+ logger.should_receive(:info).with('[Braspag] #doe: http://foo/bar, data: {:foo=>:bar, :egg=>:span}')
+ subject.do_post(:doe, { :foo => :bar, :egg => :span })
+ end
+
+ it "should not raise an error if logger is not defined" do
+ Braspag.logger = nil
+ expect {
+ subject.do_post(:doe, { :foo => :bar, :egg => :span })
+ }.to_not raise_error
+ end
+
+ it "should not set the proxy if the proxy_address is not set" do
+ request.should_not_receive(:proxy=)
+ subject.do_post(:foo, {})
+ end
+
+ context "using a proxy" do
+ before { Braspag.proxy_address = 'http://proxy.com' }
+
+ it "should set the proxy if the proxy_address is set" do
+ request.should_receive(:proxy=).with('http://proxy.com')
+ subject.do_post(:foo, {})
+ end
+ end
+ end
+end
View
277 spec/protected_credit_card_spec.rb
@@ -0,0 +1,277 @@
+require 'spec_helper'
+
+describe Braspag::ProtectedCreditCard do
+ let(:braspag_homologation_protected_card_url) { "https://cartaoprotegido.braspag.com.br" }
+ let(:braspag_production_protected_card_url) { "https://www.cartaoprotegido.com.br" }
+ let(:merchant_id) { "um id qualquer" }
+
+ before do
+ @connection = mock(:merchant_id => merchant_id, :protected_card_url => 'https://www.cartaoprotegido.com.br/Services/TestEnvironment', :homologation? => false)
+ Braspag::Connection.stub(:instance => @connection)
+ end
+
+ describe ".save" do
+ let(:params) do
+ {
+ :customer_name => "W" * 21,
+ :holder => "Joao Maria Souza",
+ :card_number => "9" * 10,
+ :expiration => "10/12",
+ :order_id => "um order id",
+ :request_id => "00000000-0000-0000-0000-000000000044"
+ }
+ end
+
+ let(:params_with_merchant_id) do
+ params.merge!(:merchant_id => merchant_id)
+ end
+
+ let(:save_protected_card_url) { "http://braspag.com/bla" }
+
+ let(:savon_double) { double('Savon') }
+
+ before do
+ @connection.should_receive(:merchant_id)
+ end
+
+ context "with valid params" do
+ let(:valid_hash) do
+ {
+ :save_credit_card_response => {
+ :save_credit_card_result => {
+ :just_click_key => 'SAVE-PROTECTED-CARD-TOKEN',
+ :success => true
+ }
+ }
+ }
+ end
+
+ let(:response) do
+ double('Response', :to_hash => valid_hash)
+ end
+
+ before do
+ Braspag::ProtectedCreditCard.should_receive(:save_protected_card_url)
+ Braspag::ProtectedCreditCard.should_receive(:check_protected_card_params)
+ .and_return(true)
+ Savon::Client.should_receive(:new).and_return(savon_double)
+ savon_double.should_receive(:request).and_return(response)
+
+ @response = Braspag::ProtectedCreditCard.save(params)
+ end
+
+ it "should return a Hash" do
+ @response.should be_kind_of Hash
+ @response.should == {
+ :just_click_key => "SAVE-PROTECTED-CARD-TOKEN",
+ :success => true
+ }
+ end
+ end
+
+ context "with invalid params" do
+ let(:invalid_hash) do
+ {
+ :save_credit_card_response => {
+ :save_credit_card_result => {
+ :just_click_key => nil,
+ :success => false
+ }
+ }
+ }
+ end
+
+ let(:response) do
+ double('Response', :to_hash => invalid_hash)
+ end
+
+ before do
+ Braspag::ProtectedCreditCard.should_receive(:check_protected_card_params)
+ .and_return(true)
+ Braspag::ProtectedCreditCard.should_receive(:save_protected_card_url)
+ .and_return(save_protected_card_url)
+ Savon::Client.should_receive(:new).and_return(savon_double)
+ savon_double.should_receive(:request).and_return(response)
+
+ @response = Braspag::ProtectedCreditCard.save(params)
+ end
+
+ it "should return a Hash" do
+ @response.should be_kind_of Hash
+ @response.should == {
+ :just_click_key => nil,
+ :success => false
+ }
+ end
+ end
+ end
+
+ describe ".get" do
+ let(:get_protected_card_url) { "http://braspag/bla" }
+
+ let(:invalid_xml) do
+ <<-EOXML
+ <CartaoProtegidoReturn xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xmlns:xsd="http://www.w3.org/2001/XMLSchema"
+ xmlns="http://www.pagador.com.br/">
+ <CardHolder>Joao Maria Souza</CardHolder>
+ <CardNumber></CardNumber>
+ <CardExpiration>10/12</CardExpiration>
+ <MaskedCardNumber>******9999</MaskedCardNumber>
+ </CartaoProtegidoReturn>
+ EOXML
+ end
+
+ let(:valid_xml) do
+ <<-EOXML
+ <CartaoProtegidoReturn xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xmlns:xsd="http://www.w3.org/2001/XMLSchema"
+ xmlns="http://www.pagador.com.br/">
+ <CardHolder>Joao Maria Souza</CardHolder>
+ <CardNumber>9999999999</CardNumber>
+ <CardExpiration>10/12</CardExpiration>
+ <MaskedCardNumber>******9999</MaskedCardNumber>
+ </CartaoProtegidoReturn>
+ EOXML
+ end
+
+ it "should raise an error when just click key is not valid" do
+ Braspag::ProtectedCreditCard.should_receive(:valid_just_click_key?)
+ .with("bla")
+ .and_return(false)
+
+ expect {
+ Braspag::ProtectedCreditCard.get "bla"
+ }.to raise_error(Braspag::InvalidJustClickKey)
+ end
+
+ it "should raise an error when Braspag returned an invalid xml as response" do
+ FakeWeb.register_uri(:post, get_protected_card_url, :body => invalid_xml)
+
+ Braspag::ProtectedCreditCard.should_receive(:get_protected_card_url)
+ .and_return(get_protected_card_url)
+
+ expect {
+ Braspag::ProtectedCreditCard.get("b0b0b0b0-bbbb-4d4d-bd27-f1f1f1ededed")
+ }.to raise_error(Braspag::UnknownError)
+ end
+
+ it "should return a Hash when Braspag returned a valid xml as response" do
+ FakeWeb.register_uri(:post, get_protected_card_url, :body => valid_xml)
+
+ Braspag::ProtectedCreditCard.should_receive(:get_protected_card_url)
+ .and_return(get_protected_card_url)
+
+ response = Braspag::ProtectedCreditCard.get("b0b0b0b0-bbbb-4d4d-bd27-f1f1f1ededed")
+ response.should be_kind_of Hash
+
+ response.should == {
+ :holder => "Joao Maria Souza",
+ :expiration => "10/12",
+ :card_number => "9" * 10,
+ :masked_card_number => "*" * 6 + "9" * 4
+ }
+ end
+
+ end
+
+ describe ".just_click_shop" do
+ context "body" do
+ let(:params) { {
+ :request_id => "123",
+ :customer_name => "Joao Silva",
+ :order_id => "999",
+ :amount => 10.50,
+ :payment_method => :redecard,
+ :number_installments => 3,
+ :payment_type => "test",
+ :just_click_key => "key",
+ :security_code => "123"
+ } }
+
+ class SavonClientTest
+ attr_accessor :response
+ attr_reader :method
+
+ def request(web, method, &block)
+ @method = method
+ instance_eval &block
+
+ @response
+ end
+
+ def soap
+ @soap ||= OpenStruct.new
+ end
+ end
+
+ before :each do
+ @savon_client_test = SavonClientTest.new
+ @savon_client_test.response = {:just_click_shop_response => {}}
+ Savon::Client.stub(:new).with('https://www.cartaoprotegido.com.br/Services/TestEnvironment/CartaoProtegido.asmx?wsdl').and_return(@savon_client_test)
+ end
+
+ after :each do
+ Savon::Client.unstub(:new)
+ end
+
+ it "should have RequestId" do
+ described_class.just_click_shop(params)
+ @savon_client_test.soap.body['justClickShopRequestWS']['RequestId'].should eq '123'
+ end
+
+ it "should have MerchantKey" do
+ described_class.just_click_shop(params)
+ @savon_client_test.soap.body['justClickShopRequestWS']['MerchantKey'].should eq 'um id qualquer'
+ end
+
+ it "should have CustomerName" do
+ described_class.just_click_shop(params)
+ @savon_client_test.soap.body['justClickShopRequestWS']['CustomerName'].should eq 'Joao Silva'
+ end
+
+ it "should have OrderId" do
+ described_class.just_click_shop(params)
+ @savon_client_test.soap.body['justClickShopRequestWS']['OrderId'].should eq '999'
+ end
+
+ it "should have Amount" do
+ described_class.just_click_shop(params)
+ @savon_client_test.soap.body['justClickShopRequestWS']['Amount'].should eq 10.50
+ end
+
+ it "should have PaymentMethod" do
+ described_class.just_click_shop(params)
+ @savon_client_test.soap.body['justClickShopRequestWS']['PaymentMethod'].should eq 20
+ end
+
+ it "should have PaymentType" do
+ described_class.just_click_shop(params)
+ @savon_client_test.soap.body['justClickShopRequestWS']['PaymentType'].should eq 'test'
+ end
+
+ it "should have NumberInstallments" do
+ described_class.just_click_shop(params)
+ @savon_client_test.soap.body['justClickShopRequestWS']['NumberInstallments'].should eq 3
+ end
+
+ it "should have JustClickKey" do
+ described_class.just_click_shop(params)
+ @savon_client_test.soap.body['justClickShopRequestWS']['JustClickKey'].should eq 'key'
+ end
+
+ it "should have SecurityCode" do
+ described_class.just_click_shop(params)
+ @savon_client_test.soap.body['justClickShopRequestWS']['SecurityCode'].should eq '123'
+ end
+ end
+
+ it ".save_protected_card_url .get_protected_card_url" do
+ @connection.stub(:protected_card_url => braspag_homologation_protected_card_url)
+
+ Braspag::ProtectedCreditCard.save_protected_card_url.should == "#{braspag_homologation_protected_card_url}/CartaoProtegido.asmx?wsdl"
+ Braspag::ProtectedCreditCard.get_protected_card_url.should == "#{braspag_homologation_protected_card_url}/CartaoProtegido.asmx/GetCreditCard"
+ end
+
+ end
+end
View
2 spec/spec_helper.rb
@@ -8,7 +8,7 @@
require 'fakeweb'
-ENV["RACK_ENV"] ||= "test"
+ENV["BRASPAG_ENV"] ||= "test"
RSpec.configure do |config|
config.mock_with :rspec

0 comments on commit 050d8b5

Please sign in to comment.
Something went wrong with that request. Please try again.