Просмотр исходного кода

PayPal支付创建订单和回调接口添加捕获异常和打印

locky 3 лет назад
Родитель
Сommit
006e04ff2c
2 измененных файлов с 69 добавлено и 65 удалено
  1. 67 63
      Controller/AiController.py
  2. 2 2
      Service/CommonService.py

+ 67 - 63
Controller/AiController.py

@@ -414,63 +414,67 @@ class AiView(View):
         if not uid or not channel or not pay_type or not ai_meal_id:
             return response.json(444)
 
-        # 判断是否为主用户
-        # dv_qs = Device_Info.objects.filter(userID_id=userID, UID=uid, isShare=False, isExist=1).values(
-        #     'vodPrimaryUserID',
-        #     'vodPrimaryMaster')
-        # if not dv_qs.exists():
-        #     return response.json(12)
-
-        # dvq = Device_Info.objects.filter(UID=uid)
-        # dvq = dvq.filter(~Q(vodPrimaryUserID='')).values('vodPrimaryUserID')
-        # if dvq.exists():
-        #     if dvq[0]['vodPrimaryUserID'] != userID:
-        #         return response.json(10033)
-
-        # 获取ai套餐数据
-        ai_sm_qs = AiStoreMeal.objects.filter(id=ai_meal_id, pay_type=pay_type, is_show=1). \
-            values('currency', 'price', 'content', 'effective_day', 'title')
-        if not ai_sm_qs.exists():
-            return response.json(173)
-        currency = ai_sm_qs[0]['currency']
-        price = ai_sm_qs[0]['price']
-        content = ai_sm_qs[0]['content']
-        day = ai_sm_qs[0]['effective_day']
-
-        orderID = CommonService.createOrderID()
-        price = round(float(price), 2)
-        if pay_type == 1:
-            # 创建PayPal支付
-            cancel_url = CommonService.get_payment_status_url(lang, 'fail')
-            call_sub_url = "{}AiService/doPayPalCallBack?orderID={}&lang={}".format(SERVER_DOMAIN_SSL, orderID, lang)
+        try:
+            # 判断是否为主用户
+            # dv_qs = Device_Info.objects.filter(userID_id=userID, UID=uid, isShare=False, isExist=1).values(
+            #     'vodPrimaryUserID',
+            #     'vodPrimaryMaster')
+            # if not dv_qs.exists():
+            #     return response.json(12)
+
+            # dvq = Device_Info.objects.filter(UID=uid)
+            # dvq = dvq.filter(~Q(vodPrimaryUserID='')).values('vodPrimaryUserID')
+            # if dvq.exists():
+            #     if dvq[0]['vodPrimaryUserID'] != userID:
+            #         return response.json(10033)
+
+            # 获取ai套餐数据
+            ai_sm_qs = AiStoreMeal.objects.filter(id=ai_meal_id, pay_type=pay_type, is_show=1). \
+                values('currency', 'price', 'content', 'effective_day', 'title')
+            if not ai_sm_qs.exists():
+                return response.json(173)
+            currency = ai_sm_qs[0]['currency']
+            price = ai_sm_qs[0]['price']
+            content = ai_sm_qs[0]['content']
+            day = ai_sm_qs[0]['effective_day']
+
+            orderID = CommonService.createOrderID()
+            price = round(float(price), 2)
+            if pay_type == 1:
+                # 创建PayPal支付
+                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
+                nowTime = int(time.time())
+                for link in payment.links:
+                    if link.rel == "approval_url":
+                        pay_url = str(link.href)
+                        Order_Model.objects.create(orderID=orderID, UID=uid, channel=channel, userID_id=userID,
+                                                   desc=content, payType=pay_type, payTime=nowTime, price=price,
+                                                   currency=currency, addTime=nowTime, updTime=nowTime, pay_url=pay_url,
+                                                   paymentID=paymentID, ai_rank_id=ai_meal_id, rank_id=1)
+                        return response.json(0, {"redirectUrl": pay_url, "orderID": orderID})
+                return response.json(10, 'create_ai_order_failed')
+        except Exception as e:
+            print(e)
+            return response.json(500, repr(e))
 
