示例#1
0
 def setUp(self):
     self.token = '123456'
     self.email = '*****@*****.**'
     self.pagseguro = PagSeguro(token=self.token, email=self.email)
     self.sender = {
         'name': u'Guybrush Treepwood',
         'area_code': 11,
         "phone": 5555555,
         "email": '*****@*****.**',
         "cpf": "00000000000",
         "born_date": "06/08/1650",
     }
     self.shipping = {
         "type": self.pagseguro.SEDEX,
         "street": "Av Brig Faria Lima",
         "number": 1234,
         "complement": "5 andar",
         "district": "Jardim Paulistano",
         "postal_code": "06650030",
         "city": "Sao Paulo",
         "state": "SP",
         "country": "BRA",
         "cost": "1234.56"
     }
     self.items = [
         {"id": "0001", "description": "Produto 1", "amount": 354.20,
          "quantity": 2, "weight": 200},
         {"id": "0002", "description": "Produto 2", "amount": 355.20,
          "quantity": 1, "weight": 200},
     ]
示例#2
0
def test_clean_none_params(sender):
    pagseguro = PagSeguro(email=EMAIL, token=TOKEN)
    sender_copy = sender.copy()
    sender_copy['cpf'] = None
    sender_copy['born_date'] = None
    pagseguro.sender = sender_copy
    pagseguro.build_checkout_params()
    assert 'senderCPF' not in pagseguro.data
    assert 'senderBornData' not in pagseguro.data
def test_clean_none_params(sender):
    pagseguro = PagSeguro(email=EMAIL, token=TOKEN)
    sender_copy = sender.copy()
    sender_copy['cpf'] = None
    sender_copy['born_date'] = None
    pagseguro.sender = sender_copy
    pagseguro.build_checkout_params()
    assert 'senderCPF' not in pagseguro.data
    assert 'senderBornData' not in pagseguro.data
    def test_clean_none_params(self):
        pagseguro = PagSeguro(email=self.email, token=self.token)
        sender = self.sender
        sender['cpf'] = None
        sender['born_date'] = None
        pagseguro.sender = self.sender
        pagseguro.build_checkout_params()

        self.assertTrue('senderCPF' not in pagseguro.data)
        self.assertTrue('senderBornData' not in pagseguro.data)
    def test_clean_none_params(self):
        pagseguro = PagSeguro(email=self.email, token=self.token)
        sender = self.sender
        sender['cpf'] = None
        sender['born_date'] = None
        pagseguro.sender = self.sender
        pagseguro.build_checkout_params()

        self.assertTrue('senderCPF' not in pagseguro.data)
        self.assertTrue('senderBornData' not in pagseguro.data)
    def test_is_valid_email(self):
        bad_email = 'john.com'
        pagseguro = PagSeguro(email=bad_email, token=self.token)
        pagseguro.sender = {'email': bad_email}
        with self.assertRaises(PagSeguroValidationError):
            pagseguro.build_checkout_params()

        # Now testing with a valid email
        pagseguro.sender['email'] = self.sender.get('email')
        self.assertEqual(is_valid_email(pagseguro.sender['email']),
                         self.sender.get('email'))
示例#7
0
 def __init__(self, cart, *args, **kwargs):
     self.cart = cart
     self.config = kwargs.get('config')
     self._record = kwargs.get('_record')
     if not isinstance(self.config, dict):
         raise ValueError("Config must be a dict")
     email = self.config.get('email')
     token = self.config.get('token')
     self.pg = PagSeguro(email=email, token=token)
     self.cart and self.cart.addlog("PagSeguro initialized {}".format(
         self.__dict__))
 def pagseguro_form_generate_values(self, values):
     pagseguro_tx_values = dict(values)
     pagseguro_tx_values.update({
         'pagseguro_email': self.pagseguro_email_account,
         'pagseguro_token': self.pagseguro_token,
         'amount': format(values['amount'], '.2f')
     })
     if self.environment == 'prod':
         config = {'sandbox': False}
     else:
         config = {'sandbox': True}
     pg = PagSeguro(email=self.pagseguro_email_account,
                    token=self.pagseguro_token,
                    config=config)
     pg.reference_prefix = None
     pg.reference = pagseguro_tx_values['reference']
     pg.items = [
         {
             "id": "0001",
             "description": pagseguro_tx_values['reference'],
             "amount": pagseguro_tx_values['amount'],
             "quantity": 1
         },
     ]
     base_url = self.env['ir.config_parameter'].sudo().get_param(
         'web.base.url')
     pg.redirect_url = base_url + pagseguro_tx_values['return_url']
     _logger.info("Redirect Url: %s" % (pg.redirect_url))
     pg.notification_url = base_url + "/payment/pagseguro/feedback"
     response = pg.checkout()
     _logger.info("Response Errors: %s" % (response.errors))
     pagseguro_tx_values.update({'payment_url': response.payment_url})
     # _logger.info(values['reference'])
     _logger.info("Transaction Values: %s" % (pagseguro_tx_values))
     return pagseguro_tx_values
