浏览代码

Merge branch 'test' of http://192.168.136.99:3000/servers/ASJServer

locky 3 年之前
父节点
当前提交
f082bcaca7
共有 3 个文件被更改,包括 152 次插入55 次删除
  1. 138 53
      Controller/AiController.py
  2. 2 1
      Controller/OrderContrller.py
  3. 12 1
      Service/CommonService.py

+ 138 - 53
Controller/AiController.py

@@ -88,6 +88,8 @@ class AiView(View):
             return response.json(444, 'error path')
             return response.json(444, 'error path')
         elif operation == 'identification':  # ai识别
         elif operation == 'identification':  # ai识别
             return self.do_ai_identification(request.POST, response)
             return self.do_ai_identification(request.POST, response)
+        elif operation == 'doPayPalCallBack':  # paypal支付回调
+            return self.do_pay_by_paypal_callback(request_dict, response)
         else:
         else:
             token = request_dict.get('token', None)
             token = request_dict.get('token', None)
             # 设备主键uid
             # 设备主键uid
@@ -97,8 +99,7 @@ class AiView(View):
                 return response.json(tko.code)
                 return response.json(tko.code)
             userID = tko.userID
             userID = tko.userID
             if operation == 'createpayorder':  # 创建支付订单
             if operation == 'createpayorder':  # 创建支付订单
-                ip = CommonService.get_ip_address(request)
-                return self.do_create_pay_order(request_dict, userID, ip, response)
+                return self.do_create_pay_order(request_dict, userID, response)
             elif operation == 'changeaistatus':  # 修改AI开关状态
             elif operation == 'changeaistatus':  # 修改AI开关状态
                 return self.do_change_ai_status(userID, request_dict, response)
                 return self.do_change_ai_status(userID, request_dict, response)
             elif operation == 'getAiStatus':  # 获取AI开关状态
             elif operation == 'getAiStatus':  # 获取AI开关状态
@@ -404,7 +405,7 @@ class AiView(View):
             # d['rank__lang__content'] = '月' if lang == 'cn' else 'month'
             # d['rank__lang__content'] = '月' if lang == 'cn' else 'month'
         return response.json(0, {'data': data, 'count': count})
         return response.json(0, {'data': data, 'count': count})
 
 
-    def do_create_pay_order(self, request_dict, userID, ip, response):
+    def do_create_pay_order(self, request_dict, userID, response):
         uid = request_dict.get('uid', None)
         uid = request_dict.get('uid', None)
         channel = request_dict.get('channel', None)
         channel = request_dict.get('channel', None)
         pay_type = int(request_dict.get('pay_type', 1))
         pay_type = int(request_dict.get('pay_type', 1))
@@ -412,58 +413,142 @@ class AiView(View):
         lang = request_dict.get('lang', 'en')
         lang = request_dict.get('lang', 'en')
         if not uid or not channel or not pay_type or not ai_meal_id:
         if not uid or not channel or not pay_type or not ai_meal_id:
             return response.json(444)
             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)
 
 
-        nowTime = int(time.time())
-        smqs = AiStoreMeal.objects.filter(id=ai_meal_id, pay_type=pay_type, is_show=1). \
-            values('currency', 'price', 'content', 'effective_day', 'title')
-        if not smqs.exists():
-            return response.json(173)
-        currency = smqs[0]['currency']
-        price = smqs[0]['price']
-        content = smqs[0]['content']
-        day = smqs[0]['effective_day']
-
-        orderID = CommonService.createOrderID()
-        price = float(price)
-        price = round(price, 2)
-        if pay_type == 1:
-            #正常扣款
-            cal_url = "{SERVER_DOMAIN_SSL}web/paid2/fail.html".format(SERVER_DOMAIN_SSL=SERVER_DOMAIN_SSL)
-            if lang != 'cn':
-                cal_url = "{SERVER_DOMAIN_SSL}web/paid2/en_fail.html".format(SERVER_DOMAIN_SSL=SERVER_DOMAIN_SSL)
-            call_sub_url = "{SERVER_DOMAIN_SSL}cloudstorage/dopaypalcallback?orderID={orderID}&lang={lang}". \
-                format(SERVER_DOMAIN_SSL=SERVER_DOMAIN_SSL, orderID=orderID, lang=lang)
-            # call_sub_url = "http://binbin.uicp.vip/cloudstorage/dopaypalcallback?orderID={orderID}".format(
-            # SERVER_DOMAIN_SSL=SERVER_DOMAIN_SSL, orderID=orderID)
-            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='', commodity_code='', commodity_type=1,
-                                       ai_rank_id=ai_meal_id, rank_id=1, order_type=1, status=1)
-            has = AiService.objects.filter(uid=uid, channel=channel, use_status=1)
-            if has.exists():
-                use_status = 0
-                endTime = 0
+        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))
+
+    def do_pay_by_paypal_callback(self, request_dict, response):
+        logger = logging.getLogger('info')
+        logger.info('AI订单---paypal支付回调')
+        paymentId = request_dict.get('paymentId', None)
+        PayerID = request_dict.get('PayerID', None)
+        orderID = request_dict.get('orderID', None)
+        lang = request_dict.get('lang', 'en')
+
+        if not orderID:
+            pay_failed_url = CommonService.get_payment_status_url(lang, 'fail')
+            return HttpResponseRedirect(pay_failed_url)
+
+        logger.info("paymentID: {}, payerID: {}".format(paymentId, PayerID))
+
+        # redis加锁,防止订单重复
+        redisObj = RedisObject()
+        isLock = redisObj.CONN.setnx(orderID + 'do_notify', 1)
+        redisObj.CONN.expire(orderID + 'do_notify', 60)
+        if not isLock:
+            return response.json(5)
+        try:
+            order_qs = Order_Model.objects.filter(orderID=orderID, status=0)
+            if not order_qs.exists():
+                return response.json(173)
+
+            paypalrestsdk.configure(PAYPAL_CRD)
+            payment = paypalrestsdk.Payment.find(paymentId)
+            logger.info("payment: {}".format(payment))
+
+            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)
+
+            nowTime = int(time.time())
+            order_list = order_qs.values("UID", "channel", "commodity_code", "ai_rank__effective_day", "isSelectDiscounts",
+                                         "userID__userID", "userID__username", "coupon_id")
+            userid = order_list[0]['userID__userID']
+            username = order_list[0]['userID__username']
+            UID = order_list[0]['UID']
+            channel = order_list[0]['channel']
+            effective_day = order_list[0]['ai_rank__effective_day']
+
+            ai_service_qs = AiService.objects.filter(Q(uid=UID), Q(channel=channel), Q(use_status=1))
+            ai_service_dict = {'orders_id': orderID,
+                               'uid': UID,
+                               'channel': channel,
+                               'detect_status': 1,
+                               'addTime': nowTime,
+                               'updTime': nowTime,
+                               'detect_group': '1'
+                               }
+            if ai_service_qs.exists():      # 有正在使用的套餐,套餐结束时间保存为套餐有效期
+                ai_service_dict['endTime'] = effective_day * 24 * 60 * 60
             else:
             else:
