Example #1
0
    def test_checkout_realizado_com_erro(self):
        from pagseguro.signals import checkout_realizado_com_erro

        # load signal function
        def load_signal(sender, data, **kwargs):
            self.assertEqual(data['success'], False)
            self.assertEqual(data['status_code'], 401)
            self.assertEqual(data['message'], 'Unauthorized')

        # mock requests
        responses.add(
            responses.POST,
            CHECKOUT_URL,
            body='Unauthorized',
            status=401,
        )

        # connect to signal
        checkout_realizado_com_erro.connect(load_signal)

        # create new checkout
        pagseguro_api = PagSeguroApi()
        pagseguro_api.add_item(
            PagSeguroItem(id='1',
                          description='My item',
                          amount='10.00',
                          quantity=1))

        # load notification
        pagseguro_api.checkout()
Example #2
0
    def test_checkout_realizado(self):
        from pagseguro.signals import checkout_realizado

        # load signal function
        def load_signal(sender, data, **kwargs):
            self.assertEqual(data['success'], True)
            self.assertEqual(data['code'], '67DB59D3BDBD84EAA4396F929DB350A7')
            self.assertEqual(data['status_code'], 200)

        # mock requests
        responses.add(
            responses.POST,
            CHECKOUT_URL,
            body=checkout_response_xml,
            status=200,
        )

        # connect to signal
        checkout_realizado.connect(load_signal)

        # create new checkout
        pagseguro_api = PagSeguroApi()
        pagseguro_api.add_item(
            PagSeguroItem(id='1',
                          description='My item',
                          amount='10.00',
                          quantity=1))

        # load notification
        pagseguro_api.checkout()
Example #3
0
def pagseguro(id,descricao,valor,codigo,taxa):

	compra = PagSeguroItem(id=id,description=descricao,amount=valor,quantity=1)

	pagseguro_api = PagSeguroApi(reference=codigo,extraAmount=taxa)
	pagseguro_api.add_item(compra)
	data = pagseguro_api.checkout()
	url = data['redirect_url']

	return url
Example #4
0
    def post(self, request):
        f = CompraForm(request.POST)

        item = PagSeguroItem(id=Red_Pontos.id,
                             description=Red_Pontos.description,
                             amount=Red_Pontos.get_preco(f['quantidade'].data),
                             quantity=str(f['quantidade'].data))

        pagseguro_api = PagSeguroApi(email=config('PAGSEGURO_EMAIL'),
                                     token=config('PAGSEGURO_TOKEN'))
        pagseguro_api.add_item(item)
        data = pagseguro_api.checkout()

        return redirect(data['redirect_url'])
Example #5
0
def create_pagseguro_cart(payment):
    """
    Create PagSeguro cart and make the checkout
    :param payment: Payment used to make the cart and add the items
    :return: Payment
    """
    cart = PagSeguroApi(reference=payment.id)
    cart.add_item(create_pagseguro_item(payment.rental))
    data = cart.checkout()
    if data.get('success', False):
        payment.code = data.get('code')
        payment.redirect_url = data.get('redirect_url')
    payment.status_code = data.get('status_code')
    payment.save()
    return payment
Example #6
0
 def start_payment(self, request, amount):
     event = self.subscription.event
     api = PagSeguroApi()
     self.transaction.amount = amount
     self.transaction.save()
     api.params['reference'] = self.transaction.id
     api.params['notificationURL'] = self.my_pay_url(request)
     log.debug('Set notification URI: %s', api.params['notificationURL'])
     api.add_item(PagSeguroItem(id=self.transaction.id, description=event.name, amount=amount, quantity=1))
     data = api.checkout()
     if data['success']:
         return prg_redirect(data['redirect_url'])
     else:
         log.error('Data returned error. %s', repr(data))
         raise ValueError('PagSeguro denied pay. %s' % repr(data))
