Beispiel #1
0
    def create_payment(self, data):
        """
        Создать платёж.
        """
        payment = Payment.create(data, self.generate_idempotence_key())

        # TODO: Сделать специальный класс для данной ошибки и описание.
        payment_status = payment.status
        if payment_status not in PaymentStatus.available_choices():
            raise YandexKassaException()

        # TODO: Сделать специальный класс для данной ошибки и описание.
        payment_payment_method = payment.payment_method.type
        if payment_payment_method not in PaymentMethod.available_choices():
            raise YandexKassaException()

        data = {
            'amount': payment.amount.value,
            'confirmation_url': payment.confirmation.confirmation_url,
            'created_at': dateparse.parse_datetime(payment.created_at),
            'currency': payment.amount.currency,
            'metadata': payment.metadata,
            'payment_id': payment.id,
            'payment_method': payment_payment_method,
            'status': payment_status,
        }

        if payment.description:
            data['description'] = payment.description

        return data
Beispiel #2
0
def payment_formation(order):
    Configuration.account_id = settings.YANDEX_SHOP_ID
    Configuration.secret_key = settings.YANDEX_SECRET_KEY
    independent_key = str(uuid.uuid4())
    payment = Payment.create(
        {
            "amount": {
                "value": order.amount,
                "currency": "RUB"
            },
            "confirmation": {
                "type": "redirect",
                "return_url": "https://expertsovet.com"
            },
            "receipt": {
                "email":
                order.email,
                "payment_subject":
                order.good.payment_subject,
                "payment_mode":
                order.good.payment_mode,
                "items": [{
                    "description": order.good.subtitle[:128],
                    "quantity": 1,
                    "amount": {
                        "value": order.amount,
                        "currency": "RUB"
                    },
                    "vat_code": "1",
                }]
            },
            "description": f"Заказ №{order.id}"
        }, independent_key)
    return payment
Beispiel #3
0
    def get(self, request, value=3000, id=None):
        Configuration.account_id = '718911'
        Configuration.secret_key = 'test_LvcNnzMH8UOAI0Rc6Dw7MvP8O6WAZoQwsF0kW7e5tY4'

        print(id)
        nmb = int(value / 3000)

        currency = "RUB"

        return_url = "https://chestnokfest.live/tickets/payment_redirect/"

        description = str("Покупка " + str(nmb) + " билета(ов) за " +
                          str(value))

        payment = Payment.create({
            "amount": {
                "value": value,
                "currency": currency
            },
            "confirmation": {
                "type": "redirect",
                "return_url": return_url
            },
            "description": description,
            "metadata": {
                'id': id,
            }
        })

        return HttpResponseRedirect(payment.confirmation.confirmation_url)
Beispiel #4
0
async def buy_course(user_id, course_id, redirect_url):
    course = await CourseModel.get(course_id)
    if course.cost is None or course.cost <= 0:
        await PurchasedCoursesModel.create(
            course_id=course_id,
            user_id=user_id
        )
        return None
    payment = Payment.create({ 
        "amount": {
            "value": '{:.2f}'.format(course.cost),
            "currency": "RUB"
        },
        "confirmation": {
            "type": "redirect", 
            "return_url": redirect_url
        },
        "capture": True, 
        "description": "Покупка курса {name}".format(name=course.name)
    }, uuid.uuid4())

    await PaymentModel.create(
        user_id=user_id,
        course_id=course_id,
        order_id=payment.id
    )

    return payment.confirmation.confirmation_url
Beispiel #5
0
    def pay_without_payment_id(self, order, value):
        return_url = f"{self.site_url}pay/{order.id}/"

        payment = Payment.create(
            {
                "amount": {
                    "value": value,
                    "currency": "RUB"
                },
                "capture": True,
                "payment_method_data": {
                    "type": "bank_card"
                },
                "confirmation": {
                    "type": "redirect",
                    "return_url": return_url
                },
                "description": f"Заказ {order.id}",
                "save_payment_method": True,
                "metadata": {
                    "order_id": order.id
                }
            }, str(uuid.uuid4()))

        return payment
