Esempio n. 1
0
 def charge_customer(self, package_object):
     charges.create(amount=decimal.Decimal(package_object.amount),
                    customer=self.request.user.customer.stripe_id,
                    currency=package_object.currency,
                    description=package_object.packageid
                    )
     return
Esempio n. 2
0
 def save(self):
     user = self.context.get('user')
     amount = self.validated_data['amount']
     try:
         charges.create(
             amount=amount,
             customer=user.customer.stripe_id,
         )
     except:
         raise PaymentRequired
Esempio n. 3
0
    def post(self, request, campaign_id, *args, **kwargs):
        # Validate request and campaign status
        try:
            campaign = Campaign.objects.get(id=campaign_id)
        except Campaign.DoesNotExist:
            return HttpResponseBadRequest("Campaign with ID {campaign_id} does not exist.".format(campaign_id=campaign_id))
        else:
            if not campaign.open():
                return HttpResponseBadRequest("This campaign is no longer accepting investments.")
        form = PaymentChargeForm(request.POST, campaign=campaign)
        if not form.is_valid():
            return HttpResponseBadRequest(unicode(form.errors))
        d = form.cleaned_data

        # Get card and customer
        card = d['card']
        customer = customers.get_customer_for_user(request.user)
        if not customer:
            customer = customers.create(request.user, card=card, plan=None, charge_immediately=False)

        # Create charge
        num_shares = d['num_shares']
        amount = decimal.Decimal(campaign.total(num_shares))
        try:
            charge = charges.create(amount=amount, customer=customer.stripe_id)
        except CardError as e:
            return HttpResponseBadRequest(e.message)
        Investment.objects.create(charge=charge, campaign=campaign, num_shares=num_shares)
        return HttpResponse(status=205)
Esempio n. 4
0
 def charge_customer(self, amount, source):
     charge = charges.create(
         amount=amount,
         customer=self.customer,
         source=source,
         send_receipt=False
     )
     return charge
Esempio n. 5
0
    def post(self, request, campaign_id, *args, **kwargs):
        # Validate request and campaign status
        try:
            campaign = Campaign.objects.get(id=campaign_id)
        except Campaign.DoesNotExist:
            return Response(
                "Campaign with ID {campaign_id} does not exist.".format(
                    campaign_id=campaign_id),
                status=status.HTTP_400_BAD_REQUEST,
            )
        else:
            if not campaign.open():
                return Response(
                    "This campaign is no longer accepting investments.",
                    status=status.HTTP_400_BAD_REQUEST,
                )
        form = PaymentChargeForm(request.data, campaign=campaign)
        if not form.is_valid():
            return Response(str(form.errors),
                            status=status.HTTP_400_BAD_REQUEST)
        d = form.cleaned_data

        # Get card and customer
        card = d["card"]
        customer = customers.get_customer_for_user(request.user)
        if not customer:
            customer = customers.create(request.user,
                                        card=card,
                                        plan=None,
                                        charge_immediately=False)
            card = Card.objects.get(customer=customer)
        else:
            # Check if we have the card the user is using
            # and if not, create it
            card_fingerprint = stripe.Token.retrieve(
                card)["card"]["fingerprint"]
            cards_with_fingerprint = Card.objects.filter(
                customer=customer, fingerprint=card_fingerprint)
            if cards_with_fingerprint.exists():
                card = cards_with_fingerprint[0]
            else:
                card = sources.create_card(customer=customer, token=card)

        # Create charge
        num_shares = d["num_shares"]
        amount = decimal.Decimal(campaign.total(num_shares))
        try:
            charge = charges.create(amount=amount,
                                    customer=customer.stripe_id,
                                    source=card)
        except stripe.CardError as e:
            return Response(e.message, status=status.HTTP_400_BAD_REQUEST)
        Investment.objects.create(charge=charge,
                                  campaign=campaign,
                                  num_shares=num_shares)
        return Response(status=status.HTTP_205_RESET_CONTENT)
