• This repository has been archived on 17/Nov/2017
  • Stars
    star
    141
  • Rank 250,849 (Top 6 %)
  • Language
    Ruby
  • Created over 14 years ago
  • Updated about 8 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Um plugin para o Ruby on Rails que permite utilizar o PagSeguro

PAGSEGURO

Este projeto não está mais sendo mantido. Use pagseguro/ruby, a gem oficial.

Este é um plugin do Ruby on Rails que permite utilizar o PagSeguro, gateway de pagamentos do UOL.

SOBRE O PAGSEGURO

Carrinho Próprio

Trabalhando com carrinho próprio, sua loja mantém os dados do carrinho. O processo de inclusão de produtos no carrinho de compras acontece no próprio site da loja. Quando o comprador quiser finalizar sua compra, ele é enviado ao PagSeguro uma única vez com todos os dados de seu pedido. Aqui também, você tem duas opções. Pode enviar os dados do pedido e deixar o PagSeguro solicitar os dados do comprador, ou pode solicitar todos os dados necessários para a compra em sua loja e enviá-los ao PagSeguro.

Retorno Automático

Após o processo de compra e pagamento, o usuário é enviado de volta a seu site. Para isso, você deve configurar uma URL de retorno.

Antes de enviar o usuário para essa URL, o robô do PagSeguro faz um POST para ela, em segundo plano, com os dados e status da transação. Lendo esse POST, você pode obter o status do pedido. Se o pagamento entrou em análise, ou se o usuário pagou usando boleto bancário, o status será "Aguardando Pagamento" ou "Em Análise". Nesses casos, quando a transação for confirmada (o que pode acontecer alguns dias depois) a loja receberá outro POST, informando o novo status. Cada vez que a transação muda de status, um POST é enviado.

REQUISITOS

A versão atual que está sendo mantida suporta Rails 3.0.0 ou superior.

Se você quiser esta biblioteca em versão mais antigas do Rails (2.3, por exemplo) deverá usar o branch legacy, QUE NÃO É MAIS MANTIDO.

COMO USAR

Configuração

O primeiro passo é instalar a biblioteca. Para isso, basta executar o comando

gem install pagseguro

Adicione a biblioteca ao arquivo Gemfile:

gem "pagseguro", "~> 0.1.10"

Lembre-se de utilizar a versão que você acabou de instalar.

Depois de instalar a biblioteca, você precisará executar gerar o arquivo de configuração, que deve residir em config/pagseguro.yml. Para gerar um arquivo de modelo execute

rails generate pagseguro:install

O arquivo de configuração gerado será parecido com isto:

development: &development
  developer: true
  base: "http://localhost:3000"
  return_to: "/pedido/efetuado"
  email: [email protected]

test:
  <<: *development

production:
  authenticity_token: 9CA8D46AF0C6177CB4C23D76CAF5E4B0
  email: [email protected]
  return_to: "/pedido/efetuado"

Esta gem possui um modo de desenvolvimento que permite simular a realização de pedidos e envio de notificações; basta utilizar a opção developer. Ela é ativada por padrão nos ambientes de desenvolvimento e teste. Você deve configurar as opções base, que deverá apontar para o seu servidor e a URL de retorno, que deverá ser configurada no próprio PagSeguro, na página https://pagseguro.uol.com.br/Security/ConfiguracoesWeb/RetornoAutomatico.aspx.

Para o ambiente de produção, que irá efetivamente enviar os dados para o PagSeguro, você precisará adicionar o e-mail cadastrado como vendedor e o authenticity_token, que é o Token para Conferência de Segurança, que pode ser conseguido na página https://pagseguro.uol.com.br/Security/ConfiguracoesWeb/RetornoAutomatico.aspx.

Montando o formulário

Para montar o seu formulário, você deverá utilizar a classe PagSeguro::Order. Esta classe deverá ser instanciada recebendo um identificador único do pedido. Este identificador permitirá identificar o pedido quando o PagSeguro notificar seu site sobre uma alteração no status do pedido.

