示例#1
0
def donation_session_stripe(request):
    ''' Creates a Stripe session object and gets a session id which is used in
    the frontend to during the redirect to stripe website.
    '''
    stripe.api_key = settings.STRIPE_PRIVATE_KEY
    if request.method == 'POST':
        form = DonateForm(request.POST, user=request.user)
        if form.is_valid():
            email_to = request.user.email if request.user.is_authenticated() else None
            amount = form.cleaned_data['amount']
            domain = "http://%s" % Site.objects.get_current().domain
            return_url_success = urlparse.urljoin(domain, reverse('donation-success'))
            return_url_success += '?token={}'.format(form.encoded_data)
            return_url_cancel = urlparse.urljoin(domain, reverse('donate'))
            session = stripe.checkout.Session.create(
                customer_email=email_to,
                payment_method_types=['card'],
                line_items=[{
                    'name': 'Freesound donation',
                    'description': 'Donation for freesound.org',
                    'images': ['https://freesound.org/media/images/logo.png'],
                    'amount': int(amount*100),
                    'currency': 'eur',
                    'quantity': 1,
                }],
              success_url=return_url_success,
              cancel_url=return_url_cancel,
            )
            return JsonResponse({"session_id":session.id})
        else:
            return JsonResponse({'errors': form.errors})
    # If request is GET return an error 400
    return HttpResponse(status=400)
示例#2
0
def donate(request):
    authenticated = False
    donated = False
    user_admin = False
    if request.user.is_superuser and request.user.is_staff:
        user_admin = True
    if request.user.is_authenticated():
        authenticated = True

    donations = Donate.objects.values()
    form = DonateForm(request.POST or None, request.FILES or None)
    if request.method == 'POST':
        smth = True
        for donation in donations:
            if 'accept' + str(donation['id_donate']) in request.POST:
                book = Book(ISBN=donation['ISBN'],
                            title=donation['title'],
                            author=donation['author'],
                            genre=donation['genre'],
                            image=donation['image'])
                book.save()
                Donate.objects.filter(id_donate=donation['id_donate']).delete()
                email_user(user=request.user,
                           subject='donate book',
                           message='Your book donation for' + donation.title +
                           ' has been accepted')
                smth = False
                break
            if 'reject' + str(donation['id_donate']) in request.POST:
                Donate.objects.filter(id_donate=donation['id_donate']).delete()
                smth = False
                email_user(user=request.user,
                           subject='donate book',
                           message='Your book donation for' + donation.title +
                           ' has been declined')
                break
        if smth and form.is_valid():
            donation = form.save(commit=False)
            donation.user = request.user
            donation.image = form.cleaned_data['simage']
            donation.save()
            donated = True
            email_user(user=request.user,
                       subject='donate book',
                       message='Request for donating ' + donation.title +
                       " received")
    donations = Donate.objects.values()

    return render_to_response("book_donate.html",
                              context_instance=RequestContext(
                                  request, {
                                      'authenticated': authenticated,
                                      'user_admin': user_admin,
                                      'donations': donations,
                                      'form': form,
                                      'donated': donated
                                  }))
示例#3
0
def donate():
    foodbanks = db.session.query(
        User.id, User.name).filter_by(user_type=TYPE_FOODBANK).all()

    categories = db.session.query(Category).all()
    categories = Category.query.all()
    # load all of the category->food mapping to memory
    category_food_dict = {}
    for category in categories:
        food_items = category.food_items.all()
        category_food_dict[str(category.id)] = food_items
    print '------------category_food_dict----------------'
    print category_food_dict
    form = DonateForm(foodbank_choices=foodbanks)
    # form = DonateForm()
    if form.plus_button.data:
        form.food_items.append_entry()
    elif form.minus_button.data:
        form.food_items.pop_entry()
    elif form.validate_on_submit():  #post successfully
        # insert the donation request into database
        new_request_header = RequestHeader(
            from_user=current_user.id,
            to_user=int(form.donate_to.data),
            appointment_date=form.appointment_date.data,
            appointment_time=form.appointment_time.data,
            request_type=REQUEST_DONATION,
            beneficiary=form.beneficiary.data,
            frequency=form.frequency.data,
            notes=form.notes.data,
            status=REQUEST_PENDING)

        db.session.add(new_request_header)
        db.session.commit()

        for entry in form.food_items.entries:
            new_request_detail = RequestDetail(
                request_header_id=new_request_header.id,
                food_item_id=entry.data['food_item'],
                category_id=entry.data['category'],
                quantity=entry.data['quantity'],
                weight=entry.data['weight'],
                nutrition=entry.data['nutrition'],
                expiration_date=entry.data['expiration_date'])
            db.session.add(new_request_detail)

        db.session.commit()
        flash("You have successfully submitted a donation request!")
        return redirect(url_for('dashboard'))

    return render_template('donate_request.html',
                           donateForm=form,
                           user=current_user)
示例#4
0
def donate(request):
    authenticated = False
    donated = False
    user_admin = False
    if request.user.is_superuser and request.user.is_staff:
        user_admin = True
    if request.user.is_authenticated():
        authenticated = True

    donations = Donate.objects.values()
    form = DonateForm(request.POST or None, request.FILES or None)
    if request.method == 'POST':
        smth = True
        for donation in donations:
            if 'accept' + str(donation['id_donate']) in request.POST:
                book = Book(ISBN=donation['ISBN'],
                            title=donation['title'],
                            author=donation['author'],
                            genre=donation['genre'],
                            image=donation['image']
                            )
                book.save()
                Donate.objects.filter(id_donate=donation['id_donate']).delete()
                email_user(user=request.user,
                           subject='donate book',
                           message='Your book donation for' + donation.title + ' has been accepted')
                smth = False
                break
            if 'reject' + str(donation['id_donate']) in request.POST:
                Donate.objects.filter(id_donate=donation['id_donate']).delete()
                smth = False
                email_user(user=request.user,
                           subject='donate book',
                           message='Your book donation for' + donation.title + ' has been declined')
                break
        if smth and form.is_valid():
            donation = form.save(commit=False)
            donation.user = request.user
            donation.image = form.cleaned_data['simage']
            donation.save()
            donated = True
            email_user(user=request.user,
                       subject='donate book',
                       message='Request for donating ' + donation.title + " received")
    donations = Donate.objects.values()

    return render_to_response("book_donate.html", context_instance=RequestContext(request,
                                                                                  {'authenticated': authenticated,
                                                                                   'user_admin': user_admin,
                                                                                   'donations': donations, 'form': form,
                                                                                   'donated': donated}))
示例#5
0
def donate(request):
    ''' Donate page: display form for donations where if user is logged in
    we give the option to doneate anonymously otherwise we just give the option
    to enter the name that will be displayed.
    If request is post we generate the data to send to paypal.
    '''
    if request.method == 'POST':
        form = DonateForm(request.POST, user=request.user)
        if form.is_valid():
            amount = form.cleaned_data['amount']
            returned_data_str = form.encoded_data
            domain = "https://%s" % Site.objects.get_current().domain
            return_url = urlparse.urljoin(domain,
                                          reverse('donation-complete-paypal'))
            data = {
                "url": settings.PAYPAL_VALIDATION_URL,
                "params": {
                    "cmd": "_donations",
                    "currency_code": "EUR",
                    "business": settings.PAYPAL_EMAIL,
                    "item_name": "Freesound donation",
                    "custom": returned_data_str,
                    "notify_url": return_url,
                    "no_shipping": 1,
                    "lc": "en_US"
                }
            }

            if form.cleaned_data['recurring']:
                data['params']['cmd'] = '_xclick-subscriptions'
                data['params']['a3'] = amount
                # src - indicates recurring subscription
                data['params']['src'] = 1
                # p3 - number of time periods between each recurrence
                data['params']['p3'] = 1
                # t3 - time period (D=days, W=weeks, M=months, Y=years)
                data['params']['t3'] = 'M'
                # sra - Number of times to reattempt on failure
                data['params']['sra'] = 1
                data['params']['item_name'] = 'Freesound monthly donation'
            else:
                data['params']['amount'] = amount
        else:
            data = {'errors': form.errors}
        return JsonResponse(data)
    else:
        form = DonateForm(user=request.user)
        tvars = {'form': form, 'stripe_key': settings.STRIPE_PUBLIC_KEY}
        return render(request, 'donations/donate.html', tvars)
