Exemplo n.º 1
0
def payment_pagodigital(request):
    # Vars
    integrator = Integrator.get('pagodigital')
    baseurl = Setting.get_var('baseurl')
    template = 'pagodigital/pagodigital.html'

    # Verifico ApiKey
    cap = __check_apikey(request)
    if cap['status'] == 'error':
        return HttpResponse(status=http_UNAUTHORIZED)

    # Cargo el JSON
    try:
        data = json.loads(request.body)
        print "CONTENT MA: %s" % data
    except Exception:
        message = 'error decoding json'
        body = {'status': 'error', 'message': message}
        return HttpResponse(json.dumps(body),
                            content_type='application/json',
                            status=http_BAD_REQUEST)

    # Verifico las key mandatorias
    keys = ['user_id', 'email', 'payment_date', 'recurrence']
    json_loader = __validate_json(data, keys)

    if json_loader['status'] == 'error':
        return HttpResponse(json.dumps(json_loader),
                            content_type='application/json',
                            status=http_BAD_REQUEST)

    # Verifico si el usuario existe y sino lo creo
    try:
        user = User.objects.get(user_id=data['user_id'])
        user.email = data['email']
        user.save()
    except ObjectDoesNotExist:
        user = User.create(data['user_id'], data['email'], integrator.country)

    # Verifico que no tenga un User Payment activo
    up = UserPayment.get_active(user)
    if up is not None:
        if up.enabled_card:
            message = 'enabled user payment already exists'
            body = {'status': 'error', 'message': message}
            return HttpResponse(json.dumps(body),
                                content_type='application/json',
                                status=http_BAD_REQUEST)
        else:
            up.status = 'PE'
            up.save()

    # Obtengo el paquete
    if 'package_id' in data:
        package = Package.get_by_id(data['package_id'], integrator)
    else:
        package = Package.get(data['recurrence'], integrator)

    if package is None:
        message = "package not found with that duration"
        body = {'status': 'error', 'message': message}
        return HttpResponse(json.dumps(body),
                            content_type="application/json",
                            status=http_BAD_REQUEST)

    # Creo UserPayment
    up = UserPayment.create_from_package(user, package, data['payment_date'],
                                         0, 0, True)

    # Aplico descuento si existe
    if 'discount' in data and 'disc_counter' in data:
        up.discount(data['discount'], data['disc_counter'])

    # Creo el form
    form = Form.create(user, up, integrator, template, 'UP', package)
    if form is None:
        message = "form could not be created"
        body = {'status': 'error', 'message': message}
        return HttpResponse(json.dumps(body),
                            content_type="application/json",
                            status=http_INTERNAL_ERROR)

    iframe_params = {'user_id': user.user_id, 'token': form.token}
    iframe_url = '%sapi/v1/pagodigital/userpayment/form/?%s' % (
        baseurl, urlencode(iframe_params))
    body = {'status': 'success', 'value': {'url': iframe_url}}

    return HttpResponse(json.dumps(body),
                        content_type="application/json",
                        status=http_POST_OK)