示例#9
0
 def pagseguro(self):
     self.payment_option = 'pagseguro'
     self.save()
     if settings.PAGSEGURO_SANDBOX:
         pg = PagSeguro(
             email=settings.PAGSEGURO_EMAIL, token=settings.PAGSEGURO_TOKEN,
             config={'sandbox': settings.PAGSEGURO_SANDBOX}
         )
     else:
         pg = PagSeguro(
             email=settings.PAGSEGURO_EMAIL, token=settings.PAGSEGURO_TOKEN
         )
     pg.sender = {
         'email': self.user.email
     }
     pg.reference_prefix = None
     pg.shipping = None
     pg.reference = self.pk
     for item in self.items.all():
         pg.items.append(
             {
                 'id': item.product.pk,
                 'description': item.product.name,
                 'quantity': item.quantity,
                 'amount': '%.2f' % item.price
             }
         )
     return pg
示例#10
0
def pagseguro_notification(request):
    notification_code = request.POST.get('notificationCode', None)
    if notification_code:
        pg = PagSeguro(email=settings.PAGSEGURO_EMAIL,
                       token=settings.PAGSEGURO_TOKEN,
                       config={'sandbox': settings.PAGSEGURO_SANDBOX})
        notification_data = pg.check_notification(notification_code)
        status = notification_data.status
        reference = notification_data.reference
        try:
            order = Order.objects.get(pk=reference)
        except Order.DoesNotExist:
            pass
        else:
            order.pagseguro_update_status(status)
    return HttpResponse('OK')
示例#11
0
def test_parse_xml(xml):
    pg = PagSeguro(email=EMAIL, token=TOKEN)
    result = PagSeguroTransactionSearchResult(xml, pg.config)
    assert result.current_page == 1
    assert result.results_in_page == 2
    assert result.total_pages == 1
    assert len(result.transactions) == 2
示例#12
0
def pagseguro_notification(request):
    notification_code = request.POST.get('notificationCode', None)
    if notification_code:
        pg = PagSeguro(email=Dsettings.PAGSEGURO_EMAIL,
                       token=Dsettings.PAGSEGURO_TOKEN,
                       config={'sandbox': Dsettings.PAGSEGURO_SANDBOX})
        notification_data = pg.check_notification(notification_code)
        status = notification_data.status
        reference = notification_data.reference
        try:
            purchase = Purchase.objects.get(pk=reference)
        except ObjectDoesNotExist:
            return ("nao existe")
        else:
            purchase.update_status(status)
    return HttpResponse('OK')
def test_parse_xml(xml_sandbox):
    pg = PagSeguro(email='*****@*****.**', token='123456')
    result = PagSeguroTransactionSearchResult(xml_sandbox, pg.config)
    assert result.current_page == 1
    assert result.results_in_page == 2
    assert result.total_pages == 1
    assert len(result.transactions) == 2
 def setUp(self):
     self.token = '123456'
     self.email = '*****@*****.**'
     self.pagseguro = PagSeguro(token=self.token, email=self.email)
     self.sender = {
         'name': u'Guybrush Treepwood',
         'area_code': 11,
         "phone": 5555555,
         "email": '*****@*****.**',
         "cpf": "00000000000",
         "born_date": "06/08/1650",
     }
     self.shipping = {
         "type": self.pagseguro.SEDEX,
         "street": "Av Brig Faria Lima",
         "number": 1234,
         "complement": "5 andar",
         "district": "Jardim Paulistano",
         "postal_code": "06650030",
         "city": "Sao Paulo",
         "state": "SP",
         "country": "BRA",
         "cost": "1234.56"
     }
     self.items = [
         {"id": "0001", "description": "Produto 1", "amount": 354.20,
          "quantity": 2, "weight": 200},
         {"id": "0002", "description": "Produto 2", "amount": 355.20,
          "quantity": 1, "weight": 200},
     ]
示例#15
0
def pagseguro_notification(request):
    notification_code = request.POST.get('notificationCode', None)
    if notification_code:
    	pg = PagSeguro(
    		email=settings.PAGSEGURO_EMAIL, token=settings.PAGSEGURO_TOKEN,
    		config={'sandbox': settings.PAGSEGURO_SANDBOX}
    		)
    	notification_data = pg.check_notification(notification_code)
    	status = notification_data.status
    	reference = notification_data.reference
    	try:
    		order = Order.objects.get(pk=reference)
    	except Order.DoesNotExist:
    		pass
    	else:
    		order.pagseguro_update_status(status)
    	return HttpResponse('OK')	
示例#16
0
 def test_parse_xml(self):
     pg = PagSeguro(email=self.email, token=self.token)
     result = PagSeguroTransactionSearchResult(
         self.xml, pg.config
     )
     self.assertEqual(result.current_page, 1)
     self.assertEqual(result.results_in_page, 2)
     self.assertEqual(result.total_pages, 1)
     self.assertEqual(len(result.transactions), 2)
    def _pagseguro_form_validate(self, data):

        STATUS_CODE = {
            '1': 'Aguardando Pagamento',
            '2': 'Em análise',
            '3': 'Paga',
            '4': 'Disponível',
            '5': 'Em disputa',
            '6': 'Devolvida',
            '7': 'Cancelada',
            '8': 'Debitada',
            '9': 'Retenção temporária'
        }

        aqr = self.env['payment.acquirer'].search([('name', '=', 'Pagseguro')])
        if aqr.environment == 'prod':
            config = {'sandbox': False}
        else:
            config = {'sandbox': True}
        pg = PagSeguro(email=aqr.pagseguro_email_account,
                       token=aqr.pagseguro_token,
                       config=config)
        notif = pg.check_notification(data.get('notificationCode'))
        status = notif.status
        res = {
            'acquirer_reference': notif.code,
        }
        # TODO confirmation date
        if status == '1':
            _logger.info(
                'Validated Pagseguro payment for tx %s: set as pending' %
                (self.reference))
            res.update(state='pending')
            return self.write(res)
        elif status == '3':
            _logger.info('Validated Pagseguro payment for tx %s: set as done' %
                         (self.reference))
            res.update(state='done')
            return self.write(res)
        else:
            _logger.info('Error on Pagseguro payment for tx %s: set as error' %
                         (self.reference))
            res.update(state='error')
            return self.write(res)
def checkout_pg(sender, shipping, cart):
    pagseguro = PagSeguro(email=app.config['EMAIL'], token=app.config['TOKEN'])
    pagseguro.sender = sender
    shipping['type'] = pagseguro.SEDEX
    pagseguro.shipping = shipping
    pagseguro.extra_amount = "%.2f" % float(app.config['EXTRA_AMOUNT'])
    pagseguro.redirect_url = app.config['REDIRECT_URL']
    pagseguro.notification_url = app.config['NOTIFICATION_URL']
    pagseguro.items = cart.items
    for item in cart.items:
        item['amount'] = "%.2f" % float(app.config['EXTRA_AMOUNT'])
    return pagseguro
示例#19
0
def pagseguro_notification(request):
    notification_code = request.POST.get(
        'notificationCode',
        None)  #pagseguro realiza um POST e envia o notificationCode
    if notification_code:  #valida de o code foi realemnte criado, se sim ele cria um novo carrinho
        pg = PagSeguro(email=settings.PAGSEGURO_EMAIL,
                       token=settings.PAGSEGURO_TOKEN,
                       config={'sandbox': settings.PAGSEGURO_SANDBOX})
        notification_data = pg.check_notification(
            notification_code)  #ele checa o cod de verificação
        status = notification_data.status  #status do pagseguro
        reference = notification_data.reference  #id do pedido
        try:
            order = Order.objects.get(pk=reference)  #ele busca o pedido
        except Order.DoesNotExist:
            pass
        else:
            order.pagseguro_update_status(status)  #se houver o pedido
    return HttpResponse('OK')
示例#20
0
def notification_view(request):
    notification_code = request.POST.get('notificationCode')

    pg = PagSeguro(
        email=settings.PAGSEGURO_EMAIL,
        token=settings.PAGSEGURO_TOKEN,
    )
    notification_data = pg.check_notification(notification_code)

    inscricao = Inscricao.objects.get(
        payment_reference=notification_data.reference)

    inscricao.sit_pagseguro = notification_data.status

    if notification_data.status == 3 or notification_data.status == "3":
        inscricao.status = 2

    inscricao.save()

    return HttpResponse("")
示例#21
0
 def __init__(self, cart, *args, **kwargs):
     self.cart = cart
     self.config = kwargs.get('config')
     self._record = kwargs.get('_record')
     if not isinstance(self.config, dict):
         raise ValueError("Config must be a dict")
     email = self.config.get('email')
     token = self.config.get('token')
     self.pg = PagSeguro(email=email, token=token)
     self.cart and self.cart.addlog(
         "PagSeguro initialized {}".format(self.__dict__)
     )
