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
Esempio n. 2
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)
Esempio n. 3
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
Esempio n. 4
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)
Esempio n. 5
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.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)

        # get grossAmount to populate a payment with methods
        try:
            ref = reference.replace(prefix, '')
            qs = Cart.objects.filter(
                reference_code=ref) or Cart.objects.filter(id=ref)

            if not qs:
                return "Cart not found"

            self.cart = qs[0]

            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)

            fee_amount = getattr(response, 'feeAmount', None)
            if fee_amount:
                self.cart.set_tax(fee_amount)
                msg = "Tax set to: %s" % fee_amount
                self.cart.addlog(msg)

            # send response to reference and products
            self.cart.send_response(response, 'pagseguro')

            return msg
        except Exception as e:
            msg = "Error in notification: {} - {}".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)

            # get grossAmount to populate a payment with methods
            try:
                # self.cart = Cart.objects.get(
                #     reference_code=reference.replace(PREFIX, '')
                # )
                ref = reference.replace(prefix, '')
                qs = Cart.objects.filter(
                    reference_code=ref) or Cart.objects.filter(id=ref)

                if not qs:
                    return "Cart not found"

                self.cart = qs[0]

                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")

                fee_amount = getattr(response, 'feeAmount', None)
                if fee_amount:
                    self.cart.set_tax(fee_amount)
                    msg = "Tax set to: %s" % fee_amount
                    self.cart.addlog(msg)

                # send response to reference and products
                self.cart.send_response(response, 'pagseguro')

                return render_template('cart/confirmation.html', **context)
            except Exception as e:
                msg = "Error in confirmation: {} - {}".format(reference, e)
                logger.error(msg)
        return render_template('cart/simple_confirmation.html', **context)
Esempio n. 6
0
    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,
        })
Esempio n. 7
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)