Skip to content

Instantly share code, notes, and snippets.

@rafaismyname
Created August 30, 2013 22:52
Show Gist options
  • Save rafaismyname/6395061 to your computer and use it in GitHub Desktop.
Save rafaismyname/6395061 to your computer and use it in GitHub Desktop.
Moip library for Rails - TODO: Turn it int a gem.
require 'httparty'
require 'builder'
class MoipClient
include HTTParty
CONFIG = YAML.load_file(File.join(Rails.root, 'config', 'moip.yml'))[Rails.env]
STATUS = { 1 => "authorized", 2 => "started", 3 => "printed", 4 => "completed", 5 => "canceled", 6 => "analysing", 7 => "returned" }
base_uri "#{CONFIG["uri"]}/ws/alpha"
basic_auth CONFIG["token"], CONFIG["key"]
class << self
def authorize(attributes = {})
xml = mount_new_payment_request(attributes)
response = post('/EnviarInstrucao/Unica', :body => xml)
raise(StandardError, "Webservice can't be reached") if response.nil?
response = response["EnviarInstrucaoUnicaResponse"]["Resposta"]
raise(StandardError, response["Erro"]["__content__"]) if response["Status"] == "Falha"
{ token: response["Token"], request_id: response["ID"] }
end
def get_status(token)
response = get("/ConsultarInstrucao/#{token}")
raise(StandardError, "Webservice can't be reached") if response.nil?
response = response["ConsultarTokenResponse"]["RespostaConsultar"]
raise(StandardError, response["Erro"]["__content__"]) if response["Status"] == "Falha"
format_status_response(response)
end
def charge_url(token)
"#{CONFIG["uri"]}/Instrucao.do?token=#{token}"
end
def notification(params)
notification = {}
notification[:transaction_id] = params["id_transacao"]
notification[:amount] = sprintf("%.2f", params["valor"].to_f / 100).to_d
notification[:status] = STATUS[params["status_pagamento"].to_i]
notification[:code] = params["cod_moip"]
notification[:payment_type] = params["tipo_pagamento"]
notification[:email] = params["email_consumidor"]
notification
end
protected
def format_status_response(params)
response = { request_id: params["ID"] }
params = params["Autorizacao"]
if !params.nil?
response[:payer] = { name: params["Pagador"]["Nome"], email: params["Pagador"]["Email"] }
address = params["EnderecoCobranca"]
response[:address] = { street: address["Logradouro"], number: address["Numero"], complement: address["Complemento"], neighborhood: address["Bairro"],
zip: address["CEP"], city: address["Cidade"], state: address["Estado"], country: address["Pais"],
phone: address["TelefoneFixo"] }
payment = params["Pagamento"]
if !payment.nil?
if payment.kind_of?(Array)
latest = payment.first
payment.each {|p| latest = p if DateTime.parse(p["Data"]) > DateTime.parse(latest["Data"])}
payment = latest
end
response[:payment] = { date: DateTime.parse(payment["Data"]), instalments: payment["Parcela"]["TotalParcelas"].to_i,
amount: payment["TotalPago"]["__content__"].to_f,
payer_fee: payment["TaxaParaPagador"]["__content__"].to_f, owner_fee: payment["TaxaMoIP"]["__content__"].to_f,
status: STATUS[payment["Status"]["Tipo"].to_i], payment_gateway_id: payment["CodigoMoIP"],
payment_method: "#{payment["FormaPagamento"]} - #{payment["InstituicaoPagamento"]}" }
end
end
response
end
protected
def mount_new_payment_request(attributes)
xml = Builder::XmlMarkup.new.EnviarInstrucao do |e|
e.InstrucaoUnica do |i|
i.Recebedor do |r|
r.LoginMoIP attributes[:receiver]
r.Apelido attributes[:receiver_name]
end
i.Razao attributes[:reason]
i.IdProprio attributes[:id]
i.URLRetorno attributes[:callback_url]
i.URLNotificacao attributes[:notify_url]
i.Valores do |v|
v.Valor(attributes[:value], :moeda => "BRL")
v.Acrescimo(attributes[:extra], :moeda => "BRL")
v.Deducao(attributes[:discount], :moeda => "BRL")
end
i.Mensagens do |m|
if !attributes[:messages].nil?
if attributes[:messages].kind_of?(String)
m.Mensagem attributes[:messages]
else
attributes[:messages].each do |msg|
m.Mensagem msg
end
end
end
end
end
end
end
end
end
@rafaismyname
Copy link
Author

moip.yml:

development:
uri: https://desenvolvedor.moip.com.br/sandbox
token: #secret
key: #secret

test:
uri: https://desenvolvedor.moip.com.br/sandbox
token: #secret
key: #secret

production:
uri: https://www.moip.com.br
token: #secret
key: #secret

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment