Эх сурвалжийг харах

优化创建支付订单接口

locky 2 жил өмнө
parent
commit
f1ebdcb0a1
1 өөрчлөгдсөн 116 нэмэгдсэн , 61 устгасан
  1. 116 61
      Controller/AiController.py

+ 116 - 61
Controller/AiController.py

@@ -230,7 +230,8 @@ class AiView(View):
             redisObj.del_data(key=redis_key)
             return response.json(474)
 
-    def do_create_pay_order(self, request_dict, request, user_id, response):
+    @classmethod
+    def do_create_pay_order(cls, request_dict, request, user_id, response):
         """
         创建支付订单
         @param request_dict: 请求数据
@@ -271,22 +272,22 @@ class AiView(View):
             else:
                 store_meal_name = '未知套餐'
 
-            nowTime = int(time.time())
-            orderID = CommonService.createOrderID()
+            now_time = int(time.time())
             price = round(float(price), 2)
+            order_id = CommonService.createOrderID()
 
             order_dict = {
-                'orderID': orderID,
+                'orderID': order_id,
                 'UID': uid,
                 'channel': channel,
                 'userID_id': user_id,
                 'desc': content,
                 'payType': pay_type,
-                'payTime': nowTime,
+                'payTime': now_time,
                 'price': price,
                 'currency': currency,
-                'addTime': nowTime,
-                'updTime': nowTime,
+                'addTime': now_time,
+                'updTime': now_time,
                 'ai_rank_id': rank,
                 'rank_id': 1,
                 'order_type': 1,
@@ -295,21 +296,33 @@ class AiView(View):
 
             # 创建订单数据和返回支付回调链接
             if pay_type == 1:  # PayPal支付
-                order_dict['paymentID'], order_dict['pay_url'] = self.create_paypal_payment(lang, orderID, price,
-                                                                                            currency, content, response)
-                res_data = {'redirectUrl': order_dict['pay_url'], 'orderID': orderID}
-            elif pay_type == 2:  # 支付宝
-                order_dict['pay_url'] = self.create_alipay_payment(lang, orderID, price, title, content, response)
-                res_data = {'redirectUrl': order_dict['pay_url'], 'orderID': orderID}
+                res_dict = cls.create_paypal_payment(lang, order_id, price, currency, content)
+                if not res_dict:
+                    return response.json(10, 'create ai order failed')
+                order_dict['paymentID'], order_dict['pay_url'] = res_dict['payment_id'], res_dict['pay_url']
+                res_data = {'orderID': order_id, 'redirectUrl': order_dict['pay_url']}
+
+            elif pay_type == 2:  # 支付宝支付
+                res_dict = cls.create_alipay_payment(lang, order_id, price, title, content)
+                if not res_dict:
+                    return response.json(10, 'create ai order failed')
+                order_dict['pay_url'] = res_dict['pay_url']
+                res_data = {'orderID': order_id, 'redirectUrl': order_dict['pay_url']}
+
             elif pay_type == 3:  # 微信支付
                 ip = CommonService.get_ip_address(request)
-                order_dict['pay_url'], sign_params = self.create_wechat_payment(lang, orderID, price, ip, content,
-                                                                                response)
-                res_data = {'redirectUrl': order_dict['pay_url'], 'orderID': orderID, 'result': sign_params}
+                res_dict = cls.create_wechat_payment(lang, order_id, price, ip, content)
+                if not res_dict:
+                    return response.json(10, 'create ai order failed')
+                order_dict['pay_url'], sign_params = res_dict['pay_url'], res_dict['sign_params']
+                res_data = {'orderID': order_id, 'redirectUrl': order_dict['pay_url'], 'result': sign_params}
+
             else:
                 return response.json(444, {'param': 'pay_type'})
+
             Order_Model.objects.create(**order_dict)
             return response.json(0, res_data)
+
         except Exception as e:
             return response.json(500, repr(e))
 
@@ -573,57 +586,99 @@ class AiView(View):
             return response.json(500, repr(e))
 
     @staticmethod
-    def create_paypal_payment(lang, orderID, price, currency, content, response):
+    def create_paypal_payment(lang, order_id, price, currency, content):
+        """
+        创建PayPal支付
+        @param lang: 语言
+        @param order_id: 订单id
+        @param price: 价格
+        @param currency: 货币
+        @param content: 内容
+        @return: pay_dict
+        """
         cancel_url = CommonService.get_payment_status_url(lang, 'fail')
-        call_sub_url = "{}AiService/doPayPalCallBack?orderID={}&lang={}".format(SERVER_DOMAIN_SSL, orderID, lang)
-
-        paypalrestsdk.configure(PAYPAL_CRD)
-        payment = paypalrestsdk.Payment({
-            "intent": "sale",
-            "payer": {"payment_method": "paypal"},
-            "redirect_urls": {"return_url": call_sub_url, "cancel_url": cancel_url},
-            "transactions": [{
-                "item_list": {"items": [
-                    {"name": "Cloud video", "sku": "1", "price": price, "currency": "USD", "quantity": 1}]},
-                "amount": {"total": price, "currency": currency},
-                "description": content}]})
-        if not payment.create():  # 创建失败
-            return response.json(10, payment.error)
-        paymentID = payment['id']  # 获取paymentID
-        for link in payment.links:
-            if link.rel == "approval_url":
-                pay_url = str(link.href)
-                return paymentID, pay_url
-        return response.json(10, 'create_ai_order_failed')
+        call_sub_url = "{}AiService/doPayPalCallBack?orderID={}&lang={}".format(SERVER_DOMAIN_SSL, order_id, lang)
+
+        try:
+            paypalrestsdk.configure(PAYPAL_CRD)
+            payment = paypalrestsdk.Payment({
+                "intent": "sale",
+                "payer": {"payment_method": "paypal"},
+                "redirect_urls": {"return_url": call_sub_url, "cancel_url": cancel_url},
+                "transactions": [{
+                    "item_list": {"items": [
+                        {"name": "Cloud video", "sku": "1", "price": price, "currency": "USD", "quantity": 1}]},
+                    "amount": {"total": price, "currency": currency},
+                    "description": content}]})
+
+            pay_dict = {}
+            if not payment.create():  # 创建失败
+                return pay_dict
+            payment_id = payment['id']  # 获取payment id
+            for link in payment.links:
+                if link.rel == "approval_url":
+                    pay_url = str(link.href)
+                    pay_dict['payment_id'] = payment_id
+                    pay_dict['pay_url'] = pay_url
+                    return pay_dict
+            return pay_dict
+        except Exception as e:
+            print(e)
+            return {}
 
     @staticmethod
-    def create_alipay_payment(lang, orderID, price, title, content, response):
-        aliPayObj = AliPayObject()
-        alipay = aliPayObj.conf()
-        subject = title + content
-        order_string = alipay.api_alipay_trade_wap_pay(
-            out_trade_no=orderID,
-            total_amount=price,
-            subject=subject,
-            return_url="{}web/paid2/success.html".format(SERVER_DOMAIN_SSL),
-            notify_url="{}AiService/doAlipayCallBack".format(SERVER_DOMAIN_SSL),
-            quit_url="{}web/paid2/fail.html".format(SERVER_DOMAIN_SSL),
-            passback_params=quote("lang=" + lang)
-        )
-        if not order_string:
-            return response.json(10, '生成订单错误.')
-        return aliPayObj.alipay_prefix + order_string
+    def create_alipay_payment(lang, order_id, price, title, content):
+        """
+        创建支付宝支付
+        @param lang: 语言
+        @param order_id: 订单id
+        @param price: 价格
+        @param title: 标题
+        @param content: 内容
+        @return: pay_dict
+        """
+        try:
+            aliPayObj = AliPayObject()
+            alipay = aliPayObj.conf()
+            subject = title + content
+            order_string = alipay.api_alipay_trade_wap_pay(
+                out_trade_no=order_id,
+                total_amount=price,
+                subject=subject,
+                return_url="{}web/paid2/success.html".format(SERVER_DOMAIN_SSL),
+                notify_url="{}AiService/doAlipayCallBack".format(SERVER_DOMAIN_SSL),
+                quit_url="{}web/paid2/fail.html".format(SERVER_DOMAIN_SSL),
+                passback_params=quote("lang=" + lang)
+            )
+            if not order_string:
+                return {}
+            return {'pay_url': aliPayObj.alipay_prefix + order_string}
+        except Exception as e:
+            print(e)
+            return {}
 
     @staticmethod
-    def create_wechat_payment(lang, orderID, price, ip, content, response):
-        pay = WechatPayObject()
+    def create_wechat_payment(lang, order_id, price, ip, content):
+        """
+        创建微信支付
+        @param lang: 语言
+        @param order_id: 订单id
+        @param price: 价格
+        @param ip: ip
+        @param content: 内容
+        @return: pay_dict
+        """
         pay_url = "{}AiService/doWechatCallBack".format(SERVER_DOMAIN_SSL)
-        # 统一调用接口
-        pay.get_parameter(orderID, content, float(price) * 100, ip, pay_url, quote("lang=" + lang))
-        sign_params = pay.re_finall(orderid=orderID)
-        if not sign_params:
-            return response.json(10, '生成订单错误.')
-        return pay_url, sign_params
+        try:
+            pay = WechatPayObject()
+            pay.get_parameter(order_id, content, float(price) * 100, ip, pay_url, quote("lang=" + lang))
+            sign_params = pay.re_finall(orderid=order_id)
+            if not sign_params:
+                return {}
+            return {'pay_url': pay_url, 'sign_params': sign_params}
+        except Exception as e:
+            print(e)
+            return {}
 
     def do_pay_by_paypal_callback(self, request_dict, response):
         logger = logging.getLogger('info')