示例#22
0
 def pagseguro(self):
     self.payment_option = 'pagseguro'
     self.save()
     #if settings.PAGSEGURO_SANDBOX: #valida para estar no ambiente de sendbox
     pg = PagSeguro(
         email=settings.PAGSEGURO_EMAIL,
         token=settings.PAGSEGURO_TOKEN,
         config={'sandbox': settings.PAGSEGURO_SANDBOX}
     )  #Cria a instancia do pagseguro, passando o email configurado no settings, e o token tabem.
     #else:
     #    pg = PagSeguro(
     #        email=settings.PAGSEGURO_EMAIL, token=settings.PAGSEGURO_TOKEN
     #    )#config sobrepoe a configuração padrao da API
     pg.sender = {
         'email': self.user.email
     }  #informações de quem ta realizando a compra
     pg.reference_prefix = None  #prfixo adicionado junto com o id pedido
     pg.shipping = None  #dados de entrega
     pg.reference = self.pk  #id do pedido
     for item in self.items.all(
     ):  #para cada item de pedido, ele adicioa carrinho
         pg.items.append({
             'id': item.product.pk,
             'description': item.product.name,
             'quantity': item.quantity,
             'amount':
             '%.2f' % item.price  #ele pede o preço em forma de STR
         })
     return pg
示例#23
0
 def pagseguro(self):
     self.payment_option = 'pagseguro'
     self.save()
     pg = PagSeguro(email=settings.PAGSEGURO_EMAIL,
                    token=settings.PAGSEGURO_TOKEN,
                    config={'sandbox': settings.PAGSEGURO_SANDBOX})
     pg.sender = {'email': self.order.user.email}
     pg.reference_prefix = ''
     pg.shipping = {
         "type": 1,
         "street": "Av Brig Faria Lima",
         "number": 1234,
         "complement": "5 andar",
         "district": "Jardim Paulistano",
         "postal_code": "06650030",
         "city": "Sao Paulo",
         "state": "SP",
         "country": "BRA",
     }
     pg.reference = self.order.pk
     for item in self.order.items.all():
         pg.items.append({
             'id': item.product.pk,
             'description': item.product.name,
             'quantity': item.quantity,
             'amount': '%.2f' % item.price,
             'weight': '1000'
         })
     return pg
示例#24
0
def notification_view(request):
    notification_code = request.POST['notificationCode']
    pg = PagSeguro(email="*****@*****.**",
                   token="6B1E3EF957F84EF4913EFDA3B76D6D84")
    notification_data = pg.check_notification(notification_code)

    order = Order.query.filter_by(
        id=notification_data['reference'][3:]).first()

    def dbUpdate(order):
        if notification_data['status'] == 1:
            order.status = 'aguardado-pagamento'

        elif notification_data['status'] == 2:
            order.status = 'cancelado'

        elif notification_data['status'] == 3:
            order.status = 'pago'

        db.session.commit()

    return dbUpdate(order)
示例#25
0
def checkout_pg(sender, shipping, cart):
    pg = PagSeguro(email=app.config['EMAIL'], token=app.config['TOKEN'])
    pg.sender = sender
    shipping['type'] = pg.SEDEX
    pg.shipping = shipping
    pg.extra_amount = "%.2f" % float(app.config['EXTRA_AMOUNT'])
    pg.redirect_url = app.config['REDIRECT_URL']
    pg.notification_url = app.config['NOTIFICATION_URL']
    pg.items = cart.items
    for item in cart.items:
        item['amount'] = "%.2f" % float(app.config['EXTRA_AMOUNT'])
    return pg
    def _pagseguro_form_get_tx_from_data(self, data):
        aqr = self.env['payment.acquirer'].search([('name', '=', 'Pagseguro')])
        if aqr.environment == 'prod':
            config = {'sandbox': False}
        else:
            config = {'sandbox': True}
        pg = PagSeguro(email=aqr.pagseguro_email_account,
                       token=aqr.pagseguro_token,
                       config=config)
        notif = pg.check_notification(data.get('notificationCode'))
        reference, amount, currency = notif.reference, notif.grossAmount, 'BRL'
        tx = self.search([('reference', '=', reference)])
        if not tx or len(tx) > 1:
            error_msg = _('received data for reference %s') % (
                pprint.pformat(reference))
            if not tx:
                error_msg += _('; no order found')
            else:
                error_msg += _('; multiple order found')
            _logger.info(error_msg)
            raise ValidationError(error_msg)

        return tx
def test_is_valid_cpf():
    bad_cpf = '123.456.267-45'
    pagseguro = PagSeguro(email=EMAIL, token=TOKEN)
    pagseguro.sender = {'cpf': bad_cpf}
    with pytest.raises(PagSeguroValidationError):
        pagseguro.build_checkout_params()

    # Now testing with a valid email
    pagseguro.sender['cpf'] = '482.268.465-28'
    assert is_valid_cpf(pagseguro.sender['cpf']) == pagseguro.sender['cpf']

    pagseguro.sender['cpf'] = '48226846528'
    assert is_valid_cpf(pagseguro.sender['cpf']) == pagseguro.sender['cpf']
