Beispiel #1
0
    def post(self, request):

        serializer = self.serializer_class(data=request.data)

        if serializer.is_valid():

            # Get or create the customer
            try:
                customer = Customer.objects.get(user=request.user)
            except Customer.DoesNotExist:
                customer = customers.create(user=request.user)

            if not customers.can_charge(customer):

                if serializer.data["card_number"]:
                    try:
                        token = stripe_token.create(
                            card={
                                "number": serializer.data["card_number"],
                                "exp_month": serializer.data["card_exp_month"],
                                "exp_year": serializer.data["card_exp_year"],
                                "cvc": serializer.data["card_cvc"]
                            })
                    except stripe.error.CardError as e:
                        data = {
                            "non_field_errors":
                            [e.json_body["error"]["message"]]
                        }
                        return Response(data,
                                        status=status.HTTP_400_BAD_REQUEST)

                    try:
                        sources.create_card(customer, token)
                    except stripe.error.CardError as e:
                        data = {
                            "non_field_errors":
                            [e.json_body["error"]["message"]]
                        }
                        return Response(data,
                                        status=status.HTTP_400_BAD_REQUEST)

            try:
                subscriptions.create(customer=customer,
                                     plan=serializer.data["plan_id"])
            except stripe.error.InvalidRequestError as e:
                data = {"non_field_errors": [e.json_body["error"]["message"]]}
                return Response(data, status=status.HTTP_400_BAD_REQUEST)

            subscription = SubscriptionUpdateSerializer(
                data={"plan_id": serializer.data["plan_id"]})
            subscription.is_valid()

            return Response(subscription.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
Beispiel #2
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)
    def test_subscribe_update(self):
        """Test update a subscription."""

        customer = customers.create(user=self.normal_user)
        token = stripe_token.create(
            card={
                "number": self.card["card_number"],
                "exp_month": self.card["card_exp_month"],
                "exp_year": self.card["card_exp_year"],
                "cvc": self.card["card_cvc"]
            })
        sources.create_card(customer, token)
        subscriptions.create(customer=customer, plan="MF-MONTHLY")

        self.client.credentials(HTTP_AUTHORIZATION='Token ' +
                                self.normal_user_token.key)

        data = {
            'plan_id': "MF-YEARLY",
        }

        url = reverse('stripe-api:subscription-update')
        response = self.client.post(url, data, format='json')
        self.assertEqual(response.status_code, status.HTTP_200_OK)

        # Check that the customer was created and has a subscription
        customer = Customer.objects.get(user=self.normal_user)
        subscription = Subscription.objects.get(customer=customer)
        self.assertTrue(subscription.plan_id, data['plan_id'])

        if self.display_doc:
            # Generate documentation
            content = {
                'title': "Subscribe",
                'http_method': 'POST',
                'url': url,
                'payload': self.jsonify(data),
                'response': self.jsonify(response.data),
                'response_status': response.status_code,
                'description': ("Subscribe to a give plan with card details.")
            }
            self.doc.display_section(content)
Beispiel #4
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()
Beispiel #5
0
def process_stripe_user(store, card_token, existing_cards=None):

    # Get the current stores stripe customer info.
    stripe_customer = get_customer_for_user(store)
    # Get all the current customers/stores payment methods
    if not existing_cards:
        existing_cards = Card.objects.filter(
            customer=stripe_customer).order_by("created_at")

    stripe_card_token = card_token

    # If the store has no stripe customer, create one.
    if not stripe_customer:
        stripe_customer = create_without_account_custom(store,
                                                        card=stripe_card_token)
    else:
        # Save the new card to the existing user, and delete old cards.
        for card in existing_cards:
            delete_card(stripe_customer, card.stripe_id)

        create_card(stripe_customer, token=stripe_card_token)

    return stripe_customer
Beispiel #6
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)
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
Beispiel #8
0
 def create_card(self, request):
     token = request.POST.get('stripeToken')
     holder = request.POST.get('card_holder')
     card = sources.create_card(self.customer, token=token)
     sources.update_card(self.customer, card.stripe_id, name=holder)
Beispiel #9
0
 def create_card(self, customer, stripe_token):
     sources.create_card(customer=customer, token=stripe_token)