示例#1
0
def create_payment_intent(request):
    stripe.api_key = settings.STRIPE_KEY

    value = request.POST.get("value", None)
    if not value:
        return Response({'error': 'Value must exist.'},
                        status=status.HTTP_200_OK)

    value = int(value) * 100

    if value < 1:
        return Response({'error': 'Value must be greater than or equal to 1.'},
                        status=status.HTTP_200_OK)

    uuid = request.POST.get("user", None)
    if not uuid:
        return Response({'error': 'ID must exist.'}, status=status.HTTP_200_OK)

    profile = Profile.objects.filter(uuid=uuid)
    if not profile:
        return Response({'error': 'This profile doesn\'t exist.'},
                        status=status.HTTP_200_OK)
    profile = profile.first()

    payment = Payment()
    payment.entertainer = profile
    payment.save()

    session = stripe.checkout.Session.create(
        payment_method_types=['card'],
        line_items=[{
            'name':
            'Donation to ' + profile.entertainer_name,
            'amount':
            value,
            'currency':
            'aud',
            'quantity':
            1,
            'description':
            'Thank you for your donation to ' + profile.entertainer_name,
            'images': [
                "{0}{1}{2}".format(settings.BASE_API_URL, settings.MEDIA_URL,
                                   profile.logo)
            ],
        }],
        payment_intent_data={
            'application_fee_amount': int(0.02 * value),
            'transfer_data': {
                'destination': profile.stripe_id,
            },
        },
        success_url=settings.BASE_URL + 'confirmation/' + str(payment.uuid),
        cancel_url=settings.BASE_URL + 'tip-user/' + str(profile.uuid),
    )

    payment.stripe_id = session.payment_intent
    payment.save()

    return Response({'client_secret': session}, status=status.HTTP_200_OK)
示例#2
0
    def create(self, validated_data):
        """Crear pago de especialista."""
        match = validated_data.pop('match')
        instance = Payment(**validated_data)
        instance.save()
        match.status = 5
        if 'test' not in sys.argv:
            client_id = match.client_id
            specialist_id = match.specialist_id
            qset_client = Client.objects.filter(pk=client_id)
            qset_spec = Specialist.objects.filter(pk=specialist_id)
            dict_pending = NotificationClientSerializer(qset_client).data
            dict_pending_sp = NotificationSpecialistSerializer(qset_spec).data
            badge_count = dict_pending["queries_pending"] + dict_pending[
                "match_pending"]
            badge_count_sp = dict_pending_sp[
                "queries_pending"] + dict_pending_sp["match_pending"]
            disp_name = display_specialist_name(match)
            disp_name_to_specialist = display_client_name(match.client)
            data_notif_push = {
                "title": disp_name,
                "body": match.subject,
                "sub_text": "",
                "ticker": trans("successful hiring"),
                "badge": badge_count,
                "icon": match.category.image,
                "type": Params.TYPE_NOTIF["match_success"],
                "queries_pending": dict_pending["queries_pending"],
                "match_pending": dict_pending["match_pending"],
                "match_id": match.id
            }
            data_specialist = {
                "title": disp_name_to_specialist,
                "body": match.subject,
                "sub_text": "",
                "ticker": trans("successful hiring"),
                "badge": badge_count_sp,
                "icon": match.category.image,
                "type": Params.TYPE_NOTIF["match_success"],
                "queries_pending": dict_pending_sp["queries_pending"],
                "match_pending": dict_pending_sp["match_pending"],
                "match_id": match.id
            }
            # envio de notificacion push
            Notification.fcm_send_data(user_id=client_id, data=data_notif_push)

            Notification.fcm_send_data(user_id=specialist_id,
                                       data=data_specialist)
        match.save()

        sellercontact = match.client.sellercontact_set.get()
        sellercontact.type_contact = 3
        sellercontact.save()

        sale = match.sale_detail.sale
        sale.status = 3
        sale.save()

        return instance
示例#3
0
def add_payment(request):
    payment = Payment(
        date=request.GET['date'],
        pay_out=request.GET['pay_out'],
        pay_in=request.GET['pay_in'],
    )
    payment.save()
    return HttpResponse("OK")