示例#28
0
 def pay_pagseguro(self):
     # import pdb;pdb.set_trace()
     pg = PagSeguro(email="*****@*****.**", token="4194D1DFC27E4E1FAAC0E1B20690B5B5")
     pg.sender = {
         "name": self.user.full_name,
         "email": self.user.email,
     }
     pg.reference_prefix = None
     pg.reference = self.id
     
     for item in self.itens.all():
         pg.add_item(id=item.option.id, description=item.option.title, amount=item.option.new_price, quantity=item.quantity, weight=0)
     # pg.redirect_url = "http://meusite.com/obrigado"
     response = pg.checkout()
     self.code_pagseguro = response.code
     self.save()
     return response.payment_url
示例#29
0
def test_is_valid_email(sender):
    bad_email = 'john.com'
    pagseguro = PagSeguro(email=bad_email, token=TOKEN)
    pagseguro.sender = {'email': bad_email}
    with pytest.raises(PagSeguroValidationError):
        pagseguro.build_checkout_params()

    # Now testing with a valid email
    pagseguro.sender['email'] = sender['email']
    assert is_valid_email(pagseguro.sender['email']) == sender['email']
    def test_is_valid_email(self):
        bad_email = 'john.com'
        pagseguro = PagSeguro(email=bad_email, token=self.token)
        pagseguro.sender = {'email': bad_email}
        with self.assertRaises(PagSeguroValidationError):
            pagseguro.build_checkout_params()

        # Now testing with a valid email
        pagseguro.sender['email'] = self.sender.get('email')
        self.assertEqual(is_valid_email(pagseguro.sender['email']),
                         self.sender.get('email'))
    def test_is_valid_cpf(self):
        bad_cpf = '123.456.267-45'
        pagseguro = PagSeguro(email=self.email, token=self.token)
        pagseguro.sender = {'cpf': bad_cpf}
        with self.assertRaises(PagSeguroValidationError):
            pagseguro.build_checkout_params()

        # Now testing with a valid email
        pagseguro.sender['cpf'] = '482.268.465-28'
        self.assertEqual(is_valid_cpf(pagseguro.sender['cpf']),
                         pagseguro.sender['cpf'])

        pagseguro.sender['cpf'] = '48226846528'
        self.assertEqual(is_valid_cpf(pagseguro.sender['cpf']),
                         pagseguro.sender['cpf'])
示例#32
0
    def get(self, request, *args, **kwargs):

        try:
            purchase = Purchase.objects.get(pk=self.kwargs.get('pk'))
        except ObjectDoesNotExist:
            return Response('Esse id nao existe.')

        pg = PagSeguro(email=Dsettings.PAGSEGURO_EMAIL,
                       token=Dsettings.PAGSEGURO_TOKEN,
                       config={'sandbox': Dsettings.PAGSEGURO_SANDBOX})
        pg.reference_prefix = None
        pg.shipping = None

        user_id = self.request.user.id
        email = self.request.user.email
        pg.sender = {'email': email}
        pk = self.kwargs.get('pk')
        pg.reference = pk

        cart_id = Purchase.objects.filter(
            id=pk).values('id_cart_id')[0].get('id_cart_id')

        itens = Item.objects.filter(id_cart=cart_id)

        for item in itens:
            obj = Product.objects.filter(id=item.id_product_id).values('price')
            price = obj[0].get('price')
            obj2 = Product.objects.filter(id=item.id_product_id).values('name')
            name = obj2[0].get('name')
            pg.items.append({
                'id': item.id_product_id,
                'description': str(name),
                'quantity': item.quantity,
                'amount': '%.2f' % price
            })
        response = pg.checkout()

        if Purchase.objects.filter(
                id=pk).values('payment_link')[0].get('payment_link') == '-':

            p = Purchase.objects.get(id=pk)
            p.payment_link = response.payment_url
            p.save()
        else:
            return Response(
                Purchase.objects.filter(
                    id=pk).values('payment_link')[0].get('payment_link'))
        return Response(response.payment_url)
    def test_is_valid_cpf(self):
        bad_cpf = '123.456.267-45'
        pagseguro = PagSeguro(email=self.email, token=self.token)
        pagseguro.sender = {'cpf': bad_cpf}
        with self.assertRaises(PagSeguroValidationError):
            pagseguro.build_checkout_params()

        # Now testing with a valid email
        pagseguro.sender['cpf'] = '482.268.465-28'
        self.assertEqual(is_valid_cpf(pagseguro.sender['cpf']),
                         pagseguro.sender['cpf'])

        pagseguro.sender['cpf'] = '48226846528'
        self.assertEqual(is_valid_cpf(pagseguro.sender['cpf']),
                         pagseguro.sender['cpf'])
