chenjunkai 6 年之前
父節點
當前提交
a6a829b9a4
共有 2 個文件被更改,包括 271 次插入48 次删除
  1. 270 47
      Controller/CloudVod.py
  2. 1 1
      Controller/Test.py

+ 270 - 47
Controller/CloudVod.py

@@ -24,7 +24,9 @@ from django.http import JsonResponse, HttpResponseRedirect, HttpResponse
 from django.utils.decorators import method_decorator
 from django.views.decorators.csrf import csrf_exempt
 from django.views.generic.base import View
+from alipay import AliPay
 
+from Ansjer.config import BASE_DIR
 from Ansjer.config import OSS_STS_ACCESS_KEY, OSS_STS_ACCESS_SECRET, OSS_ROLE_ARN, SERVER_DOMAIN, PAYPAL_CRD
 from Model.models import Device_Info, Order_Model, Store_Meal, VodHlsModel, OssCrdModel, UID_Bucket
 from Object.ResponseObject import ResponseObject
@@ -94,6 +96,8 @@ class CloudVodView(View):
             return self.do_pay_ok()
         elif operation == 'payError':
             return self.do_pay_error()
+        elif operation == 'aliPayCallback':
+            return self.do_ali_pay_callback(request)
         else:
             token = request_dict.get('token', None)
             # 设备主键uid
@@ -113,11 +117,138 @@ class CloudVodView(View):
             elif operation == 'findVod':
                 return self.do_find_playlist(request_dict, userID, response)
             # 支付宝支付
-            elif operation == 'aliPay':
-                return
+            elif operation == 'aliPayCreateOrder':
+                return self.do_pay_by_ali(request_dict, userID, response)
             else:
                 return response.json(414)
 