-                use_status = 1
-                endTime = nowTime+(day*86400)
-            # return response.json(0)
-            AiService.objects.create(orders_id=orderID, uid=uid, channel=channel, detect_status=1,
-                                       endTime=endTime, addTime=nowTime, updTime=nowTime,
-                                     use_status=use_status, detect_group='1')
-            return response.json(0, {"orderID": orderID})
-        return response.json(10, 'generate_order_false')
+                ai_service_dict['use_status'] = 1
+                ai_service_dict['endTime'] = nowTime + effective_day * 24 * 60 * 60
+            with transaction.atomic():
+                # 更新设备主用户
+                Device_Info.objects.filter(UID=UID, vodPrimaryUserID='', vodPrimaryMaster='').\
+                    update(vodPrimaryUserID=userid, vodPrimaryMaster=username)
+                # 更新订单数据,返回支付成功url
+                order_qs.update(status=1, updTime=nowTime)
+                # 创建AiService数据
+                AiService.objects.create(**ai_service_dict)
+
+            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')
+            return HttpResponseRedirect(pay_failed_url)
 
 
     def update_jpush_time(self,userID, request_dict, response):
     def update_jpush_time(self,userID, request_dict, response):
         logger = logging.getLogger('info')
         logger = logging.getLogger('info')

+ 2 - 1
Controller/OrderContrller.py

@@ -118,7 +118,7 @@ class OrderView(View):
         uid_list = []
         uid_list = []
         for od in order_list:
         for od in order_list:
             uid_list.append(od['UID'])
             uid_list.append(od['UID'])
-        didqs = Device_Info.objects.filter(userID_id=userID, UID__in=uid_list).values('id', 'UID', 'Type')
+        didqs = Device_Info.objects.filter(userID_id=userID, UID__in=uid_list).values('id', 'UID', 'Type', 'serial_number')
         for d in order_list:
         for d in order_list:
             if d['status'] == 0:
             if d['status'] == 0:
                 if d['addTime'] + 3600 < nowTime:
                 if d['addTime'] + 3600 < nowTime:
@@ -127,6 +127,7 @@ class OrderView(View):
                 if d['UID'] == did['UID']:
                 if d['UID'] == did['UID']:
                     d['did'] = did['id']
                     d['did'] = did['id']
                     d['Type'] = did['Type']
                     d['Type'] = did['Type']
+                    d['serialNumber'] = did['serial_number']
                     data.append(d)
                     data.append(d)
             d['rank__content'] = d['rank__lang__content']
             d['rank__content'] = d['rank__lang__content']
             del d['rank__lang__content']
             del d['rank__lang__content']

+ 12 - 1
Service/CommonService.py

@@ -8,9 +8,10 @@ from random import Random
 import ipdb
 import ipdb
 import simplejson as json
 import simplejson as json
 from django.core import serializers
 from django.core import serializers
+from django.http import HttpResponseRedirect
 from django.utils import timezone
 from django.utils import timezone
 from pyipip import IPIPDatabase
 from pyipip import IPIPDatabase
-from Ansjer.config import BASE_DIR, UNICODE_ASCII_CHARACTER_SET
+from Ansjer.config import BASE_DIR, UNICODE_ASCII_CHARACTER_SET, SERVER_DOMAIN_SSL
 import OpenSSL.crypto as ct
 import OpenSSL.crypto as ct
 from base64 import encodebytes
 from base64 import encodebytes
 from Controller.CheckUserData import RandomStr
 from Controller.CheckUserData import RandomStr
@@ -492,3 +493,13 @@ GCqvlyw5dfxNA+EtxNE2wCW/LW7ENJlACgcfgPlBZtpLheWoZB/maw4=
         # print('signature:', signature)
         # print('signature:', signature)
         return signature
         return signature
 
 
+    @staticmethod
+    def get_payment_status_url(lang, payment_status):
+        # 返回相应的支付状态url
+        if lang == 'cn':
+            file_name = 'success.html' if payment_status == 'success' else 'fail.html'
+        else:
+            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
+