Пример #1
0
def buy_app_checkout(request):
    """ Send a user with session created in start_app_buy to pay the bill.
    F5 token is needed in session to get no errors.
    """
    user_id = request.session.get('user_id', None)
    if not user_id:
        return HttpResponse(json.dumps({'error': True}))

    gateway = 'mellat'
    request_data = {'gateway': gateway,
                    'token': request.session.get('token', None)}

    headers = f5.get_api_header()
    res = requests.post(GenericPayAPI, headers=headers, data=request_data)

    if res.status_code == 200:
        # Set order_status to 1 => StartPayment
        order_id = request.session['order_id']
        change_order_status(order_id, 1)

        analytics.track(user_id, 'buyapp_payment', {
            "gateway": gateway,
        })
        return HttpResponse(res)

    return HttpResponse(json.dumps({'error': True}))
Пример #2
0
def start_pay(request, gateway):
    if not request.session.get("token", None):
        print "Error in Token"
        return HttpResponse(json.dumps({"error": True}))
    if 'invoice_id' in request.session:
        del request.session['invoice_id']
        request.session.save()

    if request.session.get('gift', False):
        return gift_start_payment(request, gateway)

    if request.user.is_authenticated():
        user_id = request.session['user_id']
    else:
        user_id = request.session['user_id']
    payurl = settings.FPAN['host'] + settings.FPAN['urls']['v2payment']
    auth = (settings.FPAN['auth']['username'],
            settings.FPAN['auth']['password'])
    payload = {
        'gateway': gateway,
        'token': request.session['token'],
        'user_id': user_id
    }
    r = requests.post(payurl,
                      data=payload,
                      headers=f5.get_api_header(),
                      verify=False)
    analytics.track(user_id, 'start_payment', {"gateway": gateway})
    if r.status_code != 200:
        return HttpResponse(json.dumps({'error': True}))

    return HttpResponse(r.text, content_type="text/html")
Пример #3
0
def change_plan(request, device_id):
    get_object_or_404(Device, id=device_id, user=request.user)

    tup = f5.device_details(request, device_id)
    if not tup or tup == ('', ''):
        raise Http404

    if tup[0][u'paid']:
        raise Http404

    ERROR = False
    if request.method == "POST" and "active-plan" in request.POST:
        try:
            plan = request.POST["active-plan"]
            url = settings.FPAN['host'] + settings.FPAN['urls']['change_plan']
            payload = {'plan': plan, 'device_id': device_id}
            r = requests.post(url,
                              data=payload,
                              headers=f5.get_api_header(),
                              verify=False)
            print r.content
            if r.status_code == 200:
                from apps.devices.views import start_invoice_pay
                return HttpResponseRedirect(
                    reverse(start_invoice_pay,
                            kwargs={'invoice_id': r.json()['invoice_id']}))
            else:
                ERROR = True
        except:
            ERROR = True

    plans = parse_plans(request)
    variables = dict(plans=plans, ERROR=ERROR)
    return render_to_response('change_plan.html',
                              RequestContext(request, variables))
Пример #4
0
def plans_json(request):
    plans_url = settings.FPAN['host'] + settings.FPAN['urls']['plans']
    auth = (settings.FPAN['auth']['username'],
            settings.FPAN['auth']['password'])
    r = requests.get(plans_url, headers=f5.get_api_header(), verify=False)

    if r.status_code != 200:
        res = {"results": {"error": True}}
    else:
        res = r.json()

    return HttpResponse(json.dumps(res["results"]))
Пример #5
0
def invoice(request, invoiceId=None):
    subscribeUrl = settings.FPAN['host'] + settings.FPAN['urls'][
        'invoice'] + invoiceId
    auth = (settings.FPAN['auth']['username'],
            settings.FPAN['auth']['password'])
    r = requests.get(subscribeUrl, headers=f5.get_api_header(), verify=False)

    if r.status_code != 200:
        return HttpResponse(
            "Failed to process your payment. Contact [email protected]")

    res = r.json()
    device = get_object_or_404(Device, pk=int(res['subscription']['uuid']))

    if device.user.id.user_id != get_user_id(request.session['_auth_user_id']):
        raise Http404
    token = generate_token(TOKEN_LENGTH)

    while DeviceChallengeToken.objects.filter(token=token).count() > 0:
        token = generate_token(TOKEN_LENGTH)

    DeviceChallengeToken.objects.create(device=device,
                                        token=token,
                                        is_used=False)

    url = reverse('apps.devices.views.mobileconfig_static', args=(token, ))
    mobileconfig_url = request.build_absolute_uri(url)

    # Provice email along with identify traits to make customer.io happy
    analytics.identify(device.user.id.user_id,
                       traits={"email": device.user.username})
    #HTTPS FOR VERIFIED MOBILECONFIG FILE
    mobileconfig_url = mobileconfig_url.replace("http://", "https://")
    # Use {{create_account.mobileconf_url}} in customer.io email body
    send_mobileconfig_analytics(device.user, request)
    event = "create_account"
    if len(device.user.device_set.all()) > 1:
        event = "add_new_device"

    if device.user.allow_sms:
        short_url = shorten_url(mobileconfig_url)
        send_sms(device.user.mobile_number, short_url, "activation.sms",
                 device.user)

    analytics.track(device.user.id.user_id, event, {
        "mobileconf_url": mobileconfig_url,
        "email": device.user.username
    })
    analytics.track(device.user.id.user_id, 'sign_up_newsletter',
                    {"email": device.user.username})
    return redirect("/panel/devices/welcome/%s" % invoiceId)
Пример #6
0
def block_device_switch(request):
    """Get a udid (device_id) in a post request and call F5's block_device API by its related uuid.
    """
    if request.user.is_superuser:
        auth = HTTPBasicAuth(settings.FPAN['auth']['username'],
                             settings.FPAN['auth']['password'])
        udid = request.POST.get("udid")
        if not udid:
            raise Http404
        uuid = Device.objects.get(device_id=udid).id
        res = requests.post(
            'http://localhost:3000/fpan/api/v2/block_device_switch',
            headers=f5.get_api_header(),
            data={"device_id": uuid})
        return HttpResponse(res.content)
    raise PermissionDenied()
Пример #7
0
def gift_create(request):
    try:
        plan = request.POST["plan"]
        request.session["plan"] = plan
        from apps.panel.f5adapter import plan_details
        request.session["price"] = plan_details(request, plan)["price"]
        subscribeUrl = settings.FPAN['host'] + settings.FPAN['urls']['v2gift']
        auth = (settings.FPAN['auth']['username'],
                settings.FPAN['auth']['password'])
        form = request.session['giftform']
        payload = {
            'plan': plan,
            'giver_id': form.instance.giver_id,
            'getter_id': form.instance.getter_id,
            'giver_email': form.instance.giver_email,
            'getter_email': form.instance.getter_email,
            'giver_name': form.instance.giver_name,
            'getter_name': form.instance.getter_name,
            'callback_url':
            request.build_absolute_uri(reverse('gift_callback')),
            'callback_token': request.session.session_key
        }
        r = requests.post(subscribeUrl,
                          headers=f5.get_api_header(),
                          data=payload,
                          verify=False)
        res = r.json()
        if (res['success']):
            analytics.track(request.session['user_id'], 'gift_choose_plan',
                            {"plan": get_plan_label(res["label"])})
            request.session['plan_label'] = res["label"]
            request.session['token'] = res['token']
            del res['token']
            for bank in res['active_invoice_payment_url']:
                res['active_invoice_payment_url'][bank] = reverse(
                    'start_pay', kwargs={'gateway': bank})
            return HttpResponse(json.dumps(res))
    except:
        import sys
        print sys.exc_info()
        import traceback
        print traceback.format_exc()
    return HttpResponse(
        json.dumps({
            'error': True,
            'errors': u"خطا در مراحل ثبت درخواست پرداخت"
        }))
Пример #8
0
def gift_start_payment(request, gateway):
    payurl = settings.FPAN['host'] + settings.FPAN['urls']['v2_gift_payment']
    auth = (settings.FPAN['auth']['username'],
            settings.FPAN['auth']['password'])
    payload = {
        'gateway': gateway,
        'token': request.session['token'],
    }
    r = requests.post(payurl,
                      data=payload,
                      headers=f5.get_api_header(),
                      verify=False)
    analytics.track(request.session['giver_id'], 'gift_start_payment',
                    {"gateway": gateway})
    if r.status_code != 200:
        return HttpResponse(json.dumps({'error': True}))

    return HttpResponse(r.text, content_type="text/html")