示例#34
0
 def pagseguro(self):
     self.opcao_pagamento = 'pagseguro'
     self.save()
     pg = PagSeguro(email=settings.PAGSEGURO_EMAIL,
                    token=settings.PAGSEGURO_TOKEN,
                    config={'sandbox': settings.PAGSEGURO_SANDBOX})
     pg.sender = {'email': self.user.email}
     pg.reference_prefix = ''
     pg.shipping = None
     pg.reference = self.pk
     for item in self.items.all():
         pg.items.append({
             'id': item.produto.pk,
             'description': item.produto.nome,
             'quantity': item.quantidade,
             'amount': '%.2f' % item.preco
         })
     return pg
示例#35
0
def make_pg():
    pg = PagSeguro(email="*****@*****.**", token="ABCDEFGHIJKLMNO")
    pg.sender = {
        "name": "Bruno Rocha",
        "area_code": 11,
        "phone": 981001213,
        "email": "*****@*****.**",
    }
    pg.shipping = {
        "type": pg.SEDEX,
        "street": "Av Brig Faria Lima",
        "number": 1234,
        "complement": "5 andar",
        "district": "Jardim Paulistano",
        "postal_code": "06650030",
        "city": "Sao Paulo",
        "state": "SP",
        "country": "BRA"
    }
    pg.extra_amount = 12.70
    pg.redirect_url = "http://meusite.com/obrigado"
    pg.notification_url = "http://meusite.com/notification"
    return pg
示例#36
0
文件: auth.py 项目: IKrehan/Brownies
def paymentValidation(order_id):

    config = {'sandbox': True, 'USE_SHIPPING': False}

    pg = PagSeguro(email="*****@*****.**",
                   token="ABCDEFGHIJKLMNO",
                   config=config)

    pg.sender = {
        "name": current_user.name + current_user.surname,
        "area_code": current_user.phone[:2],
        "phone": current_user.phone[2:],
        "email": current_user.email,
    }

    pg.reference = order_id

    pg.extra_amount = 0

    order = Order.query.filter_by(id=order_id).first()
    itens = order.itens

    for item in itens:
        product = Product.query.filter_by(id=item.id)

        pg.items.append(
            {
                "id": product.id,
                "description": product.desc,
                "amount": product.price,
                "quantity": item.quantity,
                "weight": None
            }, )

    pg.redirect_url = url_for('views.thanks')

    return
