Beispiel #1
0
    def post(self, request:HttpRequest, *args, **kwargs) -> APIResponse:
        """
        """

        data = request.body.decode('utf-8')
        json_data = json.loads(data)

        payout = paypalrestsdk.Payout({
            "sender_batch_header": {
                "sender_batch_id": ''.join(random.choice(string.ascii_uppercase) for i in range(12)),
                "email_subject": "You have a payment"
            },
            "items": [{
                "recipient_type": "EMAIL",
                "amount": {
                    "value": json_data["amount"],
                    "currency": "EUR"
                },
                "receiver": json_data["receiver"],
                "note": "Take my test money",
                "sender_item_id": "item_0"
            }]
        })

        if payout.create(sync_mode=False):
            return APIResponse(HTTPStatus.OK, _("Payout %(payout_batch_id)d created successfully") % {'payout_batch_id': payout.batch_header.payout_batch_id})
        else:
            return APIResponse(HTTPStatus.INTERNAL_SERVER_ERROR, payout.error)
Beispiel #2
0
 def post(self, request:HttpRequest, *args, **kwargs) -> APIResponse:
     try:
         data = request.body.decode('utf-8')
         json_data = json.loads(data)
     except JSONDecodeError:
         return APIResponse(HTTPStatus.NO_CONTENT, _("A content is required to create %(verbose_name)s") % {'verbose_name' : self.singular_name})
     object_: JSONMixin = self.model.objects.create(name=json_data['name'])
     object_.users.add(*User.objects.filter(id__in=json_data['users'].split(",")))
     return APIResponse(HTTPStatus.CREATED, _("%(verbose_name_plural)s created successfully") % {'verbose_name_plural': self.plural_name}, object_.serialize(request))
Beispiel #3
0
    def post(self, request, **kwargs):
        data = request.body.decode('utf-8')
        json_data = json.loads(data)

        user = authenticate(username=json_data['username'], password=json_data['password'])
        if user is not None:
            token = Token({'uid': user.id})
            token.sign()
            return APIResponse(HTTPStatus.OK, "User logged in", {'token': str(token), 'user': user.serialize(request)})
        else:
            return APIResponse(HTTPStatus.UNAUTHORIZED, "Wrong user credentials")
Beispiel #4
0
    def get(self, request:HttpRequest, *args, **kwargs) -> APIResponse:
        """
        """

        payment_id = request.GET.get("paymentId")
        db_payment = Payment.objects.get(payments__contains=[payment_id])
        if db_payment.payments[payment_id] == Payment.STATUS.COMPLETED:
            return APIResponse(HTTPStatus.FORBIDDEN, _("Your payment is already completed"))
        db_payment.payments[payment_id] = Payment.STATUS.FAILED
        db_payment.save()
        return redirect(f"http://pp.split2021.live/#/result?title=Annule&msg={_('Paiement annulé')}")
Beispiel #5
0
 def get(self, request, *args, **kwargs):
     if 'distance' in request.GET:
         distance =  request.GET.pop('distance')
         if not 'user' in request.GET:
             return APIResponse(HTTPStatus.BAD_REQUEST, "distance lookup needs the user lookup")
         user_id = request.GET.pop('user')
         user = User.objects.get(id=user_id)
         # p = pi/180
         # a = 0.5 - cos((lat2-lat1)*p)/2 + cos(lat1*p) * cos(lat2*p) * (1-cos((lon2-lon1)*p))/2
         # offer_distance = 12742 * asin(sqrt(a)) #2*R*asin...
         self.queryset = self.queryset.annotate(distance=Func(F('latitude') - user.latitude, function='ABS') + Func(F('longitude') - user.longitude, function='ABS')).filter(distance__lte=distance)
     return super().get(request, *args, **kwargs)
Beispiel #6
0
    def post(self, request:HttpRequest, id:int, *args, **kwargs) -> APIResponse:
        """
        """

        try:
            db_payment = Payment.objects.get(id=id)
        except ObjectDoesNotExist as e:
            return NotFound(str(e))
        failed = list()

        for payment in db_payment.payments.values():
            if payment['status'] != Payment.STATUS.COMPLETED:
                if payment['status'] == Payment.STATUS.PROCESSING:
                    payment['status'] = Payment.STATUS.REFUNDED
                continue

            sale_id = payment['sale_id']
            sale = paypalrestsdk.Sale.find(sale_id)

            refund = sale.refund({
                "amount": {
                    "total": payment['amount'],
                    "currency": db_payment.currency
                }
            })
            if not refund.success():
                failed.append(sale_id)
            else:
                payment['status'] = Payment.STATUS.REFUNDED

        db_payment.save()

        if failed:
            return APIResponse(HTTPStatus.OK, _("Refund failed for %(payments_failed)s") % {'payments_faled': ', '.join(failed)})
        else:
            return APIResponse(HTTPStatus.OK, _("Refund successful"))
Beispiel #7
0
 def get(self, request, **kwargs):
     return APIResponse(
         HTTPStatus.OK, "URLs available",
         list(set(v[1] for v in get_resolver(None).reverse_dict.values())))
Beispiel #8
0
    def post(self, request:HttpRequest, *args, **kwargs) -> APIResponse:
        """
        """

        data = request.body.decode('utf-8')
        json_data = json.loads(data)

        currency = json_data.get('currency') or "EUR"

        group_id = json_data.get('group')
        if group_id is None or not PaymentGroup.objects.filter(id=group_id).exists():
            return APIResponse(HTTPStatus.BAD_REQUEST, _("A payment cannot be created without a group"))

        total = round(json_data['total'], 2)
        users_mail = json_data['users']
        if not users_mail:
            return APIResponse(HTTPStatus.BAD_REQUEST, _("A payment cannot be created without at least one user"))
        if User.objects.filter(email__in=users_mail).count() != len(users_mail):
            return APIResponse(HTTPStatus.BAD_REQUEST, _("At least one user does not exist"))

        user_sum = round(sum(users_mail.values()), 2)
        if user_sum != total:
            return APIResponse(HTTPStatus.BAD_REQUEST, _("Total (%(total)d) does not match users sum (%(user_sum)d)") % {'total': total, 'user_sum': user_sum})
        target = json_data['target']

        payments_links = {}
        db_payment = Payment.objects.create(group_id=group_id, currency=currency, total=total, target=target)
        for mail, price in users_mail.items():
            payment = paypalrestsdk.Payment({
                "intent": "sale",
                "payer": {
                    "payment_method": "paypal"
                },
                "redirect_urls": {
                    "return_url": f"http://{request.get_host()}/api/payment/execute",
                    "cancel_url": f"http://{request.get_host()}/api/payment/cancel"},
                "transactions": [{
                    "item_list": {
                        "items": [{
                            "name": "item",
                            "sku": "item",
                            "price": price,
                            "currency": currency,
                            "quantity": 1
                        }
                    ]},
                    "amount": {
                        "total": price,
                        "currency": currency
                    },
                    "description": "Test payment from Split API"
                }]
            })
            if not payment.create():
                return APIResponse(HTTPStatus.INTERNAL_SERVER_ERROR, _("Failed to create payment for user %(mail)s") % {'mail': mail})
            payments_links[mail] = list((link.method, link.href, price) for link in payment.links)
            db_payment.payments[payment.id] = {'status': Payment.STATUS.PROCESSING, 'amount': price}

        db_payment.save()
        payments_links['id'] = db_payment.id
        return APIResponse(HTTPStatus.OK, _("Sucessfully created payments"), payments_links)