Beispiel #6
0
    def get(self, request):
        with open('/Users/blockbusted/PycharmProjects/config_shop_file.json') as config_file:
            config = json.load(config_file)
        Configuration.account_id = config['YANDEX_SHOP_ID']
        Configuration.secret_key = config['YANDEX_SECRET_KEY']

        order_pk = self.request.session['order_pk']
        order = Order.objects.get(pk=order_pk)
        amount = order.get_total_order_price()
        idempotence_key = str(uuid.uuid4())
        payment = Payment.create({
            #  "payment_token": idempotence_key,
            "amount": {
                "value": 1,
                "currency": "RUB"
            },
            "confirmation": {
                "type": "redirect",
                "return_url": "cart:payment-yandex-notifications"
            },
            "description": "Заказ №"+str(order_pk)
        })

        order_payment = OrderPayment()
        order_payment.order_pk = order_pk
        if self.request.user.is_authenticated:
            order_payment.user = self.request.user
        order_payment.amount = amount
        order_payment.save()
        return HttpResponseRedirect(payment.confirmation.confirmation_url)
Beispiel #7
0
 def createPayment(self,user,amount,booking=None,payment_type="account"):
     '''
         Create yandex kassa payment object. payment_type = True - autopayment otherwise is add card
     '''
     if self.getCurrentTransaction(user,amount,booking,payment_type) is not None:
         print("Yes getCurrentTransaction")
         return self.getCurrentTransaction(user,amount,booking,payment_type).getInfo()
     payment_info = {
         "amount": {
             "value": str(decimal.Decimal(amount)),
             "currency": "RUB"
         },
         "description": "Привязка карты"
     }
     payment_info.update(self.createReceipt(user,amount))
     if payment_type == "full":
         payment_info.update(self.createAutoPayment(user))
     else: #payment_type == "account": # False
         payment_info.update(self.createConfirmation())
     payment_object = Payment.create(payment_info)
     self.create(
         user = user,
         booking = booking,
         price = amount,
         date = now(),
         status = payment_object.status,
         payment_type = payment_type,
         payment_id = payment_object.id,
         created_at = payment_object.created_at,
         expires_at = payment_object.expires_at,
         checkouted = False
     )
     return payment_object
Beispiel #8
0
def pay(value, order_id, email, items, delivery):
    Configuration.account_id = settings.YA_ACCOUNT_ID
    Configuration.secret_key = settings.YA_SECRET_KEY

    payment_items = [
        {"description": f'{item.item.title} [{item.size.title}]', "quantity": "1",
         "amount": {"value": item.item.price, "currency": "RUB"},
         "vat_code": 1} for item in items]
    if delivery:
        payment_items += [{"description": "Доставка", "quantity": "1", "amount": {"value": delivery, "currency": "RUB"},
                           "vat_code": 1}]

    payment = Payment.create({
        "amount": {
            "value": value,
            "currency": "RUB"
        },
        "confirmation": {
            "type": "embedded",
            "return_url": "https://test.hrsmnt.ru/#/"
        },
        "receipt": {
            "customer": {
                "email": email,
            },
            "items": payment_items
        },
        "capture": True,
        "description": f"Заказ №{order_id}"
    }, uuid.uuid4())

    return payment.confirmation.confirmation_token, payment.id
Beispiel #9
0
    def pay_with_payment_id(self, order, value):
        payment = Payment.create(
            {
                "amount": {
                    "value": value,
                    "currency": "RUB"
                },
                "description": f"Заказ {order.id}",
                "payment_method_id": self.payment_id
            }, str(uuid.uuid4()))

        return payment
Beispiel #10
0
def do_payment(track_code):
    ad = Ads.query.filter_by(track=track_code).first()
    form = ProcessPayment()

    if current_user.is_authenticated:
        user = Users.query.get(current_user.id)

        if ad in user.ads.all():
            is_own = True
        else:
            is_own = False
    else:
        is_own = False

    if form.validate_on_submit() and form.submit.data:

        Configuration.account_id = Variables.query.get(3).value
        Configuration.secret_key = Variables.query.get(4).value

        print(form.waste.data)

        payment = Payment.create(
            {
                "amount": {
                    "value":
                    int(ad.price) - int(current_user.collected_m)
                    if form.waste.data else ad.price,
                    "currency":
                    "RUB"
                },
                "confirmation": {
                    "type": "redirect",
                    "return_url": "https://vk.com/id608742663"
                },
                "capture": True,
                "description": "Оплата объявления {}".format(ad.track),
                "metadata": {
                    "track": ad.track,
                    "bonus_used": 1 if form.waste.data else 0,
                    "payer": current_user.id if is_own else 'unregistered user'
                }
            }, uuid.uuid4())

        print('передано в оплату')
        return redirect(payment.confirmation.confirmation_url)
    return render_template('do_payment.html',
                           form=form,
                           ad=ad,
                           is_own=is_own,
                           current_user=current_user,
                           price_btn_text='Оплатить {}₽'.format(ad.price))
Beispiel #11
0
def pay(request, timeslot_id):
    amount = 3400
    timeslot = TimeSlot.objects.get(pk=timeslot_id)
    user = create_user(request)
    enroll = Enroll.objects.create(timeslot_id=timeslot_id, user=user, )
    enroll.save()
    payment = Payment.objects.create(enroll=enroll, status="initial", amount=amount, )
    payment.save()
    yandex_payment = YandexPayment.create({
        "amount": {
            "value": amount,
            "currency": "RUB"
        },
        "payment_method_data": {
            "type": "bank_card"
        },
        "confirmation": {
            "type": "redirect",
            "return_url": settings.KASSA_REDIRECT_URL
        },
        "capture": False,
        "description": "Консультация " + timeslot.specialist.middle_name + " " + timeslot.specialist.first_name,
        "receipt": {
            "items": [{
                "description": "Консультация " + timeslot.specialist.middle_name + " " + timeslot.specialist.first_name,
                "quantity": 1,
                "amount": {
                    "value": amount,
                    "currency": "RUB"
                },
                "vat_code": 1,
                "payment_subject": "service",
                "payment_mode": "full_prepayment"

            }],
            "tax_system_code": 3,
            "email": user.email,

        }
    }, uuid.uuid4())

    payment_id = yandex_payment.id
    payment.yandex_payment = payment_id
    payment.save()

    print(yandex_payment)
    return HttpResponseRedirect(yandex_payment.confirmation.confirmation_url)
Beispiel #12
0
    def handle_payment(self, order_number, total, **kwargs):
        """
        Called from submit method
        Handle any payment processing and record payment sources and events.

        This method is designed to be overridden within your project.

        This method is responsible for handling payment and recording the
        payment sources (using the add_payment_source method) and payment
        events (using add_payment_event) so they can be
        linked to the order when it is saved later on.
        """
        method = self.checkout_session.payment_method()
        if method == 'cod':
            source_type, is_created = models.SourceType.objects.get_or_create(
                name='cash')
            redirect_url = ''
        elif method == 'yandex_kassa':
            Configuration.account_id = settings.KASSA_ID
            Configuration.secret_key = settings.KASSA_TOKEN
            source_type, is_created = models.SourceType.objects.get_or_create(
                name='online')
            payment = Payment.create(
                {
                    "amount": {
                        "value": str(total.incl_tax),
                        "currency": "RUB"
                    },
                    "confirmation": {
                        "type": "redirect",
                        "return_url":
                        "http://127.0.0.1:8000/checkout/thank-you/"
                    },
                    "capture": True,  # холдирование - False
                    "description": order_number
                },
                uuid.uuid4())
            redirect_url = payment.confirmation.confirmation_url

        source = source_type.sources.model(source_type=source_type,
                                           amount_allocated=total.incl_tax,
                                           currency=total.currency)
        self.add_payment_source(source)
        self.add_payment_event('Authorised', total.incl_tax)
        if redirect_url:
            # return redirect(redirect_url)
            raise RedirectRequired(redirect_url)
Beispiel #13
0
 def createPaymentObject(self, capture=False, save_payment_method=True):
     '''
         Returns Yandex Kassa Object if rentor i.e user and price are set.
     '''
     if self.rentor is None:
         return None
     if self.price is None:
         return None
     return Payment.create({
         "amount": {
             "value": "{0}".format(str(decimal.Decimal(self.price))),
             "currency": "RUB"
         },
         "confirmation": {
             "type": "embedded"
         },
         "receipt": {
             "customer": {
                 "full_name":
                 "{0} {1}".format(self.rentor.first_name,
                                  self.rentor.last_name),
                 "email":
                 "{0}".format(self.rentor.email)
             },
             "items": [{
                 "description": "Оплата аренды",
                 "quantity": "2.00",
                 "amount": {
                     "value":
                     "{0}".format(str(decimal.Decimal(self.price))),
                     "currency": "RUB"
                 },
                 "vat_code": "2",
                 "payment_mode": "full_prepayment",
                 "payment_subject": "commodity"
             }]
         },
         "capture":
         capture,
         "save_payment_method":
         save_payment_method,
         "description":
         "Оплата аренды №{0}".format(self.pk)
     })
Beispiel #14
0
def create_payment(price, days):
    payment = Payment.create({
        "amount": {
            "value": f"{price}",
            "currency": "RUB"
        },
        "confirmation": {
            "type": "redirect",
            "return_url": "http://localhost:3000/pay_success"
        },
        "capture": True,
        "description": "Заказ №1",
        'metadata': {
            'days': days
        }
    })
    p_id = payment.id
    print(p_id)
    return payment.confirmation.confirmation_url, p_id
Beispiel #15
0
def index_page(request):
    if request.method == 'POST':
        form = PaymentInfoForm(request.POST)
        if form.is_valid():

            payment = Payment.create(
                {
                    "amount": {
                        "value": form.cleaned_data['money'],
                        "currency": "RUB"
                    },
                    "confirmation": {
                        "type": "redirect",
                        "return_url": settings.ALLOWED_HOSTS[0]
                    },
                    "receipt": {
                        "customer": {
                            "full_name":
                            "ФИО",
                            "phone":
                            ''.join(
                                re.findall(r'\d', form.cleaned_data['phone']))
                        },
                        "items": [{
                            "description": "Оплата бронирования",
                            "quantity": "1.00",
                            "amount": {
                                "value": form.cleaned_data['money'],
                                "currency": "RUB"
                            },
                            "vat_code": "2",
                            "payment_mode": "full_prepayment",
                            "payment_subject": "commodity"
                        }]
                    },
                    "capture": True,
                    "description": form.cleaned_data['phone']
                }, uuid.uuid4())
            return HttpResponseRedirect(payment.confirmation.confirmation_url)
    else:
        form = PaymentInfoForm()
    return render(request, 'index.html', {'form': form})
Beispiel #16
0
 def create_yandex_payment(self, user):
     payment_data = {
         'amount': {'value': self.cost, 'currency': 'RUB'},
         'confirmation': {'type': 'redirect', 'return_url': 'https://sample-shop.com/'},
         'capture': True,
         'description': self.__str__(),
         'receipt': {
             'customer': {'email': user.email},
             'items': [
                 {
                     'description': item.name,
                     'quantity': item.count,
                     'amount': {'value': item.price, 'currency': 'RUB'},
                     'vat_code': 1,
                 }
                 for item in self.order.items.all()
             ],
         },
     }
     return YandexPayment.create(payment_data, self.inner_key)
Beispiel #17
0
 def payPrice(self):
     if self.rentor is None:
         print("r")
         return None
     if self.price is None:
         print("p")
         return None
     if self.payment_type != 2:
         print("pt")
         return None
     if self.status is True:
         print("s")
         return None
     return Payment.create({
         "amount": {
             "value": self.renta.getPrice(),
             "currency": "RUB"
         },
         "capture": "true",
         "payment_method_id": self.rentor.usersdocuments.yakey,
         "description": "Заказ ID:{0}".format(self.pk)
     })
Beispiel #18
0
    def get(self, type_id):
        """
        Принимаем payment_id [GET]
        Создаем платеж
        Меняем статус платежа
        Сохраняем
        :param request:
        :param format:
        :return:
        """
        order_id = self.request.GET.get('order_id')
        order = Orders.objects.get(id=order_id)
        # status = int(order.status_order)
        value = order.order_price

        payment = Payment.create(
            {
                "amount": {
                    "value": value,
                    "currency": "RUB"
                },
                "confirmation": {
                    "type": "redirect",
                    "return_url": "{}".format(config.url)
                },
                "capture": "false",
                "description": "Заказ №{}".format(order_id),
                "metadata": {
                    "order_id": "37"
                }
            }, uuid.uuid4())

        # get confirmation url
        confirmation_url = payment.confirmation.confirmation_url
        order.payment_id = payment.id
        order.status_order = 2
        order.save()

        return HttpResponseRedirect(confirmation_url)
Beispiel #19
0
    def post(self, request):
        print(request.data)
        amount = request.data.get('amount')
        payment_type = request.data.get('pay_type')

        Configuration.account_id = settings.YA_SHOP_ID
        Configuration.secret_key = settings.YA_API
        pay_id = uuid.uuid4()
        payment = Payment.create(
            {
                "amount": {
                    "value": amount,
                    "currency": "RUB"
                },
                "payment_method": {
                    "type": payment_type,
                },
                "confirmation": {
                    "type":
                    "redirect",
                    "return_url":
                    f'{settings.HOST}/profile/balance?pay_id={pay_id}'
                },
                "capture":
                True,
                "description":
                f'Пополнение баланса пользователя ID {request.user.id}. {request.user.get_full_name()}'
            }, pay_id)

        pt = PaymentType.objects.get(method=payment_type)
        PaymentObj.objects.create(user=request.user,
                                  pay_id=payment.id,
                                  pay_code=pay_id,
                                  amount=int(amount),
                                  type=pt,
                                  status='Не оплачен')

        return Response(payment.confirmation.confirmation_url)
Beispiel #20
0
def pay(request, payment_id):
    order = get_object_or_404(UserAccount, key=payment_id)
    payment = Payment.create({
        "amount": {
            "value": "{0}".format(str(decimal.Decimal(order.price))),
            "currency": "RUB"
        },
        "confirmation": {
            "type": "embedded"
        },
        "receipt": {
            "customer": {
                "full_name": "{0} {1}".format(order.first_name,
                                              order.last_name),
                "email": "{0}".format(order.email)
            },
            "items": [{
                "description": "Оплата занятий",
                "quantity": "2.00",
                "amount": {
                    "value": "{0}".format(str(decimal.Decimal(order.price))),
                    "currency": "RUB"
                },
                "vat_code": "2",
                "payment_mode": "full_prepayment",
                "payment_subject": "commodity"
            }]
        },
        "capture": True,
        "description": "Заказ №{0}".format(order.pk)
    })
    order.payment_id = payment.id
    order.save()
    return render(request, "sprache/pay.html", {
        "payment": payment,
        "order": order
    })
Beispiel #21
0
def create_payment(order):
    Configuration.configure(settings.YANDEX_CHECKOUT_CLIENT_ID,
                            settings.YANDEX_CHECKOUT_SECRET_KEY)
    idempotence_key = str(uuid.uuid4())
    yandex_payment = YandexPayment.create(
        {
            'amount': {
                'value': str(order.total_cost),
                'currency': 'RUB',
            },
            'description': f'Платеж по заказу {order.id}',
            'confirmation': {
                'type': 'embedded'
            }
        }, idempotence_key)

    payment = Payment.objects.create(
        order=order,
        yandex_id=yandex_payment.id,
        status=yandex_payment.status,
        amount=yandex_payment.amount.value,
        currency=yandex_payment.amount.currency,
        confirmation_token=yandex_payment.confirmation.confirmation_token)
    return payment
Beispiel #22
0
    def charge(self,
               value: str,
               currency: str,
               description: str,
               save_payment_method: bool = None) -> [str, str]:
        """
        Make a payment request to Yandex Checkout.
        """
        # todo: correct error handling
        try:
            payment_response = Payment.create({
                "amount": {
                    "value": value,
                    "currency": currency,
                },
                "confirmation": {
                    "type": "redirect",
                    "return_url": settings.
                    YANDEX_CHECKOUT_RETURN_URL  # replace with user's orders page
                },
                "capture":
                True,
                "description":
                description,
                "save_payment_method":
                save_payment_method
            })
        except UnauthorizedError:
            raise UnauthorizedError("Set Yandex Checkout keys in env vars.")

        payment_response = json.loads(payment_response.json())

        # TODO: exception handling

        return (payment_response["confirmation"]["confirmation_url"],
                payment_response.get('id'))
Beispiel #23
0
    def get(self, type_id):
        """
        Принимаем payment_id
        :param request:
        :param format:
        :return:
        """
        order_id = self.request.GET.get('order_id')
        order = Orders.objects.get(id=order_id)
        # status = int(order.status_order)
        value = order.order_price

        payment = Payment.create(
            {
                "amount": {
                    "value": value,
                    "currency": "RUB"
                },
                "confirmation": {
                    "type": "redirect",
                    "return_url": "http://192.168.1.131:8080/"
                },
                "capture": "false",
                "description": "Заказ №1",
                "metadata": {
                    "order_id": "37"
                }
            }, uuid.uuid4())

        # get confirmation url
        confirmation_url = payment.confirmation.confirmation_url
        order.payment_id = payment.id
        order.status_order = 2
        order.save()

        return HttpResponseRedirect(confirmation_url)
Beispiel #24
0
 def charge_recurrent(self,
                      external_id: str,
                      amount: Decimal,
                      currency: str,
                      description: str) -> bool:
     """
     Charge customer with saved payment information. Return false if not succeeded.
     """
     payment_response = Payment.create({
         "amount": {
             "value": str(amount),
             "currency": currency
         },
         "payment_method_id": external_id,
         "description": description
     })
     payment_response = json.loads(payment_response.json())
     status = payment_response.get('status')
     if status == 'succeeded':
         return True
     if status == 'canceled' and payment_response['cancellation_details']['reason'] == 'permission_revoked':
         return False
     # Raise exception to retry task with backoff.
     raise YandexPaymentError(f"Yandex payment error response {payment_response}")
Beispiel #25
0
Configuration.secret_key = 'test_N1nxSKIVxuNqTJIOC12laqvuVpFtH8_0Zsdby3F6T74'

payment = Payment.create({
    "amount": {
        "value": "500.00",
        "currency": "RUB"
    },
    "confirmation": {
        "type": "redirect",
        "return_url": "https://www.merchant-website.com/return_url"
    },
    "capture": True,
    "description": "Заказ №2",
    'receipt': {
        "customer": {
            'phone': "79221379198"
        },
        "items": {
            "description": "Сapybara",
            "quantity": 5.000,
            "amount": {
                "value": "2500.50",
                "currency": "RUB"
            },
            "vat_code": 2,
            "payment_mode": "full_payment",
        }
    }
})
print(payment.confirmation.confirmation_url)
Beispiel #26
0
 def post(self, request, *args, **kwargs):
     Configuration.account_id = settings.YANDEX_ACCOUNT_ID
     Configuration.secret_key = settings.YANDEX_SECRET_KEY
     code = None
     coupon = None
     try:
         code = self.request.data['code']
     except KeyError:
         pass
     if self.request.data['game_id'] != kwargs.get('pk'):
         return Response({
             'game_id': 'Must be equal to game id from url!',
         },
                         status=status.HTTP_400_BAD_REQUEST)
     reserved_places_count = TemporaryReserve.objects.filter(
         user=self.request.user.pk, game=kwargs.get('pk')).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)
     game = Game.objects.get(pk=self.request.data['game_id'])
     if code:
         serializer = CouponCheckSerializer(data=self.request.data)
         if serializer.is_valid():
             coupon = Coupon.objects.get(
                 code=serializer.validated_data.get('code'))
             if coupon.type == 'INDIVIDUAL':
                 if coupon.user != self.request.user:
                     return Response(
                         {
                             'error':
                             'Invalid user for this INDIVIDUAL coupon!',
                         },
                         status=status.HTTP_400_BAD_REQUEST)
                 summa = self.apply_individual_discount(
                     coupon, game, reserved_places_count)
             else:
                 summa = self.apply_general_discount(
                     coupon, game, reserved_places_count)
         else:
             return Response(serializer.errors,
                             status=status.HTTP_400_BAD_REQUEST)
     else:
         summa = game.price * reserved_places_count
     payment = Payment.create({
         'amount': {
             'value': str(summa),
             'currency': 'RUB',
         },
         'confirmation': {
             'type': 'embedded',
         },
         'capture': True,
         'description': 'Description',
     })
     if coupon:
         discount = round(coupon.discount, 2)
         discount_units = coupon.units
     else:
         discount = 0
         discount_units = ''
     GamePayment.objects.create(
         identifier=payment.id,
         user=self.request.user,
         game=game,
         coupon=coupon,
         summa=round(game.price * reserved_places_count, 2),
         discount=discount,
         discount_units=discount_units,
         summa_with_discount=round(summa, 2),
         currency='RUB',
         places_count=reserved_places_count,
         status='PENDING',
     )
     return Response(
         {
             'yandex_token': payment.confirmation.confirmation_token,
             'payment_id': payment.id,
         },
         status=status.HTTP_200_OK)