Пример #9
0
def gen_promo(promo_type, partner=None, campaign=None):
    """Generate a dict of promo_code requested from f5's API based on type
    """
    gen_promo_url = settings.FPAN['host'] + settings.FPAN['urls'][
        'generate_promo']
    data = {'type': promo_type}
    if partner:
        data['partner'] = partner
    elif campaign:
        data['campaign'] = campaign

    r = requests.post(gen_promo_url, data=data, headers=f5.get_api_header())

    if r.status_code == 200 and 'error' not in r.json():
        promo = r.json()
    else:
        promo = None

    return promo
Пример #10
0
def process_promo(request, promo):
    """Get a invoice token and apply promo on it.
    """
    promourl = settings.FPAN['host'] + settings.FPAN['urls']['apply']
    payload = {'promo_code': promo, 'token': request.session['token']}
    r = requests.post(promourl,
                      data=payload,
                      headers=f5.get_api_header(),
                      verify=False)
    if r.status_code != 200:
        return None
    res = r.json()
    if 'success' in r.json():
        res = r.json()
        if request.user.is_authenticated():
            analytics.track(request.session['user_id'], 'promo_code_enter',
                            {"promo_code": promo})
        else:
            analytics.track(request.session['user_id'], 'promo_code_enter',
                            {"promo_code": promo})
        request.session["price"] = res["final_price"]
    return res
Пример #11
0
def start_invoice_pay(request, invoice_id):
    from apps.panel.views import welcome_device
    if request.method == "POST" and 'gateway' in request.POST:
        payurl = settings.FPAN['host'] + settings.FPAN['urls'][
            'invoice_payment']
        auth = (settings.FPAN['auth']['username'],
                settings.FPAN['auth']['password'])
        callback_url = request.build_absolute_uri(
            reverse(welcome_device, kwargs={'invoice_id': invoice_id}))
        payload = {
            'gateway': request.POST['gateway'],
            'user_id': request.session['user_id'],
            'invoice_id': invoice_id,
            'callback_url': callback_url,
            'token': request.session['token'],
        }
        print callback_url
        r = requests.post(payurl,
                          data=payload,
                          headers=f5.get_api_header(),
                          verify=False)

        if r.status_code != 200:
            return HttpResponse(json.dumps({'error': True}))
        request.session["invoice_id"] = invoice_id
        return HttpResponse(r.text, content_type="text/html")
    else:
        try:
            request.session['user_id'] = get_user_id(
                request.session['_auth_user_id'])
            payurl = settings.FPAN['host'] + settings.FPAN['urls'][
                'begin_invoice_payment']
            auth = (settings.FPAN['auth']['username'],
                    settings.FPAN['auth']['password'])
            callback_url = request.build_absolute_uri(
                reverse(welcome_device, kwargs={'invoice_id': invoice_id}))
            payload = {
                'user_id': request.session['user_id'],
                'invoice_id': invoice_id,
            }
            r = requests.post(payurl,
                              data=payload,
                              headers=f5.get_api_header(),
                              verify=False)
            js = r.json()
            request.session['token'] = js['token']
            f5_settings = f5.get_settings(request)
            payment_availablity = 'block' if 'OMGPAY_DISABLE_FOR_USERS' in f5_settings and f5_settings[
                'OMGPAY_DISABLE_FOR_USERS'] == True else 'none'
            variables = dict(
                invoice={
                    "invoice_url": js['url'],
                    "plan_label": js['label'],
                    "plan_amt": js[u'plan_amount'],
                    "amount": js[u'amount'],
                },
                payment_availablity=payment_availablity,
            )
            return render_to_response('invoice_payment.html',
                                      RequestContext(request, variables))
        except:
            raise Http404
