From c2514cd5b5049672642a7615bb5d174826c87e95 Mon Sep 17 00:00:00 2001 From: PCoder Date: Sat, 14 Sep 2019 21:57:35 +0530 Subject: [PATCH] Add code to subscribe user to recurring subscriptions --- ucloud_pay.py | 59 +++++++++++++++++++++++++++++++++++++++++++++------ 1 file changed, 52 insertions(+), 7 deletions(-) diff --git a/ucloud_pay.py b/ucloud_pay.py index a347a6a..6d16e6f 100644 --- a/ucloud_pay.py +++ b/ucloud_pay.py @@ -10,6 +10,7 @@ from pyotp import TOTP from config import etcd_client as client, logging, APP_PORT from stripe_utils import StripeUtils from uuid import uuid4 +import time app = Flask(__name__) api = Api(app) @@ -37,6 +38,20 @@ def check_otp(name, realm, token): ) return response.status_code +def get_plan_id_from_product(product): + plan_id = "ucloud-v1-" + plan_id += product["name"].strip().replace(' ', '-') + "-" + plan_id += product["type"] + return plan_id + +def get_order_id(): + order_id_kv = client.get("/v1/last_order_id") + if order_id_kv: + order_id = int(order_id_kv.value) + 1 + else: + order_id = config("INIT_ORDER_ID") + client.put("/v1/last_order_id", order_id) + return "OR-{}".format(order_id) class ListProducts(Resource): @staticmethod @@ -255,18 +270,48 @@ class ProductOrder(Resource): logging.debug("Product {} is recurring payment".format( product_obj["name"]) ) + plan_id = get_plan_id_from_product(product_obj) + res = stripe_utils.get_or_create_stripe_plan( + stripe_plan_id=plan_id, amount=product_obj["price"], + name=plan_id + ) + if res["response_object"]: + logging.debug("Obtained plan {}".format(plan_id)) + subscription_res = stripe_utils.subscribe_customer_to_plan( + stripe_customer.id, + [{"plan": plan_id}] + ) + subscription_obj = subscription_res["response_object"] + if (subscription_obj is None + or subscription_obj.status != 'active'): + logging.error("Could not create subscription") + if subscription_obj is None: + logging.error("subscription_obj is None") + else: + logging.error("subscription status is NOT active") + logging.error("Detail = {}".format( + subscription_res["error"] + )) + return { "message": "Error subscribing to plan. " + "Details: {}".format( + subscription_res["error"]) }, 400 + else: + logging.debug("Created subscription successfully") + order_obj = { + "order_id": get_order_id(), + "ordered_at": int(time.time()), + "product": product_obj, + } + return {"message": "Order successful", + "order_details": order_obj}, 200 + else: + logging.error("Could not create plan {}".format(plan_id)) + elif product_obj['type'] == "one-time": logging.debug( "Product {} is one-time " "payment".format(product_obj["type"]) ) - - - - # If charge successful, create an order object - - # Else handle unsuccessful cases with grace - except KeyError as key_error: logging.error("Key error occurred") logging.error(str(key_error))