コード例 #1
0
ファイル: actions.py プロジェクト: benlk/muckrock
def pay_request(request, jurisdiction, jidx, slug, idx):
    """Pay us through CC for the payment on a request"""
    foia = _get_foia(jurisdiction, jidx, slug, idx)
    token = request.POST.get('stripe_token')
    email = request.POST.get('stripe_email')
    email = validate_stripe_email(email)
    amount = request.POST.get('stripe_amount')
    if request.method == 'POST':
        error_msg = None
        if not token:
            error_msg = 'Missing Stripe token.'
        if not email:
            error_msg = 'Missing email address.'
        if not amount:
            error_msg = 'Missing payment amount.'
        if error_msg is not None:
            messages.error(request, 'Payment error: %s' % error_msg)
            logger.warning('Payment error: %s', error_msg, exc_info=sys.exc_info())
            return redirect(foia)
        try:
            metadata = {
                'email': email,
                'action': 'request-fee',
                'foia': foia.pk
            }
            amount = int(amount)
            request.user.profile.pay(token, amount, metadata)
            foia.pay(request.user, amount / 100.0)
        except (stripe.InvalidRequestError, stripe.CardError, ValueError) as exception:
            messages.error(request, 'Payment error: %s' % exception)
            logger.warning('Payment error: %s', exception, exc_info=sys.exc_info())
            return redirect(foia)
        msg = 'Your payment was successful. We will get this to the agency right away!'
        messages.success(request, msg)
    return redirect(foia)
コード例 #2
0
def buy_requests(request, username=None):
    """A purchaser buys requests for a recipient. The recipient can even be themselves!"""
    url_redirect = request.GET.get('next', 'acct-my-profile')
    bundles = int(request.POST.get('bundles', 1))
    recipient = get_object_or_404(User, username=username)
    purchaser = request.user
    request_price = bundles * 2000
    if purchaser.is_authenticated():
        request_count = bundles * purchaser.profile.bundled_requests()
    else:
        request_count = bundles * 4
    try:
        if request.POST:
            stripe_token = request.POST.get('stripe_token')
            stripe_email = request.POST.get('stripe_email')
            stripe_email = validate_stripe_email(stripe_email)
            if not stripe_token or not stripe_email:
                raise KeyError('Missing Stripe payment data.')
            # take from the purchaser
            stripe_retry_on_error(
                    stripe.Charge.create,
                    amount=request_price,
                    currency='usd',
                    source=stripe_token,
                    metadata={
                        'email': stripe_email,
                        'action': 'request-purchase',
                        },
                    idempotency_key=True,
                    )
            # and give to the recipient
            recipient.profile.num_requests += request_count
            recipient.profile.save()
            # record the purchase
            request.session['ga'] = 'request_purchase'
            msg = 'Purchase successful. '
            if recipient == purchaser:
                msg += '%d requests have been added to your account.' % request_count
            else:
                msg += '%d requests have been gifted to %s' % (request_count, recipient.first_name)
                gift_description = '%d requests' % request_count
                # notify the recipient with an email
                gift.delay(recipient, purchaser, gift_description)
            messages.success(request, msg)
            logger.info('%s purchased %d requests', purchaser.username, request_count)
    except KeyError as exception:
        msg = 'Payment error: %s' % exception
        messages.error(request, msg)
        logger.warn('Payment error: %s', exception, exc_info=sys.exc_info())
    except stripe.CardError as exception:
        msg = 'Payment error: %s Your card has not been charged.' % exception
        messages.error(request, msg)
        logger.warn('Payment error: %s', exception, exc_info=sys.exc_info())
    except (stripe.error.InvalidRequestError, stripe.error.APIError) as exc:
        msg = 'Payment error: Your card has not been charged.'
        messages.error(request, msg)
        logger.warn('Payment error: %s', exc, exc_info=sys.exc_info())
    return redirect(url_redirect)
コード例 #3
0
 def post(self, request, **kwargs):
     """
     First we validate the payment form, so we don't charge someone's card by accident.
     Next, we charge their card. Finally, use the validated payment form to create and
     return a CrowdfundRequestPayment object.
     """
     # pylint: disable=too-many-locals
     token = request.POST.get('stripe_token')
     email = request.POST.get('stripe_email')
     email = validate_stripe_email(email)
     payment_form = CrowdfundPaymentForm(request.POST)
     if payment_form.is_valid() and token and email:
         amount = payment_form.cleaned_data['stripe_amount']
         # If there is no user but the show and full_name fields are filled in,
         # and a user with that email does not already exists,
         # create the user with our "miniregistration" functionality and then log them in
         user = request.user if request.user.is_authenticated else None
         registered = False
         show = payment_form.cleaned_data['show']
         full_name = payment_form.cleaned_data['full_name']
         email_exists = User.objects.filter(email__iexact=email).exists()
         if user is None and show and full_name and not email_exists:
             user = self.miniregister(full_name, email)
             registered = True
         crowdfund = payment_form.cleaned_data['crowdfund']
         try:
             if (crowdfund.can_recur()
                     and payment_form.cleaned_data['recurring']):
                 crowdfund.make_recurring_payment(token, email, amount,
                                                  show, user)
                 event = 'Recurring Crowdfund Payment'
                 kwargs = {}
             else:
                 crowdfund.make_payment(token, email, amount, show, user)
                 event = 'Crowdfund Payment'
                 kwargs = {'charge': float(amount)}
         except stripe.StripeError as payment_error:
             logging.warn(payment_error)
             return self.return_error(request, payment_error)
         else:
             mixpanel_event(
                 request, event, {
                     'Amount': float(amount),
                     'Crowdfund': crowdfund.name,
                     'Crowdfund ID': crowdfund.pk,
                     'Show': show,
                 }, **kwargs)
         if request.is_ajax():
             data = {
                 'authenticated':
                 user.is_authenticated() if user else False,
                 'registered': registered,
             }
             return JsonResponse(data, status=200)
         else:
             messages.success(request, 'Thank you for your contribution!')
             return redirect(self.get_redirect_url())
     return self.return_error(request)