Example #7
0
def pagamento(request):

    codigo_cliente = request.GET.get('codigo_cliente')
    recarga_id = request.GET.get('recarga_id')
    request.session['codigo_cliente'] = codigo_cliente

    recarga = Recarga.objects.get(pk=recarga_id)
    cliente = Cliente.objects.get(pk=codigo_cliente)

    item1 = PagSeguroItem(id=recarga.pk,
                          description='Recarga Keep Mensagens - %s' %
                          recarga.valor.valor,
                          amount=recarga.valor.valor,
                          quantity=1)
    pagseguro_api = PagSeguroApi(
        reference='%s-%s' % (codigo_cliente, recarga.pk),
        senderEmail=cliente.email,
        senderName=cliente.nome,
    )

    pagseguro_api.add_item(item1)
    data = pagseguro_api.checkout()

    if data['status_code'] != 200:
        recarga.data_cancelamento = datetime.datetime.now()
        recarga.save()
        messages.error(
            request,
            'Ocorreu um erro para prosseguir a recarga, contate o suporte.')

        return HttpResponseRedirect('/recargas/' % cliente.url)

    requests.post("%s/cria-recarga-cliente/" % cliente.url,
                  data={
                      'recarga_id': recarga_id,
                      'valor_id': recarga.valor_id,
                      'token': '92817488F00646D0$sso09asada'
                  })

    dados = {
        'titulo': "Pagamento",
        'recarga': recarga,
        'cliente': cliente,
        'redirect_url': data['redirect_url'],
        'menu': "menu_mensagens",
    }

    return render(request, 'recarga/pagamento.html', dados)
    def handle_successful_order(self, order):
        super(SuccessResponseView, self).handle_successful_order(order)

        reference = order.number
        pagseguro_api = PagSeguroApi(reference=reference)

        for line in order.lines.all():
            item = PagSeguroItem(id=line.pk,
                                 description=line.description,
                                 amount='{0:.2f}'.format(line.stockrecord.price_excl_tax),
                                 quantity=line.quantity)
            pagseguro_api.add_item(item)

        data = pagseguro_api.checkout()

        return redirect(data['redirect_url'])
    def handle_successful_order(self, order):
        super(SuccessResponseView, self).handle_successful_order(order)

        reference = order.number
        pagseguro_api = PagSeguroApi(reference=reference)

        for line in order.lines.all():
            item = PagSeguroItem(id=line.pk,
                                 description=line.description,
                                 amount='{0:.2f}'.format(
                                     line.stockrecord.price_excl_tax),
                                 quantity=line.quantity)
            pagseguro_api.add_item(item)

        data = pagseguro_api.checkout()

        return redirect(data['redirect_url'])
Example #10
0
 def create_checkout(self, cart):
     purchase = self.create_purchase(cart)
     pagseguro_api = PagSeguroApi(reference=str(purchase.id))
     for cart_item in cart.cart_items.all():
         ticket = cart_item.ticket
         item = PagSeguroItem(id=str(ticket.id),
                              description=ticket.title,
                              amount=str(cart_item.unit_price),
                              quantity=cart_item.quantity)
         pagseguro_api.add_item(item)
     pagseguro_data = pagseguro_api.checkout()
     if pagseguro_data['success'] is False:
         raise CheckoutException(pagseguro_data['message'])
     purchase.pagseguro_redirect_url = pagseguro_data['redirect_url']
     purchase.save()
     cart.closed = True
     cart.save()
     return purchase
Example #11
0
 def pagseguro(self, subscription):
     obj = get_object_or_404(Subscription, pk=subscription)
     item = PagSeguroItem(
         id=obj.course.pk,
         description=obj.course.name,
         amount=obj.course.price,
         quantity=obj.students.count()
     )
     pg = PagSeguroApi(
         reference=obj.pk,
         senderEmail=obj.email
     )
     pg.add_item(item)
     data = pg.checkout()
     if data.get('success'):
         return data['redirect_url']
     else:
         messages.error(self.request, "Houve um erro ao processar seus dados. Se o problema persistir entre em contato: (61) 8121-7870 ou (61) 9193-0933")
         return reverse("course:checkout")
Example #12
0
 def get_redirect_url(self, *args, **kwargs):
     inscription = PagSeguroItem(
         id=self.object.pk,
         description='Incrição no torneio: {}'.format(self.object.tournament.title),
         quantity=self.object.competitors.all().count(),
         amount=self.object.tournament.price
     )
     pagseguro_api = PagSeguroApi(reference=self.object.slug)
     pagseguro_api.add_item(inscription)
     data = pagseguro_api.checkout()
     if not data['success']:
         logging.error('Falha ao processar pagamento')
         logging.error('ID da inscrição: {}'.format(self.object.slug))
         messages.error(
             self.request,
             'Houve um problema ao processar seu pagamento, ' \
             'entre em contato se o problema persistir'
         )
         return reverse('tournaments:list')
     return data['redirect_url']
