浏览代码

添加取消paypal订单的逻辑

tanghongbin 4 年之前
父节点
当前提交
febc01f001
共有 2 个文件被更改,包括 129 次插入6 次删除
  1. 109 4
      Controller/CloudVod.py
  2. 20 2
      Controller/OrderContrller.py

+ 109 - 4
Controller/CloudVod.py

@@ -128,6 +128,12 @@ class CloudVodView(View):
                 return self.do_pay_status(request_dict, userID)
             elif operation == 'createPayOrder':
                 return self.do_create_pay_order(request_dict, userID, response)
+            # elif operation == 'queryAlipayOrder':
+            #     return self.query_alipay_order(request_dict, userID, response)
+            # elif operation == 'alipayCancel':
+            #     return self.do_alipay_cancel(request_dict, userID, response)
+            # elif operation == 'alipayRefund':
+            #     return self.do_alipay_refund(request_dict, userID, response)
             else:
                 return response.json(414)
 
@@ -157,7 +163,7 @@ class CloudVodView(View):
             print(rank_id)
             UID = order_list[0]['UID']
             channel = order_list[0]['channel']
-            order_qs.update(status=1, updTime=nowTime)
+            order_qs.update(status=1, updTime=nowTime, trade_no=data['trade_no'])
 
             smqs = Store_Meal.objects.filter(id=rank_id).values("day", "bucket_id", "bucket__storeDay")
             bucketId = smqs[0]['bucket_id']
@@ -207,7 +213,7 @@ class CloudVodView(View):
         if not channel or not rank:
             return response.json(444, 'channel,rank')
         smqs = Store_Meal.objects.filter(id=rank). \
-            values("currency", "price", "content", "day", "bucket__storeDay", "bucket__region", "type")
+            values("title", "currency", "price", "content", "day", "bucket__storeDay", "bucket__region", "type")
         if not smqs.exists():
             # 套餐不存在
             return response.json(173)
@@ -236,12 +242,13 @@ class CloudVodView(View):
             order_string = alipay.api_alipay_trade_wap_pay(
                 out_trade_no=orderID,
                 total_amount=price,
-                subject="测试哟",
+                subject=smqs[0]['title'],
                 return_url="{SERVER_DOMAIN_SSL}cloudVod/payOK".format(SERVER_DOMAIN_SSL=SERVER_DOMAIN_SSL),
                 notify_url="{SERVER_DOMAIN_SSL}cloudVod/aliPayCallback".format(SERVER_DOMAIN_SSL=SERVER_DOMAIN_SSL)
                 # return_url="http://192.168.136.40/cloudVod/payOK",
                 # notify_url="http://192.168.136.40/cloudVod/aliPayCallback"
             )
+            print(order_string)
         except Exception as e:
             print(repr(e))
             return response.json(10, repr(e))
@@ -675,7 +682,7 @@ class CloudVodView(View):
             if link.rel == "approval_url":
                 approval_url = str(link.href)
                 print("Redirect for approval: %s" % (approval_url))