示例#6
0
文件: views.py 项目: MTG/freesound
def donate(request):
    ''' Donate page: display form for donations where if user is logged in
    we give the option to doneate anonymously otherwise we just give the option
    to enter the name that will be displayed.
    If request is post we generate the data to send to paypal.
    '''
    if request.method == 'POST':
        form = DonateForm(request.POST, user=request.user)
        if form.is_valid():
            amount = form.cleaned_data['amount']
            returned_data_str = form.encoded_data
            domain = "https://%s" % Site.objects.get_current().domain
            return_url = urlparse.urljoin(domain, reverse('donation-complete-paypal'))
            data = {"url": settings.PAYPAL_VALIDATION_URL,
                    "params": {
                        "cmd": "_donations",
                        "currency_code": "EUR",
                        "business": settings.PAYPAL_EMAIL,
                        "item_name": "Freesound donation",
                        "custom": returned_data_str,
                        "notify_url": return_url,
                        "no_shipping": 1,
                        "lc": "en_US"
                        }
                    }

            if form.cleaned_data['recurring']:
                data['params']['cmd'] = '_xclick-subscriptions'
                data['params']['a3'] = amount
                # src - indicates recurring subscription
                data['params']['src'] = 1
                # p3 - number of time periods between each recurrence
                data['params']['p3'] = 1
                # t3 - time period (D=days, W=weeks, M=months, Y=years)
                data['params']['t3'] = 'M'
                # sra - Number of times to reattempt on failure
                data['params']['sra'] = 1
                data['params']['item_name'] = 'Freesound monthly donation'
            else:
                data['params']['amount'] = amount
        else:
            data = {'errors': form.errors}
        return JsonResponse(data)
    else:
        default_donation_amount = request.GET.get(settings.DONATION_AMOUNT_REQUEST_PARAM, None)
        form = DonateForm(user=request.user, default_donation_amount=default_donation_amount)
        tvars = {'form': form, 'stripe_key': settings.STRIPE_PUBLIC_KEY}
        return render(request, 'donations/donate.html', tvars)
示例#7
0
def donation_complete_stripe(request):
    """
    This view receives a stripe token of a validated credit card and requests for the actual donation.
    If the donation is successfully done it stores it and send the email to the user.
    """
    donation_received = False
    donation_error = False
    if request.method == 'POST':
        form = DonateForm(request.POST, user=request.user)

        token = request.POST.get('stripeToken', False)
        email = request.POST.get('stripeEmail', False)

        if form.is_valid() and token and email:
            amount = form.cleaned_data['amount']
            stripe.api_key = settings.STRIPE_PRIVATE_KEY
            try:
                # Charge the user's card:
                charge = stripe.Charge.create(
                    amount=int(amount * 100),
                    currency="eur",
                    description="Freesound.org Donation",
                    source=token,
                )
                if charge['status'] == 'succeeded':
                    donation_received = True
                    messages.add_message(
                        request, messages.INFO,
                        'Thanks! your donation has been processed.')
                    _save_donation(form.encoded_data, email, amount, 'eur',
                                   charge['id'], 's')
            except stripe.error.CardError as e:
                # Since it's a decline, stripe.error.CardError will be caught
                body = e.json_body
                err = body.get('error', {})
                donation_error = err.get('message', False)
            except stripe.error.StripeError as e:
                logger.error("Can't charge donation whith stripe: %s", e)
    if donation_error:
        messages.add_message(
            request, messages.WARNING,
            'Error processing the donation. %s' % err.get('message'))
    elif not donation_received:
        messages.add_message(request, messages.WARNING,
                             'Your donation could not be processed.')
    return redirect('donate')