+    def do_ali_pay_callback(self, request):
+        response = ResponseObject()
+        data = request.POST.dict()
+        signature = data["sign"]
+        data.pop('sign')
+        orderID = data['trade_no']
+        print(json.dumps(data))
+        print(signature)
+        # verify
+        app_private_key_string = open(BASE_DIR + '/Controller/alipay_private_2048.pem').read()
+        alipay_public_key_string = open(BASE_DIR + '/Controller/alipay_public_2048.pem').read()
+        alipay = AliPay(
+            appid="2016092200569234",
+            app_notify_url=None,  # the default notify path
+            app_private_key_string=app_private_key_string,
+            alipay_public_key_string=alipay_public_key_string,
+            sign_type="RSA2",  # RSA or RSA2
+            debug=False  # False by default
+        )
+        success = alipay.verify(data, signature)
+        if success and data["trade_status"] in ("TRADE_SUCCESS", "TRADE_FINISHED"):
+            print("trade succeed")
+            order_qs = Order_Model.objects.filter(orderID=orderID)
+            nowTime = int(time.time())
+            order_qs.update(status=1, updTime=nowTime)
+            order_list = order_qs.values("UID", "rank_id", "channel")
+            rank_id = order_list[0]['rank_id']
+            UID = order_list[0]['UID']
+            channel = order_list[0]['channel']
+            smqs = Store_Meal.objects.filter(id=rank_id).values("day", "bucket_id", "bucket__storeDay")
+            bucketId = smqs[0]['bucket_id']
+            if not smqs.exists():
+                return response.json(0, '套餐已删除')
+            addTime = int(smqs[0]["day"]) * 24 * 3600
+            ubqs = UID_Bucket.objects.filter(uid=UID, channel=channel). \
+                values("bucket_id", "endTime", "bucket__storeDay")
+            nowTime = int(time.time())
+            if ubqs.exists():
+                # 判断是否过期了
+                if nowTime > ubqs[0]['endTime']:
+                    ubqs.update(endTime=nowTime + addTime)
+                else:
+                    # 同一个bucket续费
+                    if bucketId == ubqs[0]['bucket_id']:
+                        ubqs.update(endTime=ubqs[0]['endTime'] + addTime)
+                    else:
+                        if ubqs[0]['bucket__storeDay'] > smqs[0]['bucket__storeDay']:
+                            return response.json(10, '不可选低级别套餐')
+                        else:
+                            # 升级
+                            origin_storeDay = int(ubqs[0]['bucket__storeDay'])
+                            upgrade_storeDay = int(smqs[0]['bucket__storeDay'])
+                            ctcTime = ubqs[0]['endTime'] - nowTime
+                            multiple = math.ceil(upgrade_storeDay / origin_storeDay)
+                            ubqs.update(endTime=ctcTime / multiple + addTime + ubqs[0]['endTime'], bucket_id=bucketId)
+                            # 付款成功把oss token删除
+                            OssCrdModel.objects.filter(uid=UID, channel=channel).delete()
+            # 新增模式
+            else:
+                print('create')
+                UID_Bucket.objects.create(uid=UID, channel=channel,
+                                          bucket_id=bucketId, endTime=nowTime + addTime)
+            red_url = "{SERVER_DOMAIN}cloudVod/payOK".format(SERVER_DOMAIN=SERVER_DOMAIN)
+            return HttpResponseRedirect(red_url)
+        return response.json(0, signature)
+
+    def do_pay_by_ali(self, request_dict, userID, response):
+        did = request_dict.get('did', None)
+        rank = request_dict.get('rank', None)
+        channel = request_dict.get('channel', None)
+        qs = Device_Info.objects.filter(userID_id=userID, id=did, isShare=False).values("UID")
+        if not qs.exists():
+            return response.json(12)
+        if not did or not channel or not rank:
+            return response.json(444, 'did,channel,rank')
+        smqs = Store_Meal.objects.filter(id=rank). \
+            values("currency", "price", "content", "day", "bucket__storeDay", "bucket__region")
+        if not smqs.exists():
+            return response.json(10, '套餐不存在')
+        currency = smqs[0]['currency']
+        price = smqs[0]['price']
+        content = smqs[0]['content']
+        day = smqs[0]['day']
+        uid = qs[0]['UID']
+        nowTime = int(time.time())
+        ubqs = UID_Bucket.objects.filter(uid=uid, channel=channel, endTime__gte=nowTime). \
+            values("bucket__storeDay", "bucket__region")
+        if ubqs.exists():
+            if ubqs[0]['bucket__region'] != smqs[0]['bucket__region']:
+                return response.json(712)  # 区域不一致
+            # elif ubqs[0]['bucket__storeDay'] > smqs[0]['bucket__storeDay']:
+            #     return response.json(711)  # 不可降级
+            elif ubqs[0]['bucket__storeDay'] != smqs[0]['bucket__storeDay']:
+                return response.json(713)  # 不可更改套餐
+            # 续费流程
+        nowTime = int(time.time())
+        # 新增流程
+        orderID = CommonService.createOrderID()
+        app_private_key_string = open(BASE_DIR + '/Controller/alipay_private_2048.pem').read()
+        alipay_public_key_string = open(BASE_DIR + '/Controller/alipay_public_2048.pem').read()
+        try:
+            alipay = AliPay(
+                appid="2016092200569234",
+                app_notify_url=None,  # the default notify path
+                app_private_key_string=app_private_key_string,
+                alipay_public_key_string=alipay_public_key_string,
+                sign_type="RSA2",  # RSA or RSA2
+                debug=False  # False by default
+            )
+            order_string = alipay.api_alipay_trade_wap_pay(
+                out_trade_no=orderID,
+                total_amount=0.01,
+                subject="实用性充气式玩具",
+                return_url="http://test.dvema.com/cloudVod/payOK",
+                notify_url="http://test.dvema.com/cloudVod/aliPayCallback")
+        except Exception as e:
+            print(repr(e))
+            return response.json(10, repr(e))
+        if order_string:
+            redirectUrl = "https://openapi.alipaydev.com/gateway.do?" + order_string
+            Order_Model.objects.create(orderID=orderID, UID=uid, channel=channel, userID_id=userID, desc=content,
+                                       price=price, currency=currency, addTime=nowTime, updTime=nowTime,
+                                       endTime=nowTime + int(day) * 3600 * 24, rank_id=rank, paypal='', payType=1)
+            return response.json(0, {"redirectUrl": redirectUrl})
+        else:
+            return response.json(10, '生成订单错误')
+
     def do_get_details(self, request_dict, response):
         did = request_dict.get('did', None)
         dvqs = Device_Info.objects.filter(id=did, isShare=False).values('UID')
