Procházet zdrojové kódy

内购日志认证接口日志打印优化

linhaohong před 9 měsíci
rodič
revize
82f8bc635f
1 změnil soubory, kde provedl 72 přidání a 28 odebrání
  1. 72 28
      Controller/InAppPurchaseController.py

+ 72 - 28
Controller/InAppPurchaseController.py

@@ -4,6 +4,7 @@
 import logging
 import time
 import json
+import threading
 
 import requests
 from appstoreserverlibrary.api_client import AppStoreServerAPIClient, GetTransactionHistoryVersion
@@ -90,9 +91,9 @@ class InAppPurchaseView(View):
         redis_obj = RedisObject()
         redis_key = order_id + 'in_app_purchase'
         is_lock = redis_obj.CONN.setnx(redis_key, 1)
-        redis_obj.CONN.expire(redis_key, 60)
         if not is_lock:
             return response.json(5)
+        redis_obj.CONN.expire(redis_key, 60)
 
         try:
             # 从交易信息中获取product_id
@@ -110,14 +111,45 @@ class InAppPurchaseView(View):
             receipt_util = ReceiptUtility()
 
             transaction_id = receipt_util.extract_transaction_id_from_app_receipt(receipt)
-            logger.info(f"订单orderId:{order_id}, transaction_id:{transaction_id}")
 
             if transaction_id is None:
                 pay_result_url = CommonService.get_payment_status_url(lang, 'fail')
                 return response.json(0, {'url': pay_result_url})
+            logger.info(f"苹果内购认证交易订单orderID:{order_id}, transaction_id:{transaction_id}, 时间戳: {int(time.time())}")
 
-            transaction_info = client.get_transaction_info(transaction_id)
+            order_qs = Order_Model.objects.filter(orderID=order_id, UID=uid).values("rank_id")
 
+            if not order_qs.exists():
+                return response.json(173, "订单不存在")
+            if Order_Model.objects.filter(orderID=order_id, transaction_id=transaction_id).exists():
+                return response.json(174, "订单已支付充值")
+            if UID_Bucket.objects.filter(orderId=order_id).exists():
+                return response.json(174, "订单已充值")
+            if Unused_Uid_Meal.objects.filter(order_id=order_id).exists():
+                return response.json(174, "订单已充值")
+
+            OrderPayLog.objects.create(order_id=order_id, order_no=transaction_id,
+                                       business_name=f"内购验单",
+                                       created_time=int(time.time()), updated_time=int(time.time()),
+                                       access_result="SUCCESS")
+
+            # 查询交易信息
+            attempts = 0
+            while attempts < 6:
+                try:
+                    transaction_info = client.get_transaction_info(transaction_id)
+                    break
+                except ConnectionError as err:
+                    attempts += 1
+                    if attempts == 5:
+                        OrderPayLog.objects.create(order_id=order_id, order_no=transaction_id,
+                                                   business_name=f"{order_id}获取transactionInfo",
+                                                   created_time=int(time.time()), updated_time=int(time.time()),
+                                                   access_result="ERROR")
+                    logger.info(f"订单orderId:{order_id}, transaction_id:{transaction_id}, 获取支付信息超时")
+                    return response.json(5)
+
+            logger.info(f"订单orderId:{order_id}, transaction_id:{transaction_id}, 成功获取支付信息, 时间戳: {int(time.time())}")
             signed_transaction_info = transaction_info.signedTransactionInfo
 
             root_certificates = []
@@ -143,15 +175,12 @@ class InAppPurchaseView(View):
                 product_id = payload.productId
 
             if not product_id:
+                logger.info(f"苹果内购认证交易订单orderID:{order_id}, product_id获取失败")
                 pay_result_url = CommonService.get_payment_status_url(lang, 'fail')
                 return response.json(0, {'url': pay_result_url})
 
             now_time = int(time.time())
-            order_qs = Order_Model.objects.filter(orderID=order_id, UID=uid).values("rank_id")
-            if not order_qs.exists():
-                return response.json(173, "订单不存在")
-            if Order_Model.objects.filter(orderID=order_id, transaction_id=transaction_id).exists():
-                return response.json(174, "订单已支付充值")
+
             store_qs = Store_Meal.objects.filter(id=order_qs[0]['rank_id']).values(
                 'id', 'currency', 'price', 'lang__content', 'day', 'commodity_type', 'lang__title', 'expire',
                 'commodity_code', 'discount_price', 'bucket_id', 'bucket__mold', 'cycle_config_id', 'is_ai')