Пример #12
0
def add_device_for_user(request, form_initial, data):
    """ Get a request object, device form_initialization data and user data
    to make a device object for user and return proper bank gateway to pay.
    """
    form = NewForm(data or None, initial=form_initial)
    if form.is_valid():
        request.session['deviceform'] = form.instance
        request.session["plan"] = data["plan"]
        from apps.panel.f5adapter import plan_details
        request.session["price"] = plan_details(request, data["plan"])["price"]
        subscribeUrl = settings.FPAN['host'] + settings.FPAN['urls'][
            'v2subscribe']
        auth = (settings.FPAN['auth']['username'],
                settings.FPAN['auth']['password'])
        payload = {
            'plan': form.cleaned_data['plan'],
            'email': form.instance.email,
            'callback_url':
            request.build_absolute_uri(reverse('payment_callback')),
            'callback_token': request.session.session_key
        }
        r = requests.post(subscribeUrl,
                          headers=f5.get_api_header(),
                          data=payload,
                          verify=False)
        try:
            res = r.json()
            if (res['success']):
                request.session['token'] = res['token']
                del res['token']

                if request.user.is_authenticated():
                    analytics.track(request.session['user_id'], 'choose_plan',
                                    {"plan": get_plan_label(res["label"])})
                else:
                    analytics.track(request.session['user_id'], 'choose_plan',
                                    {"plan": get_plan_label(res["label"])})

                    # If user uses a referral link and the referredBy attribute is registered in our system
                    # give him discount if configured so in F5
                    referredBy = request.session.get('referredBy', None)
                    if referredBy:
                        # Generate new promo code if user haven't one yet
                        if request.session.get('referral_promo', None):
                            promo = request.session['referral_promo']
                        elif get_user_by_id(referredBy):
                            # In case user doesn't have referral_promo,
                            # Generate, apply and save it
                            referrer_name = get_user_by_id(referredBy).username
                            promo = gen_promo('referred',
                                              partner=referrer_name)
                        else:
                            promo = gen_promo('campaign', campaign=referredBy)

                        if promo:
                            request.session['referral_promo'] = promo
                            # Apply promo if any generated.
                            ppromo = process_promo(request, promo['code'])
                            if ppromo and 'success' in ppromo:
                                res['referral_promo'] = ppromo

                for bank in res['active_invoice_payment_url']:
                    res['active_invoice_payment_url'][bank] = reverse(
                        'start_pay', kwargs={'gateway': bank})
                return res
        except:
            import sys
            print sys.exc_info()
            import traceback
            print traceback.format_exc()
        return {'error': True, 'errors': u"خطا در مراحل ثبت درخواست پرداخت"}
    else:
        return {'error': True, 'errors': dict(form.errors.items())}
Пример #13
0
def start_buy_App(request):
    """ Setup session to buy App
    """

    # In case of service is not available is required :D
    try:
        if not check_balance():
            raise
    except:
        return render_to_response("appbuy_unavailable.html")

    if not request.session.session_key:
        request.session.flush()

    try:
        try:
            user_id = request.GET.get('userid', None)
            app_id = request.GET.get('appid', None)
            apple_id = request.GET.get('PROJECT2', None)

            validate_email(apple_id)
            user_email_obj = UserEmail.objects.filter(user_id=user_id)

            black_listed = BlackList.objects.get(itunes_id=appid)
            if not user_id or not app_id or black_listed:
                raise
        except:
            raise ValueError(ERRORS['DATA_VALIDATION'])

        user = User.objects.get(id=user_email_obj)
        app_data = get_app_data(app_id)
        us_fee = get_us_fee(user_id, app_data)
        ir_fee = change_to_local_price(us_fee)

        order_model = BoughtApp(user=user,
                                # Truncate application name to first 100 char
                                app_name=app_data['app_name'][:100],
                                itunes_id=app_id,
                                apple_id=apple_id,
                                ir_fee=ir_fee,
                                us_fee=us_fee,
                                appstore_url=app_data['appstore_url'],
                                icon_normal=app_data['icon_normal'],
                                icon_large=app_data['icon_large'],
                                icon_huge=app_data['icon_huge'])

        # Save order object:
        order_model.save()

        # Save order_id to session to have access to object in feature.
        request.session['ir_fee'] = ir_fee
        request.session['us_fee'] = us_fee
        request.session['user_id'] = user_id
        request.session['apple_id'] = apple_id
        request.session['order_id'] = order_model.id
        request.session['app_name'] = app_data['app_name']
        request.session['itunes_id'] = app_data['itunes_id']
        request.session['icon_huge'] = app_data['icon_huge']
        request.session['icon_large'] = app_data['icon_large']
        request.session['icon_normal'] = app_data['icon_normal']
        request.session['user_name'] = user.first_name + user.last_name

        request.session.set_expiry(0)
        request.session.save()

        # Initialize the invoice on F5
        callback_url = request.build_absolute_uri(reverse('finishAppPayment'))
        order_data = {'email': apple_id,
                      'amount': ir_fee,
                      'callback_url': callback_url,
                      'callback_token': request.session.session_key}

        try:
            res = requests.post(GenericInitUrl, headers=f5.get_api_header(),
                                data=order_data).json()
            if not res['success']:
                raise
        except:
            raise ValueError(ERRORS["GenericInitAPI"])

        # Set token so F5 is able to know us.
        request.session['token'] = res['token']
        request.session.set_expiry(0)
    except ValueError as error:
        request.session['error'] = error.args[0]
        error_url = request.build_absolute_uri(reverse("error"))
        return HttpResponseRedirect(error_url)

    analytics.track(user_id, 'start_buy_App', {
        'app_id': app_id,
        'apple_id': apple_id,
    })

    payment_url = request.build_absolute_uri(reverse("AppCheckout"))
    return HttpResponseRedirect(payment_url)