@@ -135,29 +266,77 @@ class CloudVodView(View):
         response = HttpResponse()
         response.content = '''
 <!DOCTYPE html>
-<html lang="en">
+<html>
 <head>
-    <meta charset="UTF-8">
-    <meta name="viewport"
-          content="width=device-width,initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no"/>
-    <title>msg</title>
+	<!--浏览器不缓存-->
+	<meta http-equiv="Pragma" content="no-cache">
+	<meta http-equiv="Cache-Control" content="no-cache">
+	<meta http-equiv="Expires" content="0">
+	<!--utf-8-->
+    <meta http-equiv="content-type" content="text/html;charset=utf-8">
+    <!-- viewport的<meta>标签,这个标签可以修改在大部分的移动设备上面的显示,为了确保适当的绘制和触屏缩放。-->
+    <meta name="viewport" content="width=device-width, initial-scale=1.0">
+    <link rel="shortcut icon" href="https://test.dvema.com/web/images/favicon.ico" type="image/x-icon"  charset="utf-8"/>  
+    <title>Trading particulars</title>
+    <style>
+    	.title_head{
+    		height: 50px;
+    		border-radius: 5px;
+    		background-color: #c3c6c7; 
+    		text-align: center;
+    		line-height: 50px;
+    	}
+    	.content{
+    		text-align: center;
+    		margin-top: 50px;
+    		font-size: 20px;
+    		color : #ec7648
+    	}
+    	.content_img{
+    		width: 60px; 
+    		height: 60px;
+    	}
+    	.bottom{
+    		 margin-bottom: 10px; 
+    		 margin-top: 250px; 
+    		 color : #ec7648
+    	}
+    	.bottom_div{
+    		border: 1px solid #ec7648; 
+    		line-height: 38px; 
+    		text-align: center; 
+    		width: 100px; 
+    		height: 38px;
+    		border-radius: 5px;
+    	}
+    	
+    	.bottom_div:hover{
+    		background-color: #dde4e2;
+    	}
+    </style>
 </head>
 <body>
-<div class="content"
-     style="text-align:center;overflow: hidden;padding:20% 10% 10% 10%;margin:0 10%;background-color: #fff;box-shadow:0 4px 20px rgba(0,0,0,0.1);word-break: break-all;min-height: 300px">
-    <span style="padding: 10px 20px; background-color: #EB6F5A;border-radius:4px;color:#fff;"
-          onclick="payOKButton()">付款失败</span>
-</div>
-</body>
-<script type="text/javascript">
-    // 点击付款成功按钮
+	<div class="title_head">Trading particulars</div>
+    <div class="content">
+    	<p >
+    		<img src="https://test.dvema.com/web/images/failed.jpg" class="content_img">
+    		<br />
+    		Payment failure
+    	</p>
+    </div>
+    <center class="bottom">
+    	<div class="bottom_div" onclick="payOKButton()"> 
+    	 Finish
+    	</div>
+    </center>
+    <script> 	    // 点击付款成功按钮
     function payOKButton() {
         // 复杂数据
-        // JS通知WKWebView
-        console.log('fail')
+        console.log('success')
         window.webkit.messageHandlers.jsCallOC.postMessage({"status": 0});
     }
-</script>
+	</script>
+</body> 
 </html>
                 '''
         return response