Example #13
0
def aniversario_doar(request, slug_usuario, slug_missao):
    aniversario_instance = get_object_or_404(Aniversario,
                                             usuario__slug=slug_usuario,
                                             missao__slug=slug_missao)
    if aniversario_instance.finalizado:
        messages.error(
            request,
            'Aniversário Solidário já foi finalizado. Por isso você não editar mais nenhuma informação!'
        )
        return redirect(
            reverse('aniversario:index',
                    kwargs={
                        'slug_usuario': slug_usuario,
                        'slug_missao': slug_missao
                    }))
    valor = request.GET.get('valor')
    if valor:
        if int(valor) < 25:
            messages.error(request,
                           'O valor minimo em uma doação é de 25 reais')
        else:
            pagamento = Pagamento.objects.create(valor=valor)
            doacao = Doacao.objects.create(
                usuario=request.user
                if request.user.is_authenticated() else None,
                aniversario=aniversario_instance,
                pagamento=pagamento)
            pagseguro_item = PagSeguroItem(id=str(doacao.aniversario.id),
                                           description=str(doacao),
                                           amount='%.2f' %
                                           float(doacao.pagamento.valor),
                                           quantity=1)
            pagseguro_api = PagSeguroApi(reference=str(doacao.id))
            pagseguro_api.add_item(pagseguro_item)
            pagseguro_data = pagseguro_api.checkout()
            doacao.pagamento.checkout = Checkout.objects.get(
                code=pagseguro_data.get('code'))
            doacao.pagamento.save(update_fields=['checkout'])
            return redirect(pagseguro_data.get('redirect_url'))
    return render(request, 'nucleo/aniversario_doar.html',
                  {'aniversario': aniversario_instance})
Example #14
0
def teste_pagseguro(request):
    pagseguro_api = PagSeguroApi(
        reference='id-unico-de-referencia-do-seu-sistema')
    item1 = PagSeguroItem(id='0001',
                          description='Notebook Prata',
                          amount='24300.00',
                          quantity=1)
    item2 = PagSeguroItem(id='0002',
                          description='Meu item 0002',
                          amount='150.00',
                          quantity=1,
                          shipping_cost='25.00',
                          weight=500)
    pagseguro_api.add_item(item1)
    pagseguro_api.add_item(item2)

    api = PagSeguroApiTransparent()
    api.add_item(item1)

    sender = {
        'name': 'Jose Comprador',
        'area_code': 11,
        'phone': 56273440,
        'email': '*****@*****.**',
        'cpf': '22111944785',
    }
    api.set_sender(**sender)

    shipping = {
        'street': "Av. Brigadeiro Faria Lima",
        'number': 1384,
        'complement': '5o andar',
        'district': 'Jardim Paulistano',
        'postal_code': '01452002',
        'city': 'Sao Paulo',
        'state': 'SP',
        'country': 'BRA',
    }
    api.set_shipping(**shipping)

    api.set_payment_method('creditcard')
def pay_pagseguro(data, payment, test=False):
    item1 = PagSeguroItem(id='0001', description='Pagamento', amount=data.get('value'), quantity=1)
    pagseguro_api = PagSeguroApi(reference='paymentserver', email=data.get('code'), token=data.get('key'))
    pagseguro_api.add_item(item1)
    response = pagseguro_api.checkout()
    # import pdb;pdb.set_trace()
    if response and response.get('status_code') == 200:
        payment.pagseguro_url = response.get('redirect_url')
        payment.pagseguro_code = response.get('code')
        payment.is_authorized = False
        payment.is_paid = False
        payment.save()
        return payment
    else:
        payment.status_code = response.get('status_code')
        payment.response_text = response.get('message')
        payment.paid_at = datetime.now()
        payment.is_authorized = False
        payment.is_paid = False
        payment.save()
        raise APIException(u'Erro %s' % response.get('message'))
    def test_checkout_realizado(self):
        from pagseguro.signals import checkout_realizado

        # load signal function
        def load_signal(sender, data, **kwargs):
            self.assertEqual(
                data['success'], True
            )
            self.assertEqual(
                data['code'], '67DB59D3BDBD84EAA4396F929DB350A7'
            )
            self.assertEqual(
                data['status_code'], 200
            )

        # mock requests
        httpretty.register_uri(
            httpretty.POST,
            CHECKOUT_URL,
            body=checkout_response_xml,
            status=200,
        )

        # connect to signal
        checkout_realizado.connect(load_signal)

        # create new checkout
        pagseguro_api = PagSeguroApi()
        pagseguro_api.add_item(
            PagSeguroItem(
                id='1',
                description='My item',
                amount='10.00',
                quantity=1
            )
        )

        # load notification
        pagseguro_api.checkout()
    def test_checkout_realizado_com_erro(self):
        from pagseguro.signals import checkout_realizado_com_erro

        # load signal function
        def load_signal(sender, data, **kwargs):
            self.assertEqual(
                data['success'], False
            )
            self.assertEqual(
                data['status_code'], 401
            )
            self.assertEqual(
                data['message'], 'Unauthorized'
            )

        # mock requests
        httpretty.register_uri(
            httpretty.POST,
            CHECKOUT_URL,
            body='Unauthorized',
            status=401,
        )

        # connect to signal
        checkout_realizado_com_erro.connect(load_signal)

        # create new checkout
        pagseguro_api = PagSeguroApi()
        pagseguro_api.add_item(
            PagSeguroItem(
                id='1',
                description='My item',
                amount='10.00',
                quantity=1
            )
        )

        # load notification
        pagseguro_api.checkout()
