def handle_user_signed_up(sender, **kwargs): log( user=kwargs.get("user"), action="USER_SIGNED_UP", extra={} ) customers.create(kwargs.get("user"))
def create_account(sender, **kwargs): user = kwargs["instance"] if kwargs["created"]: account = Account(user=user) account.save() # stripe customer create(user, charge_immediately=False)
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)
def create_customer(self, user, token): return customers.create( user, card=token, plan=None, charge_immediately=False )
def RegisterView(request): msg = '' email = '' password = '' plan = '' if request.POST: email = request.POST.get('email') password = request.POST.get('password') plan = request.POST.get('plan', settings.PINAX_STRIPE_DEFAULT_PLAN) user = User.objects.filter(email=email).first() if user is not None: msg="email_exists" else: user = User() user.username = email user.is_active = False user.email = email user.password = password user.set_password(password) user.save() site_name = get_current_site(request) # todo: change hard code subject subject = 'Activate account' # generate message # print(urlsafe_base64_encode(force_bytes(user.pk))) message = render_to_string('app/account_activation_email.html', { 'user': user, 'domain': site_name.domain, 'uid': urlsafe_base64_encode(force_bytes(user.pk)).decode("utf-8"), 'token': account_activation_token.make_token(user), }) msg = "register_success" # send activation link to the user user.email_user(subject, message) from pinax.stripe.actions import customers customers.create(user=user, plan=plan) return render(request, 'v2/registration/register_done.html', { 'msg': msg, 'email': email, 'password': password}) plans = get_main_plan() return render(request, 'v2/registration/register.html', { 'msg': msg, 'email': email, 'password': password, 'plan': plan, 'plans': plans})
def signup(request): # TODO Rewrite this to generic View. if request.method == 'POST': form = SignupForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') raw_password = form.cleaned_data.get('password1') user = authenticate(username=username, password=raw_password) # Creating Stripe customer id. customers.create(user=user) login(request, user) return redirect('index') else: form = SignupForm() return render(request, 'registration/signup.html', {'form': form})
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 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)
def process_charge(request): if request.is_ajax(): card_dict = json.loads(request.POST.get('token')) token = card_dict['id'] # Charge the user's card: customer = Customer.objects.filter(user_id=request.user).first() if customer == None: customer = customers.create(user=request.user) plan = Plan.objects.get(stripe_id=request.POST['plan']) try: subs = subscriptions.create(customer=customer, plan=plan.stripe_id, token=token) valid = subscriptions.is_valid(subs) except Exception as e: return JsonResponse({'valid': False, 'message': e.message}) return JsonResponse({'valid': valid})
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 process_free_charge(request): if request.is_ajax(): # Charge the user's card: customer = Customer.objects.filter(user_id=request.user).first() if customer == None: customer = customers.create(user=request.user) plan = Plan.objects.get(stripe_id=request.POST['plan']) coupon = request.POST['coupon'] #should check that it is actually free before processing try: subs = subscriptions.create(customer=customer, plan=plan.stripe_id, coupon=coupon.upper()) valid = subscriptions.is_valid(subs) except Exception as e: return JsonResponse({'valid': False, 'message': e.message}) return JsonResponse({'valid': valid})
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)
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()
def upgrade(request): if request.is_ajax(): token = request.POST.get('token_id') # Charge the user's card: customer = Customer.objects.filter(user_id=request.user).first() if customer == None: customer = customers.create(user=request.user) plan = Plan.objects.get(stripe_id=request.POST['plan']) coupon = request.POST['coupon'] try: if coupon == '': subs = subscriptions.create(customer=customer, plan=plan.stripe_id, token=token) else: subs = subscriptions.create(customer=customer, plan=plan.stripe_id, coupon=coupon.upper(), token=token) valid = subscriptions.is_valid(subs) except Exception as e: return JsonResponse({'valid': False, 'message': e.message}) return JsonResponse({'valid': valid})
def customer(self): if not hasattr(self, "_customer"): self._customer = customers.get_customer_for_user(self.request.user) if self._customer is None: self._customer = customers.create(self.request.user) return self._customer
def check_stripe_customer(self, user): try: Customer.objects.get(user=user) except Customer.DoesNotExist: customers.create(user=user, card=self.request.POST['stripeToken']) return
def handle_user_signed_up(sender, **kwargs): log(user=kwargs.get('user'), action='USER_SIGNED_UP', extra={}) customers.create(kwargs.get('user'))
def create_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) Cart.objects.create(user=instance) customers.create(user=instance)
def check_stripe_customer(self, user): try: Customer.objects.get(user=user) except Customer.DoesNotExist: customers.create(user=user, card=self.request.POST['stripeToken']) return
def create_customer(self): customers.create(user=self.created_user)
def handle_user_signed_up(sender, **kwargs): log(user=kwargs.get("user"), action="USER_SIGNED_UP", extra={}) customers.create(kwargs.get("user"))