Esempio n. 6
0
 def signup(self, request, user):
     user.name = self.cleaned_data['name']
     if 'publisher' in request.path:
         user.is_publisher = True
         payload = jwt_payload_handler(user)
         token = jwt_encode_handler(payload)
         user.token = token
     else:
         try:
             customer = customers.create(user)
             sources.create_card(customer, request.POST.get("stripeToken"))
             add_on = request.POST.get('amount')
             if add_on != '':
                 add_on = Decimal(add_on)
                 charges.create(amount=add_on,
                                customer=user.customer.stripe_id)
                 user.balance = user.balance + add_on
         except stripe.CardError as e:
             user.delete()
             raise forms.ValidationError(smart_str(e))
     user.save()
Esempio n. 7
0
 def post(self, request, *args, **kwargs):
     try:
         add_on = Decimal(request.POST.get('amount'))
     except:
         messages.error(request, 'Amount was not in the desired format.')
         can_charge = True
         balance = request.user.balance
         data = {'balance': balance, 'can_charge': can_charge}
         return render(request, self.template_name, data)
     try:
         charges.create(amount=add_on,
                        customer=request.user.customer.stripe_id)
     except CardError as e:
         body = e.json_body
         err = body.get('error', {})
         messages.error(request, err.get('message'))
         return redirect("/reload")
     user = User.objects.get(username=request.user.username)
     user.balance = user.balance + add_on
     user.save()
     messages.success(request, "Payment was successfully processed.")
     url = self.get_redirect_url() or '/user'
     return redirect(url)
Esempio n. 8
0
    def post(self, request, campaign_id, *args, **kwargs):
        # Validate request and campaign status
        try:
            campaign = Campaign.objects.get(id=campaign_id)
        except Campaign.DoesNotExist:
            return Response(
                "Campaign with ID {campaign_id} does not exist.".format(campaign_id=campaign_id),
                status=status.HTTP_400_BAD_REQUEST
            )
        else:
            if not campaign.open():
                return Response(
                    "This campaign is no longer accepting investments.",
                    status=status.HTTP_400_BAD_REQUEST
                )
        form = PaymentChargeForm(request.data, campaign=campaign)
        if not form.is_valid():
            return Response(str(form.errors), status=status.HTTP_400_BAD_REQUEST)
        d = form.cleaned_data

        # Get card and customer
        card = d['card']
        customer = customers.get_customer_for_user(request.user)
        if not customer:
            customer = customers.create(request.user, card=card, plan=None, charge_immediately=False)
            card = Card.objects.get(customer=customer)
        else:
            # Check if we have the card the user is using
            # and if not, create it
            card_fingerprint = stripe.Token.retrieve(card)['card']['fingerprint']
            cards_with_fingerprint = Card.objects.filter(customer=customer, fingerprint=card_fingerprint)
            if cards_with_fingerprint.exists():
                card = cards_with_fingerprint[0]
            else:
                card = sources.create_card(customer=customer, token=card)

        # Create charge
        num_shares = d['num_shares']
        amount = decimal.Decimal(campaign.total(num_shares))
        try:
            charge = charges.create(amount=amount, customer=customer.stripe_id, source=card)
        except stripe.CardError as e:
            return Response(e.message, status=status.HTTP_400_BAD_REQUEST)
        Investment.objects.create(charge=charge, campaign=campaign, num_shares=num_shares)
        return Response(status=status.HTTP_205_RESET_CONTENT)
Esempio n. 9
0
def charge(customer, amount):
    amount = Decimal(amount)
    return create(amount=amount, customer=customer, send_receipt=False)
Esempio n. 10
0
 def charge_customer(self, recharge_pack):
     charges.create(amount=decimal.Decimal(recharge_pack.amount), customer=self.request.user.customer.stripe_id,
                    currency=recharge_pack.currency, description=recharge_pack.rechargeid)
     return
Esempio n. 11
0
 def charge_customer(self, recharge_pack):
     charges.create(amount=decimal.Decimal(recharge_pack.amount),
                    customer=self.request.user.customer.stripe_id,
                    currency=recharge_pack.currency,
                    description=recharge_pack.rechargeid)
     return
Esempio n. 12
0
 def charge_customer(self, package_object):
     charges.create(amount=decimal.Decimal(package_object.amount),
                    customer=self.request.user.customer.stripe_id,
                    currency=package_object.currency,
                    description=package_object.packageid)
     return