class CartController < ApplicationController
  def checkout
    # Busca o pedido associado ao usuario; esta logica deve
    # ser implementada por voce, da maneira que achar melhor
    @invoice = current_user.invoices.last

    # Instanciando o objeto para geracao do formulario
    @order = PagSeguro::Order.new(@invoice.id)

    # adicionando os produtos do pedido ao objeto do formulario
    @invoice.products.each do |product|
      # Estes sao os atributos necessarios. Por padrao, peso (:weight) eh definido para 0,
      # quantidade eh definido como 1 e frete (:shipping) eh definido como 0.
      @order.add :id => product.id, :price => product.price, :description => product.title
    end
  end
end

Se você precisar, pode definir o tipo de frete com o método shipping_type.

@order.shipping_type = "SD" # Sedex
@order.shipping_type = "EN" # PAC
@order.shipping_type = "FR" # Frete Proprio

Se você precisar, pode definir os dados de cobrança com o método billing.

@order.billing = {
  :name                  => "John Doe",
  :email                 => "[email protected]",
  :address_zipcode       => "01234-567",
  :address_street        => "Rua Orobo",
  :address_number        => 72,
  :address_complement    => "Casa do fundo",
  :address_neighbourhood => "Tenorio",
  :address_city          => "Pantano Grande",
  :address_state         => "AC",
  :address_country       => "Brasil",
  :phone_area_code       => "22",
  :phone_number          => "1234-5678"
}

Depois que você definiu os produtos do pedido, você pode exibir o formulário.

<!-- app/views/cart/checkout.html.erb -->
<%= pagseguro_form @order, :submit => "Efetuar pagamento!" %>

Por padrão, o formulário é enviado para o email no arquivo de configuração. Você pode mudar o email com a opção :email.

<%= pagseguro_form @order, :submit => "Efetuar pagamento!", :email => @account.email %>

Recebendo notificações

Toda vez que o status de pagamento for alterado, o PagSeguro irá notificar sua URL de retorno com diversos dados. Você pode interceptar estas notificações com o método pagseguro_notification. O bloco receberá um objeto da classe PagSeguro::Notification e só será executado se for uma notificação verificada junto ao PagSeguro.

class CartController < ApplicationController
  skip_before_filter :verify_authenticity_token

  def confirm
    return unless request.post?

	pagseguro_notification do |notification|
	  # Aqui voce deve verificar se o pedido possui os mesmos produtos
	  # que voce cadastrou. O produto soh deve ser liberado caso o status
	  # do pedido seja "completed" ou "approved"
	end

	render :nothing => true
  end
end

O método pagseguro_notification também pode receber como parâmetro o authenticity_token que será usado pra verificar a autenticação.

class CartController < ApplicationController
  skip_before_filter :verify_authenticity_token

  def confirm
    return unless request.post?
	# Se voce receber pagamentos de contas diferentes, pode passar o
	# authenticity_token adequado como parametro para pagseguro_notification
	account = Account.find(params[:seller_id])
	pagseguro_notification(account.authenticity_token) do |notification|
	end

	render :nothing => true
  end
end

O objeto notification possui os seguintes métodos:

  • PagSeguro::Notification#products: Lista de produtos enviados na notificação.
  • PagSeguro::Notification#shipping: Valor do frete
  • PagSeguro::Notification#status: Status do pedido
  • PagSeguro::Notification#payment_method: Tipo de pagamento
  • PagSeguro::Notification#processed_at: Data e hora da transação
  • PagSeguro::Notification#buyer: Dados do comprador
  • PagSeguro::Notification#valid?(force=false): Verifica se a notificação é válida, confirmando-a junto ao PagSeguro. A resposta é jogada em cache e pode ser forçada com PagSeguro::Notification#valid?(:force)

ATENÇÃO: Não se esqueça de adicionar skip_before_filter :verify_authenticity_token ao controller que receberá a notificação; caso contrário, uma exceção será lançada.

Utilizando modo de desenvolvimento

Toda vez que você enviar o formulário no modo de desenvolvimento, um arquivo YAML será criado em tmp/pagseguro-#{Rails.env}.yml. Esse arquivo conterá todos os pedidos enviados.

Depois, você será redirecionado para a URL de retorno que você configurou no arquivo config/pagseguro.yml. Para simular o envio de notificações, você deve utilizar a rake pagseguro:notify.