Beispiel #27
0
import uuid

from yandex_checkout import Configuration, Payment

idemp_key = uuid.uuid4()

print(idemp_key)

Configuration.account_id = 'test_656330'
Configuration.secret_key = 'test_iGJ8jf2z8j8tWXgb8VKuwWZ3UD_69xrKiX7iqDHIcEc'

payment = Payment.create(
    {
        "amount": {
            "value": "100.00",
            "currency": "RUB"
        },
        "confirmation": {
            "type": "redirect",
            "return_url": "https://www.merchant-website.com/return_url"
        },
        "capture": True,
        "description": "Заказ №1"
    }, idemp_key)
Beispiel #28
0
    def post(self, request, marathon_id):
        user = self.request.user
        if not models.Account.objects.filter(user=user).exists():
            return HttpResponseRedirect('/')

        log = models.Logging.objects.create(action="Создание платежа в Яндекс кассе. api/views.YandexPayment.post()")
        account = user.account
        result = {}

        # lesson_num = request.POST.get('open_widget')

        try:
            marathon = models.Marathon.objects.get(pk=marathon_id)
            # есть ли актуальный (не просроченный) платеж за урок
            earlyer_pay = models.Payment.objects.filter(
                account=account, marathon=marathon, date_approve__gte=timezone.now() - datetime.timedelta(days=62)
            ).exists()
            if earlyer_pay:
                raise Exception('Payment exists')
        except:
            result['error'] = 'Ошибка данных для формирования нового платежа'
            return HttpResponseRedirect('/me')

        if marathon.cost == 0:
            try:
                new_payment = models.Payment.objects.create(account=account,
                                                        marathon=marathon,
                                                        date_pay=timezone.now(),
                                                        date_approve=timezone.now(),
                                                        status="succeeded")
                log.input_data = f"account {account.user.username}\nmarathon {marathon.pk}\ntime  {timezone.now()}\n"
                log.output_data = f"payment_pk {new_payment.pk},\nuuid {new_payment.pk}"
                log.result = log.SUCCESS
                log.save()
            except Exception as exc:
                log.result = log.FAIL
                log.output_data = f"{exc}"
                log.save()

            return HttpResponseRedirect(f'/me?marathon={marathon.pk}')

        try:
            idempotence_key = uuid.uuid4()
            Configuration.account_id = shopid
            Configuration.secret_key = yandex_api_key
            payment_params = {
                "amount": {
                    "value": f"{marathon.cost}.00",
                    "currency": "RUB"
                },
                "confirmation": {
                    "type": "embedded"
                },
                "capture": True,
                "description": f"Марафон {marathon.title[:75]}",
                "receipt": {
                    "customer": {
                        "full_name": f"{account.user.get_full_name()}",
                        "phone": f"{account.phone}",
                        "email": f"{account.user.email}",
                    },
                    "items": [
                        {
                            "description": f"Марафон {marathon.title[:75]}",
                            "quantity": "1.00",
                            "amount": {
                                "value": f"{marathon.cost}.00",
                                "currency": "RUB"
                            },
                            "vat_code": "1",
                            # TODO    1-Без НДС 2-НДС по ставке 0% 3-НДС по ставке 10% 4-НДС чека по ставке 20% 5-НДС чека по расчетной ставке 10/110 6 	НДС чека по расчетной ставке 20/120
                            "payment_mode": "full_prepayment",
                            "payment_subject": "intellectual_activity",
                            "save_payment_method": False,
                            # "receipt_phone":""
                        }
                    ]
                }}
            payment = Payment.create(payment_params, idempotence_key)
            payment_dict = {key: value.__dict__ if isinstance(value, BaseObject) else value for key, value in
                            payment.__dict__.items()}
            log.input_data = f"{shopid}\n{yandex_api_key}\n{payment_params}\n{idempotence_key}"
        except Exception as err:
            log.result = log.FAIL
            log.output_data = f"{err}"
            log.save()
        else:
            new_payment = models.Payment.objects.create(uuid=idempotence_key,
                                                        amount=marathon.cost,
                                                        account=account,
                                                        marathon=marathon,
                                                        request=f"{shopid}\n{yandex_api_key}\n{payment_params}\n{idempotence_key}",
                                                        response=f"{payment_dict}",
                                                        yuid=payment.id,
                                                        status=payment.status,
                                                        confirmation_token=payment.confirmation.confirmation_token)
            log.result = log.SUCCESS
            log.output_data = f"{payment_dict}"
            log.save()
            return HttpResponseRedirect(f'/api/payment/widget/{idempotence_key}')
        return HttpResponseRedirect(f'/me')
