PaymentCycle.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282
  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. from paypalrestsdk.notifications import WebhookEvent
  15. import logging
  16. #周期扣款相关
  17. class Paypal:
  18. def subscriptions(store_info,lang,orderID):
  19. cycle_config = PayCycleConfigModel.objects.filter(id=store_info['cycle_config_id']).values()
  20. if not cycle_config:
  21. return False
  22. cal_url = "{SERVER_DOMAIN_SSL}web/paid2/fail.html".format(SERVER_DOMAIN_SSL=SERVER_DOMAIN_SSL)
  23. if lang != 'cn':
  24. cal_url = "{SERVER_DOMAIN_SSL}web/paid2/en_fail.html".format(SERVER_DOMAIN_SSL=SERVER_DOMAIN_SSL)
  25. return_url = "{SERVER_DOMAIN_SSL}payCycle/paypalCycleReturn?lang={lang}". \
  26. format(SERVER_DOMAIN_SSL=SERVER_DOMAIN_SSL, lang=lang)
  27. # call_sub_url = "http://binbin.uicp.vip/cloudstorage/dopaypalcallback?orderID={orderID}".format(
  28. # SERVER_DOMAIN_SSL=SERVER_DOMAIN_SSL, orderID=orderID)
  29. BillingPlan = {
  30. "description": orderID,
  31. "merchant_preferences": {
  32. "auto_bill_amount": "YES",
  33. "cancel_url": cal_url, # 取消协议url
  34. "initial_fail_amount_action": "CANCEL",
  35. "max_fail_attempts": "1", # 允许的最大失败付款尝试次数
  36. "return_url": return_url, # 客户批准协议的url
  37. # "notify_url": "http://www.notify.com", #通知客户协议已创建的 URL。只读并保留供将来使用。
  38. "setup_fee": {
  39. "currency": store_info['currency'],
  40. "value": store_info['price'],
  41. }
  42. },
  43. "name": store_info['lang__content'],
  44. "payment_definitions": [
  45. {
  46. "amount": {
  47. "currency": store_info['currency'],
  48. "value": store_info['price']
  49. },
  50. # "charge_models": [
  51. # {
  52. # "amount": {
  53. # "currency": "USD",
  54. # "value": "20"
  55. # },
  56. # "type": "TAX" #税金
  57. # }
  58. # ],
  59. "cycles": cycle_config[0]['cycles'],
  60. "frequency": cycle_config[0]['frequency'],
  61. "frequency_interval": cycle_config[0]['frequencyInterval'],
  62. "name": store_info['lang__title'],
  63. "type": "REGULAR"
  64. },
  65. ],
  66. "type": "INFINITE",
  67. }
  68. paypalrestsdk.configure(PAYPAL_CRD)
  69. billing_plan = paypalrestsdk.BillingPlan(BillingPlan)
  70. if billing_plan.create():
  71. billing_plan.activate() # 激活
  72. plan_id = billing_plan.id
  73. else:
  74. print(billing_plan.error)
  75. return False
  76. now_time = int(time.time())
  77. if cycle_config[0]['frequency'] == "DAY":
  78. start_date_timestamp = now_time + 86400 - 3600 # 下次扣款为明天,提前1个小时扣款
  79. start_date_str = CommonService.timestamp_to_str(start_date_timestamp, "%Y-%m-%dT%H:%M:%SZ")
  80. elif cycle_config[0]['frequency'] == "MONTH":
  81. start_date_timestamp = CommonService.calcMonthLater(1, now_time) - (5 * 86400) #下次扣款为下个月提前5天扣款
  82. start_date_str = CommonService.timestamp_to_str(start_date_timestamp, "%Y-%m-%dT%H:%M:%SZ")
  83. #订阅
  84. billingAgreement = {
  85. "name": store_info['lang__content'],
  86. "description": orderID,
  87. "start_date": start_date_str,
  88. "plan": {
  89. "id": plan_id
  90. },
  91. "payer": {
  92. "payment_method": "paypal"
  93. },
  94. }
  95. billing_agreement = paypalrestsdk.BillingAgreement(billingAgreement)
  96. # print(billing_agreement.create())
  97. if billing_agreement.create():
  98. for link in billing_agreement.links:
  99. if link.rel == "approval_url":
  100. return {"plan_id": plan_id, "url": link.href}
  101. else:
  102. print(billing_agreement.error)
  103. return False
  104. class PaypalCycleNotify(View):
  105. def get(self, request, *args, **kwargs):
  106. request.encoding = 'utf-8'
  107. operation = kwargs.get('operation')
  108. return self.validation(request.GET, request, operation)
  109. def post(self, request, *args, **kwargs):
  110. request.encoding = 'utf-8'
  111. operation = kwargs.get('operation')
  112. return self.validation(request.POST, request, operation)
  113. def validation(self, request_dict, request, operation):
  114. response = ResponseObject()
  115. if operation is None:
  116. return response.json(444, 'error path')
  117. elif operation == 'paypalCycleReturn': # paypal成功订阅回调
  118. return self.do_paypal_cycle_return(request_dict, response)
  119. elif operation == 'paypalCycleNotify': # paypal 周期付款回调
  120. return self.do_paypal_webhook_notify(request_dict,request, response)
  121. def do_paypal_cycle_return(self, request_dict, response):
  122. lang = request_dict.get('lang', 'en')
  123. token = request_dict.get('token',None)
  124. paypalrestsdk.configure(PAYPAL_CRD)
  125. billing_agreement = paypalrestsdk.BillingAgreement()
  126. billing_agreement_response = billing_agreement.execute(token)
  127. if billing_agreement_response.error:
  128. print(billing_agreement_response.error)
  129. red_url = "{SERVER_DOMAIN_SSL}web/paid2/fail.html".format(SERVER_DOMAIN_SSL=SERVER_DOMAIN_SSL)
  130. if lang != 'cn':
  131. red_url = "{SERVER_DOMAIN_SSL}web/paid2/en_fail.html".format(SERVER_DOMAIN_SSL=SERVER_DOMAIN_SSL)
  132. return HttpResponseRedirect(red_url)
  133. orderID = billing_agreement_response.description
  134. agreement_id = billing_agreement_response.id
  135. promotion_rule_id = ''
  136. try:
  137. order_qs = Order_Model.objects.filter(orderID=orderID, status=0)
  138. if not orderID:
  139. print("not orderID")
  140. red_url = "{SERVER_DOMAIN_SSL}web/paid2/fail.html".format(SERVER_DOMAIN_SSL=SERVER_DOMAIN_SSL)
  141. if lang != 'cn':
  142. red_url = "{SERVER_DOMAIN_SSL}web/paid2/en_fail.html".format(SERVER_DOMAIN_SSL=SERVER_DOMAIN_SSL)
  143. return HttpResponseRedirect(red_url)
  144. order_list = order_qs.values("UID", "channel", "commodity_code", "rank", "isSelectDiscounts",
  145. "userID__userID",
  146. "userID__username")
  147. userid = order_list[0]['userID__userID']
  148. username = order_list[0]['userID__username']
  149. UID = order_list[0]['UID']
  150. channel = order_list[0]['channel']
  151. rank = order_list[0]['rank']
  152. smqs = Store_Meal.objects.filter(id=rank). \
  153. values("day", "bucket_id", "bucket__storeDay", "expire")
  154. bucketId = smqs[0]['bucket_id']
  155. if not smqs.exists():
  156. print("not smqs")
  157. red_url = "{SERVER_DOMAIN_SSL}web/paid2/fail.html".format(SERVER_DOMAIN_SSL=SERVER_DOMAIN_SSL)
  158. if lang != 'cn':
  159. red_url = "{SERVER_DOMAIN_SSL}web/paid2/en_fail.html".format(SERVER_DOMAIN_SSL=SERVER_DOMAIN_SSL)
  160. return HttpResponseRedirect(red_url)
  161. # ##
  162. ubqs = UID_Bucket.objects.filter(uid=UID).values("id", "bucket_id", "bucket__storeDay", "bucket__region",
  163. "endTime", "use_status")
  164. expire = smqs[0]['expire']
  165. if order_list[0]['isSelectDiscounts'] == 1:
  166. expire = smqs[0]['expire'] * 2
  167. # 是否有促销
  168. nowTime = int(time.time())
  169. promotion = PromotionRuleModel.objects.filter(status=1, startTime__lte=nowTime,
  170. endTime__gte=nowTime).values('id','ruleConfig')
  171. if promotion.exists():
  172. promotion_rule_id = promotion[0]['id']
  173. expire = expire * 2
  174. with transaction.atomic():
  175. if ubqs.exists():
  176. ubq = ubqs[0]
  177. if ubq['use_status'] == 1 and ubq['bucket_id'] == bucketId: #套餐使用中并且相同套餐叠加过期时间
  178. endTime = CommonService.calcMonthLater(expire, ubq['endTime'])
  179. UID_Bucket.objects.filter(id=ubq['id']).update \
  180. (uid=UID, channel=channel, bucket_id=bucketId,
  181. endTime=endTime, updateTime=nowTime)
  182. else: #已过期或者不相同的套餐加入未使用的关联套餐表
  183. has_unused = Unused_Uid_Meal.objects.filter(uid=UID, bucket_id=bucketId).values("id")
  184. nums = 2 if order_list[0]['isSelectDiscounts'] == 1 else 1
  185. if promotion.exists():
  186. nums = nums + 1
  187. if has_unused.exists():
  188. Unused_Uid_Meal.objects.filter(id=has_unused[0]['id']).update(num=F('num') + nums)
  189. else:
  190. Unused_Uid_Meal.objects.create(uid=UID,channel=channel,addTime=nowTime,num=nums,
  191. expire=smqs[0]['expire'],bucket_id=bucketId)
  192. UID_Bucket.objects.filter(id=ubq['id']).update(has_unused=1)
  193. uid_bucket_id = ubq['id']
  194. else:
  195. endTime = CommonService.calcMonthLater(expire)
  196. ub_cqs = UID_Bucket.objects.create \
  197. (uid=UID, channel=channel, bucket_id=bucketId, endTime=endTime, addTime=nowTime,
  198. updateTime=nowTime,use_status=1)
  199. uid_bucket_id = ub_cqs.id
  200. dvq = Device_Info.objects.filter(UID=UID, vodPrimaryUserID='', vodPrimaryMaster='')
  201. if dvq.exists():
  202. dvq_set_update_dict = {
  203. 'vodPrimaryUserID': userid,
  204. 'vodPrimaryMaster': username
  205. }
  206. dvq.update(**dvq_set_update_dict)
  207. # uid_main_exist = UIDMainUser.objects.filter(UID=UID)
  208. # if not uid_main_exist.exists():
  209. # uid_main_dict = {
  210. # 'UID': UID,
  211. # 'user_id': userid
  212. # }
  213. # UIDMainUser.objects.create(**uid_main_dict)
  214. order_qs.update(status=1, updTime=nowTime, uid_bucket_id=uid_bucket_id,
  215. promotion_rule_id=promotion_rule_id,agreement_id=agreement_id)
  216. datetime = time.strftime("%Y-%m-%d", time.localtime())
  217. sys_msg_text_list = ['温馨提示:尊敬的客户,您的' + UID + '设备在' + datetime + '已成功订阅云存套餐',
  218. 'Dear customer,you already subscribed the cloud storage package successfully for device ' + UID + ' on ' + time.strftime(
  219. "%b %dth,%Y", time.localtime())]
  220. CloudStorage.CloudStorageView.do_vod_msg_Notice(self, UID, channel, userid, lang, sys_msg_text_list, 'SMS_219738485')
  221. # return response.json(0)
  222. red_url = "{SERVER_DOMAIN_SSL}web/paid2/success.html".format(SERVER_DOMAIN_SSL=SERVER_DOMAIN_SSL)
  223. if lang != 'cn':
  224. red_url = "{SERVER_DOMAIN_SSL}web/paid2/en_success.html".format(SERVER_DOMAIN_SSL=SERVER_DOMAIN_SSL)
  225. return HttpResponseRedirect(red_url)
  226. except Exception as e:
  227. print(repr(e))
  228. if order_qs:
  229. order_qs.update(status=10, promotion_rule_id=promotion_rule_id)
  230. red_url = "{SERVER_DOMAIN_SSL}web/paid2/fail.html".format(SERVER_DOMAIN_SSL=SERVER_DOMAIN_SSL)
  231. if lang != 'cn':
  232. red_url = "{SERVER_DOMAIN_SSL}web/paid2/en_fail.html".format(SERVER_DOMAIN_SSL=SERVER_DOMAIN_SSL)
  233. return HttpResponseRedirect(red_url)
  234. def do_paypal_webhook_notify(self, request_dict, request, response):
  235. paymentId = request_dict.get('paymentId', None)
  236. PayerID = request_dict.get('PayerID', None)
  237. lang = request_dict.get('lang', 'en')
  238. token = request_dict.get('token',None)
  239. import json
  240. logger = logging.getLogger('info')
  241. json_str = request.body.decode("utf-8")
  242. logger.info('json_str----------------')
  243. logger.info(json_str)
  244. return response.json(json_str)
  245. paypalrestsdk.configure(PAYPAL_CRD)
  246. # The payload body sent in the webhook event
  247. event_body = '{"id":"WH-0G2756385H040842W-5Y612302CV158622M","create_time":"2015-05-18T15:45:13Z","resource_type":"sale","event_type":"PAYMENT.SALE.COMPLETED","summary":"Payment completed for $ 20.0 USD","resource":{"id":"4EU7004268015634R","create_time":"2015-05-18T15:44:02Z","update_time":"2015-05-18T15:44:21Z","amount":{"total":"20.00","currency":"USD"},"payment_mode":"INSTANT_TRANSFER","state":"completed","protection_eligibility":"ELIGIBLE","protection_eligibility_type":"ITEM_NOT_RECEIVED_ELIGIBLE,UNAUTHORIZED_PAYMENT_ELIGIBLE","parent_payment":"PAY-86C81811X5228590KKVNARQQ","transaction_fee":{"value":"0.88","currency":"USD"},"links":[{"href":"https://api.sandbox.paypal.com/v1/payments/sale/4EU7004268015634R","rel":"self","method":"GET"},{"href":"https://api.sandbox.paypal.com/v1/payments/sale/4EU7004268015634R/refund","rel":"refund","method":"POST"},{"href":"https://api.sandbox.paypal.com/v1/payments/payment/PAY-86C81811X5228590KKVNARQQ","rel":"parent_payment","method":"GET"}]},"links":[{"href":"https://api.sandbox.paypal.com/v1/notifications/webhooks-events/WH-0G2756385H040842W-5Y612302CV158622M","rel":"self","method":"GET"},{"href":"https://api.sandbox.paypal.com/v1/notifications/webhooks-events/WH-0G2756385H040842W-5Y612302CV158622M/resend","rel":"resend","method":"POST"}]}'
  248. # Paypal-Transmission-Id in webhook payload header
  249. transmission_id = "dfb3be50-fd74-11e4-8bf3-77339302725b"
  250. # Paypal-Transmission-Time in webhook payload header
  251. timestamp = "2015-05-18T15:45:13Z"
  252. # Webhook id created
  253. webhook_id = "4JH86294D6297924G"
  254. # Paypal-Transmission-Sig in webhook payload header
  255. actual_signature = "thy4/U002quzxFavHPwbfJGcc46E8rc5jzgyeafWm5mICTBdY/8rl7WJpn8JA0GKA+oDTPsSruqusw+XXg5RLAP7ip53Euh9Xu3UbUhQFX7UgwzE2FeYoY6lyRMiiiQLzy9BvHfIzNIVhPad4KnC339dr6y2l+mN8ALgI4GCdIh3/SoJO5wE64Bh/ueWtt8EVuvsvXfda2Le5a2TrOI9vLEzsm9GS79hAR/5oLexNz8UiZr045Mr5ObroH4w4oNfmkTaDk9Rj0G19uvISs5QzgmBpauKr7Nw++JI0pr/v5mFctQkoWJSGfBGzPRXawrvIIVHQ9Wer48GR2g9ZiApWg=="
  256. # Paypal-Cert-Url in webhook payload header
  257. cert_url = 'https://api.sandbox.paypal.com/v1/notifications/certs/CERT-360caa42-fca2a594-a5cafa77'
  258. # PayPal-Auth-Algo in webhook payload header
  259. auth_algo = 'sha256'
  260. response = WebhookEvent.verify(
  261. transmission_id, timestamp, webhook_id, event_body, cert_url, actual_signature, auth_algo)
  262. print(response)