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
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
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 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
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
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
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_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 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_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_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 __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 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
def pagseguro_notification(request): notification_code = request.POST.get('notificationCode', None) if notification_code: if settings.PAGSEGURO_SANDBOX: pg = PagSeguro(email=settings.PAGSEGURO_EMAIL, token=settings.PAGSEGURO_TOKEN, config=Config()) else: pg = PagSeguro( email=settings.PAGSEGURO_EMAIL, token=settings.PAGSEGURO_TOKEN, ) 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')
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']
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 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 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 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
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: purchase = Purchase.objects.get(pk=reference) except Purchase.DoesNotExist: pass else: purchase.pagseguro_update_status(status) return HttpResponse('Pagamento atualizado!')
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
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 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')
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("")
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)
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 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
def test_pagseguro_with_bad_config(): with pytest.raises(Exception): PagSeguro(email=EMAIL, token=TOKEN, config=2)
def pagseguro(): return PagSeguro(token=TOKEN, email=EMAIL)