@@ -165,29 +344,79 @@ class CloudVodView(View):
     def do_pay_ok(self):
         response = HttpResponse()
         response.content = '''
-        <!DOCTYPE html>
-<html lang="en">
+
+<!DOCTYPE html>
+<html>
 <head>
-    <meta charset="UTF-8">
-    <meta name="viewport"
-          content="width=device-width,initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no"/>
-    <title>msg</title>
+	<!--浏览器不缓存-->
+	<meta http-equiv="Pragma" content="no-cache">
+	<meta http-equiv="Cache-Control" content="no-cache">
+	<meta http-equiv="Expires" content="0">
+	<!--utf-8-->
+    <meta http-equiv="content-type" content="text/html;charset=utf-8">
+    <!-- viewport的<meta>标签,这个标签可以修改在大部分的移动设备上面的显示,为了确保适当的绘制和触屏缩放。-->
+    <meta name="viewport" content="width=device-width, initial-scale=1.0">
+    <link rel="shortcut icon" href="https://test.dvema.com/web/images/favicon.ico" type="image/x-icon"  charset="utf-8"/>  
+    <title>Trading particulars</title>
+    <style>
+    	.title_head{
+    		height: 50px;
+    		border-radius: 5px;
+    		background-color: #c3c6c7; 
+    		text-align: center;
+    		line-height: 50px;
+    	}
+    	.content{
+    		text-align: center;
+    		margin-top: 50px;
+    		font-size: 20px;
+    		color : green
+    	}
+    	.content_img{
+    		width: 60px; 
+    		height: 60px;
+    	}
+    	.bottom{
+    		 margin-bottom: 10px; 
+    		 margin-top: 250px; 
+    		 color : green
+    	}
+    	.bottom_div{
+    		border: 1px solid green; 
+    		line-height: 38px; 
+    		text-align: center; 
+    		width: 100px; 
+    		height: 38px;
+    		border-radius: 5px;
+    	}
+    	
+    	.bottom_div:hover{
+    		background-color: #dde4e2;
+    	}
+    </style>
 </head>
 <body>
-<div class="content"
-     style="text-align:center;overflow: hidden;padding:20% 10% 10% 10%;margin:0 10%;background-color: #fff;box-shadow:0 4px 20px rgba(0,0,0,0.1);word-break: break-all;min-height: 300px">
-    <span style="padding: 10px 20px; background-color: #EB6F5A;border-radius:4px;color:#fff;"
-          onclick="payOKButton()">付款成功</span>
-</div>
-</body>
-<script type="text/javascript">
-    // 点击付款成功按钮
+	<div class="title_head">Trading particulars</div>
+    <div class="content">
+    	<p >
+    		<img src="https://test.dvema.com/web/images/timg.jpg" class="content_img">
+    		<br />
+    		Successful payment
+    	</p>
+    </div>
+    <center class="bottom">
+    	<div class="bottom_div" onclick="payOKButton()"> 
+    	 Finish
+    	</div>
+    </center>
+    <script> 	    // 点击付款成功按钮
     function payOKButton() {
         // 复杂数据
-          console.log('success')
+        console.log('success')
         window.webkit.messageHandlers.jsCallOC.postMessage({"status": 1});
     }
-</script>
+	</script>
+</body> 
 </html>
         '''
         return response
@@ -237,8 +466,7 @@ class CloudVodView(View):
             format(SERVER_DOMAIN=SERVER_DOMAIN, orderID=orderID)
         # call_sub_url = "http://192.168.136.40:8077/cloudVod/payExecute?orderID={orderID}".format(
         #     SERVER_DOMAIN=SERVER_DOMAIN, orderID=orderID)
-        # call_clc_url = "{SERVER_DOMAIN}cloudVod/payError".format(SERVER_DOMAIN=SERVER_DOMAIN)
-        call_clc_url = "{SERVER_DOMAIN}web/paid/failed_en.html".format(SERVER_DOMAIN=SERVER_DOMAIN)
+        call_clc_url = "{SERVER_DOMAIN}cloudVod/payError".format(SERVER_DOMAIN=SERVER_DOMAIN)
         # call_clc_url = "{SERVER_DOMAIN}cloudVod/cancleorder?orderID={orderID}". \
         #     format(SERVER_DOMAIN=SERVER_DOMAIN, orderID=orderID)
         paypalrestsdk.configure(PAYPAL_CRD)
@@ -407,8 +635,7 @@ class CloudVodView(View):
         PayerID = request_dict.get('PayerID', None)
         orderID = request_dict.get('orderID', None)
         if not paymentId or not PayerID or not orderID:
-            red_url = "{SERVER_DOMAIN}web/paid/failed_en.html".format(SERVER_DOMAIN=SERVER_DOMAIN)
-            red_url = "{SERVER_DOMAIN}web/paid/failed_cn.html".format(SERVER_DOMAIN=SERVER_DOMAIN)
+            red_url = "{SERVER_DOMAIN}cloudVod/payError".format(SERVER_DOMAIN=SERVER_DOMAIN)
             return HttpResponseRedirect(red_url)
         paypalrestsdk.configure(PAYPAL_CRD)
         # ID of the payment. This ID is provided when creating payment.