示例#8
0
def donate():
    form = DonateForm()
    if form.validate_on_submit():
        amount = form.amount.data
        email = form.email.data
        amount = str(amount)
        if ".0" in amount[-2:]:
            amount = int(float(amount))
            session['amount_cents'] = amount * 100  #int(amount+"00")
            session['amount_display'] = "{}.00".format(amount)
        else:
            a, b = str(amount).split('.')
            b = b[:2]
            session['amount_cents'] = int(a + b)
            session['amount_display'] = "{}.{}".format(a, b)
        session['email'] = email
        return redirect(url_for('confirm'))
    return render_template('donate.html', form=form)
示例#9
0
def donate():
    form = DonateForm()
    if form.validate_on_submit():
        amount = form.amount.data
        email = form.email.data
        amount = str(amount)
        if ".0" in amount[-2:]:
            amount = int(float(amount))
            session['amount_cents'] = amount*100 #int(amount+"00")
            session['amount_display'] = "{}.00".format(amount)
        else:
            a,b = str(amount).split('.')
            b = b[:2]
            session['amount_cents'] = int(a+b)
            session['amount_display'] = "{}.{}".format(a,b)
        session['email'] = email
        return redirect(url_for('confirm'))
    return render_template('donate.html', form = form)
示例#10
0
def donate(request):
    ''' Donate page: display form for donations where if user is logged in
    we give the option to doneate anonymously otherwise we just give the option
    to enter the name that will be displayed.
    If request is post we generate the data to send to paypal.
    '''
    default_donation_amount = request.GET.get(settings.DONATION_AMOUNT_REQUEST_PARAM, None)
    form = DonateForm(user=request.user, default_donation_amount=default_donation_amount)
    tvars = {'form': form, 'stripe_key': settings.STRIPE_PUBLIC_KEY}
    return render(request, 'donations/donate.html', tvars)
示例#11
0
文件: views.py 项目: MTG/freesound
def donation_complete_stripe(request):
    """
    This view receives a stripe token of a validated credit card and requests for the actual donation.
    If the donation is successfully done it stores it and send the email to the user.
    """
    donation_received = False
    donation_error = False
    if request.method == 'POST':
        form = DonateForm(request.POST, user=request.user)

        token = request.POST.get('stripeToken', False)
        email = request.POST.get('stripeEmail', False)

        if form.is_valid() and token and email:
            amount = form.cleaned_data['amount']
            stripe.api_key = settings.STRIPE_PRIVATE_KEY
            try:
                # Charge the user's card:
                charge = stripe.Charge.create(
                  amount=int(amount*100),
                  currency="eur",
                  description="Freesound.org Donation",
                  source=token,
                )
                if charge['status'] == 'succeeded':
                    donation_received = True
                    messages.add_message(request, messages.INFO, 'Thanks! your donation has been processed.')
                    _save_donation(form.encoded_data, email, amount, 'eur', charge['id'], 's')
            except stripe.error.CardError as e:
                # Since it's a decline, stripe.error.CardError will be caught
                body = e.json_body
                err  = body.get('error', {})
                donation_error = err.get('message', False)
            except stripe.error.StripeError as e:
                logger.error("Can't charge donation whith stripe: %s", e)
    if donation_error:
        messages.add_message(request, messages.WARNING, 'Error processing the donation. %s' % err.get('message'))
    elif not donation_received:
        messages.add_message(request, messages.WARNING, 'Your donation could not be processed.')
    return redirect('donate')
示例#12
0
def donate_blood(request):
    Users = RegisteredUser.objects.all().filter(user=request.user)
    User = RegisteredUser()
    for user in Users:
        User = user
    if request.method == 'POST':
        form = DonateForm(request.POST)
        if form.is_valid():
            form = form.save(commit=False)
            form.address = User.address
            form.donated_by = User
            form.blood_type = User.blood_group
            form.save()
            return redirect('home')
    else:
        form = DonateForm()
        return render(request, 'donate.html', {'form': form})