Ejemplo n.º 1
0
 def get(self, request):
     uuid = request.session.pop('payment') if 'payment' in request.session else None
     payment = None
     if uuid is not None:
         payment = models.Payment.objects.filter(uuid=uuid).first()
         if payment:
             payment_id = payment.yuid
             log = models.Logging.objects.create(
                 action="Запрос данных в Яндекс кассе для ReturnUrl после оплаты. api/views.PaymentReturnUrl.get()",
                 input_data=f"yuid: {payment_id}")
             try:
                 payment_info = Payment.find_one(payment_id)
             except Exception as err:
                 log.result = log.FAIL
                 log.output_data = f"{err}"
                 log.save()
             else:
                 if payment.status != payment_info.status:
                     payment.status_set(payment_info.status)
                     # models.Payment.objects.filter(pk=payment.pk).update(status=payment_info.status)
                     # payment.status = payment_info.status
                     # if payment_info.status == 'succeeded':
                     #     payment.date_approve = timezone.now()
                     # payment.save()
                 log.result = log.SUCCESS
                 try:
                     payment_info_dict = {key: value.__dict__ if isinstance(value, BaseObject) else value for key, value
                                     in payment_info.__dict__.items()}
                     log.output_data = f"{payment_info_dict}"
                 except:
                     log.output_data = f"{payment_info}"
                 log.save()
     form_html = get_template('includes/payment_info.html').render(context={'payment': payment}, request=request)
     context = self.make_context(content=form_html, title='Статус платежа')
     return render(request, 'general.html', context=context)
Ejemplo n.º 2
0
    def payment_status(self, payment_id):
        """
        Получить информацию о платеже.
        """
        payment = Payment.find_one(payment_id)

        created_at = (dateparse.parse_datetime(payment.created_at)
                      if payment.created_at else None)
        captured_at = (dateparse.parse_datetime(payment.captured_at)
                       if payment.captured_at else None)
        expires_at = (dateparse.parse_datetime(payment.expires_at)
                      if payment.expires_at else None)

        return {
            'amount': payment.amount.value,
            'captured_at': captured_at,
            'created_at': created_at,
            'currency': payment.amount.currency,
            'description': payment.description,
            'expires_at': expires_at,
            'metadata': payment.metadata,
            'payment_method': payment.payment_method.type,
            'receipt_registration': payment.receipt_registration,
            'status': payment.status,
        }
Ejemplo n.º 3
0
    def post(self, request):
        print(request.data)
        pay_id = request.data.get('pay_id')
        Configuration.account_id = settings.YA_SHOP_ID
        Configuration.secret_key = settings.YA_API

        paymentObj = PaymentObj.objects.get(pay_code=pay_id)
        print(paymentObj)
        if not paymentObj.is_payed:
            payment = Payment.find_one(paymentObj.pay_id)
            print(payment)
            if payment.status == 'succeeded':
                paymentObj.is_payed = True
                paymentObj.status = 'Оплачен'
                paymentObj.save()
                paymentObj.user.balance += paymentObj.amount
                paymentObj.user.save(force_update=True)

            all_refferals = Refferal.objects.filter(refferal=paymentObj.user)

            print(all_refferals)
            if all_refferals.exists():
                for reffreal in all_refferals:
                    print(reffreal.master)
                    reffreal.master.partner_balance += int(paymentObj.amount *
                                                           10 / 100)
                    reffreal.master.save()
                    reffreal.earned += int(paymentObj.amount * 10 / 100)
                    reffreal.save()

        return Response(status=200)