示例#37
0
class PagSeguroProcessor(BaseProcessor):

    STATUS_MAP = {
        "1": "checked_out",
        "2": "analysing",
        "3": "confirmed",
        "4": "completed",
        "5": "refunding",
        "6": "refunded",
        "7": "cancelled"
    }

    def __init__(self, cart, *args, **kwargs):
        self.cart = cart
        self.config = kwargs.get('config')
        self._record = kwargs.get('_record')
        if not isinstance(self.config, dict):
            raise ValueError("Config must be a dict")
        email = self.config.get('email')
        token = self.config.get('token')
        self.pg = PagSeguro(email=email, token=token)
        self.cart and self.cart.addlog(
            "PagSeguro initialized {}".format(self.__dict__)
        )

    def validate(self, *args, **kwargs):
        self.pg.sender = self.cart.sender_data
        self.pg.shipping = self.cart.shipping_data
        self.pg.reference = self.cart.get_uid()
        extra_costs = self.cart.get_extra_costs()
        if extra_costs:
            self.pg.extra_amount = "%.2f" % extra_costs

        self.pg.items = [
            {
                "id": item.get_uid(),
                "description": item.title[:100],
                "amount": "%.2f" % item.unity_plus_extra,
                "weight": item.weight,
                "quantity": int(item.quantity or 1)
            }
            for item in self.cart.items if item.total >= 0
        ]

        if hasattr(self.cart, 'redirect_url'):
            self.pg.redirect_url = self.cart.redirect_url
        else:
            self.pg.redirect_url = self.config.get('redirect_url')

        if hasattr(self.cart, 'notification_url'):
            self.pg.notification_url = self.cart.notification_url
        else:
            self.pg.notification_url = self.config.get('notification_url')

        self.cart.addlog("pagSeguro validated {}".format(self.pg.data))
        return True  # all data is valid

    def process(self, *args, **kwargs):
        kwargs.update(self._record.config)
        kwargs.update(self.cart.config)
        response = self.pg.checkout(**kwargs)
        self.cart.addlog(
            (
                "lib checkout data:{pg.data}\n"
                " code:{r.code} url:{r.payment_url}\n"
                " errors: {r.errors}\n"
                " xml: {r.xml}\n"
            ).format(
                pg=self.pg, r=response
            )
        )
        if not response.errors:
            self.cart.checkout_code = response.code
            #self.cart.status = 'checked_out'  # should set on redirect url
            self.cart.addlog("PagSeguro processed! {}".format(response.code))
            return redirect(response.payment_url)
        else:
            self.cart.addlog(
                'PagSeguro error processing {}'.format(
                    response.errors
                )
            )
            return render_template("cart/checkout_error.html",
                                   response=response, cart=self.cart)

    def notification(self):
        code = request.form.get('notificationCode')
        if not code:
            return "notification code not found"

        response = self.pg.check_notification(code)
        reference = getattr(response, 'reference', None)
        if not reference:
            return "reference not found"

        PREFIX = self.pg.config.get('REFERENCE_PREFIX', '') or ''
        PREFIX = PREFIX.replace('%s', '')

        status = getattr(response, 'status', None)
        transaction_code = getattr(response, 'code', None)

        # TODO: get grossAmount to populate a payment with methods
        try:
            self.cart = Cart.objects.get(
                reference_code=reference.replace(PREFIX, '')
            )

            self.cart.set_status(
                self.STATUS_MAP.get(str(status), self.cart.status)
            )

            if transaction_code:
                self.cart.transaction_code = transaction_code
            msg = "Status changed to: %s" % self.cart.status
            self.cart.addlog(msg)
            return msg
        except Exception as e:
            msg = "Cart not found: {} - {}".format(reference, e)
            logger.error(msg)
            return msg

    def confirmation(self):  # redirect_url
        context = {}
        transaction_param = self.config.get(
            'transaction_param',
            self.pg.config.get('TRANSACTION_PARAM', 'transaction_id')
        )
        transaction_code = request.args.get(transaction_param)
        if transaction_code:
            context['transaction_code'] = transaction_code
            response = self.pg.check_transaction(transaction_code)
            logger.debug(response.xml)
            reference = getattr(response, 'reference', None)
            if not reference:
                logger.error("no reference found")
                return render_template('cart/simple_confirmation.html',
                                       **context)
            PREFIX = self.pg.config.get('REFERENCE_PREFIX', '') or ''
            PREFIX = PREFIX.replace('%s', '')

            status = getattr(response, 'status', None)

            # TODO: get grossAmount to populate a payment with methods
            try:
                self.cart = Cart.objects.get(
                    reference_code=reference.replace(PREFIX, '')
                )

                self.cart.set_status(
                    self.STATUS_MAP.get(str(status), self.cart.status)
                )

                self.cart.transaction_code = transaction_code
                msg = "Status changed to: %s" % self.cart.status
                self.cart.addlog(msg)
                context['cart'] = self.cart
                logger.info("Cart updated")
                return render_template('cart/confirmation.html', **context)
            except Exception as e:
                msg = "Cart not found: {} - {}".format(reference, e)
                logger.error(msg)
        return render_template('cart/simple_confirmation.html', **context)
示例#38
0
def notification_view(request):
    notification_code = request.POST['notificationCode']
    pg = PagSeguro(email=app.config['EMAIL'], token=app.config['TOKEN'])
    pg.check_notification(notification_code)
示例#39
0
def test_pagseguro_with_bad_config():
    with pytest.raises(Exception):
        PagSeguro(email=EMAIL, token=TOKEN, config=2)
示例#40
0
def pagseguro():
    return PagSeguro(token=TOKEN, email=EMAIL)
示例#41
0
def test_add_items_util(items):
    pagseguro = PagSeguro(token=TOKEN, email=EMAIL)
    pagseguro.add_item(**items[0])
    pagseguro.add_item(**items[1])
    assert len(pagseguro.items) == 2
