Class: PagSeguro::Notification

Inherits:
Object
  • Object
show all
Defined in:
lib/pagseguro/notification.rb

Constant Summary collapse

API_URL =
"https://pagseguro.uol.com.br/Security/NPI/Default.aspx"
MAPPING =

Map all the attributes from PagSeguro.

{
  :payment_method => "TipoPagamento",
  :order_id       => "Referencia",
  :processed_at   => "DataTransacao",
  :status         => "StatusTransacao",
  :transaction_id => "TransacaoID",
  :shipping_type  => "TipoFrete",
  :shipping       => "ValorFrete",
  :notes          => "Anotacao"
}
STATUS =

Map order status from PagSeguro.

{
  "Completo"          => :completed,
  "Aguardando Pagto"  => :pending,
  "Aprovado"          => :approved,
  "Em Análise"        => :verifying,
  "Cancelado"         => :canceled,
  "Devolvido"         => :refunded
}
PAYMENT_METHOD =

Map payment method from PagSeguro.

{
  "Cartão de Crédito" => :credit_card,
  "Boleto"            => :invoice,
  "Pagamento"         => :pagseguro,
  "Pagamento Online"  => :online_transfer,
  "Doação"            => :donation
}

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(params, token = nil) ⇒ Notification

Expects the params object from the current request. PagSeguro will send POST with ISO-8859-1 encoded data, so we need to normalize it to UTF-8.



48
49
50
51
# File 'lib/pagseguro/notification.rb', line 48

def initialize(params, token = nil)
  @token = token
  @params = PagSeguro.developer? ? params : normalize(params)
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(method, *args) ⇒ Object



144
145
146
147
# File 'lib/pagseguro/notification.rb', line 144

def method_missing(method, *args)
  return mapping_for(method) if MAPPING[method]
  super
end

Instance Attribute Details

#paramsObject

The Rails params hash.



42
43
44
# File 'lib/pagseguro/notification.rb', line 42

def params
  @params
end

Instance Method Details

#buyerObject

Return the buyer info.



124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
# File 'lib/pagseguro/notification.rb', line 124

def buyer
  @buyer ||= {
    :name    => params["CliNome"],
    :email   => params["CliEmail"],
    :phone   => {
      :area_code => params["CliTelefone"].to_s.split(" ").first,
      :number => params["CliTelefone"].to_s.split(" ").last
    },
    :address => {
      :street => params["CliEndereco"],
      :number => params["CliNumero"],
      :complements => params["CliComplemento"],
      :neighbourhood => params["CliBairro"],
      :city => params["CliCidade"],
      :state => params["CliEstado"],
      :postal_code => params["CliCEP"]
    }
  }
end

#denormalize(hash) ⇒ Object

Denormalize the specified hash converting all data to ISO-8859-1.



63
64
65
66
67
# File 'lib/pagseguro/notification.rb', line 63

def denormalize(hash)
  each_value(hash) do |value|
    Utils.to_iso8859(value)
  end
end

#mapping_for(name) ⇒ Object

A wrapper to the params hash, sanitizing the return to symbols.



157
158
159
# File 'lib/pagseguro/notification.rb', line 157

def mapping_for(name)
  params[MAPPING[name]]
end

#normalize(hash) ⇒ Object

Normalize the specified hash converting all data to UTF-8.



55
56
57
58
59
# File 'lib/pagseguro/notification.rb', line 55

def normalize(hash)
  each_value(hash) do |value|
    Utils.to_utf8(value)
  end
end

#payment_methodObject

Return the payment method. Will be mapped to the PAYMENT_METHOD constant.



109
110
111
# File 'lib/pagseguro/notification.rb', line 109

def payment_method
  @payment_method ||= PAYMENT_METHOD[mapping_for(:payment_method)]
end

#processed_atObject

Parse the processing date to a Ruby object.



115
116
117
118
119
120
# File 'lib/pagseguro/notification.rb', line 115

def processed_at
  @processed_at ||= begin
    groups = *mapping_for(:processed_at).match(/(\d{2})\/(\d{2})\/(\d{4}) ([\d:]+)/sm)
    Time.parse("#{groups[3]}-#{groups[2]}-#{groups[1]} #{groups[4]}")
  end
end

#productsObject

Return a list of products sent by PagSeguro. The values will be normalized (e.g. currencies will be converted to cents, quantity will be an integer)



73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
# File 'lib/pagseguro/notification.rb', line 73

def products
  @products ||= begin
    items = []

    for i in (1..params["NumItens"].to_i)
      items << {
        :id          => params["ProdID_#{i}"],
        :description => params["ProdDescricao_#{i}"],
        :quantity    => params["ProdQuantidade_#{i}"].to_i,
        :price       => to_price(params["ProdValor_#{i}"]),
        :shipping    => to_price(params["ProdFrete_#{i}"]),
        :fees        => to_price(params["ProdExtras_#{i}"])
      }
    end

    items
  end
end

#respond_to?(method, include_private = false) ⇒ Boolean

Returns:

  • (Boolean)


149
150
151
152
# File 'lib/pagseguro/notification.rb', line 149

def respond_to?(method, include_private = false)
  return true if MAPPING[method]
  super
end

#shippingObject

Return the shipping fee. Will be converted to a float number.



95
96
97
# File 'lib/pagseguro/notification.rb', line 95

def shipping
  to_price mapping_for(:shipping)
end

#statusObject

Return the order status. Will be mapped to the STATUS constant.



102
103
104
# File 'lib/pagseguro/notification.rb', line 102

def status
  @status ||= STATUS[mapping_for(:status)]
end

#to_hashObject

Return all useful properties in a single hash.



175
176
177
178
179
# File 'lib/pagseguro/notification.rb', line 175

def to_hash
  MAPPING.inject({}) do |buffer, (name,value)|
    buffer.merge(name => __send__(name))
  end
end

#valid?(force = false) ⇒ Boolean

Cache the validation. To bypass the cache, just provide an argument that is evaluated as true.

invoice.valid?
invoice.valid?(:nocache)

Returns:

  • (Boolean)


167
168
169
170
171
# File 'lib/pagseguro/notification.rb', line 167

def valid?(force=false)
  @valid = nil if force
  @valid = validates? if @valid.nil?
  @valid
end