Exemplo n.º 2
0
def payment_commercegate(request):
    # Verifico ApiKey
    cap = __check_apikey(request)
    if cap['status'] == 'error':
        return HttpResponse(status=http_UNAUTHORIZED)

    # Cargo el JSON
    try:
        data = json.loads(request.body)
        print "CONTENT MA: %s" % data
    except Exception:
        message = 'error decoding json'
        body = {'status': 'error', 'message': message}

        return HttpResponse(json.dumps(body),
                            content_type='application/json',
                            status=http_BAD_REQUEST)

    # Verifico las key mandatorias
    keys = ['user_id', 'email', 'recurrence']

    json_loader = __validate_json(data, keys)

    if json_loader['status'] == 'error':
        json_loader[
            'message'] = 'Ocurrió un error con el pago, por favor reintente nuevamente más tarde'

        return HttpResponse(json.dumps(json_loader),
                            content_type='application/json',
                            status=http_BAD_REQUEST)

    # Obtengo pais
    country = Country.get_by_code(data['user_id'].split("_")[0].lower())

    # Obtengo Integrador
    integrator = Integrator.get_by_country('commerce_gate', country)
    if integrator is None:
        message = "integrator does not exist for country %s" % country.name
        body = {'status': 'error', 'message': message}
        return HttpResponse(json.dumps(body),
                            content_type="application/json",
                            status=http_BAD_REQUEST)

    # Obtengo Integrator Settings
    redirect_url_failed = IntegratorSetting.get_var(integrator,
                                                    'redirect_url_failed')
    redirect_url_success = IntegratorSetting.get_var(integrator,
                                                     'redirect_url_success')
    endpoint = IntegratorSetting.get_var(integrator, 'endpoint')
    endpoint_token = IntegratorSetting.get_var(integrator, 'endpoint_token')
    website_id = IntegratorSetting.get_var(integrator, 'website_id')
    customer_id = IntegratorSetting.get_var(integrator, 'customer_id')

    # Verifico si el usuario existe y sino lo creo
    try:
        user = User.objects.get(user_id=data['user_id'])
        user.email = data['email']
        user.save()
    except ObjectDoesNotExist:
        user = User.create(data['user_id'], data['email'], integrator.country)

    # Obtengo el paquete
    if 'package_id' in data:
        package = Package.get_by_id(data['package_id'], integrator)
    else:
        package = Package.get(data['recurrence'], integrator)

    if package is None:
        message = "package not found with that duration"
        body = {'status': 'error', 'message': message}

        return HttpResponse(json.dumps(body),
                            content_type="application/json",
                            status=http_BAD_REQUEST)

    # Si tiene algun UserPayment habilitado devuelvo un error
    up = UserPayment.get_active(user)
    if up is not None:
        message = 'enabled user payment already exists'
        body = {'status': 'error', 'message': message}
        return HttpResponse(json.dumps(body),
                            content_type='application/json',
                            status=http_BAD_REQUEST)
    else:
        up = UserPayment.create_from_package(user, package)

    payment_id = "PH_%s_%d" % (user.user_id, int(time()))

    # Creo el PaymentHistory
    ph = PaymentHistory.create(up, payment_id, integrator)

    params = {
        'cid': customer_id,
        'wid': website_id,
        'packid': package.package_id,
        'username': data['user_id'],
        'email': data['email']
    }
    url = '%s?%s' % (endpoint_token, urlencode(params))

    try:
        resp, content = Http().request(url, 'POST')
    except Exception as e:
        message = "communication error with commercegate, waiting callback"
        body = {'status': 'error', 'message': message}

        return HttpResponse(json.dumps(body),
                            content_type="application/json",
                            status=http_PAYMENT_REQUIRED)

    iframe_params = {'cid': customer_id, 'wid': website_id, 'token': content}

    if redirect_url_success:
        iframe_params['successUrl'] = redirect_url_success

    if redirect_url_failed:
        iframe_params['failedUrl'] = "%s://%s/commercegate/error/%s" % (
            request.scheme, request.META['HTTP_HOST'], up.user_payment_id)

    iframe_url = '%s?%s' % (endpoint, urlencode(iframe_params))
    body = {'status': 'success', 'value': {'url': iframe_url}}

    return HttpResponse(json.dumps(body),
                        content_type="application/json",
                        status=http_POST_OK)