Ejemplo n.º 4
0
 def post(self, *args, **kwargs):
     Configuration.account_id = settings.YANDEX_ACCOUNT_ID
     Configuration.secret_key = settings.YANDEX_SECRET_KEY
     user = self.request.user
     try:
         game = Game.objects.get(pk=kwargs.get('pk'))
     except Game.DoesNotExist:
         return Response({
             'error': 'Game does not exist!',
         },
                         status=status.HTTP_400_BAD_REQUEST)
     user_registered_places = UserInTeam.objects.filter(game=game.pk,
                                                        user=user.pk)
     if user_registered_places.count() == 0:
         return Response(
             {
                 'error': 'User has no purchased seats for this game!',
             },
             status=status.HTTP_400_BAD_REQUEST)
     user_game_payments = GamePayment.objects.filter(user=user.pk,
                                                     game=game.pk,
                                                     status='SUCCEEDED')
     if user_game_payments.count() == 0:
         return Response(
             {
                 'error': 'User has no successful payments for this game!',
             },
             status=status.HTTP_400_BAD_REQUEST)
     refunds = []
     non_refundable_payments = []
     unregistered_places_count = 0
     for game_payment in user_game_payments:
         payment = Payment.find_one(game_payment.identifier)
         if payment.status == 'succeeded':
             game_payment_refund = create_refund(game_payment, user, game)
             refunds.append(game_payment_refund)
             if game_payment_refund.status == 'SUCCEEDED':
                 del_objects = UserInTeam.objects.filter(
                     game=game.pk, user=user.pk)[:game_payment.places_count]
                 for del_object in del_objects:
                     del_object.delete()
                     unregistered_places_count += game_payment.places_count
         else:
             non_refundable_payments.append(game_payment)
     if len(refunds):
         create_timeline_block('GAME_MESSAGE',
                               settings.USER_CANCEL_REGISTRATION, user,
                               'APP', game)
     return Response(
         {
             'refunds':
             GamePaymentRefundSerializer(refunds, many=True).data,
             'non_refundable_payments':
             GamePaymentSerializer(non_refundable_payments, many=True).data,
             'unregistered_places_count':
             unregistered_places_count,
         },
         status=status.HTTP_200_OK)
Ejemplo n.º 5
0
    def check_pay(self, payment_id):
        paid = False
        time_while_end = datetime.now() + timedelta(seconds=33)
        while paid == False and datetime.now(tz=None) <= time_while_end:
            payment_result = Payment.find_one(payment_id)
            paid = payment_result.paid
            time.sleep(3)

        if paid:
            paid = payment_result

        return paid
Ejemplo n.º 6
0
def paycheck(request, payment_id):
    order = get_object_or_404(UserAccount, key=payment_id)
    payment = Payment.find_one(order.payment_id)
    if payment.status == "succeeded":
        order.status = True
        order.save()
        try:
            send_mail(
                'Алгоритм языка | Оплата занятий',
                'Вы успешно оплатили заказ № {0} на сумму: {1}'.format(
                    order.pk, str(decimal.Decimal(order.price))),
                '*****@*****.**',
                ['{0}'.format(order.email)],
                fail_silently=False,
            )
        except Exception as e:
            print("Email sendr exception {0}".format(e))
    return render(request, "sprache/success.html", {"number": order.pk})
Ejemplo n.º 7
0
def refresh_payment(payment):
    Configuration.configure(settings.YANDEX_CHECKOUT_CLIENT_ID,
                            settings.YANDEX_CHECKOUT_SECRET_KEY)
    yandex_payment = YandexPayment.find_one(payment.yandex_id)

    need_to_set_payed = False
    if payment.status == Payment.PENDING and yandex_payment.status in (
            Payment.WAITING_FOR_CAPTURE, Payment.SUCCEEDED):
        need_to_set_payed = True

    payment.status = yandex_payment.status
    if yandex_payment.cancellation_details:
        payment.cancellation_reason = yandex_payment.cancellation_details.reason
    payment.save(update_fields=['status', 'cancellation_reason'])

    if need_to_set_payed:
        set_order_payed(payment.order)

    return payment
