Example #1
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')
Example #2
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')
Example #3
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')	
    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)
Example #5
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')
Example #6
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("")
Example #7
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)
    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 notification_view(request):
    notification_code = request.POST['notificationCode']
    pg = PagSeguro(email=app.config['EMAIL'], token=app.config['TOKEN'])
    pg.check_notification(notification_code)
Example #10
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)
Example #11
0
class Transcation:

    config = None
    use_shipping = False
    host = 'http://45.132.242.190'
    sandbox = settings.PAGSEGURO_SANDBOX
    notification_url = reverse_lazy('api.v1:pag-notification')

    def __init__(self):
        self.pg = PagSeguro(email=settings.PAGSEGURO_EMAIL,
                            token=settings.PAGSEGURO_TOKEN,
                            config=self.get_config())
        self.pg.payment = {'mode': 'default'}
        self.config = Config.objects.first()

    def set_senderHash(self, senderHash):
        self.senderHash = senderHash

    def set_notification_url(self):
        self.pg.notification_url = '{}{}'.format(self.host,
                                                 self.notification_url)

    def set_sender(self, profile):
        self.pg.sender = {
            "name": profile.user.get_full_name(),
            "email": profile.user.email,
            "hash": self.senderHash,
            "phone": {
                "areaCode": profile.phone[:2],
                "number": profile.phone[2:],
            },
            "documents": [{
                "type": "CPF",
                "value": profile.cpf
            }],
            'address': {
                'street': profile.address,
                'number': profile.number,
                'complement': profile.complement,
                'district': profile.district,
                'city': profile.city.name,
                'state': profile.city.state.uf,
                'postalCode': profile.zipcode,
                'country': 'BRA'
            }
        }

    def get_config(self):
        return {'sandbox': self.sandbox, 'USE_SHIPPING': self.use_shipping}

    def get_session(self):
        return self.pg.transparent_checkout_session()

    def get_notification(self, code):
        return self.pg.check_notification(code)

    def cancel(self, code):
        url = f'{self.pg.config.QUERY_TRANSACTION_URL}/cancels'
        self.pg.data.update({'transactionCode': code})
        return self.pg.post(url)

    def ticket(self, data):
        date = datetime.now().date() + timedelta(days=self.config.trial_period)
        self.set_notification_url()
        self.pg.ticket = {
            'firstDueDate': date.isoformat(),
            'numberOfPayments': 1,
            'amount': str(self.config.value),
            'description': self.config.plan_name,
        }
        return self.pg.generate_ticket()

    def credit_card(self, card, profile):
        self.set_notification_url()
        self.pg.code = self.config.plan_code
        self.pg.payment.update({'method': 'creditCard'})
        self.pg.credit_card = {
            'token': card.get('card_token'),
            'holder': {
                'name': card.get('card_name'),
                'birthDate': profile.birthday.strftime('%d/%m/%Y'),
                'documents': [{
                    'type': 'CPF',
                    'value': profile.cpf
                }],
                "phone": {
                    "areaCode": profile.phone[:2],
                    "number": profile.phone[2:],
                }
            }
        }
        return self.pg.pre_approval_ask()

    def create_new_plan(self):
        self.pg.pre_approval = {
            'charge': 'AUTO',
            'name': self.config.plan_name,
            'details': self.config.plan_description,
            'amount_per_payment': self.config.value,
            'trial_period_duration': self.config.trial_period,
            'period': 'MONTHLY'
        }
        return self.pg.pre_approval_request()
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)
Example #13
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)