Example #18
0
def CartPageView(request):

    cart = Cart(request)
    pagseguro_api = PagSeguroApi(reference='2309238123939293')

    if request.method == 'POST':

        for item in cart.getall():
            print(item)
            pag_item = PagSeguroItem(id=item['id'],
                                     description=item['title'],
                                     amount=item['price'],
                                     quantity=item['quantity'],
                                     shipping_cost='25.00',
                                     weight=500)
            pagseguro_api.add_item(pag_item)
        data = pagseguro_api.checkout()
        return redirect(data['redirect_url'])

    return render(request, 'cart.html', {
        'products': cart.getall(),
        'totalprice': cart.totalprice()
    })
Example #19
0
 def get_redirect_url(self, *args, **kwargs):
     sett = Settings.get()
     if not sett.require_payment:
         add_message(self.request, ERROR, 'Pagamentos desabilitados')
         return '/'
     item = PagSeguroItem(
         id='1',
         description=f'Ingresso para {settings.EVENT_NAME}',
         amount=f'{sett.ticket_price}',
         quantity=1
     )
     reference = get_random_string(length=32)
     api = PagSeguroApi(reference=reference)
     api.add_item(item)
     checkout = api.checkout()
     if checkout['success']:
         hacker = self.request.user.profile.hacker
         hacker.transaction_reference = reference
         hacker.save()
         return checkout['redirect_url']
     else:
         add_message(self.request, ERROR, 'Erro ao criar pedido de pagamento. Tente novamente mais tarde.')
         return '/'
Example #20
0
    def checkout(self, request):
        # print(request.data)
        pagseguro_api = PagSeguroApi(
            currency=request.data["currency"],
            reference=request.data["reference"],
            senderEmail=request.data[
                "senderEmail"],  #"*****@*****.**",#request.data["senderEmail"],
            senderName=request.data["senderName"],
            senderAreaCode=request.data["senderAreaCode"],
            senderPhone=request.data["senderPhone"],
            shipping_cost=0,
        )  # request.data["senderPhone"])
        item1 = PagSeguroItem(
            id=request.data["itemId"],
            description=request.data["itemDescription"],
            amount=request.data["itemAmount"],
            quantity=request.data["itemQuantity"],
        )

        pagseguro_api.add_item(item1)
        data = pagseguro_api.checkout()

        return Response(data)
Example #21
0
def start_payment(request, order, variant):
    """
    waiting_payments = order.payments.filter(status='waiting').exists()
    if waiting_payments:
        return redirect('order:payment', token=order.token)
    billing = order.billing_address
    total = order.get_total()
    defaults = {'total': total.gross,
                'tax': total.tax, 'currency': total.currency,
                'delivery': order.get_delivery_total().gross,
                'billing_first_name': billing.first_name,
                'billing_last_name': billing.last_name,
                'billing_address_1': billing.street_address_1,
                'billing_address_2': billing.street_address_2,
                'billing_city': billing.city,
                'billing_postcode': billing.postal_code,
                'billing_country_code': billing.country,
                'billing_email': order.user_email,
                'description': _('Order %(order_number)s') % {
                    'order_number': order},
                'billing_country_area': billing.country_area,
                'customer_ip_address': get_client_ip(request)}
    variant_choices = settings.CHECKOUT_PAYMENT_CHOICES
    if variant not in [code for code, dummy_name in variant_choices]:
        raise Http404('%r is not a valid payment variant' % (variant,))
    with transaction.atomic():
        order.change_status('payment-pending')
        payment, dummy_created = Payment.objects.get_or_create(
            variant=variant, status='waiting', order=order, defaults=defaults)
        try:
            form = payment.get_form(data=request.POST or None)
        except RedirectNeeded as redirect_to:
            return redirect(str(redirect_to))
        except Exception:
            logger.exception('Error communicating with the payment gateway')
            messages.error(
                request,
                _('Oops, it looks like we were unable to contact the selected'
                  ' payment service'))
            payment.change_status('error')
            return redirect('order:payment', token=order.token)
    template = 'order/payment/%s.html' % variant

    return TemplateResponse(request, [template, 'order/payment/default.html'],
                            {'form': form, 'payment': payment})
    """
    order.change_status('payment-pending')
    items = order.get_items()
    total = 0
    for item in items:
        total += item.quantity * item.unit_price_net
    if total >= int(settings.DISCOUNT_THRESHOLD):
        pagseguro_api = PagSeguroApi(reference='luanavizzon',
                                     sender_email=order.user_email,
                                     extraAmount="%0.2f" % (-float(total) *
                                                            (0.4)))
    elif order.discount_amount is not None:
        pagseguro_api = PagSeguroApi(reference='luanavizzon',
                                     sender_email=order.user_email,
                                     extraAmount="%0.2f" %
                                     -order.discount_amount.gross)
    else:
        pagseguro_api = PagSeguroApi(reference='luanavizzon',
                                     sender_email=order.user_email)
    flag = 0
    for item in items:
        if flag == 0 and float(order.get_delivery_total().gross) > 0:
            pagseguro_api.add_item(
                PagSeguroItem(id=item.product_sku,
                              description=item.product,
                              amount="%0.2f" % item.unit_price_net,
                              quantity=item.quantity,
                              shipping_cost="%0.2f" %
                              (float(order.get_delivery_total().gross) /
                               float(item.quantity))))
            flag = 1
        else:
            pagseguro_api.add_item(
                PagSeguroItem(id=item.product_sku,
                              description=item.product,
                              amount="%0.2f" % item.unit_price_net,
                              quantity=item.quantity))
    data = pagseguro_api.checkout()

    return redirect(data['redirect_url'])