$ rake pagseguro:notify ID=<id do pedido>

O ID do pedido deve ser o mesmo que foi informado quando você instanciou a class PagSeguro::Order. Por padrão, o status do pedido será completed e o tipo de pagamento credit_card. Você pode especificar esses parâmetros como no exemplo abaixo.

$ rake pagseguro:notify ID=1 PAYMENT_METHOD=invoice STATUS=canceled NOTE="Enviar por motoboy" NAME="José da Silva" EMAIL="[email protected]"

PAYMENT_METHOD

  • credit_card: Cartão de crédito
  • invoice: Boleto
  • online_transfer: Pagamento online
  • pagseguro: Transferência entre contas do PagSeguro

STATUS

  • completed: Completo
  • pending: Aguardando pagamento
  • approved: Aprovado
  • verifying: Em análise
  • canceled: Cancelado
  • refunded: Devolvido

Codificação (Encoding)

Esta biblioteca assume que você está usando UTF-8 como codificação de seu projeto. Neste caso, o único ponto onde os dados são convertidos para UTF-8 é quando uma notificação é enviada do UOL em ISO-8859-1.

Se você usa sua aplicação como ISO-8859-1, esta biblioteca NÃO IRÁ FUNCIONAR. Nenhum patch dando suporte ao ISO-8859-1 será aplicado; você sempre pode manter o seu próprio fork, caso precise.

TROUBLESHOOTING

Quero utilizar o servidor em Python para testar o retorno automático, mas recebo OpenSSL::SSL::SSLError (SSL_connect returned=1 errno=0 state=SSLv3 read server certificate B)

Neste caso, você precisa forçar a validação do POST enviado. Basta acrescentar a linha:

pagseguro_notification do |notification|
  notification.valid?(:force => true)
  # resto do codigo...
end

AUTOR:

Nando Vieira (http://simplesideias.com.br)

Recomendar no Working With Rails

COLABORADORES:

LICENÇA:

(The MIT License)

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 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.

More Repositories

1

i18n-js

It's a small library to provide the I18n translations on the Javascript. It comes with Rails support.
Ruby
3,702
star
2

browser

Do some browser detection with Ruby. Includes ActionController integration.
Ruby
2,388
star
3

kitabu

A framework for creating e-books from Markdown using Ruby. Using the Prince PDF generator, you'll be able to get high quality PDFs. Also supports EPUB, Mobi, Text and HTML generation.
Ruby
659
star
4

recurrence

A simple library that handles recurring events.
Ruby
556
star
5

sparkline

Generate SVG sparklines with JavaScript without any external dependency.
JavaScript
501
star
6

paypal-recurring

PayPal Express Checkout API Client for recurring billing.
Ruby
257
star
7

cpf_cnpj

🇧🇷 Validate, generate and format CPF/CNPJ numbers. Include command-line tools.
Ruby
220
star
8

password_strength

Check password strength against several rules. Includes ActiveRecord/ActiveModel support.
JavaScript
182
star
9

cpf

🇧🇷 Validate, generate and format CPF numbers
TypeScript
161
star
10

coupons

Coupons is a Rails engine for creating discount coupons.
Ruby
140
star
11

cpf_cnpj.js

Validate, generate and format CPF/CNPJ numbers
JavaScript
118
star
12

i18n

A small library to provide the I18n translations on the JavaScript.
TypeScript
113
star
13

uptime_checker

Check if your sites are online for $7/mo.
112
star
14

module

Define namespaces as constructor functions (or any object).
JavaScript
105
star
15

qe

A simple interface over several background job libraries like Resque, Sidekiq and DelayedJob.
Ruby
102
star
16

has_calendar

A view helper that creates a calendar using a table. You can easily add events with any content.
Ruby
101
star
17

sinatra-subdomain

Separate routes for subdomains in Sinatra apps
Ruby
96
star
18

validators

Some ActiveModel/ActiveRecord validators
Ruby
96
star
19

dotfiles

My dotfiles
Shell
88
star
20

rack-api

Create web app APIs that respond to one or more formats using an elegant DSL.
Ruby
86
star
21

notifier

Send system notifications on several platforms with a simple and unified API. Currently supports Notification Center, Libnotify, OSD, KDE (Knotify and Kdialog) and Snarl
Ruby
84
star
22

factory_bot-preload

Preload factories (factory_bot) just like fixtures. It will be easy and, probably, faster!
Ruby
83
star
23

cnpj

🇧🇷 Validate, generate and format CNPJ numbers
TypeScript
81
star
24

dispatcher-js

Simple jQuery dispatcher for web apps.
JavaScript
75
star
25

gem-open

Open gems into your favorite editor by running a specific gem command
Ruby
69
star
26

test_notifier

Display system notifications (dbus, growl and snarl) after running tests. It works on Mac OS X, Linux and Windows. Powerful when used with Autotest ZenTest gem for Rails apps.
Ruby
63
star
27

test_squad

Running JavaScript tests on your Rails app, the easy way.
Ruby
56
star
28

vscode-linter

Extension for code linting, all in one package. New linters can be easily added through an extension framework.
TypeScript
56
star
29

has_friends

Add friendship support to Rails apps with this plugin
Ruby
55
star
30

breadcrumbs

Breadcrumbs is a simple Rails plugin that adds a breadcrumbs object to controllers and views.
Ruby
55
star
31

minitest-utils

Some utilities for your Minitest day-to-day usage.
Ruby
52
star
32

photomatic

Your photography is what matters.
Ruby
50
star
33

normalize_attributes

Sometimes you want to normalize data before saving it to the database like down casing e-mails, removing spaces and so on. This Rails plugin allows you to do so in a simple way.
Ruby
49
star
34

burgundy

A simple wrapper for objects (think of Burgundy as a decorator/presenter) in less than 150 lines.
Ruby
49
star
35

ar-uuid

Override migration methods to support UUID columns without having to be explicit about it.
Ruby
46
star
36

rubygems_proxy

Rack app for caching RubyGems files. Very useful in our build server that sometimes fails due to our network or rubygems.org timeout.
Ruby
43
star
37

post_commit

Post commit allows you to notify several services with a simple and elegant DSL. Five services are supported for now: Basecamp, Campfire, FriendFeed, LightHouse and Twitter.
Ruby
42
star
38

permalink

Add permalink support to Rails apps with this plugin
Ruby
40
star
39

keyring-node

Simple encryption-at-rest with key rotation support for Node.js.
JavaScript
39
star
40

superconfig

Access environment variables. Also includes presence validation, type coercion and default values.
Ruby
38
star
41

sublime-better-ruby

Sublime Text Ruby package (snippets, builder, syntax highlight)
Ruby
37
star
42

simple_presenter

A simple presenter/facade/decorator/whatever implementation.
Ruby
33
star
43

voltage

A simple observer implementation on POROs (Plain Old Ruby Object) and ActiveRecord objects.
Ruby
31
star
44

redis-settings

Store application and user settings on Redis. Comes with ActiveRecord support.
Ruby
31
star
45

tokens

Add token support to Rails apps with this plugin
Ruby
31
star
46

boppers

A simple bot framework for individuals.
Ruby
29
star
47

babel-schmooze-sprockets

Add Babel support to sprockets using Schmooze.
JavaScript
29
star
48

streamdeck

A lean framework for developing Elgato Stream Deck plugins.
TypeScript
28
star
49

sublime-text

My SublimeText settings
26
star
50

has_ratings

Add rating support to Rails apps with this plugin
Ruby
25
star
51

commentable

Add comment support to Rails apps with this plugin
Ruby
23
star
52

sinatra-basic-auth

Authentication with BasicAuth that can require different credentials for different realms.
Ruby
23
star
53

rails-routes

Enable config/routes/*.rb on your Rails application.
Ruby
23
star
54

aitch

A simple HTTP client.
Ruby
21
star
55

swiss_knife

Here's my swiss-knife Rails helpers.
Ruby
21
star
56

messages-app

Use alert messages in your README.
HTML
19
star
57

rails-env

Avoid environment detection on Rails
Ruby
19
star
58

defaults

Add default value for ActiveRecord attributes
Ruby
18
star
59

ar-check

Enable PostgreSQL's CHECK constraints on ActiveRecord migrations
Ruby
17
star
60

email_data

This project is a compilation of datasets related to emails. Includes disposable emails, disposable domains, and free email services.
Ruby
17
star
61

sublime-text-screencasts

Screencasts sobre Sublime Text
HTML
17
star
62

simple_auth

SimpleAuth is an authentication library to be used when everything else is just too complicated.
Ruby
17
star
63

attr_keyring

Simple encryption-at-rest with key rotation support for Ruby.
Ruby
17
star
64

has_bookmarks

Add bookmark support to Rails apps with this plugin
Ruby
17
star
65

paginate

Paginate collections using SIZE+1 to determine if there is a next page. Includes ActiveRecord and ActionView support.
Ruby
16
star
66

pry-meta

Meta package that requires several pry extensions.
Ruby
15
star
67

svg_optimizer

Some SVG optimization based on Node's SVGO
Ruby
15
star
68

react-starter-pack

Starter-pack for react + webpack + hot reload + mocha + enzyme + production build
JavaScript
15
star
69

check_files

Check non-reloadable files changes on Rails apps.
Ruby
15
star
70

url_signature

Create and verify signed urls. Supports expiration time.
Ruby
15
star
71

activities

Activities is a gem that enables social activities in ActiveRecord objects.
Ruby
14
star
72

using-es6-with-asset-pipeline-on-ruby-on-rails

Example for my article about ES6 + Asset Pipeline
Ruby
14
star
73

whiteboard

A small app using Canvas + Socket.IO to provide a shared whiteboard.
JavaScript
14
star
74

sublime-better-rspec

Better RSpec syntax highlighting, with matchers for v3. Also includes implementation/spec toggling command.
Python
13
star
75

ar-sequence

Add support for PostgreSQL's SEQUENCE on ActiveRecord migrations.
Ruby
13
star
76

page_meta

Easily define <meta> and <link> tags. I18n support for descriptions, keywords and titles.
Ruby
13
star
77

boppers-uptime

A bopper to check if your sites are online.
Ruby
13
star
78

has_versions

A simple plugin to version ActiveRecord objects
Ruby
13
star
79

csr

Generate CSR (Certificate Signing Request) using Ruby and OpenSSL.
Ruby
13
star
80

haikunate

Generate Heroku-like memorable random names like adorable-ox-1234.
Ruby
13
star
81

module-component

Define auto-discoverable HTML UI components using Module.js.
JavaScript
12
star
82

alfred-workflows

Alfred workflows
12
star
83

twitter_cleanup

Remove old tweets periodically using Github Actions
Ruby
12
star
84

storage

This gem provides a simple API for multiple storage backends. Supported storages: Amazon S3 and FileSystem.
Ruby
12
star
85

has_layout

Add conditional layouts with ease
Ruby
11
star
86

kalendar

A view helper that creates a calendar using a table. You can easily add events with any content.
Ruby
11
star
87

stellar-paperwallet

Make paper wallets to keep your Stellar addresses safe.
JavaScript
10
star
88

tagger

Tagging plugin for Ruby on Rails apps
Ruby
10
star
89

page_title

Set the page title on Rails apps.
Ruby
10
star
90

dogo

A simple URL shortener service backed by Redis.
Ruby
10
star
91

has_notifications

This plugin was created to act as a proxy between different notification systems (Mail, Jabber, etc) based on the user's preferences.
Ruby
10
star
92

formatter

has_markup is an ActiveRecord plugin that integrates Tidy, Markdown, Textile and sanitize helper method into a single plugin.
Ruby
10
star
93

shortcuts

Because mouse is for noobies.
Ruby
9
star
94

ar-enum

Add support for creating `ENUM` types in PostgreSQL with ActiveRecord
Ruby
9
star
95

ar-timestamptz

Make ActiveRecord's PostgreSQL adapter use timestamptz as datetime columns.
Ruby
9
star
96

parsel-js

Encrypt and decrypt data with a given key.
JavaScript
8
star
97

access_token

Access token for client-side and API authentication.
Ruby
8
star
98

ember-and-rails

Ruby
8
star
99

sinatra-oauth-twitter

Sample app used on Guru-SP meetup
Ruby
8
star
100

bolt

A nicer test runner for golang
Go
8
star