Beispiel #1
0
 def get(self, request, *args, **kwargs):
     pid = self.request.GET.get('pid')
     pagseguro_api = PagSeguroApi()
     data = pagseguro_api.get_transaction(pid)
     if data['success']:
         transaction = data['transaction']
         payment = Payment(
             status=transaction['status'],
             transaction=transaction['code']
         )
         if transaction['status'] in ['3', '4']:
             payment.paid = True
         payment.save()
         inscription = Inscription.objects.get(slug=transaction['reference'])
         inscription.payment = payment
         if payment.paid:
             inscription.confirmed = True
         inscription.save()
         kwargs['inscription'] = inscription
         context = self.get_context_data(**kwargs)
         return self.render_to_response(context)
     else:
         logging.error('Falha na página de retorno do pagamento')
         logging.error('Transação: {}'.format(pid))
         return HttpResponseServerError()
Beispiel #2
0
 def get_data(self, code):
     if not code:
         return
     pg = PagSeguroApi()
     data = pg.get_transaction(code)
     if data['success']:
         self.update_transaction_status(data['transaction']['status'])
         return data
     return {}
Beispiel #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
Beispiel #4
0
def receive_notification(request):
    notification_code = request.POST.get('notificationCode', None)
    notification_type = request.POST.get('notificationType', None)

    if notification_code and notification_type == 'transaction':
        pagseguro_api = PagSeguroApi()
        response = pagseguro_api.get_notification(notification_code)

        if response.status_code == 200:
            return HttpResponse(six.b('Notificação recebida com sucesso.'))

    return HttpResponse(six.b('Notificação inválida.'), status=400)
    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'])
Beispiel #6
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")
Beispiel #7
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']
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()
Beispiel #11
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))
 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()
Beispiel #13
0
def atualiza_compra(retorno):

	id_pagseguro = retorno.replace("-", "")
	pagseguro_api = PagSeguroApi()
	data = pagseguro_api.get_transaction(id_pagseguro)
	reference = data['transaction']['reference']

	#print 'usuario de retorno é %s' %usuario
	u = Cadastro.objects.get(cod_cliente=reference)
	user = u.id
	nome = u.nome
	usuario = u.user_id
	email_cad = u.email

	#id_pagseguro = id_pagseguro.replace("-", "")
	agora = datetime.datetime.now()

	try:

		r = Retorno.objects.get(code=id_pagseguro)
		retorno = str(r.code)
		unico = str(id_pagseguro)

		if retorno == unico:

			status_atual = Retorno.objects.values_list('status').filter(code=id_pagseguro)[0]
			status_atual = int(status_atual[0])
			status = data['transaction']['status']
			status = int(status)

			if status_atual !=  status:

				Retorno.objects.filter(code=retorno).update(lastEventDate=agora,status=status)

				if status == 3:
					atualiza_pago(id_pagseguro,usuario,status)

			else:
				### Atualiza da data da ultima consulta

				if status == 1:
					Retorno.objects.filter(code=retorno).update(lastEventDate=agora)

				if status == 2:

					mail.send(
					    [email_cad],
					    sender=settings.DEFAULT_FROM_EMAIL,
					    template='status_2',
					    context={'nome': nome},
					)
				if status == 7:

					mail.send(
					    [email_cad],
					    sender=settings.DEFAULT_FROM_EMAIL,
					    template='status_7',
					    context={'nome': nome},
					)

	except ObjectDoesNotExist:


		date = data['transaction']['date']
		lastEventDate = data['transaction']['lastEventDate']
		code = data['transaction']['code']
		code = code.replace("-", "")
		reference = data['transaction']['reference']
		status = data['transaction']['status']
		paymentMethod = data['transaction']['paymentMethod']['type']
		paymentMethodCode = data['transaction']['paymentMethod']['code']
		grossAmount = data['transaction']['grossAmount']
		discountAmount = data['transaction']['discountAmount']
		netAmount = data['transaction']['netAmount']
		extraAmount = data['transaction']['extraAmount']
		item = data['transaction']['items']['item']['description']
		id_plano = data['transaction']['items']['item']['id']
		name = data['transaction']['sender']['name']
		email = data['transaction']['sender']['email']
		areaCode = data['transaction']['sender']['phone']['areaCode']
		phone = data['transaction']['sender']['phone']['number']

		Retorno.objects.create(date=date,lastEventDate=lastEventDate,code=code,reference=reference,status=status,
								paymentMethod=paymentMethod,paymentMethodCode=paymentMethodCode,grossAmount=grossAmount,
								discountAmount=discountAmount,netAmount=netAmount,extraAmount=extraAmount,item=item,id_plano=id_plano,
								name=name,email=email,phone=areaCode+phone)
		mail.send(
		    [email_cad],
		    sender=settings.DEFAULT_FROM_EMAIL,
		    template='status_1',
		    context={'nome': name},
		)
		
		status = int(status)

		if status == 2:

			mail.send(
			    [email_cad],
			    sender=settings.DEFAULT_FROM_EMAIL,
			    template='status_2',
			    context={'nome': name},
			)

		if status == 3:
			atualiza_pago(id_pagseguro,usuario,status)