Example #22
0
def completar_pagamento(request, doacao_id):
    if not request.method == 'POST':
        return redirect(
            reverse('financeiro:doacao_pagamento:index',
                    kwargs={'doacao_id': doacao_id}))

    doacao = get_object_or_404(Doacao, id=doacao_id, usuario=request.user)

    payment_method = request.POST.get('payment_method')
    pagseguro_item = PagSeguroItem(id=str(doacao.aniversario.id),
                                   description=str(doacao),
                                   amount='%.2f' %
                                   float(doacao.pagamento.valor),
                                   quantity=1)

    if payment_method == 'pagseguro':
        pagseguro_api = PagSeguroApi(reference=str(doacao.id))
        pagseguro_api.add_item(pagseguro_item)
        pagseguro_data = pagseguro_api.checkout()
        doacao.pagamento.checkout = Checkout.objects.get(
            code=pagseguro_data.get('code'))
        doacao.pagamento.save(update_fields=['checkout'])
        return redirect(pagseguro_data.get('redirect_url'))

    sender = {
        'name': request.user.nome,
        'area_code': request.user.telefone_ddd,
        'phone': request.user.telefone_numero,
        'email': request.user.email,
        'cpf': request.user.cleaned_cpf
    }

    endereco = None

    if request.POST.get('endereco') == 'novo':
        endereco = Endereco.objects.create(
            usuario=request.user,
            lagradouro=request.POST.get('endereco-lagradouro'),
            numero=int(request.POST.get('endereco-numero')),
            complemento=request.POST.get('endereco-complemento'),
            bairro=request.POST.get('endereco-bairro'),
            cep=request.POST.get('endereco-cep'),
            cidade=request.POST.get('endereco-cidade'),
            estado=request.POST.get('endereco-estado'))
    else:
        endereco = Endereco.objects.get(usuario=request.user,
                                        id=int(request.POST.get('endereco')))

    if endereco:
        pagseguro_api = PagSeguroApiTransparent(reference=str(doacao.id))
        pagseguro_api.add_item(pagseguro_item)
        pagseguro_api.set_sender(**sender)
        pagseguro_api.set_shipping(**endereco.pagseguro_serialize())
        pagseguro_api.set_payment_method(payment_method)
        pagseguro_api.set_sender_hash(request.POST.get('sender_hash'))

        if payment_method == 'boleto':
            pagseguro_data = pagseguro_api.checkout()
            doacao.pagamento.boleto_link = pagseguro_data.get(
                'transaction').get('paymentLink')
            doacao.pagamento.save(update_fields=['boleto_link'])
            return redirect(
                reverse('financeiro:doacao_pagamento:gerar_boleto',
                        kwargs={'doacao_id': doacao.id}))
        if payment_method == 'creditcard':
            pagseguro_api.set_creditcard_token(request.POST.get('card_token'))
            pagseguro_api.set_creditcard_data(
                quantity=1,
                value='%.2f' % doacao.pagamento.valor,
                name=request.POST.get('nome-no-cartao'),
                birth_date=request.POST.get('data-nascimento-cartao'),
                cpf=request.POST.get('cpf-cartao'),
                area_code=request.POST.get('telefone-ddd'),
                phone=request.POST.get('telefone'))

            endereco_cartao = None
            endereco_cartao_opt = request.POST.get('endereco-cartao')
            if endereco_cartao_opt == 'mesmo':
                endereco_cartao = endereco
            elif endereco_cartao_opt == 'novo':
                endereco_cartao = Endereco.objects.create(
                    usuario=request.user,
                    lagradouro=request.POST.get('endereco-cartao-lagradouro'),
                    numero=int(request.POST.get('endereco-cartao-numero')),
                    complemento=request.POST.get(
                        'endereco-cartao-complemento'),
                    bairro=request.POST.get('endereco-cartao-bairro'),
                    cep=request.POST.get('endereco-cartao-cep'),
                    cidade=request.POST.get('endereco-cartao-cidade'),
                    estado=request.POST.get('endereco-cartao-estado'))
            else:
                endereco_cartao = Endereco.objects.get(
                    usuario=request.user,
                    id=int(request.POST.get('endereco-cartao')))
            pagseguro_api.set_creditcard_billing_address(
                **endereco_cartao.pagseguro_serialize())

            pagseguro_data = pagseguro_api.checkout()
            doacao.pagamento.cartao = Checkout.objects.get(
                code=pagseguro_data.get('code'))
            doacao.pagamento.save(update_fields=['cartao'])
            return redirect(
                reverse('aniversario:doacao_realizada',
                        kwargs={
                            'slug_usuario': doacao.aniversario.usuario.slug,
                            'slug_missao': doacao.aniversario.missao.slug
                        }))

    raise Http404()