-            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
-            nowTime = int(time.time())
-            for link in payment.links:
-                if link.rel == "approval_url":
-                    pay_url = str(link.href)
-                    Order_Model.objects.create(orderID=orderID, UID=uid, channel=channel, userID_id=userID,
-                                               desc=content, payType=pay_type, payTime=nowTime, price=price,
-                                               currency=currency, addTime=nowTime, updTime=nowTime, pay_url=pay_url,
-                                               paymentID=paymentID, ai_rank_id=ai_meal_id, rank_id=1)
-                    return response.json(0, {"redirectUrl": pay_url, "orderID": orderID})
-            return response.json(10, 'create_ai_order_failed')
-
-    def do_pay_by_paypal_callback(self, request_dict, response):  # paypal支付回调
+    def do_pay_by_paypal_callback(self, request_dict, response):
         logger = logging.getLogger('info')
-        logger.info('---------进入paypal异步回调')
+        logger.info('AI订单---paypal支付回调')
         paymentId = request_dict.get('paymentId', None)
         PayerID = request_dict.get('PayerID', None)
         orderID = request_dict.get('orderID', None)
@@ -480,7 +484,7 @@ class AiView(View):
             pay_failed_url = CommonService.get_payment_status_url(lang, 'fail')
             return HttpResponseRedirect(pay_failed_url)
 
-        logger.info("paymentID={paymentId},payerID={PayerID}".format(paymentId=paymentId, PayerID=PayerID))
+        logger.info("paymentID: {}, payerID: {}".format(paymentId, PayerID))
 
         # redis加锁,防止订单重复
         redisObj = RedisObject()
@@ -495,12 +499,11 @@ class AiView(View):
 
             paypalrestsdk.configure(PAYPAL_CRD)
             payment = paypalrestsdk.Payment.find(paymentId)
-            logger.info("payment------")
-            logger.info(payment)
+            logger.info("payment: {}".format(payment))
 
-            payres = payment.execute({"payer_id": PayerID})
-            logger.info(payres)
-            if not payres:
+            payer = payment.execute({"payer_id": PayerID})
+            logger.info('payres: {}'.format(payer))
+            if not payer:
                 pay_failed_url = CommonService.get_payment_status_url(lang, 'fail')
                 redisObj.del_data(key=orderID + 'do_notify')
                 return HttpResponseRedirect(pay_failed_url)
@@ -523,7 +526,7 @@ class AiView(View):
                                'updTime': nowTime,
                                'detect_group': '1'
                                }
-            if ai_service_qs.exists():      # 存在正在使用的套餐
+            if ai_service_qs.exists():      # 有正在使用的套餐,套餐结束时间保存为套餐有效期
                 ai_service_dict['endTime'] = effective_day * 24 * 60 * 60
             else:
                 ai_service_dict['use_status'] = 1
@@ -537,10 +540,11 @@ class AiView(View):
                 # 创建AiService数据
                 AiService.objects.create(**ai_service_dict)
 
-            pay_success_url = CommonService.get_payment_status_url(lang, 'fail')
+            pay_success_url = CommonService.get_payment_status_url(lang, 'success')
             redisObj.del_data(key=orderID + 'do_notify')
             return HttpResponseRedirect(pay_success_url)
         except Exception as e:
+            logger.info('AI订单paypal支付回调异常:{}'.format(repr(e)))
             order_qs.update(status=10)
             pay_failed_url = CommonService.get_payment_status_url(lang, 'fail')
             redisObj.del_data(key=orderID + 'do_notify')

+ 2 - 2
Service/CommonService.py

@@ -497,9 +497,9 @@ GCqvlyw5dfxNA+EtxNE2wCW/LW7ENJlACgcfgPlBZtpLheWoZB/maw4=
     def get_payment_status_url(lang, payment_status):
         # 返回相应的支付状态url
         if lang == 'cn':
-            file_name = 'success.html' if payment_status == 'success' else 'en_success.html'
+            file_name = 'success.html' if payment_status == 'success' else 'fail.html'
         else:
-            file_name = 'fail.html' if payment_status == 'fail' else 'en_fail.html'
+            file_name = 'en_success.html' if payment_status == 'success' else 'en_fail.html'
         pay_failed_url = "{}web/paid2/{}".format(SERVER_DOMAIN_SSL, file_name)
         return pay_failed_url