Beispiel #14
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()
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)
Beispiel #16
0
def registra_compra(id_pagseguro,usuario):
	
	print usuario
	u = Cadastro.objects.get(user_id=usuario)
	user = u.id
	print user
	pagseguro_api = PagSeguroApi()
	data = pagseguro_api.get_transaction(id_pagseguro)
	id_pagseguro = id_pagseguro.replace("-", "")
	agora = datetime.now()

	try:

		r = Retorno.objects.get(code=id_pagseguro)
		retorno = str(r.code)
		print type(retorno)
		unico = str(id_pagseguro)
		print type(unico)

		if retorno == unico:

			status_atual = Retorno.objects.values_list('status').filter(code=id_pagseguro)[0]
			status_atual = int(status_atual[0])
			status = data['transaction']['status']
			status = int(status)

			if status_atual !=  status:

				print 'é diferente'
				Retorno.objects.filter(code=retorno).update(lastEventDate=agora,status=status)

				if status == 3:
					atualiza_pago(id_pagseguro,usuario,status)

				# if status == 3:

				# 	print user
				# 	pega_plano_cadastro = Cadastro.objects.values_list('plano').filter(id=user)[0]
				# 	pega_plano_cadastro = pega_plano_cadastro[0]
				# 	print 'o plano cadastrado é %s' %pega_plano_cadastro

				# 	#print compra['redirect_url']
				# 	### INIICIO Pega o valor do plano e o valor por consulta de obtem a quantidade de consultas
				# 	x = Plano.objects.get(id=pega_plano_cadastro)
				# 	id_plano = x.id
				# 	print id_plano
				# 	descricao = x.plano
				# 	valorD = x.valor
				# 	print valorD
				# 	valor = int(x.valor)
				# 	v_consulta = x.valor_consulta
				# 	try:
				# 		result = valor / v_consulta
				# 		print result
				# 		result = decimal.Decimal(result)
				# 	except ZeroDivisionError:
				# 		result = 00.00
				# 	## FIM Pega o valor do plano e o valor por consulta de obtem a quantidade de consultas

				# 	pega_plano_cliente = PlanoCliente.objects.values_list('plano').filter(cliente=user)[0]
				# 	pega_plano_cliente = pega_plano_cliente[0]
				# 	print 'plano é %s' %pega_plano_cliente

				# 	try:
				# 		### INICIO cria o plano baseado no retorno do PagSeguro ###
				# 		PlanoCliente.objects.create(cliente=user,plano=pega_plano_cliente,consultas=result,consultas_gratis=0)
				# 		### FIM cria o plano baseado no retorno do PagSeguro ###

				# 	except IntegrityError:
						
				# 		print 'ja tem <--------'
				# 		# Pega o plano no cadastro do cliente
				# 		p = Cadastro.objects.get(id=user)
				# 		p = p.plano
				# 		print 'Cadastro %s' %p
						
				# 		# Pega o plano comprado
				# 		d = Retorno.objects.get(code=retorno)
				# 		d = d.id_plano
				# 		print 'Retorno %s' %d

				# 		b = PlanoCliente.objects.get(cliente=user)
				# 		b = b.plano
				# 		print 'PlanoCliente %s' %b

				# 		if b != p:
				# 			print 'planos sao diferentes'
				# 			PlanoCliente.objects.filter(plano=b).update(plano=p)
				# 			b = PlanoCliente.objects.get(cliente=user)
				# 			b = b.plano
				# 			print b

				# 		x = PlanoCliente.objects.get(cliente=user)
				# 		id_plano = x.id
				# 		print id_plano
				# 		consultas = int(x.consultas)
				# 		print 'saldo atual é %s' %(consultas)


				# 		z = Plano.objects.get(id=d)
				# 		valor = int(z.valor)
				# 		print valor
				# 		valor_consulta = z.valor_consulta
				# 		print valor_consulta
				# 		results = int(valor / valor_consulta)
				# 		print 'saldo a ser somado é %s' %(results)

				# 		controle = Retorno.objects.values_list('controle').filter(code=id_pagseguro)[0]
				# 		controle = controle[0]
				# 		print controle

				# 		if controle == 0:

				# 			novo_saldo = consultas + results
				# 			print 'o novo saldo é %s' %novo_saldo
				# 			PlanoCliente.objects.filter(cliente=user).update(consultas=novo_saldo)
				# 			Retorno.objects.filter(code=retorno).update(controle=1,consultas=results)
				# 			Retorno.objects.filter(code=retorno).update(lastEventDate=agora,status=status)


			else:
				print 'é igual'
				### Atualiza da data da ultima consulta
				if status == 1:
					Retorno.objects.filter(code=retorno).update(lastEventDate=agora)


	except ObjectDoesNotExist:


		date = data['transaction']['date']
		lastEventDate = data['transaction']['lastEventDate']
		code = data['transaction']['code']
		code = code.replace("-", "")
		reference = data['transaction']['reference']
		status = data['transaction']['status']
		paymentMethod = data['transaction']['paymentMethod']['type']
		paymentMethodCode = data['transaction']['paymentMethod']['code']
		grossAmount = data['transaction']['grossAmount']
		discountAmount = data['transaction']['discountAmount']
		netAmount = data['transaction']['netAmount']
		extraAmount = data['transaction']['extraAmount']
		item = data['transaction']['items']['item']['description']
		id_plano = data['transaction']['items']['item']['id']
		name = data['transaction']['sender']['name']
		email = data['transaction']['sender']['email']
		areaCode = data['transaction']['sender']['phone']['areaCode']
		phone = data['transaction']['sender']['phone']['number']

		Retorno.objects.create(date=date,lastEventDate=lastEventDate,code=code,reference=reference,status=status,
								paymentMethod=paymentMethod,paymentMethodCode=paymentMethodCode,grossAmount=grossAmount,
								discountAmount=discountAmount,netAmount=netAmount,extraAmount=extraAmount,item=item,id_plano=id_plano,
								name=name,email=email,phone=areaCode+phone)
		
		status = int(status)

		if status == 3:
			atualiza_pago(id_pagseguro,usuario,status)
Beispiel #17
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())

    @responses.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
        responses.add(
            responses.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)

    @responses.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
        responses.add(
            responses.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']))

    @responses.activate
    def test_get_invalid_notification(self):
        # mock requests
        responses.add(
            responses.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')

    @responses.activate
    def test_get_valid_notification(self):
        # mock requests
        responses.add(
            responses.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)

    @responses.activate
    def test_get_invalid_transaction(self):
        # mock requests
        responses.add(
            responses.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')

    @responses.activate
    def test_get_valid_transaction(self):
        # mock requests
        responses.add(
            responses.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)
Beispiel #18
0
 def test_items_is_instance_variable(self):
     # Regression test
     api1 = PagSeguroApi()
     api2 = PagSeguroApi()
     self.assertIsNot(api1.items, api2.items)