Example #23
0
class PagSeguroApiTest(TestCase):
    def setUp(self):
        self.item1 = PagSeguroItem(id='1',
                                   description='My item 1',
                                   amount='10.00',
                                   quantity=1)
        self.item2 = PagSeguroItem(id='2',
                                   description='My item 2',
                                   amount='10.00',
                                   quantity=1)
        self.item3 = PagSeguroItem(id='3',
                                   description='My item 3',
                                   amount='10.00',
                                   quantity=1,
                                   shipping_cost='10.00',
                                   weight=300)
        self.pagseguro_api = PagSeguroApi()

    def test_add_item(self):
        self.pagseguro_api.add_item(self.item1)
        self.assertIn(self.item1, self.pagseguro_api.get_items())

        self.pagseguro_api.add_item(self.item2)
        self.assertIn(self.item1, self.pagseguro_api.get_items())
        self.assertIn(self.item2, self.pagseguro_api.get_items())

        self.pagseguro_api.add_item(self.item3)
        self.assertIn(self.item1, self.pagseguro_api.get_items())
        self.assertIn(self.item2, self.pagseguro_api.get_items())
        self.assertIn(self.item3, self.pagseguro_api.get_items())

    def test_clear_items(self):
        self.pagseguro_api.add_item(self.item1)
        self.pagseguro_api.add_item(self.item2)
        self.pagseguro_api.add_item(self.item3)
        self.pagseguro_api.clear_items()
        self.assertNotIn(self.item1, self.pagseguro_api.get_items())
        self.assertNotIn(self.item2, self.pagseguro_api.get_items())
        self.assertNotIn(self.item3, self.pagseguro_api.get_items())

    @httpretty.activate
    def test_invalid_checkout(self):
        self.pagseguro_api.add_item(self.item1)
        self.pagseguro_api.add_item(self.item2)
        self.pagseguro_api.add_item(self.item3)

        # mock requests
        httpretty.register_uri(
            httpretty.POST,
            CHECKOUT_URL,
            body='Unauthorized',
            status=401,
        )

        data = self.pagseguro_api.checkout()
        self.assertEqual(data['success'], False)
        self.assertEqual(data['message'], 'Unauthorized')
        self.assertEqual(data['status_code'], 401)

    @httpretty.activate
    def test_valid_checkout(self):
        self.pagseguro_api.add_item(self.item1)
        self.pagseguro_api.add_item(self.item2)
        self.pagseguro_api.add_item(self.item3)

        # mock requests
        httpretty.register_uri(
            httpretty.POST,
            CHECKOUT_URL,
            body=checkout_response_xml,
            status=200,
        )

        data = self.pagseguro_api.checkout()
        self.assertEqual(data['success'], True)
        self.assertEqual(data['status_code'], 200)
        self.assertEqual(data['code'], '67DB59D3BDBD84EAA4396F929DB350A7')
        self.assertEqual(data['date'], parse('2014-06-07T00:52:04.000-03:00'))
        self.assertEqual(data['redirect_url'],
                         '{0}?code={1}'.format(PAYMENT_URL, data['code']))

    @httpretty.activate
    def test_get_invalid_notification(self):
        # mock requests
        httpretty.register_uri(
            httpretty.GET,
            NOTIFICATION_URL +
            '/{0}'.format('A5182C-C9EF48EF48D2-1FF4AF6FAC82-EB2948'),
            body='Unauthorized',
            status=401,
        )

        response = self.pagseguro_api.get_notification(
            'A5182C-C9EF48EF48D2-1FF4AF6FAC82-EB2948')
        self.assertEqual(response.status_code, 401)
        self.assertEqual(response.text, 'Unauthorized')

    @httpretty.activate
    def test_get_valid_notification(self):
        # mock requests
        httpretty.register_uri(
            httpretty.GET,
            NOTIFICATION_URL +
            '/{0}'.format('A5182C-C9EF48EF48D2-1FF4AF6FAC82-EB2948'),
            body=notification_response_xml,
            status=200,
        )

        response = self.pagseguro_api.get_notification(
            'A5182C-C9EF48EF48D2-1FF4AF6FAC82-EB2948')
        self.assertEqual(response.status_code, 200)

    @httpretty.activate
    def test_get_invalid_transaction(self):
        # mock requests
        httpretty.register_uri(
            httpretty.GET,
            TRANSACTION_URL +
            '/{0}'.format('9E884542-81B3-4419-9A75-BCC6FB495EF1'),
            body='Unauthorized',
            status=401,
        )

        data = self.pagseguro_api.get_transaction(
            '9E884542-81B3-4419-9A75-BCC6FB495EF1')
        self.assertEqual(data['status_code'], 401)
        self.assertEqual(data['message'], 'Unauthorized')

    @httpretty.activate
    def test_get_valid_transaction(self):
        # mock requests
        httpretty.register_uri(
            httpretty.GET,
            TRANSACTION_URL +
            '/{0}'.format('9E884542-81B3-4419-9A75-BCC6FB495EF1'),
            body=transaction_response_xml,
            status=200,
        )

        data = self.pagseguro_api.get_transaction(
            '9E884542-81B3-4419-9A75-BCC6FB495EF1')
        self.assertEqual(data['status_code'], 200)
        self.assertEqual(data['transaction']['code'],
                         '9E884542-81B3-4419-9A75-BCC6FB495EF1')

    def test_base_params_is_instance_variable(self):
        # Regression test
        api1 = PagSeguroApi()
        api2 = PagSeguroApi()
        self.assertIsNot(api1.base_params, api2.base_params)

    def test_params_is_instance_variable(self):
        # Regression test
        api1 = PagSeguroApi()
        api2 = PagSeguroApi()
        self.assertIsNot(api1.params, api2.params)

    def test_items_is_instance_variable(self):
        # Regression test
        api1 = PagSeguroApi()
        api2 = PagSeguroApi()
        self.assertIsNot(api1.items, api2.items)
