def create_subscription(request): data = request.data # run the `create_stripe_data` management command and get the price_id # from the Stripe console and add it to `.env` as SUBSCRIPTION_PRICE_ID price_id = os.environ.get("SUBSCRIPTION_PRICE_ID", "price_abc124") try: logger.info("Creating Stripe Customer") stripe_customer = stripe.Customer.create(email=request.user.email) logger.info("Stripe Customer created") if "id" in stripe_customer: stripe_customer_id = stripe_customer["id"] else: # what happens if Customer.create is called with # an email that already exists? return JsonResponse({"message": "Error creating Stripe Customer"}) # Attach the payment method to the customer logger.info("Attaching payment info to customer") stripe.PaymentMethod.attach( data["paymentMethodId"], customer=stripe_customer_id, ) # Set the default payment method on the customer logger.info("Setting default payment method for customer") stripe.Customer.modify( stripe_customer_id, invoice_settings={ "default_payment_method": data["paymentMethodId"], }, ) # Create the subscription logger.info("Creating Stripe Subscription") stripe_subscription = stripe.Subscription.create( customer=stripe_customer_id, items=[{ "price": price_id }], expand=["latest_invoice.payment_intent"], ) # save the subscription to the user user = request.user logger.info("Creating Subscription (Django object)") subscription_object = Subscription( stripe_customer_id=stripe_customer_id, # leave a grace period of a few days before cancelling subscription valid_through=datetime.fromtimestamp( stripe_subscription["current_period_end"] + TWO_DAYS # two days in seconds ), stripe_subscription_id=stripe_subscription["id"], ) logger.info("Save subscription model") subscription_object.save() logger.info("Save subscription model to user") user.subscription = subscription_object user.save() return Response(stripe_subscription) except Exception as e: return Response({"message": str(e)})
def parse_subscription(self, row: List[str], users: List[User]): if row[1]: user = self.find_user(*self.get_user(row[1]), users) for i, ceil in enumerate(row[25: 31]): if ceil == self.TRUE: user.subscriptions.append(Subscription(self.SUB_MAP[i]))