@@ -162,10 +191,7 @@ class InAppPurchaseView(View):
             is_ai = store_qs[0]['is_ai']
             expire = store_qs[0]['expire']
             end_time = CommonService.calcMonthLater(expire)
-            if UID_Bucket.objects.filter(orderId=order_id).exists():
-                return response.json(174, "订单已充值")
-            if Unused_Uid_Meal.objects.filter(order_id=order_id).exists():
-                return response.json(174, "订单已充值")
+
             # 查询设备是否已开过云存
             use_flag = True
             uid_bucket_qs = UID_Bucket.objects.filter(uid=uid). \
@@ -204,33 +230,51 @@ class InAppPurchaseView(View):
 
             order_qs.update(status=1, uid_bucket_id=uid_bucket_id, transaction_id=transaction_id, create_vod=1)
 
-            # 发送云存开通信息
-            date_time = time.strftime("%Y-%m-%d", time.localtime())
-            # 如果存在序列号,消息提示用序列号
-            device_info_qs = Device_Info.objects.filter(UID=uid).values('serial_number', 'Type')
-            serial_number = device_info_qs[0]['serial_number']
-            device_type = device_info_qs[0]['Type']
-            if serial_number:
-                device_name = CommonService.get_full_serial_number(uid, serial_number, device_type)
-            else:
-                device_name = uid
-            sys_msg_text_list = [
-                '温馨提示:尊敬的客户,您的{}设备在{}已成功购买云存套餐'.format(device_name, date_time),
-                'Dear customer,you already subscribed the cloud storage package successfully for device {} on '.
-                format(device_name, time.strftime('%b %dth,%Y', time.localtime()))]
-            cls.do_vod_msg_notice(uid, user_id, lang, sys_msg_text_list)
+            # 构建云存套餐消息
+            sys_msg_text_list = cls.cloud_storage_message(uid)
+
+            # 发送云存套餐购买消息
+            asy = threading.Thread(target=cls.do_vod_msg_notice,
+                                   args=(uid, user_id, lang, sys_msg_text_list))
+            asy.start()
 
             redis_obj.del_data(redis_key)
             pay_result_url = CommonService.get_payment_status_url(lang, 'success')
+
+            OrderPayLog.objects.create(order_id=order_id, order_no=transaction_id,
+                                       business_name=f"内购充值成功",
+                                       created_time=int(time.time()), updated_time=int(time.time()),
+                                       access_result="SUCCESS")
+
             return response.json(0, {'url': pay_result_url})
 
         except Exception as e:
             redis_obj.del_data(redis_key)
-            LOGGER.info('苹果内购认证交易接口异常:{}'.
+            logger.info('苹果内购认证交易接口异常:{}'.
                         format('error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e))))
+            OrderPayLog.objects.create(order_id=order_id, business_name=f"内购验单异常",
+                                       created_time=int(time.time()), updated_time=int(time.time()), access_result="ERROR")
             pay_result_url = CommonService.get_payment_status_url(lang, 'fail')
             return response.json(0, {'url': pay_result_url})
 
+    @classmethod
+    def cloud_storage_message(cls, uid):
+        # 发送云存开通信息
+        date_time = time.strftime("%Y-%m-%d", time.localtime())
+        # 如果存在序列号,消息提示用序列号
+        device_info_qs = Device_Info.objects.filter(UID=uid).values('serial_number', 'Type')
+        serial_number = device_info_qs[0]['serial_number']
+        device_type = device_info_qs[0]['Type']
+        if serial_number:
+            device_name = CommonService.get_full_serial_number(uid, serial_number, device_type)
+        else:
+            device_name = uid
+        sys_msg_text_list = [
+            '温馨提示:尊敬的客户,您的{}设备在{}已成功购买云存套餐'.format(device_name, date_time),
+            'Dear customer,you already subscribed the cloud storage package successfully for device {} on '.
+            format(device_name, time.strftime('%b %dth,%Y', time.localtime()))]
+        return sys_msg_text_list
+
     @classmethod
     def do_vod_msg_notice(cls, uid, user_id, lang, sys_msg_text_list):
         """