@@ -416,8 +643,7 @@ class CloudVodView(View):
         payres = payment.execute({"payer_id": PayerID})
         print(payres)
         if not payres:
-            red_url = "{SERVER_DOMAIN}web/paid/failed_en.html".format(SERVER_DOMAIN=SERVER_DOMAIN)
-            red_url = "{SERVER_DOMAIN}web/paid/failed_cn.html".format(SERVER_DOMAIN=SERVER_DOMAIN)
+            red_url = "{SERVER_DOMAIN}cloudVod/payError".format(SERVER_DOMAIN=SERVER_DOMAIN)
             return HttpResponseRedirect(red_url)
             # print(payment.error)  # Error Hash
             # return response.json(10, payment.error)
@@ -462,9 +688,7 @@ class CloudVodView(View):
             UID_Bucket.objects.create(uid=UID, channel=channel,
                                       bucket_id=bucketId, endTime=nowTime + addTime)
             # return response.json(0)
-        red_url = "{SERVER_DOMAIN}web/paid/paid_en.html".format(SERVER_DOMAIN=SERVER_DOMAIN)
-        # red_url = "{SERVER_DOMAIN}web/paid/paid_cn.html".format(SERVER_DOMAIN=SERVER_DOMAIN)
-        # red_url = "{SERVER_DOMAIN}cloudVod/payOK".format(SERVER_DOMAIN=SERVER_DOMAIN)
+        red_url = "{SERVER_DOMAIN}cloudVod/payOK".format(SERVER_DOMAIN=SERVER_DOMAIN)
         return HttpResponseRedirect(red_url)
 
     def do_change_status(self, request_dict, userID, response):
@@ -519,11 +743,10 @@ class CloudVodView(View):
         storeDay = qs[0]['bucket__storeDay']
         bucketID = qs[0]['bucket_id']
         endTime = int(storeTime) + storeDay * 86400
-        VodHlsModel.objects.create(uid=UID, channel=channel, time=storeTime, endTime=endTime, bucket_id=bucketID,
-                                   sec=sec)
+        VodHlsModel.objects.create(uid=UID, channel=channel, time=storeTime,
+                                   endTime=endTime, bucket_id=bucketID, sec=sec)
         return response.json(0)
 
-    # http://test.dvema.com/cloudVod/filterVod?token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySUQiOiIxNTIzNDE5MDcwMDY3ODUzMTM1MjcyNjA3MDciLCJ1c2VyIjoiMTM1MjcyNjA3MDciLCJsYW5nIjoiZW4iLCJleHAiOjE1NDg2NTU5NjR9.vuvgEJUyWA3mjVVBt2R5P9weqRmRNjWwAf_wsEG8sPk&did=138001380001548053701910104&channel=1&startTime=1&endTime=156489745645
     def do_filter_playlist(self, request_dict, userID, response):
         startTime = int(request_dict.get('startTime', None))
         endTime = int(request_dict.get('endTime', None))
@@ -574,7 +797,7 @@ class CloudVodView(View):
         nowTime = int(time.time())
         vodqs = VodHlsModel.objects.filter(uid=UID, channel=channel, time__range=(startTime, endTime),
                                            endTime__gte=nowTime) \
-            .values("time", "sec", "bucket__bucket", "bucket__endpoint", "bucket__region","id")
+            .values("time", "sec", "bucket__bucket", "bucket__endpoint", "bucket__region", "id")
         vod_play_list = []
         print(vodqs)
         for vod in vodqs:

+ 1 - 1
Controller/Test.py

@@ -51,7 +51,7 @@ class Test(View):
         from django.http import HttpResponseRedirect
         # return response.json(0,"https://openapi.alipay.com/gateway.do? + {order_string}".format(order_string=order_string))
         print(order_string)
-        return HttpResponseRedirect("https://openapi.alipaydev.com/gateway.do?" + order_string)
+        return HttpResponseRedirect("https://openapi.alipaydev.com/gateway.do?" + order_string+'&order')
         return HttpResponseRedirect("https://openapi.alipay.com/gateway.do?" + order_string)
 
     def post(self, request, *args, **kwargs):