Esempio n. 13
0
def charge(amount,
           card_number,
           card_exp_month,
           card_exp_year,
           card_cvc,
           currency=settings.STRIPE_DEFAULT_CURRENCY,
           description=None,
           user=None):

    # Create a customer reference if we have a user
    if user:
        try:
            customer = Customer.objects.get(user=user)
        except Customer.DoesNotExist:
            customer = Customer.objects.create(user=user, currency=currency)
    else:
        customer = None

    # Request a card token from Stripe
    try:
        token = stripe_token.create(
            card={
                "number": card_number,
                "exp_month": card_exp_month,
                "exp_year": card_exp_year,
                "cvc": card_cvc
            })
    except stripe.error.CardError as e:
        data = {"non_field_errors": [e.json_body["error"]["message"]]}
        return data

    if customer:
        # Add that card as a source and register it with the customer
        try:
            sources.create_card(customer, token)
        except stripe.error.CardError as e:
            data = {"non_field_errors": [e.json_body["error"]["message"]]}
            return data
    else:
        try:
            source = stripe_source.create(type='card', token=token)
        except stripe.error.CardError as e:
            data = {"non_field_errors": [e.json_body["error"]["message"]]}
            return data

    # Charge the source with the right amount
    try:
        amount_int = int(amount * 100)
        if customer:
            charges.create(customer=customer,
                           amount=amount_int,
                           description=description)
        else:
            stripe_charge.create(source=source,
                                 amount=amount_int,
                                 currency=currency,
                                 description=description)
    except stripe.error.CardError as e:
        data = {"non_field_errors": [e.json_body["error"]["message"]]}
        return data

    return True
Esempio n. 14
0
    def _do_finishing_process(self):
        bid_queryset = self.get_active_bid_queryset()
        if bid_queryset.count() == 0:
            self.status = AUCTION_STATUS_CANCELLED_DUE_TO_NO_BIDS
            self.save()
            return

        highest_bid = bid_queryset.get(price=self.current_price)
        highest_bid.status = BID_STATUS_WON
        highest_bid.save()

        bid_queryset.exclude(price=highest_bid.price).update(
            status=BID_STATUS_LOST)

        try:
            charge = charges.create(
                amount=Decimal(highest_bid.price),
                customer=highest_bid.user.customer.stripe_id,
            )
        except:
            raise PaymentRequired

        if not charge.paid:
            """
            This will make logic below to set status to `waiting for payment` unneeded
            """
            raise PaymentRequired

        sale = Sale(
            price=highest_bid.price,
            status=SALE_STATUS_WAITING_FOR_PAYMENT,
            auction=self,
            product=self.product,
            user=highest_bid.user,
            stripe_charge_id=charge.stripe_id,
        )
        if charge.paid:
            sale.status = SALE_STATUS_RECEIVED_PAYMENT
            sale.payment_received = timezone.now()
        sale.save()

        if charge.paid:
            self.status = AUCTION_STATUS_WAITING_TO_SHIP

            try:
                HistoryRecord.objects.create_history_record(
                    self, None, HISTORY_RECORD_AUCTION_PAYMENT,
                    {'amount': highest_bid.price})
            except:
                pass
        else:
            self.status = AUCTION_STATUS_WAITING_FOR_PAYMENT
        self.ended_at = timezone.now()
        self.save()

        try:
            HistoryRecord.objects.create_history_record(
                self, None, HISTORY_RECORD_AUCTION_FINISH)

            Notification.objects.create_notification(
                None, self, NOTIFICATION_AUCTION_CLOSE, {
                    'winner_user_id': highest_bid.user.pk,
                })

            bids = auction.bid_set.filter(
                status=BID_STATUS_ACTIVE).select_related('user')

            send_email(
                'Auction has ended',
                'Auction {} has ended. Unfortunately someone else has won the auction. But you can win next time!'
                .format(auction.title), [
                    bid.user.email
                    for bid in bids if bid.user.pk != highest_bid.user.pk
                ])

            send_email(
                'You have won an auction!',
                'Congratulations! Auction {} has ended, and you\'ve won the auction.'
                .format(auction.title), [
                    bid.user.email
                    for bid in bids if bid.user.pk != highest_bid.user.pk
                ])
        except:
            pass

        return charge.paid