Exemplo n.º 3
0
def create_payment(request):
    # Verifico ApiKey
    cap = __check_apikey(request)
    if cap['status'] == 'error':
        return HttpResponse(status=http_UNAUTHORIZED)

    # Cargo el json
    try:
        data = json.loads(request.body)
        print "CONTENT MA: %s" % data
    except Exception:
        user_message = "Ocurrió un error con el pago, por favor reintente nuevamente más tarde"
        message = "error decoding json"
        body = {
            'status': 'error',
            'message': message,
            "user_message": user_message
        }
        return HttpResponse(json.dumps(body),
                            content_type="application/json",
                            status=http_BAD_REQUEST)

    # Verifico las key mandatorios del json
    keys = [
        'user_id', 'email', 'country', 'token', 'card_number', 'card_exp',
        'card_type', 'integrator', 'amount', 'currency', 'payment_date',
        'recurrence'
    ]
    json_loader = __validate_json(data, keys)
    if json_loader['status'] == 'error':
        json_loader[
            'user_message'] = "Ocurrió un error con el pago, por favor reintente nuevamente más tarde"
        return HttpResponse(json.dumps(json_loader),
                            content_type="application/json",
                            status=http_BAD_REQUEST)

    # Verifico que la currency exista
    try:
        currency = Currency.objects.get(code=data['currency'].lower())
    except ObjectDoesNotExist:
        user_message = "Ocurrió un error con el pago, por favor reintente nuevamente más tarde"
        message = "currency %s does not exist" % data['currency']
        body = {
            'status': 'error',
            'message': message,
            'user_message': user_message
        }
        return HttpResponse(json.dumps(body),
                            content_type="application/json",
                            status=http_BAD_REQUEST)

    # Verifico que el pais exista
    try:
        country = Country.objects.get(code=data['country'].lower())
    except ObjectDoesNotExist:
        user_message = "Ocurrió un error con el pago, por favor reintente nuevamente más tarde"
        message = "country %s does not exist" % data['country']
        body = {
            'status': 'error',
            'message': message,
            'user_message': user_message
        }
        return HttpResponse(json.dumps(body),
                            content_type="application/json",
                            status=http_BAD_REQUEST)

    # Verifico que el integrador exista
    try:
        integrator = Integrator.objects.get(name=data['integrator'],
                                            country=country)
    except ObjectDoesNotExist:
        user_message = "Ocurrió un error con el pago, por favor reintente nuevamente más tarde"
        message = "integrator %s does not exist for country %s" % (
            data['integrator'], country.name)
        body = {
            'status': 'error',
            'message': message,
            'user_message': user_message
        }
        return HttpResponse(json.dumps(body),
                            content_type="application/json",
                            status=http_BAD_REQUEST)

    # Verifico si el usuario existe y sino lo creo
    try:
        user = User.objects.get(user_id=data['user_id'])
        user.email = data['email']
        user.save()
    except ObjectDoesNotExist:
        user = User.create(data['user_id'], data['email'], country)

    # Si tiene algun UserPayment habilitado devuelvo un error
    if UserPayment.objects.filter(user=user, enabled=True).exists():
        user_message = "Ocurrió un error con el pago, por favor reintente nuevamente más tarde"
        message = "enabled user payment already exists"
        body = {
            'status': 'error',
            'message': message,
            'user_message': user_message
        }
        return HttpResponse(json.dumps(body),
                            content_type="application/json",
                            status=http_BAD_REQUEST)

    # Desabilito cualquier otra tarjeta del usuario
    cards = Card.objects.filter(user=user, enabled=True)
    for card in cards:
        card.disable()

    # Creo la tarjeta si no existe con el metodo del integrador
    if integrator.method == 'TO':
        card = __get_card(user, data['token'])
        if card is not None:
            card.enable()
        else:
            # Creo la nueva tarjeta
            try:
                card = Card.create_with_token(user, data['token'],
                                              data['card_number'],
                                              data['card_exp'],
                                              data['card_type'], integrator)
            except Exception:
                user_message = "Ocurrió un error con el pago, por favor reintente nuevamente más tarde"
                message = "new card could not be created"
                body = {
                    'status': 'error',
                    'message': message,
                    'user_message': user_message
                }
                return HttpResponse(json.dumps(body),
                                    content_type="application/json",
                                    status=http_INTERNAL_ERROR)
    else:
        user_message = "Ocurrió un error con el pago, por favor reintente nuevamente más tarde"
        message = "integrator %s unknown" % integrator.method
        body = {
            'status': 'error',
            'message': message,
            'user_message': user_message
        }
        return HttpResponse(json.dumps(body),
                            content_type="application/json",
                            status=http_INTERNAL_ERROR)

    # Obtengo el paquete
    if 'package_id' in data:
        package = Package.get_by_id(data['package_id'], integrator)
    else:
        package = Package.get(data['recurrence'], integrator)

    if package is None:
        user_message = "Ocurrió un error con el pago, por favor reintente nuevamente más tarde"
        message = "error getting package for %s_%s with id %d" % (
            integrator.name, country.code, int(data['recurrence']))
        body = {
            'status': 'error',
            'message': message,
            'user_message': user_message
        }
        return HttpResponse(json.dumps(body),
                            content_type="application/json",
                            status=http_BAD_REQUEST)

    # Creo un nuevo pago recurrente
    try:
        if 'discount' in data and 'disc_counter' in data:
            up = UserPayment.create_from_package(user, package,
                                                 data['payment_date'],
                                                 data['discount'],
                                                 data['disc_counter'], True)
        else:
            up = UserPayment.create_from_package(user, package,
                                                 data['payment_date'], 0, 0,
                                                 True)
    except Exception as e:
        user_message = "Ocurrió un error con el pago, por favor reintente nuevamente más tarde"
        message = "could not create user payment: (%s)" % str(e)
        body = {
            'status': 'error',
            'message': message,
            'user_message': user_message
        }
        return HttpResponse(json.dumps(body),
                            content_type="application/json",
                            status=http_INTERNAL_ERROR)

    # Realizar el pago
    if data['payment_date'] == 0 or data['payment_date'] == '0' or data[
            'payment_date'] == 0.0:
        if integrator.name == 'paymentez':
            try:
                gw = PaymentezGateway(
                    IntegratorSetting.get_var(
                        integrator, 'paymentez_server_application_code'),
                    IntegratorSetting.get_var(integrator,
                                              'paymentez_server_app_key'),
                    IntegratorSetting.get_var(integrator,
                                              'paymentez_endpoint'))
            except Exception as e:
                user_message = "Ocurrió un error con el pago, por favor reintente nuevamente más tarde"
                message = "could not create user payment: (%s)" % str(e)
                body = {
                    'status': 'error',
                    'message': message,
                    'user_message': user_message
                }
                return HttpResponse(json.dumps(body),
                                    content_type="application/json",
                                    status=http_INTERNAL_ERROR)

            # Verifico si es trial y aplico descuento si corresponde
            if up.is_trial:
                trial_flag = True
                disc_flag = False
                disc_pct = 0
            else:
                trial_flag = False
                if up.has_discount:
                    disc_flag = True
                    disc_pct = up.disc_pct
                else:
                    disc_pct = 0
                    disc_flag = False

            # Genero tx id sumando al userid el timestamp
            payment_id = "PH_%s_%d" % (user.user_id, int(time()))

            # Creo el registro en PaymentHistory
            ph = PaymentHistory.create(up, payment_id, integrator, card,
                                       disc_pct)

            if ph.amount > 0:
                try:
                    ret, content = gw.doPost(
                        PaymentezTx(user.user_id, user.email, ph.amount,
                                    'HotGo', ph.payment_id, ph.taxable_amount,
                                    ph.vat_amount, card.token))
                    print "CONTENT: %s" % str(content)
                except Exception:
                    # Pongo el pago en Waiting Callback
                    ph.status = "W"
                    ph.save()
                    user_message = "Ocurrió un error en la comunicación. Recibirás un correo electrónico en breve con " \
                                   "los detalles de tu transacción. Por cualquier duda, contáctate con [email protected]"
                    message = "communication error with paymentez, waiting callback"
                    body = {
                        'status': 'error',
                        'message': message,
                        'user_message': user_message
                    }
                    return HttpResponse(json.dumps(body),
                                        content_type="application/json",
                                        status=http_PAYMENT_REQUIRED)
            else:
                ret = True
                content = {
                    'transaction': {
                        'status_detail': '-10',
                        'id': '-10',
                        'message': 'Pago con descuento del 100%'
                    }
                }
                pr = paymentez_translator(content)

            if ret:
                # Obtengo los valores segun la respuesta de Paymentez
                pr = paymentez_translator(content)
                # Seteo los valores de la UserPayment
                up.status = pr["up_status"]
                up.message = pr["up_message"]
                up.enabled = pr["up_recurrence"]

                if up.status == 'AC':
                    # calcular next_payment_day
                    up.payment_date = up.calc_payment_date()
                    # Fija la fecha de expiration del usuario
                    user.set_expiration(up.payment_date)
                    if disc_flag:
                        up.disc_counter -= 1
                    if trial_flag:
                        up.trial_counter -= 1
                else:
                    up.channel = 'R'
                up.save()

                # Seteo los valores del PaymentHistory
                ph.status = pr["ph_status"]
                ph.gateway_id = pr["ph_gatewayid"]
                ph.message = pr["ph_message"]
                ph.save()

                if ph.status == 'A':
                    rep_status = "success"
                else:
                    rep_status = "error"

                if pr["user_expire"]:
                    user.expire()

                # POST to promiscuus
                if ph.trial:
                    ph.trial_duration = up.trial_recurrence
                else:
                    ph.trial_duration = 0
                resp_promiscuus = post_to_promiscuus(ph, 'payment_commit')
                if resp_promiscuus['status'] == 'error':
                    ph.message = "%s - Promiscuus error: %s" % (
                        ph.message, resp_promiscuus['message'])
                    ph.save()

                body = {
                    'status': rep_status,
                    'message': '',
                    'user_message': pr['user_message']
                }
                return HttpResponse(json.dumps(body),
                                    content_type="application/json",
                                    status=http_POST_OK)

            else:
                message = 'type: %s, help: %s, description: %s' % (
                    content['error']['type'], content['error']['help'],
                    content['error']['description'])
                up.reply_error(message)
                ph.error('', content)
                user_message = "Ocurrió un error con el pago, por favor reintente nuevamente más tarde"

                # POST to promiscuus
                if ph.trial:
                    ph.trial_duration = up.trial_recurrence
                else:
                    ph.trial_duration = 0
                resp_promiscuus = post_to_promiscuus(ph, 'payment_commit')
                if resp_promiscuus['status'] == 'error':
                    ph.message = "%s - Promiscuus error: %s" % (
                        ph.message, resp_promiscuus['message'])
                    ph.save()

                body = {
                    'status': 'error',
                    'message': message,
                    'user_message': user_message
                }
                return HttpResponse(json.dumps(body),
                                    content_type="application/json",
                                    status=http_UNPROCESSABLE_ENTITY)

        else:
            user_message = "Ocurrió un error con el pago, por favor reintente nuevamente más tarde"
            message = "could not create user payment: (Unknown Integrator: %s)" % str(
                integrator.name)
            body = {
                'status': 'error',
                'message': message,
                'user_message': user_message
            }
            return HttpResponse(json.dumps(body),
                                content_type="application/json",
                                status=http_INTERNAL_ERROR)

    user_message = "Suscripción exitosa"
    body = {'status': 'success', 'message': '', 'user_message': user_message}
    return HttpResponse(json.dumps(body),
                        content_type="application/json",
                        status=http_POST_OK)