class PagseguroTest(unittest.TestCase):

    def setUp(self):
        self.token = '123456'
        self.email = '*****@*****.**'
        self.pagseguro = PagSeguro(token=self.token, email=self.email)
        self.sender = {
            'name': u'Guybrush Treepwood',
            'area_code': 11,
            "phone": 5555555,
            "email": '*****@*****.**',
            "cpf": "00000000000",
            "born_date": "06/08/1650",
        }
        self.shipping = {
            "type": self.pagseguro.SEDEX,
            "street": "Av Brig Faria Lima",
            "number": 1234,
            "complement": "5 andar",
            "district": "Jardim Paulistano",
            "postal_code": "06650030",
            "city": "Sao Paulo",
            "state": "SP",
            "country": "BRA",
            "cost": "1234.56"
        }
        self.items = [
            {"id": "0001", "description": "Produto 1", "amount": 354.20,
             "quantity": 2, "weight": 200},
            {"id": "0002", "description": "Produto 2", "amount": 355.20,
             "quantity": 1, "weight": 200},
        ]

    def test_pagseguro_class(self):
        self.assertIsInstance(self.pagseguro, PagSeguro)

    def test_pagseguro_initial_attrs(self):
        self.assertIsInstance(self.pagseguro.config, Config)
        self.assertIsInstance(self.pagseguro.data, dict)
        self.assertTrue('email' in self.pagseguro.data)
        self.assertTrue('token' in self.pagseguro.data)
        self.assertTrue('currency' in self.pagseguro.data)
        self.assertEqual(self.pagseguro.data['email'], self.email)
        self.assertEqual(self.pagseguro.data['token'], self.token)
        self.assertEqual(self.pagseguro.data['currency'],
                         self.pagseguro.config.CURRENCY)
        self.assertIsInstance(self.pagseguro.items, list)
        self.assertIsInstance(self.pagseguro.sender, dict)
        self.assertIsInstance(self.pagseguro.shipping, dict)
        self.assertEqual(self.pagseguro._reference, "")
        self.assertIsNone(self.pagseguro.extra_amount)
        self.assertIsNone(self.pagseguro.redirect_url)
        self.assertIsNone(self.pagseguro.notification_url)
        self.assertIsNone(self.pagseguro.abandon_url)

    def test_build_checkout_params_with_all_params(self):
        self.pagseguro.sender = self.sender
        self.pagseguro.shipping = self.shipping
        self.pagseguro.extra_amount = 12.50
        self.pagseguro.redirect_url = '/redirecionando/'
        self.pagseguro.abandon_url = '/abandonando/'
        self.pagseguro.items = self.items
        self.pagseguro.build_checkout_params()
        # check all data fields
        self.assertIsInstance(self.pagseguro.data, dict)
        keys = ['email', 'token', 'currency', 'senderName', 'senderAreaCode',
                'senderPhone', 'senderEmail', 'senderCPF', 'senderBornDate',
                'shippingType', 'shippingAddressStreet',
                'shippingAddressNumber', 'shippingAddressComplement',
                'shippingAddressDistrict', 'shippingAddressPostalCode',
                'shippingAddressCity', 'shippingAddressState',
                'shippingAddressCountry', 'shippingCost', 'extraAmount',
                'redirectURL', 'abandonURL']
        # items
        item_keys = ['itemId%s', 'itemDescription%s', 'itemAmount%s',
                     'itemQuantity%s', 'itemWeight%s', 'itemShippingCost%s']

        for key in keys:
            self.assertTrue(key in self.pagseguro.data)

        for i, key in enumerate(item_keys, 1):
            self.assertTrue(key % i, self.pagseguro.data)

    def test_add_items_util(self):
        pagseguro = PagSeguro(email=self.email, token=self.token)
        pagseguro.add_item(**self.items[0])
        pagseguro.add_item(**self.items[1])
        self.assertEqual(len(pagseguro.items), 2)

    def test_reference(self):
        self.pagseguro.reference = '12345'
        self.assertEqual(unicode(self.pagseguro.reference), u'REF12345')

    def test_clean_none_params(self):
        pagseguro = PagSeguro(email=self.email, token=self.token)
        sender = self.sender
        sender['cpf'] = None
        sender['born_date'] = None
        pagseguro.sender = self.sender
        pagseguro.build_checkout_params()

        self.assertTrue('senderCPF' not in pagseguro.data)
        self.assertTrue('senderBornData' not in pagseguro.data)

    def test_is_valid_email(self):
        bad_email = 'john.com'
        pagseguro = PagSeguro(email=bad_email, token=self.token)
        pagseguro.sender = {
            'email': bad_email
        }
        with self.assertRaises(PagSeguroValidationError):
            pagseguro.build_checkout_params()

        # Now testing with a valid email
        pagseguro.sender['email'] = self.sender.get('email')
        self.assertEqual(is_valid_email(pagseguro.sender['email']),
                         self.sender.get('email'))

    def test_is_valid_cpf(self):
        bad_cpf = '123.456.267-45'
        pagseguro = PagSeguro(email=self.email, token=self.token)
        pagseguro.sender = {
            'cpf': bad_cpf
        }
        with self.assertRaises(PagSeguroValidationError):
            pagseguro.build_checkout_params()

        # Now testing with a valid email
        pagseguro.sender['cpf'] = '482.268.465-28'
        self.assertEqual(is_valid_cpf(pagseguro.sender['cpf']),
                         pagseguro.sender['cpf'])

        pagseguro.sender['cpf'] = '48226846528'
        self.assertEqual(is_valid_cpf(pagseguro.sender['cpf']),
                         pagseguro.sender['cpf'])
 def test_add_items_util(self):
     pagseguro = PagSeguro(email=self.email, token=self.token)
     pagseguro.add_item(**self.items[0])
     pagseguro.add_item(**self.items[1])
     self.assertEqual(len(pagseguro.items), 2)