示例#4
0
def order_payment(request):
    token = request.headers.get('token')
    token = Token.objects.filter(token=token)
    if token.exists():
        if request.method == 'POST':
            try:
                info = loads(request.body.decode('utf-8'))
                user = token[0].user
                o_id = info['orderId']
                trans_id = info['transactionId']
                trans_time = info['transactionTime']
                st = info['status']
                amount = info['amount']

                payment = Payment(user=user,
                                  order_id=o_id,
                                  trans_id=trans_id,
                                  status=st,
                                  amount=amount,
                                  trans_time=trans_time)
                payment.save()

                if st == 'FAILED':
                    return my_response(False, 'transaction failed',
                                       payment.to_json())
                else:
                    o = Order.objects.filter(order_id=o_id)
                    o.update(completed=True)
                    o = o.first()
                    notif_to_admin(
                        orderId=o_id,
                        title='order payment',
                        message='user paid for his order with trackId: ' +
                        str(o.track_id))
                    return my_response(True, 'success', payment.to_json())

            except Exception as e:
                return my_response(
                    False,
                    'error in payment order, check body send, ' + str(e), {})
        elif request.method == 'GET':
            if token[0].is_admin:
                pays = Payment.objects.all()
            else:
                pays = Payment.objects.filter(user=token[0].user)
            _list = []
            for p in pays:
                _list.append(p.to_json())
            return my_response(True, 'success', _list)
        else:
            return my_response(False, 'invalid method', {})
    else:
        return my_response(False, 'token not exist', {})
示例#5
0
def import_payments(request):
    if request.method == 'POST':
        Employee.objects.all().delete()
        req_body = request.FILES['file'].read()
        payments_dict = simplexml.loads(req_body)['payments']
        for p in payments_dict:
            payment_tosave = Payment(method=p['method'],
                                     raw_salary=p['raw_salary'],
                                     tax_rate=p['tax_rate'])
            payment_tosave.save()
        return HttpResponse(status=200)
    return HttpResponse(status=400)
示例#6
0
    def create(self, validated_data):
        """Metodo para confirmar pago."""
        fee = validated_data["monthly_fee"]
        # cambio el estatus de la cuota a pago
        # 2 PAID
        fee.status = 2
        fee.save()

        qsetdetail = SaleDetail.objects.filter(sale=fee.sale)
        # devolver plan name, validity_months, y query quantity de los productos adquiridos
        # mostrarlos en  la data
        data = {'qset': qsetdetail}
        # envio codigo pin por correo y aviso en push notification
        if fee.sale.status == 1:
            body = "Revisa tu correo, te enviamos tu codigo PIN"
            if qsetdetail.count() > 1:
                body = "Revisa tu correo, te enviamos tus codigos PIN"
            mail = BasicEmailAmazon(
                subject="Confirmación de pago. Productos comprados",
                to=fee.sale.client.username,
                template='email/pin_code')
            if 'test' not in sys.argv:
                mail.sendmail(args=data)
                qset_client = Client.objects.filter(pk=fee.sale.client_id)
                dict_pending = NotificationClientSerializer(qset_client).data
                badge_count = dict_pending["queries_pending"] + dict_pending[
                    "match_pending"]
                data_notif_push = {
                    "title": "Se ha validado tu pago",
                    "body": body,
                    "sub_text": "",
                    "ticker": "",
                    "badge": badge_count,
                    "icon":
                    'http://linkup-lb-09-916728193.us-east-1.elb.amazonaws.com/static/dashboard/dist/img/logo_grande.png',
                    "type": Params.TYPE_NOTIF["PIN"],
                    "queries_pending": dict_pending["queries_pending"],
                    "match_pending": dict_pending["match_pending"]
                }
                # envio de notificacion push
                Notification.fcm_send_data(user_id=fee.sale.client_id,
                                           data=data_notif_push)
        # buscar contacto efectivo para acualitzar estado a efectivo cliente
        # filtar por el correo del id del cliente
        SellerContact.objects.filter(
            email_exact=fee.sale.client.username).update(type_contact=3)
        # compruebo si no hay mas cuotas pendientes por pagar
        if MonthlyFee.objects.filter(sale=fee.sale, status=1).exists():
            # cambio el estatus de la ventas
            # 2 Progreso
            Sale.objects.filter(pk=fee.sale_id).update(status=2)
        else:
            # 3 pagada
            Sale.objects.filter(pk=fee.sale_id).update(status=3)

        for detail in qsetdetail:
            qacd = QueryPlansAcquired.objects.get(sale_detail=detail,
                                                  queryplansclient__owner=True)
            qpclient = qacd.queryplansclient_set.get()

            # debo chequear si es por cuotas o no
            if fee.sale.is_fee:
                new_queries = qacd.query_plans.query_quantity / qacd.query_plans.validity_months
                # libero el numero de consultas que corresponde
                qacd.available_queries += new_queries
                # actualizo cuantas consultas faltan por pagar
                qacd.queries_to_pay -= new_queries
            else:
                # libero el numero de consultas que corresponde
                qacd.available_queries = qacd.query_plans.query_quantity
                # actualizo cuantas consultas faltan por pagar
                qacd.queries_to_pay = 0
            if fee.sale.status == 1:
                qacd.status = 3
            qacd.save()
            # actualizo a pyrebase si es el elegido
            if 'test' not in sys.argv:
                if qpclient.is_chosen:
                    pyrebase.chosen_plan(
                        fee.sale.client.id,
                        {"available_queries": qacd.available_queries})
        # cambio el codigo del usuario
        user = User.objects.get(pk=fee.sale.client_id)
        if fee.sale.client.type_client == 'b':
            user.code = Params.CODE_PREFIX["client"] + user.ruc
        else:
            user.code = Params.CODE_PREFIX["client"] + user.document_number
        user.save()
        validated_data["status"] = 2
        instance = Payment(**validated_data)
        instance.save()
        return instance
