def subscribe_to_plan(uid, data) -> FlaskResponse: """ Subscribe to a plan given a user id, payment token, email, orig_system :param uid: :param data: :return: current subscriptions for user. """ customer = existing_or_new_customer( g.subhub_account, user_id=uid, email=data["email"], source_token=data["pmt_token"], origin_system=data["orig_system"], display_name=data["display_name"], ) existing_plan = has_existing_plan(customer, plan_id=data["plan_id"]) if existing_plan: return {"message": "User already subscribed."}, 409 if not customer.get("deleted"): Subscription.create(customer=customer.id, items=[{ "plan": data["plan_id"] }]) updated_customer = fetch_customer(g.subhub_account, user_id=uid) newest_subscription = find_newest_subscription( updated_customer["subscriptions"]) return create_return_data(newest_subscription), 201 else: return dict(message=None), 400
def build_stripe_subscription(customer_id: str, plan_id: str, idempotency_key: str) -> Subscription: """ Create a new Stripe subscription for a given customer :param customer_id: :param plan_id: :param idempotency_key: :return: Subscription object """ try: sub = Subscription.create( customer=customer_id, items=[{ "plan": plan_id }], idempotency_key=idempotency_key, ) return sub except ( InvalidRequestError, APIConnectionError, APIError, RateLimitError, IdempotencyError, StripeErrorWithParamCode, AuthenticationError, ) as e: logger.error("sub error", error=e) raise e
def subscribe_customer(customer: Customer, plan_id: str) -> Subscription: """ Subscribe Customer to Plan :param customer: :param plan: :return: Subscription Object """ try: sub = Subscription.create(customer=customer, items=[{"plan": plan_id}]) return sub except Exception as e: logger.error("sub error", error=e) raise InvalidRequestError("Unable to create plan", param=plan_id)