Beispiel #29
0
def cart(request):
    try:
        order = Order.objects.get(user=request.session.session_key,
                                  status=Order.PENDING)
        items = OrderItem.objects.filter(
            order=order,
            order__status=Order.PENDING,
        )
        categories = Category.objects.all()
        total = sum([item.item.price * item.quantity for item in items])

        content = {
            'items': items,
            'order': order,
            'categories': categories,
            'total': total
        }

    except mainapp.models.Order.DoesNotExist:
        content = {}

    if request.method == 'POST':
        if request.POST.get('delivery-type', None) == 'card':
            idempotence_key = str(uuid.uuid4())
            payment = Payment.create(
                {
                    "amount": {
                        "value": float(total),
                        "currency": "RUB"
                    },
                    "payment_method_data": {
                        "type": "bank_card",
                        "card": {
                            "number":
                            request.POST.get('card-number', None),
                            "expiry_year":
                            str(request.POST.get('expiry_year', None)),
                            "expiry_month":
                            str(request.POST.get('expiry_month', None)),
                            "cardholder":
                            request.POST.get('cardholder', None),
                        },
                    },
                    "confirmation": {
                        "type": "redirect",
                        "return_url": "https://www.vagonka40.ru/"
                    },
                    "description": "Заказ в vagonka40.ru"
                }, idempotence_key)

            # get confirmation url
            payment_id = payment.id

            idempotence_key = str(uuid.uuid4())
            response = Payment.capture(
                payment_id,
                {"amount": {
                    "value": float(total),
                    "currency": "RUB"
                }}, idempotence_key)

            order.delivery_type = Order.CARD
        else:
            order.delivery_type = Order.PICKUP

        order.email = request.POST['email']
        order.name = request.POST['name']
        order.phone = request.POST['phone']
        order.status = Order.COMPLETED
        order.save()
        return HttpResponseRedirect(reverse('confirmation'))

    return render(request, 'mainapp/cart.html', content)
Beispiel #30
0
def payment_process(*args, order_id):
    Configuration.account_id = YANDEX_ID
    Configuration.secret_key = YANDEX_KEY
    # Configuration.account_id = TEST_YANDEX_ID
    # Configuration.secret_key = TEST_YANDEX_KEY
    order = Order.published.get(id=order_id)
    value = float(order.get_total_cost() + order.deliver_cost)

    json_yandex = {
        "amount": {
            "value": value,
            "currency": "RUB"
        },
        "description": 'Номер заказа: {} от {}'.format(order.id, order.created.date()),
        "metadata": {
            "order_id": order.id
        },
        "capture": True,
        "confirmation": {
            "type": "redirect",
            "return_url": "https://mrpit.online"
        },
        "receipt": {
            "customer": {
                "full_name": order.client.username,
                "email": order.email,
                "phone": order.phone
            },
            "items": [
            ]
        },
    }
    items = order.items.all()
    for item in items:
        item = {
            "description": item.flavour.product,
            "quantity": item.quantity,
            "amount": {
                "value": item.price,
                "currency": "RUB"
            },
            "vat_code": "2",
            "payment_mode": "full_prepayment",
            "payment_subject": "commodity"
        }
        json_yandex["receipt"]["items"].append(item)
    delivery_item = {
        "description": "Доставка",
        "quantity": "1",
        "amount": {
            "value": order.deliver_cost,
            "currency": "RUB"
        },
        "vat_code": "2",
        "payment_mode": "full_prepayment",
        "payment_subject": "commodity"
    }
    json_yandex["receipt"]["items"].append(delivery_item)

    payment = Payment.create(json_yandex)

    return redirect(payment.confirmation.confirmation_url)