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
Exemple #2
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
 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
Exemple #4
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
Exemple #5
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)
Exemple #6
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
Exemple #7
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
Exemple #8
0
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 post(self, request, format=None):
        conferencia_pk = request.data.get("conferencia")
        inscricao_pk = request.data.get("inscricao")

        inscricao = Inscricao.objects.get(pk=inscricao_pk,
                                          conferencia_id=conferencia_pk)
        conferencia = inscricao.conferencia

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

        pg.sender = {
            "name": inscricao.nome,
            "area_code": inscricao.ddd,
            "phone": inscricao.cleanned_telefone(),
            "email": inscricao.email,
        }

        pg.shipping = {
            "type": pg.NONE,
            "street": inscricao.endereco,
            "number": inscricao.numero,
            "complement": inscricao.complemento,
            "district": inscricao.bairro,
            "postal_code": inscricao.cep,
            "city": inscricao.cidade,
            "state": inscricao.uf,
            "country": "BRA"
        }

        pg.reference_prefix = "REFID_"
        pg.reference = inscricao.pk

        pg.items = [
            {
                "id": "0001",
                "description": conferencia.titulo,
                "amount": inscricao.valor_total,
                "quantity": 1,
            },
        ]

        url_base = reverse_lazy(
            'home', kwargs={"conferencia": conferencia.titulo_slug})

        redirect_url = "{}{}".format(settings.BASE_URL, url_base)

        pg.redirect_url = redirect_url
        pg.notification_url = settings.NOTIFICATION_URL

        response = pg.checkout()

        inscricao.payment_reference = pg.reference
        inscricao.status = 1
        inscricao.save()

        return Response({
            "code": response.code,
            "transaction": response.transaction,
            "date": response.date,
            "payment_url": response.payment_url,
            "payment_link": response.payment_link,
            "errors": response.errors,
            "pre_ref": pg.reference_prefix,
            "reference": pg.reference,
        })
Exemple #10
0
def payment_post():
    if request.method == 'POST':

        config = {
            'sandbox': True,
            'CURRENCY': 'BRL',
            'USE_SHIPPING': 'false',
        }

        pg = PagSeguro(email="*****@*****.**",
                       token="6B1E3EF957F84EF4913EFDA3B76D6D84",
                       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,
        }

        orders = session['orders']
        street = session['street']
        number = session['number']
        district = session['district']
        city = session['city']
        cep = session['cep']
        complement = session['complement']

        pg.shipping = {
            "type": pg.SEDEX,
            "street": street,
            "number": number,
            "complement": complement,
            "district": district,
            "postal_code": cep,
            "city": city,
            "state": "CE",
            "country": "BRA"
        }

        new_order = Order(client_id=current_user.id,
                          street=street,
                          address_number=number,
                          district=district,
                          city=city,
                          cep=cep,
                          complement=complement,
                          price=session['subtotal'])
        db.session.add(new_order)
        db.session.flush()

        pg.reference = new_order.id
        pg.extra_amount = 0

        itens = []
        # É possivel adicionar um record ao db usando uma lista ao invés de instanciar um objeto como feito anteriormente
        for product, quantity in orders.items(
        ):  # cria uma lista de dicionários, dicionários esses que representam um objeto da tabela
            item = {}

            item['quantity'] = quantity
            item['product_id'] = Product.query.filter_by(
                title=product).first().id
            item['order_id'] = new_order.id

            itens.append(item)

        for item in itens:  #Passa pela lista de dicionarios e adiciona cada um ao banco de dados
            new_order_item = ItemOrder(**item)
            db.session.add(new_order_item)

            product = Product.query.filter_by(id=item['product_id']).first()
            pg.items.append(
                {
                    "id": product.id,
                    "description": product.desc,
                    "amount": "{:.2f}".format(product.price),
                    "quantity": item['quantity'],
                    "weight": None
                }, )
        pg.notification_url = request.url_root + "/notificacao"
        pg.redirect_url = request.url_root
        response = pg.checkout()
        new_response = PagSeguroResponse(code=response.code,
                                         date=response.date,
                                         payment_url=response.payment_url,
                                         errors=response.errors,
                                         order_id=new_order.id)
        db.session.add(new_response)

        db.session.commit()

        return redirect(response.payment_url)