-                Order_Model.objects.create(orderID=orderID, UID=uid, channel=channel, userID_id=userID, desc=content,
+                Order_Model.objects.create(orderID=orderID, UID=uid, trade_no=payment['id'], channel=channel, userID_id=userID, desc=content,
                                            price=price, currency=currency, addTime=nowTime, updTime=nowTime,
                                            endTime=nowTime + int(day) * 3600 * 24,
                                            rank_id=rank,
@@ -777,6 +784,7 @@ class CloudVodView(View):
         paypalrestsdk.configure(PAYPAL_CRD)
         # ID of the payment. This ID is provided when creating payment.
         payment = paypalrestsdk.Payment.find(paymentId)
+        print(payment)
         payres = payment.execute({"payer_id": PayerID})
         print(payres)
         if not payres:
@@ -1188,6 +1196,103 @@ class CloudVodView(View):
             response.content = falil_pay_content
             return response
 
+    def query_alipay_order(self, request_dict, userID, response):
+        out_trade_no = request_dict.get('out_trade_no', None)
+
+        if out_trade_no is None:
+            return response.json(444)
+
+        try:
+            aliPayObj = AliPayObject()
+            alipay = aliPayObj.conf()
+            result = alipay.api_alipay_trade_query(out_trade_no=out_trade_no)
+            print(result)
+        except Exception as e:
+            print(repr(e))
+            return response.json(10, repr(e))
+        return response.json(0, {'result': result})
+
+    def do_alipay_cancel(self, request_dict, userID, response):
+        out_trade_no = request_dict.get('out_trade_no', None)
+
+        if out_trade_no is None:
+            return response.json(444)
+
+        order_qs = Order_Model.objects.filter(orderID=out_trade_no)
+        if not order_qs.exists():
+            return response.json(800)
+
+        order = order_qs[0]
+
+        # 交易状态:
+        # WAIT_BUYER_PAY(交易创建,等待买家付款)
+        # TRADE_CLOSED(未付款交易超时关闭,或支付完成后全额退款)
+        # TRADE_SUCCESS(交易支付成功)
+        # TRADE_FINISHED(交易结束,不可退款)
+
+        try:
+            aliPayObj = AliPayObject()
+            alipay = aliPayObj.conf()
+            result = alipay.api_alipay_trade_query(out_trade_no=out_trade_no)
+            result = result['result']
+
+            if result['code'] == '100000':
+                trade_status = result['trade_status']
+                if trade_status == 'TRADE_CLOSED' or trade_status == 'WAIT_BUYER_PAY':
+                    order.status = 2
+                    order.updTime = int(time.time())
+                    order.save()
+                    return response.json(0)
+                else:
+                    order.status = 1
+                    order.updTime = int(time.time())
+                    order.save()
+                    return response.json(802)
+            else:
+                return response.json(10, result['sub_msg'])
+
+        except Exception as e:
+            print(repr(e))
+            return response.json(10, repr(e))
+
+    def do_alipay_refund(self, request_dict, userID, response):
+        out_trade_no = request_dict.get('out_trade_no', None)
+        refund_amount = request_dict.get('refund_amount', None)
+        reason = request_dict.get('reason', '正常退款')
+
+        if out_trade_no is None:
+            return response.json(444)
+
+        order_qs = Order_Model.objects.filter(orderID=out_trade_no)
+
+        if not order_qs.exists():
+            return response.json(800)
+
+        order = order_qs[0]
+        if refund_amount > order.price:
+            return response.json(10, '退款金额大于订单价格')
+
+        try:
+            # extra = {
+            #     'refund_currency': order[0].currency
+            # }
+            aliPayObj = AliPayObject()
+            alipay = aliPayObj.conf()
+            result = alipay.api_alipay_trade_refund(refund_amount=refund_amount, out_trade_no=out_trade_no)
+            result = result['result']
+            print(result)
+            if result['code'] == '10000':
+                order.status = 3
+                order.updTime = int(time.time())
+                order.save()
+                return response.json(0)
+            else:
+                return response.json(10, result['sub_msg'])
+
+        except Exception as e:
+            print(repr(e))
+            return response.json(10, repr(e))
+
 
 def deleteVodHls(request):
     response = ResponseObject()

+ 20 - 2
Controller/OrderContrller.py

@@ -12,10 +12,13 @@
 @Contact: chanjunkai@163.com
 """
 import time
+
+import paypalrestsdk
 from django.utils.decorators import method_decorator
 from django.views.decorators.csrf import csrf_exempt
 from django.views.generic.base import View
 
+from Ansjer.config_test import PAYPAL_CRD
 from Object.AliPayObject import AliPayObject
 from Object.ResponseObject import ResponseObject
 from Object.TokenObject import TokenObject
@@ -281,9 +284,24 @@ class OrderView(View):
             return response.json(10, repr(e))
 
     def do_cancel_paypal_order(self, order, response):
+        paypalrestsdk.configure(PAYPAL_CRD)
+        payment = paypalrestsdk.Payment.find(order.trade_no)
+        transactions = payment['transactions']
+        transaction = transactions[0]
+        related_resources = transaction['related_resources']
+        if len(related_resources) > 0:
+            related_resource = related_resources[0]
+            sale = related_resource['sale']
+            if sale['state'] == 'completed':
+                order.status = 1
+            elif sale['state'] == 'refund':
+                order.status = 3
 
-        if order.status == 0:
-            order.status = 2
             order.updTime = int(time.time())
             order.save()
+            return response.json(802)
+
+        order.status = 2
+        order.updTime = int(time.time())
+        order.save()
         return response.json(0)