示例#7
0
    def create(self, validated_data):
        """Crear pago de especialista."""
        match = validated_data.pop('match')
        # import pdb; pdb.set_trace()
        match = Match.objects.get(pk=match.id)
        instance = Payment(**validated_data)
        instance.save()
        match.specialist_payment = instance
        client = match.client
        # se verifica si ya fue cliente el usuario que solicito el match
        # si ya lo fue pasa a status 5 directo sino pasa a 4. pendiente de pago
        is_client = Sale.objects.filter(saledetail__is_billable=True,
                                        client=client,
                                        status__range=(2, 3)).exists()
        if is_client:
            match.status = 5
            disp_name_to_client = display_specialist_name(match)
            ticker_client = trans("successful hiring")
            disp_name_to_specialist = display_client_name(client)
            ticker_specialist = trans("successful hiring")
        else:
            match.status = 4
            disp_name_to_client = "Sube el recibo de tu pago"
            ticker_client = "Realiza tu pago, procederemos con tu solicitud"
            ticker_specialist = "Espera por el pago del cliente"
            disp_name_to_specialist = "Se autorizo pago"

            sale = Sale.objects.create(place="BCP",
                                       total_amount=match.price,
                                       reference_number=increment_reference(),
                                       description='pago de match',
                                       client=match.client,
                                       status=1)

            sale_detail = SaleDetail.objects.create(
                price=match.price,
                description="Contratacion de especialista",
                discount=float(0),
                pin_code='XXXXXX',
                is_billable=True,
                product_type_id=2,
                sale=sale)

        if 'test' not in sys.argv:
            client_id = match.client_id
            specialist_id = match.specialist_id
            qset_client = Client.objects.filter(pk=client_id)
            qset_spec = Specialist.objects.filter(pk=specialist_id)
            dict_pending_cl = NotificationClientSerializer(qset_client).data
            dict_pending_sp = NotificationSpecialistSerializer(qset_spec).data
            badge_count = dict_pending_cl["queries_pending"] + dict_pending_cl[
                "match_pending"]
            badge_count_sp = dict_pending_sp[
                "queries_pending"] + dict_pending_sp["match_pending"]
            data_client = {
                "title": disp_name_to_client,
                "body": match.subject,
                "sub_text": "",
                "ticker": ticker_client,
                "badge": badge_count,
                "icon": match.category.image,
                "type": Params.TYPE_NOTIF["match_success"],
                "queries_pending": dict_pending_cl["queries_pending"],
                "match_pending": dict_pending_cl["match_pending"],
                "match_id": match.id
            }
            data_specialist = {
                "title": disp_name_to_specialist,
                "body": match.subject,
                "sub_text": "",
                "ticker": ticker_specialist,
                "badge": badge_count_sp,
                "icon": match.category.image,
                "type": Params.TYPE_NOTIF["match_success"],
                "queries_pending": dict_pending_sp["queries_pending"],
                "match_pending": dict_pending_sp["match_pending"],
                "match_id": match.id
            }
            # envio de notificacion push
            Notification.fcm_send_data(user_id=client_id, data=data_client)
            Notification.fcm_send_data(user_id=specialist_id,
                                       data=data_specialist)
        match.save()
        return instance