class PagSeguroApiTest(TestCase):

    def setUp(self):
        self.item1 = PagSeguroItem(
            id='1',
            description='My item 1',
            amount='10.00',
            quantity=1
        )
        self.item2 = PagSeguroItem(
            id='2',
            description='My item 2',
            amount='10.00',
            quantity=1
        )
        self.item3 = PagSeguroItem(
            id='3',
            description='My item 3',
            amount='10.00',
            quantity=1,
            shipping_cost='10.00',
            weight=300
        )
        self.pagseguro_api = PagSeguroApi()

    def test_add_item(self):
        self.pagseguro_api.add_item(self.item1)
        self.assertIn(self.item1, self.pagseguro_api.get_items())

        self.pagseguro_api.add_item(self.item2)
        self.assertIn(self.item1, self.pagseguro_api.get_items())
        self.assertIn(self.item2, self.pagseguro_api.get_items())

        self.pagseguro_api.add_item(self.item3)
        self.assertIn(self.item1, self.pagseguro_api.get_items())
        self.assertIn(self.item2, self.pagseguro_api.get_items())
        self.assertIn(self.item3, self.pagseguro_api.get_items())

    def test_clear_items(self):
        self.pagseguro_api.add_item(self.item1)
        self.pagseguro_api.add_item(self.item2)
        self.pagseguro_api.add_item(self.item3)
        self.pagseguro_api.clear_items()
        self.assertNotIn(self.item1, self.pagseguro_api.get_items())
        self.assertNotIn(self.item2, self.pagseguro_api.get_items())
        self.assertNotIn(self.item3, self.pagseguro_api.get_items())

    @httpretty.activate
    def test_invalid_checkout(self):
        self.pagseguro_api.add_item(self.item1)
        self.pagseguro_api.add_item(self.item2)
        self.pagseguro_api.add_item(self.item3)

        # mock requests
        httpretty.register_uri(
            httpretty.POST,
            CHECKOUT_URL,
            body='Unauthorized',
            status=401,
        )

        data = self.pagseguro_api.checkout()
        self.assertEqual(data['success'], False)
        self.assertEqual(data['message'], 'Unauthorized')
        self.assertEqual(data['status_code'], 401)

    @httpretty.activate
    def test_valid_checkout(self):
        self.pagseguro_api.add_item(self.item1)
        self.pagseguro_api.add_item(self.item2)
        self.pagseguro_api.add_item(self.item3)

        # mock requests
        httpretty.register_uri(
            httpretty.POST,
            CHECKOUT_URL,
            body=checkout_response_xml,
            status=200,
        )

        data = self.pagseguro_api.checkout()
        self.assertEqual(data['success'], True)
        self.assertEqual(data['status_code'], 200)
        self.assertEqual(data['code'], '67DB59D3BDBD84EAA4396F929DB350A7')
        self.assertEqual(data['date'], parse('2014-06-07T00:52:04.000-03:00'))
        self.assertEqual(
            data['redirect_url'],
            '{0}?code={1}'.format(PAYMENT_URL, data['code'])
        )

    @httpretty.activate
    def test_get_invalid_notification(self):
        # mock requests
        httpretty.register_uri(
            httpretty.GET,
            NOTIFICATION_URL + '/{0}'.format(
                'A5182C-C9EF48EF48D2-1FF4AF6FAC82-EB2948'
            ),
            body='Unauthorized',
            status=401,
        )

        response = self.pagseguro_api.get_notification(
            'A5182C-C9EF48EF48D2-1FF4AF6FAC82-EB2948'
        )
        self.assertEqual(response.status_code, 401)
        self.assertEqual(response.text, 'Unauthorized')

    @httpretty.activate
    def test_get_valid_notification(self):
        # mock requests
        httpretty.register_uri(
            httpretty.GET,
            NOTIFICATION_URL + '/{0}'.format(
                'A5182C-C9EF48EF48D2-1FF4AF6FAC82-EB2948'
            ),
            body=notification_response_xml,
            status=200,
        )

        response = self.pagseguro_api.get_notification(
            'A5182C-C9EF48EF48D2-1FF4AF6FAC82-EB2948'
        )
        self.assertEqual(response.status_code, 200)

    @httpretty.activate
    def test_get_invalid_transaction(self):
        # mock requests
        httpretty.register_uri(
            httpretty.GET,
            TRANSACTION_URL + '/{0}'.format(
                '9E884542-81B3-4419-9A75-BCC6FB495EF1'
            ),
            body='Unauthorized',
            status=401,
        )

        data = self.pagseguro_api.get_transaction(
            '9E884542-81B3-4419-9A75-BCC6FB495EF1'
        )
        self.assertEqual(data['status_code'], 401)
        self.assertEqual(data['message'], 'Unauthorized')

    @httpretty.activate
    def test_get_valid_transaction(self):
        # mock requests
        httpretty.register_uri(
            httpretty.GET,
            TRANSACTION_URL + '/{0}'.format(
                '9E884542-81B3-4419-9A75-BCC6FB495EF1'
            ),
            body=transaction_response_xml,
            status=200,
        )

        data = self.pagseguro_api.get_transaction(
            '9E884542-81B3-4419-9A75-BCC6FB495EF1'
        )
        self.assertEqual(data['status_code'], 200)
        self.assertEqual(
            data['transaction']['code'],
            '9E884542-81B3-4419-9A75-BCC6FB495EF1'
        )

    def test_base_params_is_instance_variable(self):
        # Regression test
        api1 = PagSeguroApi()
        api2 = PagSeguroApi()
        self.assertIsNot(api1.base_params, api2.base_params)

    def test_params_is_instance_variable(self):
        # Regression test
        api1 = PagSeguroApi()
        api2 = PagSeguroApi()
        self.assertIsNot(api1.params, api2.params)

    def test_items_is_instance_variable(self):
        # Regression test
        api1 = PagSeguroApi()
        api2 = PagSeguroApi()
        self.assertIsNot(api1.items, api2.items)