浏览代码

paypal对账

peng 1 年之前
父节点
当前提交
7fb1f94c07
共有 1 个文件被更改,包括 81 次插入2 次删除
  1. 81 2
      Controller/Cron/CronTaskController.py

+ 81 - 2
Controller/Cron/CronTaskController.py

@@ -17,15 +17,16 @@ from django.db.models import Q, Sum, Count
 from django.views import View
 
 from Ansjer.config import USED_SERIAL_REDIS_LIST, UNUSED_SERIAL_REDIS_LIST, CONFIG_INFO, CONFIG_US, \
-    RESET_REGION_ID_SERIAL_REDIS_LIST, LOGGER
+    RESET_REGION_ID_SERIAL_REDIS_LIST, LOGGER, PAYPAL_CRD
 from Model.models import Device_User, Device_Info, UidSetModel, UID_Bucket, Unused_Uid_Meal, Order_Model, StsCrdModel, \
     VodHlsModel, ExperienceContextModel, AiService, VodHlsSummary, VideoPlaybackTimeModel, DeviceUserSummary, \
     CountryModel, DeviceTypeModel, OrdersSummary, DeviceInfoSummary, CompanySerialModel, \
     CloudLogModel, UidCloudStorageCount, UserExModel, DeviceDomainRegionModel, VodHlsTag, VodHlsTagType, IcloudService, \
-    Store_Meal, Lang, VodBucketModel, UnicomComboOrderInfo, UnicomDeviceInfo
+    Store_Meal, Lang, VodBucketModel, UnicomComboOrderInfo, UnicomDeviceInfo, AbnormalOrder
 from Object.RedisObject import RedisObject
 from Object.ResponseObject import ResponseObject
 from Object.utils import LocalDateTimeUtil
+from Object.utils.PayPalUtil import PayPalService
 from Service.CommonService import CommonService
 from Service.VodHlsService import SplitVodHlsObject
 from Object.UnicomObject import UnicomObjeect
@@ -1328,3 +1329,81 @@ class CronCollectDataView(View):
                             redis_obj.set_hash_data(key, redis_dict)
         except Exception as e:
             LOGGER.info('统计联通流量失败,时间为:{}'.format(int(time.time())))
+
+
+class CronComparedDataView(View):
+    def get(self, request, *args, **kwargs):
+        request.encoding = 'utf-8'
+        operation = kwargs.get('operation')
+        return self.validation(request.GET, request, operation)
+
+    def post(self, request, *args, **kwargs):
+        request.encoding = 'utf-8'
+        operation = kwargs.get('operation')
+        return self.validation(request.POST, request, operation)
+
+    def validation(self, request_dict, request, operation):
+        response = ResponseObject()
+        if operation == 'PaypalOrder':  # 定时对比paypal订单
+            return self.compared_paypal_order(response)
+        else:
+            return response.json(404)
+
+    @staticmethod
+    def compared_paypal_order(response):
+        today = datetime.datetime.today()
+        start_date = today - datetime.timedelta(days=2)
+        start_date = datetime.datetime(start_date.year, start_date.month, start_date.day)
+        end_date = start_date + datetime.timedelta(days=1)
+        end_date_stamp = int(end_date.timestamp())
+        try:
+            data = (
+                ('start_date', '{}-{}-{}T08:00:00-0800'.format(start_date.year, start_date.month, start_date.day)),
+                ('end_date', '{}-{}-{}T08:00:00-0800'.format(end_date.year, end_date.month, end_date.day)),
+                ('fields', 'all'),
+                ('page_size', '500'),
+                ('page', '1'),
+            )
+            order_list = PayPalService(PAYPAL_CRD['client_id'], PAYPAL_CRD['client_secret']).get_transactions(data)
+            thread = threading.Thread(target=CronComparedDataView.thread_compared_order,
+                                      args=(order_list['transaction_details'], end_date_stamp))
+            thread.start()
+            return response.json(0)
+        except Exception as e:
+            LOGGER.info('CronComparedDataView.compared_paypal_order, errLine:{}, errMsg:{}'.format(
+                e.__traceback__.tb_lineno, repr(e)))
+            return response.json(500)
+
+    @staticmethod
+    def thread_compared_order(order_list, timestamp):
+        for item in order_list:
+            trade_no = item['transaction_info']['transaction_id']
+            order_qs = Order_Model.objects.filter(trade_no=trade_no, payType=1)
+            if not order_qs.exists():
+                order_id = item['transaction_info'].get('transaction_subject', '')
+                agreement_id = item['transaction_info'].get('paypal_reference_id', '')
+                pay_time = datetime.datetime.strptime(item['transaction_info']['transaction_initiation_date'],
+                                                      "%Y-%m-%dT%H:%M:%S%z").timestamp()
+                order_dict = {
+                    'trade_no': trade_no,
+                    'agreement_id': agreement_id,
+                    'order_id': order_id,
+                    'pay_time': pay_time,
+                    'username': item['payer_info']['email_address'],
+                    'price': item['transaction_info']['transaction_amount']['value'],
+                    'pay_type': 1,
+                    'add_time': timestamp,
+                    'status': 0
+                }
+                if order_id and agreement_id:
+                    order_dict['pay_type'] = 0
+                params = {'trade_no': trade_no}
+                response = requests.get('https://www.zositeche.com/testApi/checkOrderExist', params=params)
+                if response.status_code != 200:
+                    # 如果响应失败,记录记录在数据库
+                    AbnormalOrder.objects.create(**order_dict)
+                    continue
+                result = response.json()
+                if result['result_code'] != 0 or not result['result']['is_exist']:
+                    # 如果响应结果为空,记录在数据库
+                    AbnormalOrder.objects.create(**order_dict)