Ejemplo n.º 8
0
def check_payment_status():
    """
    периодическая проверка неконечных статусов платежа, с момента создания которых прошел час
    (в течении часа пользователю доступен виджет оплаты в статусе -pending-)
    """
    payments = models.Payment.objects.filter(
        account__isnull=False,
        yuid__isnull=False).exclude(status__in=['succeeded', 'canceled'])
    if payments:
        try:
            upper_settings = models.UpperSetting.objects.get()
            test = upper_settings.test_mode
            if test:
                yandex_api_key = upper_settings.yandex_api_key_test
                shopid = upper_settings.shopid_test
            else:
                yandex_api_key = upper_settings.yandex_api_key
                shopid = upper_settings.shopid
        except:
            base_dir = settings.BASE_DIR

            env = environ.Env()
            env.read_env(path.join(base_dir, '.env'))
            yandex_api_key = env('YANDEX_API_KEY')
            shopid = env('SHOPID')
        Configuration.account_id = shopid
        Configuration.secret_key = yandex_api_key
        for payment in payments:
            try:
                payment_info = Payment.find_one(payment.yuid)
                if payment.status != payment_info.status:
                    payment.status_set(payment_info.status)
                    # models.Payment.objects.filter(pk=payment.pk).update(status=payment_info.status)
                    # payment.status = payment_info.status
                    # if payment_info.status == 'succeeded':
                    #     payment.date_approve = timezone.now()
                    # payment.save()
            except Exception as ex:
                print(ex)
Ejemplo n.º 9
0
 def get_yandex_payment(self):
     return YandexPayment.find_one(self.inner_id)
Ejemplo n.º 10
0
 def post(self, *args, **kwargs):
     Configuration.account_id = settings.YANDEX_ACCOUNT_ID
     Configuration.secret_key = settings.YANDEX_SECRET_KEY
     user = self.request.user
     serializer = PaymentSaveSerializer(data=self.request.data)
     if serializer.is_valid():
         payment = Payment.find_one(serializer.validated_data['payment_id'])
         game_payment = GamePayment.objects.get(
             identifier=serializer.validated_data['payment_id'])
         game_id = serializer.validated_data['game_id']
         game = Game.objects.get(pk=game_id)
         if payment.status == 'canceled':
             game_payment.status = 'CANCELED'
             game_payment.cancel_message = payment.cancellation_details.party + ': ' + payment.cancellation_details.reason
             game_payment.save()
             create_timeline_block('GAME_MESSAGE',
                                   settings.BANK_CANCEL_REGISTRATION, user,
                                   'APP', game)
             return Response(
                 {
                     'message': 'Payment was canceled!',
                     'party': payment.cancellation_details.party,
                     'reason': payment.cancellation_details.reason,
                 },
                 status=status.HTTP_400_BAD_REQUEST)
         elif payment.status == 'waiting_for_capture':
             game_payment.status = 'WAITING_FOR_CAPTURE'
             game_payment.save()
         elif payment.status == 'succeeded':
             game_payment.status = 'SUCCEEDED'
             game_payment.save()
         reserved_places = TemporaryReserve.objects.filter(game=game_id,
                                                           user=user.pk)
         reserved_places_count = reserved_places.count()
         if reserved_places_count == 0:
             return Response(
                 {
                     'error':
                     'You have no reserved seats for this game or payment time exceeded 1 hour. Try again!',
                 },
                 status=status.HTTP_400_BAD_REQUEST)
         user_in_team_places_count = UserInTeam.objects.filter(
             game=game_id, user=user.pk).count()
         team = Team.objects.get(game=game)
         if user_in_team_places_count != 0:
             for _ in range(reserved_places_count):
                 self.create_user_in_team(game, team, user, game_payment,
                                          True)
         else:
             self.create_user_in_team(game, team, user, game_payment)
             for _ in range(reserved_places_count - 1):
                 self.create_user_in_team(game, team, user, game_payment,
                                          True)
         for reserved_place in reserved_places:
             reserved_place.delete()
         create_timeline_block('GAME_MESSAGE',
                               settings.SUCCESS_REGISTRATION, user, 'APP',
                               game)
         return Response(
             {
                 'message': 'Places were registered successfully!',
             },
             status=status.HTTP_200_OK)
     return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
Ejemplo n.º 11
0
def check_payment(p_id):
    payment_status = Payment.find_one(payment_id=p_id).status
    if payment_status == 'succeeded':
        return True
    else:
        return False
Ejemplo n.º 12
0
 def getInfo(self):
     return Payment.find_one(self.payment_id)
Ejemplo n.º 13
0
 def findOne(self):
     if self.payment_id is None:
         return None
     return Payment.find_one(self.payment_id)