Пример #14
0
def profile(request):
    upd_success = upd_error = error_msg = False
    user = request.user
    user_avatar = get_avatar_url(user)
    if request.method == 'POST':
        avatar_form = AvatarUpload(request.POST, request.FILES)
        name = request.POST['name']
        email = request.POST['email']
        passw = request.POST['pass']
        mobile = request.POST['mobile_number']
        alter = False

        if email != "" and email != user.email:
            email = email.lower()
            user.username = user.email = email
            user.id.email = email
            user.id.save()
            alter = True
        user.first_name = name
        if mobile != "":
            if re.match(r'09[0-9]{9}', mobile):
                user.mobile_number = mobile
            else:
                error_msg = "شماره موبایل وارد شده نامعتبر است."
        if passw != "":
            # Clean all anonymous api token recores
            redis_client.delete(user.id.user_id)
            # Set password
            user.set_password(passw)
        try:
            validate_email(email)
            if not re.match(r'^.{8,64}$', passw):
                raise ValidationError(
                    "رمز عبور حداقل باید ۸ کاراکتر داشته باشد")
            user.full_clean()
            user.save()
            for device in Device.objects.filter(user=user):
                device.email = user.email
                device.save()
            analytics.identify(user.id.user_id, {
                "firstName": user.first_name,
                "email": user.email
            })
            if alter:
                alter_url = settings.FPAN['host'] + settings.FPAN['urls'][
                    'alter_user']
                r = requests.post(alter_url,
                                  verify=False,
                                  headers=f5.get_api_header(),
                                  data={
                                      "user_id": user.id.user_id,
                                      "email": email
                                  })
                analytics.track(user.id.user_id, "user_changed_profile", {
                    "firstName": name,
                    "email": email
                })
                js = r.json()
                js["success"]

            if avatar_form.is_valid():
                user_obj = Device.objects.filter(user=user)[0].user
                avatar_img = avatar_form.clean_avatar()
                if avatar_img:
                    user_obj.avatar = avatar_form.clean_avatar()
                    user_obj.save()
                    # Returning page like this will make user to see avatar
                    # changing result just after uploading it. No refresh is
                    # necessairy.
                    return HttpResponseRedirect('/panel/profile/')
                else:
                    raise ValidationError(
                        "عکس آپلود شده باید دارای یکی از فرمت‌ها JPEG, PNG و یا GIF بوده و دارای حجمی کمتر از ۳۰۰ کیلوبایت باشد."
                    )

            upd_success = True
        except ValidationError as e:
            import sys
            print sys.exc_info()
            error_msg = e.message

    variables = dict(error_msg=error_msg,
                     user_avatar=user_avatar,
                     user=request.user,
                     upd_success=upd_success,
                     upd_error=upd_error)
    context = RequestContext(request, variables)
    context.update(csrf(request))
    return render_to_response('myprofile.html', context)