コード例 #4
0
ファイル: views.py プロジェクト: pjsier/muckrock
 def post(self, request, **kwargs):
     """
     First we validate the payment form, so we don't charge someone's card by accident.
     Next, we charge their card. Finally, use the validated payment form to create and
     return a CrowdfundRequestPayment object.
     """
     token = request.POST.get('stripe_token')
     email = request.POST.get('stripe_email')
     email = validate_stripe_email(email)
     payment_form = CrowdfundPaymentForm(request.POST)
     if payment_form.is_valid() and token and email:
         amount = payment_form.cleaned_data['stripe_amount']
         # If there is no user but the show and full_name fields are filled in,
         # create the user with our "miniregistration" functionality and then log them in
         user = request.user if request.user.is_authenticated() else None
         registered = False
         show = payment_form.cleaned_data['show']
         full_name = payment_form.cleaned_data['full_name']
         if user is None and show and full_name:
             password = generate_key(12)
             user = miniregister(full_name, email, password)
             registered = True
         try:
             crowdfund = payment_form.cleaned_data['crowdfund']
             crowdfund.make_payment(token, email, amount, show, user)
         except (stripe.InvalidRequestError, stripe.CardError,
                 stripe.APIConnectionError,
                 stripe.AuthenticationError) as payment_error:
             logging.warn(payment_error)
             return self.return_error(request, payment_error)
         if request.is_ajax():
             data = {
                 'authenticated':
                 user.is_authenticated() if user else False,
                 'registered': registered
             }
             return JsonResponse(data, status=200)
         else:
             messages.success(request, 'Thank you for your contribution!')
             return redirect(self.get_redirect_url())
     return self.return_error(request)
コード例 #5
0
ファイル: views.py プロジェクト: WPMedia/muckrock
    def post(self, request, **kwargs):
        """
        First we validate the payment form, so we don't charge someone's card by
        accident.
        Next, we charge their card. Finally, use the validated payment form to create
        and return a CrowdfundRequestPayment object.
        """
        # pylint: disable=too-many-locals
        token = request.POST.get("stripe_token")
        email = request.POST.get("stripe_email")
        email = validate_stripe_email(email)

        payment_form = CrowdfundPaymentForm(request.POST)
        if payment_form.is_valid() and token and email:
            amount = payment_form.cleaned_data["stripe_amount"]
            # If there is no user but the show and full_name fields are filled in,
            # and a user with that email does not already exists, create the
            # user with our "miniregistration" functionality and then log them in
            user = request.user if request.user.is_authenticated else None
            registered = False
            show = payment_form.cleaned_data["show"]
            full_name = payment_form.cleaned_data["full_name"]
            email_exists = User.objects.filter(email__iexact=email).exists()
            if user is None and show and full_name and not email_exists:
                try:
                    user = self.miniregister(payment_form, full_name, email)
                except requests.exceptions.RequestException:
                    return self.return_error(request)
                registered = True
            crowdfund = payment_form.cleaned_data["crowdfund"]
            if crowdfund.expired():
                return self.return_error(request)
            try:
                if crowdfund.can_recur() and payment_form.cleaned_data["recurring"]:
                    crowdfund.make_recurring_payment(token, email, amount, show, user)
                    event = "Recurring Crowdfund Payment"
                    kwargs = {}
                else:
                    crowdfund.make_payment(token, email, amount, show, user)
                    event = "Crowdfund Payment"
                    kwargs = {"charge": float(amount)}
            except stripe.StripeError as payment_error:
                logger.warning(payment_error)
                return self.return_error(request, payment_error)
            else:
                mixpanel_event(
                    request,
                    event,
                    {
                        "Amount": float(amount),
                        "Crowdfund": crowdfund.name,
                        "Crowdfund ID": crowdfund.pk,
                        "Show": show,
                    },
                    **kwargs
                )
            if request.is_ajax():
                data = {
                    "authenticated": user.is_authenticated if user else False,
                    "registered": registered,
                }
                return JsonResponse(data, status=200)
            else:
                messages.success(request, "Thank you for your contribution!")
                return redirect(self.get_redirect_url())
        return self.return_error(request)