PaymentCycle.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253
  1. from Ansjer.config import PAYPAL_CRD,SERVER_DOMAIN,SERVER_DOMAIN_SSL
  2. from Model.models import PayCycleConfigModel,Order_Model, Store_Meal, UID_Bucket, PromotionRuleModel, Unused_Uid_Meal,Device_Info
  3. from Service.CommonService import CommonService
  4. from django.http import JsonResponse, HttpResponseRedirect, HttpResponse
  5. import requests
  6. import time
  7. from Object.ResponseObject import ResponseObject
  8. import paypalrestsdk
  9. from paypalrestsdk import BillingAgreement
  10. from django.views.generic.base import View
  11. from django.db import transaction
  12. from Controller import CloudStorage
  13. from django.db.models import Q, F, Count
  14. #周期扣款相关
  15. class Paypal:
  16. def subscriptions(store_info,lang,orderID):
  17. cycle_config = PayCycleConfigModel.objects.filter(id=store_info['cycle_config_id']).values()
  18. if not cycle_config:
  19. return False
  20. cal_url = "{SERVER_DOMAIN_SSL}web/paid2/fail.html".format(SERVER_DOMAIN_SSL=SERVER_DOMAIN_SSL)
  21. if lang != 'cn':
  22. cal_url = "{SERVER_DOMAIN_SSL}web/paid2/en_fail.html".format(SERVER_DOMAIN_SSL=SERVER_DOMAIN_SSL)
  23. return_url = "{SERVER_DOMAIN_SSL}payCycle/paypalCycleReturn?lang={lang}". \
  24. format(SERVER_DOMAIN_SSL=SERVER_DOMAIN_SSL, lang=lang)
  25. # call_sub_url = "http://binbin.uicp.vip/cloudstorage/dopaypalcallback?orderID={orderID}".format(
  26. # SERVER_DOMAIN_SSL=SERVER_DOMAIN_SSL, orderID=orderID)
  27. BillingPlan = {
  28. "description": orderID,
  29. "merchant_preferences": {
  30. "auto_bill_amount": "YES",
  31. "cancel_url": cal_url, # 取消协议url
  32. "initial_fail_amount_action": "CANCEL",
  33. "max_fail_attempts": "1", # 允许的最大失败付款尝试次数
  34. "return_url": return_url, # 客户批准协议的url
  35. # "notify_url": "http://www.notify.com", #通知客户协议已创建的 URL。只读并保留供将来使用。
  36. "setup_fee": {
  37. "currency": store_info['currency'],
  38. "value": store_info['price'],
  39. }
  40. },
  41. "name": store_info['lang__content'],
  42. "payment_definitions": [
  43. {
  44. "amount": {
  45. "currency": store_info['currency'],
  46. "value": store_info['price']
  47. },
  48. # "charge_models": [
  49. # {
  50. # "amount": {
  51. # "currency": "USD",
  52. # "value": "20"
  53. # },
  54. # "type": "TAX" #税金
  55. # }
  56. # ],
  57. "cycles": cycle_config[0]['cycles'],
  58. "frequency": cycle_config[0]['frequency'],
  59. "frequency_interval": cycle_config[0]['frequencyInterval'],
  60. "name": store_info['lang__title'],
  61. "type": "REGULAR"
  62. },
  63. ],
  64. "type": "INFINITE",
  65. }
  66. paypalrestsdk.configure(PAYPAL_CRD)
  67. billing_plan = paypalrestsdk.BillingPlan(BillingPlan)
  68. if billing_plan.create():
  69. billing_plan.activate() # 激活
  70. plan_id = billing_plan.id
  71. else:
  72. print(billing_plan.error)
  73. return False
  74. now_time = int(time.time())
  75. if cycle_config[0]['frequency'] == "DAY":
  76. start_date_timestamp = now_time + 86400 - 3600 # 下次扣款为明天,提前1个小时扣款
  77. start_date_str = CommonService.timestamp_to_str(start_date_timestamp, "%Y-%m-%dT%H:%M:%SZ")
  78. elif cycle_config[0]['frequency'] == "MONTH":
  79. start_date_timestamp = CommonService.calcMonthLater(1, now_time) - (5 * 86400) #下次扣款为下个月提前5天扣款
  80. start_date_str = CommonService.timestamp_to_str(start_date_timestamp, "%Y-%m-%dT%H:%M:%SZ")
  81. #订阅
  82. billingAgreement = {
  83. "name": store_info['lang__content'],
  84. "description": orderID,
  85. "start_date": start_date_str,
  86. "plan": {
  87. "id": plan_id
  88. },
  89. "payer": {
  90. "payment_method": "paypal"
  91. },
  92. }
  93. billing_agreement = paypalrestsdk.BillingAgreement(billingAgreement)
  94. # print(billing_agreement.create())
  95. if billing_agreement.create():
  96. for link in billing_agreement.links:
  97. if link.rel == "approval_url":
  98. return {"plan_id": plan_id, "url": link.href}
  99. else:
  100. print(billing_agreement.error)
  101. return False
  102. class PaypalCycleNotify(View):
  103. def get(self, request, *args, **kwargs):
  104. request.encoding = 'utf-8'
  105. operation = kwargs.get('operation')
  106. return self.validation(request.GET, request, operation)
  107. def post(self, request, *args, **kwargs):
  108. request.encoding = 'utf-8'
  109. operation = kwargs.get('operation')
  110. return self.validation(request.POST, request, operation)
  111. def validation(self, request_dict, request, operation):
  112. response = ResponseObject()
  113. if operation is None:
  114. return response.json(444, 'error path')
  115. elif operation == 'paypalCycleReturn': # paypal成功订阅回调
  116. return self.do_paypal_cycle_return(request_dict, response)
  117. elif operation == 'paypalCycleNotify': # paypal 周期付款回调
  118. return self.do_paypal_webhook_notify(request_dict, response)
  119. def do_paypal_cycle_return(self, request_dict, response):
  120. lang = request_dict.get('lang', 'en')
  121. token = request_dict.get('token',None)
  122. paypalrestsdk.configure(PAYPAL_CRD)
  123. billing_agreement = paypalrestsdk.BillingAgreement()
  124. billing_agreement_response = billing_agreement.execute(token)
  125. if billing_agreement_response.error:
  126. print(billing_agreement_response.error)
  127. red_url = "{SERVER_DOMAIN_SSL}web/paid2/fail.html".format(SERVER_DOMAIN_SSL=SERVER_DOMAIN_SSL)
  128. if lang != 'cn':
  129. red_url = "{SERVER_DOMAIN_SSL}web/paid2/en_fail.html".format(SERVER_DOMAIN_SSL=SERVER_DOMAIN_SSL)
  130. return HttpResponseRedirect(red_url)
  131. orderID = billing_agreement_response.description
  132. agreement_id = billing_agreement_response.id
  133. promotion_rule_id = ''
  134. try:
  135. order_qs = Order_Model.objects.filter(orderID=orderID, status=0)
  136. if not orderID:
  137. print("not orderID")
  138. red_url = "{SERVER_DOMAIN_SSL}web/paid2/fail.html".format(SERVER_DOMAIN_SSL=SERVER_DOMAIN_SSL)
  139. if lang != 'cn':
  140. red_url = "{SERVER_DOMAIN_SSL}web/paid2/en_fail.html".format(SERVER_DOMAIN_SSL=SERVER_DOMAIN_SSL)
  141. return HttpResponseRedirect(red_url)
  142. order_list = order_qs.values("UID", "channel", "commodity_code", "rank", "isSelectDiscounts",
  143. "userID__userID",
  144. "userID__username")
  145. userid = order_list[0]['userID__userID']
  146. username = order_list[0]['userID__username']
  147. UID = order_list[0]['UID']
  148. channel = order_list[0]['channel']
  149. rank = order_list[0]['rank']
  150. smqs = Store_Meal.objects.filter(id=rank). \
  151. values("day", "bucket_id", "bucket__storeDay", "expire")
  152. bucketId = smqs[0]['bucket_id']
  153. if not smqs.exists():
  154. print("not smqs")
  155. red_url = "{SERVER_DOMAIN_SSL}web/paid2/fail.html".format(SERVER_DOMAIN_SSL=SERVER_DOMAIN_SSL)
  156. if lang != 'cn':
  157. red_url = "{SERVER_DOMAIN_SSL}web/paid2/en_fail.html".format(SERVER_DOMAIN_SSL=SERVER_DOMAIN_SSL)
  158. return HttpResponseRedirect(red_url)
  159. # ##
  160. ubqs = UID_Bucket.objects.filter(uid=UID).values("id", "bucket_id", "bucket__storeDay", "bucket__region",
  161. "endTime", "use_status")
  162. expire = smqs[0]['expire']
  163. if order_list[0]['isSelectDiscounts'] == 1:
  164. expire = smqs[0]['expire'] * 2
  165. # 是否有促销
  166. nowTime = int(time.time())
  167. promotion = PromotionRuleModel.objects.filter(status=1, startTime__lte=nowTime,
  168. endTime__gte=nowTime).values('id','ruleConfig')
  169. if promotion.exists():
  170. promotion_rule_id = promotion[0]['id']
  171. expire = expire * 2
  172. with transaction.atomic():
  173. if ubqs.exists():
  174. ubq = ubqs[0]
  175. if ubq['use_status'] == 1 and ubq['bucket_id'] == bucketId: #套餐使用中并且相同套餐叠加过期时间
  176. endTime = CommonService.calcMonthLater(expire, ubq['endTime'])
  177. UID_Bucket.objects.filter(id=ubq['id']).update \
  178. (uid=UID, channel=channel, bucket_id=bucketId,
  179. endTime=endTime, updateTime=nowTime)
  180. else: #已过期或者不相同的套餐加入未使用的关联套餐表
  181. has_unused = Unused_Uid_Meal.objects.filter(uid=UID, bucket_id=bucketId).values("id")
  182. nums = 2 if order_list[0]['isSelectDiscounts'] == 1 else 1
  183. if promotion.exists():
  184. nums = nums + 1
  185. if has_unused.exists():
  186. Unused_Uid_Meal.objects.filter(id=has_unused[0]['id']).update(num=F('num') + nums)
  187. else:
  188. Unused_Uid_Meal.objects.create(uid=UID,channel=channel,addTime=nowTime,num=nums,
  189. expire=smqs[0]['expire'],bucket_id=bucketId)
  190. UID_Bucket.objects.filter(id=ubq['id']).update(has_unused=1)
  191. uid_bucket_id = ubq['id']
  192. else:
  193. endTime = CommonService.calcMonthLater(expire)
  194. ub_cqs = UID_Bucket.objects.create \
  195. (uid=UID, channel=channel, bucket_id=bucketId, endTime=endTime, addTime=nowTime,
  196. updateTime=nowTime,use_status=1)
  197. uid_bucket_id = ub_cqs.id
  198. dvq = Device_Info.objects.filter(UID=UID, vodPrimaryUserID='', vodPrimaryMaster='')
  199. if dvq.exists():
  200. dvq_set_update_dict = {
  201. 'vodPrimaryUserID': userid,
  202. 'vodPrimaryMaster': username
  203. }
  204. dvq.update(**dvq_set_update_dict)
  205. # uid_main_exist = UIDMainUser.objects.filter(UID=UID)
  206. # if not uid_main_exist.exists():
  207. # uid_main_dict = {
  208. # 'UID': UID,
  209. # 'user_id': userid
  210. # }
  211. # UIDMainUser.objects.create(**uid_main_dict)
  212. order_qs.update(status=1, updTime=nowTime, uid_bucket_id=uid_bucket_id,
  213. promotion_rule_id=promotion_rule_id,agreement_id=agreement_id)
  214. datetime = time.strftime("%Y-%m-%d", time.localtime())
  215. sys_msg_text_list = ['温馨提示:尊敬的客户,您的' + UID + '设备在' + datetime + '已成功订阅云存套餐',
  216. 'Dear customer,you already subscribed the cloud storage package successfully for device ' + UID + ' on ' + time.strftime(
  217. "%b %dth,%Y", time.localtime())]
  218. CloudStorage.CloudStorageView.do_vod_msg_Notice(self, UID, channel, userid, lang, sys_msg_text_list, 'SMS_219738485')
  219. # return response.json(0)
  220. red_url = "{SERVER_DOMAIN_SSL}web/paid2/success.html".format(SERVER_DOMAIN_SSL=SERVER_DOMAIN_SSL)
  221. if lang != 'cn':
  222. red_url = "{SERVER_DOMAIN_SSL}web/paid2/en_success.html".format(SERVER_DOMAIN_SSL=SERVER_DOMAIN_SSL)
  223. return HttpResponseRedirect(red_url)
  224. except Exception as e:
  225. print(repr(e))
  226. if order_qs:
  227. order_qs.update(status=10, promotion_rule_id=promotion_rule_id)
  228. red_url = "{SERVER_DOMAIN_SSL}web/paid2/fail.html".format(SERVER_DOMAIN_SSL=SERVER_DOMAIN_SSL)
  229. if lang != 'cn':
  230. red_url = "{SERVER_DOMAIN_SSL}web/paid2/en_fail.html".format(SERVER_DOMAIN_SSL=SERVER_DOMAIN_SSL)
  231. return HttpResponseRedirect(red_url)
  232. def do_paypal_webhook_notify(self, request_dict, response):
  233. paymentId = request_dict.get('paymentId', None)
  234. PayerID = request_dict.get('PayerID', None)
  235. lang = request_dict.get('lang', 'en')
  236. token = request_dict.get('token',None)
  237. paypalrestsdk.configure(PAYPAL_CRD)