PaymentCycle.py 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570
  1. from Ansjer.config import PAYPAL_CRD,SERVER_DOMAIN,SERVER_DOMAIN_SSL,PAYPAL_WEB_HOOK_ID
  2. from Model.models import PayCycleConfigModel,Order_Model, Store_Meal, UID_Bucket, PromotionRuleModel, Unused_Uid_Meal,Device_Info, CouponModel
  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. import json
  17. from paypalrestsdk import BillingPlan
  18. #周期扣款相关
  19. class Paypal:
  20. #检查是否有重复订阅
  21. def checkSubscriptions(userID,uid,rank):
  22. hasOrder = Order_Model.objects.filter(userID=userID,UID=uid,rank=rank).values('agreement_id','orderID').order_by('addTime')[0:1]
  23. if not hasOrder.exists() or hasOrder[0]['agreement_id'] == '':
  24. return True
  25. paypalrestsdk.configure(PAYPAL_CRD)
  26. billing_agreement = paypalrestsdk.BillingAgreement.find(hasOrder[0]['agreement_id'])
  27. if billing_agreement.state == 'Active':
  28. return False
  29. return True
  30. def subscriptions(store_info,lang,orderID,price):
  31. cycle_config = PayCycleConfigModel.objects.filter(id=store_info['cycle_config_id']).values()
  32. if not cycle_config:
  33. return False
  34. cal_url = "{SERVER_DOMAIN_SSL}web/paid2/fail.html".format(SERVER_DOMAIN_SSL=SERVER_DOMAIN_SSL)
  35. if lang != 'cn':
  36. cal_url = "{SERVER_DOMAIN_SSL}web/paid2/en_fail.html".format(SERVER_DOMAIN_SSL=SERVER_DOMAIN_SSL)
  37. return_url = "{SERVER_DOMAIN_SSL}payCycle/paypalCycleReturn?lang={lang}". \
  38. format(SERVER_DOMAIN_SSL=SERVER_DOMAIN_SSL, lang=lang)
  39. # call_sub_url = "http://binbin.uicp.vip/cloudstorage/dopaypalcallback?orderID={orderID}".format(
  40. # SERVER_DOMAIN_SSL=SERVER_DOMAIN_SSL, orderID=orderID)
  41. # exit(price)
  42. BillingPlan = {
  43. "description": orderID,
  44. "merchant_preferences": {
  45. "auto_bill_amount": "YES",
  46. "cancel_url": cal_url, # 取消协议url
  47. "initial_fail_amount_action": "CANCEL",
  48. "max_fail_attempts": "1", # 允许的最大失败付款尝试次数
  49. "return_url": return_url, # 客户批准协议的url
  50. # "notify_url": "http://www.notify.com", #通知客户协议已创建的 URL。只读并保留供将来使用。
  51. "setup_fee": {
  52. "currency": store_info['currency'],
  53. "value": price,
  54. }
  55. },
  56. "name": store_info['lang__content'],
  57. "payment_definitions": [
  58. {
  59. "amount": {
  60. "currency": store_info['currency'],
  61. "value": store_info['price']
  62. },
  63. # "charge_models": [
  64. # {
  65. # "amount": {
  66. # "currency": "USD",
  67. # "value": "20"
  68. # },
  69. # "type": "TAX" #税金
  70. # }
  71. # ],
  72. "cycles": cycle_config[0]['cycles'],
  73. "frequency": cycle_config[0]['frequency'],
  74. "frequency_interval": cycle_config[0]['frequencyInterval'],
  75. "name": store_info['lang__title'],
  76. "type": "REGULAR"
  77. },
  78. ],
  79. "type": "INFINITE",
  80. }
  81. paypalrestsdk.configure(PAYPAL_CRD)
  82. billing_plan = paypalrestsdk.BillingPlan(BillingPlan)
  83. if billing_plan.create():
  84. billing_plan.activate() # 激活
  85. plan_id = billing_plan.id
  86. else:
  87. print(billing_plan.error)
  88. return False
  89. now_time = int(time.time())
  90. if cycle_config[0]['frequency'] == "DAY":
  91. start_date_timestamp = now_time + 86400 - 3600 # 下次扣款为明天,提前1个小时扣款
  92. start_date_str = CommonService.timestamp_to_str(start_date_timestamp, "%Y-%m-%dT%H:%M:%SZ")
  93. elif cycle_config[0]['frequency'] == "MONTH":
  94. start_date_timestamp = CommonService.calcMonthLater(1, now_time) - (5 * 86400) #下次扣款为下个月提前5天扣款
  95. start_date_str = CommonService.timestamp_to_str(start_date_timestamp, "%Y-%m-%dT%H:%M:%SZ")
  96. #订阅
  97. billingAgreement = {
  98. "name": store_info['lang__content'],
  99. "description": orderID,
  100. "start_date": start_date_str,
  101. "plan": {
  102. "id": plan_id
  103. },
  104. "payer": {
  105. "payment_method": "paypal"
  106. },
  107. }
  108. billing_agreement = paypalrestsdk.BillingAgreement(billingAgreement)
  109. # print(billing_agreement.create())
  110. if billing_agreement.create():
  111. for link in billing_agreement.links:
  112. if link.rel == "approval_url":
  113. return {"plan_id": plan_id, "url": link.href}
  114. else:
  115. print(billing_agreement.error)
  116. return False
  117. class PaypalCycleNotify(View):
  118. def get(self, request, *args, **kwargs):
  119. request.encoding = 'utf-8'
  120. operation = kwargs.get('operation')
  121. return self.validation(request.GET, request, operation)
  122. def post(self, request, *args, **kwargs):
  123. request.encoding = 'utf-8'
  124. operation = kwargs.get('operation')
  125. return self.validation(request.POST, request, operation)
  126. def validation(self, request_dict, request, operation):
  127. response = ResponseObject()
  128. if operation is None:
  129. return response.json(444, 'error path')
  130. elif operation == 'paypalCycleReturn': # paypal成功订阅回调
  131. return self.do_paypal_cycle_return(request_dict, response)
  132. elif operation == 'paypalCycleNotify': # paypal 周期付款回调
  133. return self.do_paypal_webhook_notify(request_dict,request, response)
  134. elif operation == 'test': # paypal 周期付款回调
  135. return self.do_test(request_dict,request, response)
  136. def do_paypal_cycle_return(self, request_dict, response):
  137. lang = request_dict.get('lang', 'en')
  138. token = request_dict.get('token',None)
  139. paypalrestsdk.configure(PAYPAL_CRD)
  140. billing_agreement = paypalrestsdk.BillingAgreement()
  141. billing_agreement_response = billing_agreement.execute(token)
  142. if billing_agreement_response.error:
  143. print(billing_agreement_response.error)
  144. red_url = "{SERVER_DOMAIN_SSL}web/paid2/fail.html".format(SERVER_DOMAIN_SSL=SERVER_DOMAIN_SSL)
  145. if lang != 'cn':
  146. red_url = "{SERVER_DOMAIN_SSL}web/paid2/en_fail.html".format(SERVER_DOMAIN_SSL=SERVER_DOMAIN_SSL)
  147. return HttpResponseRedirect(red_url)
  148. orderID = billing_agreement_response.description
  149. agreement_id = billing_agreement_response.id
  150. promotion_rule_id = ''
  151. order_qs = Order_Model.objects.filter(orderID=orderID, status=0)
  152. order_list = order_qs.values("UID", "channel", "commodity_code", "rank", "isSelectDiscounts",
  153. "userID__userID",
  154. "userID__username", 'coupon_id')
  155. try:
  156. if not orderID:
  157. print("not orderID")
  158. red_url = "{SERVER_DOMAIN_SSL}web/paid2/fail.html".format(SERVER_DOMAIN_SSL=SERVER_DOMAIN_SSL)
  159. if lang != 'cn':
  160. red_url = "{SERVER_DOMAIN_SSL}web/paid2/en_fail.html".format(SERVER_DOMAIN_SSL=SERVER_DOMAIN_SSL)
  161. return HttpResponseRedirect(red_url)
  162. userid = order_list[0]['userID__userID']
  163. username = order_list[0]['userID__username']
  164. UID = order_list[0]['UID']
  165. channel = order_list[0]['channel']
  166. rank = order_list[0]['rank']
  167. smqs = Store_Meal.objects.filter(id=rank). \
  168. values("day", "bucket_id", "bucket__storeDay", "expire")
  169. bucketId = smqs[0]['bucket_id']
  170. if not smqs.exists():
  171. print("not smqs")
  172. red_url = "{SERVER_DOMAIN_SSL}web/paid2/fail.html".format(SERVER_DOMAIN_SSL=SERVER_DOMAIN_SSL)
  173. if lang != 'cn':
  174. red_url = "{SERVER_DOMAIN_SSL}web/paid2/en_fail.html".format(SERVER_DOMAIN_SSL=SERVER_DOMAIN_SSL)
  175. return HttpResponseRedirect(red_url)
  176. # ##
  177. ubqs = UID_Bucket.objects.filter(uid=UID).values("id", "bucket_id", "bucket__storeDay", "bucket__region",
  178. "endTime", "use_status")
  179. expire = smqs[0]['expire']
  180. if order_list[0]['isSelectDiscounts'] == 1:
  181. expire = smqs[0]['expire'] * 2
  182. # 是否有促销
  183. nowTime = int(time.time())
  184. promotion = PromotionRuleModel.objects.filter(status=1, startTime__lte=nowTime,
  185. endTime__gte=nowTime).values('id','ruleConfig')
  186. if promotion.exists():
  187. promotion_rule_id = promotion[0]['id']
  188. expire = expire * 2
  189. with transaction.atomic():
  190. if ubqs.exists():
  191. ubq = ubqs[0]
  192. if ubq['use_status'] == 1 and ubq['bucket_id'] == bucketId: #套餐使用中并且相同套餐叠加过期时间
  193. endTime = CommonService.calcMonthLater(expire, ubq['endTime'])
  194. UID_Bucket.objects.filter(id=ubq['id']).update \
  195. (uid=UID, channel=channel, bucket_id=bucketId,
  196. endTime=endTime, updateTime=nowTime)
  197. else: #已过期或者不相同的套餐加入未使用的关联套餐表
  198. has_unused = Unused_Uid_Meal.objects.filter(uid=UID, bucket_id=bucketId).values("id")
  199. nums = 2 if order_list[0]['isSelectDiscounts'] == 1 else 1
  200. if promotion.exists():
  201. nums = nums + 1
  202. if has_unused.exists():
  203. Unused_Uid_Meal.objects.filter(id=has_unused[0]['id']).update(num=F('num') + nums)
  204. else:
  205. Unused_Uid_Meal.objects.create(uid=UID,channel=channel,addTime=nowTime,num=nums,
  206. expire=smqs[0]['expire'],bucket_id=bucketId)
  207. UID_Bucket.objects.filter(id=ubq['id']).update(has_unused=1)
  208. uid_bucket_id = ubq['id']
  209. else:
  210. endTime = CommonService.calcMonthLater(expire)
  211. ub_cqs = UID_Bucket.objects.create \
  212. (uid=UID, channel=channel, bucket_id=bucketId, endTime=endTime, addTime=nowTime,
  213. updateTime=nowTime,use_status=1)
  214. uid_bucket_id = ub_cqs.id
  215. dvq = Device_Info.objects.filter(UID=UID, vodPrimaryUserID='', vodPrimaryMaster='')
  216. if dvq.exists():
  217. dvq_set_update_dict = {
  218. 'vodPrimaryUserID': userid,
  219. 'vodPrimaryMaster': username
  220. }
  221. dvq.update(**dvq_set_update_dict)
  222. # uid_main_exist = UIDMainUser.objects.filter(UID=UID)
  223. # if not uid_main_exist.exists():
  224. # uid_main_dict = {
  225. # 'UID': UID,
  226. # 'user_id': userid
  227. # }
  228. # UIDMainUser.objects.create(**uid_main_dict)
  229. # 核销coupon
  230. if order_list[0]['coupon_id']:
  231. CouponModel.objects.filter(id=order_list[0]['coupon_id']).update(use_status=1)
  232. order_qs.update(status=1, updTime=nowTime, uid_bucket_id=uid_bucket_id,
  233. promotion_rule_id=promotion_rule_id,agreement_id=agreement_id)
  234. datetime = time.strftime("%Y-%m-%d", time.localtime())
  235. sys_msg_text_list = ['温馨提示:尊敬的客户,您的' + UID + '设备在' + datetime + '已成功订阅云存套餐',
  236. 'Dear customer,you already subscribed the cloud storage package successfully for device ' + UID + ' on ' + time.strftime(
  237. "%b %dth,%Y", time.localtime())]
  238. CloudStorage.CloudStorageView.do_vod_msg_Notice(self, UID, channel, userid, lang, sys_msg_text_list, 'SMS_219738485')
  239. # return response.json(0)
  240. red_url = "{SERVER_DOMAIN_SSL}web/paid2/success.html".format(SERVER_DOMAIN_SSL=SERVER_DOMAIN_SSL)
  241. if lang != 'cn':
  242. red_url = "{SERVER_DOMAIN_SSL}web/paid2/en_success.html".format(SERVER_DOMAIN_SSL=SERVER_DOMAIN_SSL)
  243. if order_list[0]['coupon_id'] != '':
  244. CouponModel.objects.filter(id=order_list[0]['coupon_id']).update(use_status=2)
  245. return HttpResponseRedirect(red_url)
  246. except Exception as e:
  247. print(repr(e))
  248. if order_qs:
  249. order_qs.update(status=10, promotion_rule_id=promotion_rule_id)
  250. red_url = "{SERVER_DOMAIN_SSL}web/paid2/fail.html".format(SERVER_DOMAIN_SSL=SERVER_DOMAIN_SSL)
  251. if lang != 'cn':
  252. red_url = "{SERVER_DOMAIN_SSL}web/paid2/en_fail.html".format(SERVER_DOMAIN_SSL=SERVER_DOMAIN_SSL)
  253. return HttpResponseRedirect(red_url)
  254. def do_paypal_webhook_notify(self, request_dict, request, response):
  255. logger = logging.getLogger('info')
  256. json_agreement_str = request.body.decode("utf-8")
  257. json_obj = json.loads(json_agreement_str)
  258. header = request.META
  259. paypal_body = json_obj.get('resource')
  260. billing_agreement_id = paypal_body.get('billing_agreement_id')
  261. amount = paypal_body.get('amount')
  262. if not billing_agreement_id:
  263. return HttpResponse('success')
  264. transmission_id = header.get('HTTP_PAYPAL_TRANSMISSION_ID',None)
  265. transmission_time = header.get('HTTP_PAYPAL_TRANSMISSION_TIME',None)
  266. cert_url = header.get('HTTP_PAYPAL_CERT_URL',None)
  267. transmission_sig = header.get('HTTP_PAYPAL_TRANSMISSION_SIG',None)
  268. auth_algo = header.get('HTTP_PAYPAL_AUTH_ALGO',None)
  269. resource_type = json_obj.get('resource_type')
  270. # self.get_plan_desc('P-4CG284532S612303METMEINY')
  271. if resource_type == 'sale' and paypal_body.get('state') == 'completed':
  272. paypalrestsdk.configure(PAYPAL_CRD)
  273. response = paypalrestsdk.WebhookEvent.verify(
  274. transmission_id, transmission_time, PAYPAL_WEB_HOOK_ID, json_agreement_str, cert_url, transmission_sig, auth_algo)
  275. logger.info('-----------------------verify')
  276. logger.info(response)
  277. if response:
  278. try:
  279. agreement_id = paypal_body.get('billing_agreement_id')
  280. billing_agreement = paypalrestsdk.BillingAgreement.find(agreement_id)
  281. # 订阅续费订单(如果完成周期数`不是0, 则说明是续费订单,)
  282. if billing_agreement.agreement_details.cycles_completed != '0':
  283. return HttpResponse('fail')
  284. orderID = billing_agreement.description
  285. order_qs = Order_Model.objects.filter(orderID=orderID, status=1)
  286. if not order_qs:
  287. return HttpResponse('fail')
  288. order_list = order_qs.values("UID", "channel", "commodity_code", "rank", "isSelectDiscounts",
  289. "userID__userID","uid_bucket_id",
  290. "userID__username",'plan_id','addTime','desc','payType','currency','commodity_type')
  291. nowTime = int(time.time())
  292. userid = order_list[0]['userID__userID']
  293. username = order_list[0]['userID__username']
  294. UID = order_list[0]['UID']
  295. channel = order_list[0]['channel']
  296. rank = order_list[0]['rank']
  297. smqs = Store_Meal.objects.filter(id=rank). \
  298. values("day", "bucket_id", "bucket__storeDay", "expire")
  299. bucketId = smqs[0]['bucket_id']
  300. if not smqs.exists():
  301. return HttpResponse('fail')
  302. # ##
  303. ubqs = UID_Bucket.objects.filter(uid=UID).values("id", "bucket_id", "bucket__storeDay",
  304. "bucket__region",
  305. "endTime", "use_status")
  306. expire = smqs[0]['expire']
  307. # if order_list[0]['isSelectDiscounts'] == 1:
  308. # expire = smqs[0]['expire'] * 2
  309. # 是否有促销
  310. # nowTime = int(time.time())
  311. # promotion = PromotionRuleModel.objects.filter(status=1, startTime__lte=nowTime,
  312. # endTime__gte=nowTime).values('id', 'ruleConfig')
  313. # if promotion.exists():
  314. # promotion_rule_id = promotion[0]['id']
  315. # expire = expire * 2
  316. with transaction.atomic():
  317. if ubqs.exists():
  318. ubq = ubqs[0]
  319. if ubq['use_status'] == 1 and ubq['bucket_id'] == bucketId: # 套餐使用中并且相同套餐叠加过期时间
  320. endTime = CommonService.calcMonthLater(expire, ubq['endTime'])
  321. UID_Bucket.objects.filter(id=ubq['id']).update \
  322. (uid=UID, channel=channel, bucket_id=bucketId,
  323. endTime=endTime, updateTime=nowTime)
  324. else: # 已过期或者不相同的套餐加入未使用的关联套餐表
  325. has_unused = Unused_Uid_Meal.objects.filter(uid=UID, bucket_id=bucketId).values("id")
  326. # nums = 2 if order_list[0]['isSelectDiscounts'] == 1 else 1
  327. # if promotion.exists():
  328. nums = 1
  329. if has_unused.exists():
  330. Unused_Uid_Meal.objects.filter(id=has_unused[0]['id']).update(num=F('num') + nums)
  331. else:
  332. Unused_Uid_Meal.objects.create(uid=UID, channel=channel, addTime=nowTime, num=nums,
  333. expire=smqs[0]['expire'], bucket_id=bucketId)
  334. UID_Bucket.objects.filter(id=ubq['id']).update(has_unused=1)
  335. uid_bucket_id = ubq['id']
  336. else:
  337. endTime = CommonService.calcMonthLater(expire)
  338. ub_cqs = UID_Bucket.objects.create \
  339. (uid=UID, channel=channel, bucket_id=bucketId, endTime=endTime, addTime=nowTime,
  340. updateTime=nowTime, use_status=1)
  341. uid_bucket_id = ub_cqs.id
  342. dvq = Device_Info.objects.filter(UID=UID, vodPrimaryUserID='', vodPrimaryMaster='')
  343. if dvq.exists():
  344. dvq_set_update_dict = {
  345. 'vodPrimaryUserID': userid,
  346. 'vodPrimaryMaster': username
  347. }
  348. dvq.update(**dvq_set_update_dict)
  349. # uid_main_exist = UIDMainUser.objects.filter(UID=UID)
  350. # if not uid_main_exist.exists():
  351. # uid_main_dict = {
  352. # 'UID': UID,
  353. # 'user_id': userid
  354. # }
  355. # UIDMainUser.objects.create(**uid_main_dict)
  356. orderID = CommonService.createOrderID()
  357. Order_Model.objects.create(orderID=orderID, UID=UID, channel=channel, userID_id=userid,
  358. desc=order_list[0]['desc'], payType=order_list[0]['payType'], payTime=nowTime,
  359. price=amount.get('total'), currency=order_list[0]['currency'], addTime=nowTime, updTime=nowTime,
  360. pay_url='', isSelectDiscounts=0,
  361. commodity_code=order_list[0]['commodity_code'], commodity_type=order_list[0]['commodity_type'],
  362. rank_id=rank, paymentID='', coupon_id='',uid_bucket_id=uid_bucket_id,status=1,agreement_id=agreement_id,plan_id=order_list[0]['plan_id'])
  363. datetime = time.strftime("%Y-%m-%d", time.localtime())
  364. sys_msg_text_list = ['温馨提示:尊敬的客户,您的' + UID + '设备在' + datetime + '已成功续订云存套餐',
  365. 'Dear customer,you already subscribed the cloud storage package successfully for device ' + UID + ' on ' + time.strftime(
  366. "%b %dth,%Y", time.localtime())]
  367. if order_list[0]['payType'] == 1:
  368. lang = 'en'
  369. else:
  370. lang = 'cn'
  371. CloudStorage.CloudStorageView.do_vod_msg_Notice(self, UID, channel, userid, lang,
  372. sys_msg_text_list, 'SMS_219738485')
  373. logger.info('-----------------------result')
  374. logger.info('success')
  375. return HttpResponse('success')
  376. except Exception as e:
  377. print(e)
  378. return HttpResponse('fail')
  379. return HttpResponse('fail')
  380. def do_test(self, request_dict, request, response):
  381. paypalrestsdk.configure(PAYPAL_CRD)
  382. billing_agreement = paypalrestsdk.BillingAgreement
  383. billing_agreement = billing_agreement.find("I-HT38K76XPMGJ")
  384. print("Got Billing Agreement Details for Billing Agreement[%s]" % (
  385. billing_agreement.id))
  386. exit()
  387. #normal_pay
  388. # json_str = '{"id":"WH-8SU832847J141682K-0FF265943E8692615","event_version":"1.0","create_time":"2022-01-10T06:31:49.863Z","resource_type":"sale","event_type":"PAYMENT.SALE.COMPLETED","summary":"Payment completed for $ 0.02 USD","resource":{"amount":{"total":"0.02","currency":"USD","details":{"subtotal":"0.02"}},"payment_mode":"INSTANT_TRANSFER","create_time":"2022-01-10T06:31:45Z","transaction_fee":{"currency":"USD","value":"0.02"},"parent_payment":"PAYID-MHN5E5Y1RH70069CT417990V","update_time":"2022-01-10T06:31:45Z","protection_eligibility_type":"ITEM_NOT_RECEIVED_ELIGIBLE,UNAUTHORIZED_PAYMENT_ELIGIBLE","application_context":{"related_qualifiers":[{"id":"0FJ93448LU7282046","type":"CART"}]},"protection_eligibility":"ELIGIBLE","links":[{"method":"GET","rel":"self","href":"https://api.sandbox.paypal.com/v1/payments/sale/6N498138TH641260G"},{"method":"POST","rel":"refund","href":"https://api.sandbox.paypal.com/v1/payments/sale/6N498138TH641260G/refund"},{"method":"GET","rel":"parent_payment","href":"https://api.sandbox.paypal.com/v1/payments/payment/PAYID-MHN5E5Y1RH70069CT417990V"}],"id":"6N498138TH641260G","state":"completed","invoice_number":""},"links":[{"href":"https://api.sandbox.paypal.com/v1/notifications/webhooks-events/WH-8SU832847J141682K-0FF265943E8692615","rel":"self","method":"GET"},{"href":"https://api.sandbox.paypal.com/v1/notifications/webhooks-events/WH-8SU832847J141682K-0FF265943E8692615/resend","rel":"resend","method":"POST"}]}'
  389. json_agreement_str = '{"id":"WH-9BE23393R5338163R-48P08088YL173821A","event_version":"1.0","create_time":"2022-01-10T10:27:42.925Z","resource_type":"sale","event_type":"PAYMENT.SALE.COMPLETED","summary":"Payment completed for $ 0.02 USD","resource":{"billing_agreement_id":"I-K8PCK2NJC6N6","amount":{"total":"0.02","currency":"USD","details":{"subtotal":"0.02"}},"payment_mode":"INSTANT_TRANSFER","update_time":"2022-01-10T10:27:19Z","create_time":"2022-01-10T10:27:19Z","protection_eligibility_type":"ITEM_NOT_RECEIVED_ELIGIBLE,UNAUTHORIZED_PAYMENT_ELIGIBLE","transaction_fee":{"currency":"USD","value":"0.02"},"protection_eligibility":"ELIGIBLE","links":[{"method":"GET","rel":"self","href":"https://api.sandbox.paypal.com/v1/payments/sale/4H259512Y67055105"},{"method":"POST","rel":"refund","href":"https://api.sandbox.paypal.com/v1/payments/sale/4H259512Y67055105/refund"}],"id":"4H259512Y67055105","state":"completed","invoice_number":""},"links":[{"href":"https://api.sandbox.paypal.com/v1/notifications/webhooks-events/WH-9BE23393R5338163R-48P08088YL173821A","rel":"self","method":"GET"},{"href":"https://api.sandbox.paypal.com/v1/notifications/webhooks-events/WH-9BE23393R5338163R-48P08088YL173821A/resend","rel":"resend","method":"POST"}]}'
  390. header = {'wsgi.file_wrapper': '<class gunicorn.http.wsgi.FileWrapper>', 'wsgi.version': '(1, 0)', 'HTTP_CONNECTION': 'close', 'wsgi.url_scheme': 'http', 'HTTP_PAYPAL_CERT_URL': 'https://api.sandbox.paypal.com/v1/notifications/certs/CERT-360caa42-fca2a594-7a8abba8', 'HTTP_PAYPAL_TRANSMISSION_ID': '022fbbc0-7139-11ec-afa1-0114a54fc1fc', 'SERVER_NAME': '0.0.0.0', 'HTTP_CORRELATION_ID': 'be4c80f0a6c05', 'REMOTE_ADDR': '127.0.0.1', 'HTTP_PAYPAL_TRANSMISSION_SIG': 'IM3Xwyjw5YUgBKPsgyjPdMAh6DSFTtqdwy8zbJBXBhFyB77B6mEqnRfhtEgwwBhag6HsStmKBGIScFhs5Nuraru7DbT4+7Tu5fNx3oQIHeHtR/FYZoQcv86bjZ9cq+Xo04HmhUfgBAsSetS+CuY5TsN60d1m8Hld1MTDjk1UuSbk8HA3dBLiMzWT7wUw3/SUau/C7TtLnWGmdJlkFne+b/5s0+HsuXn3wQQCDIHO0sBMBo72NdlyMlLIunSdoEJ61pKi2U1jQ6qqe/59IrY2q4ufx9D6JZ4bUB6z3NQZ+Gm7zrlKabT6HkVovLJbuBgRgRWWUoY02CuVXZ9w4AzVNQ==', 'REMOTE_PORT': '58060', 'HTTP_ACCEPT': '*/*', 'CONTENT_TYPE': 'application/json', 'HTTP_USER_AGENT': 'PayPal/AUHR-214.0-56015767', 'SCRIPT_NAME': '', 'HTTP_X_FORWARDED_FOR': '173.0.80.117', 'HTTP_HOST': 'test.zositechc.cn:443', 'wsgi.multiprocess': True, 'SERVER_PROTOCOL': 'HTTP/1.0', 'PATH_INFO': '/payCycle/paypalCycleNotify', 'SERVER_SOFTWARE': 'gunicorn/19.7.1', 'wsgi.input': '<gunicorn.http.body.Body object at 0x7fb966cddfd0>', 'REQUEST_METHOD': 'POST', 'wsgi.errors': '<gunicorn.http.wsgi.WSGIErrorsWrapper object at 0x7fb966cdda90>', 'CONTENT_LENGTH': '1226', 'wsgi.run_once': False, 'HTTP_X_B3_SPANID': 'e8ede80526720f95', 'HTTP_PAYPAL_AUTH_ALGO': 'SHA256withRSA', 'QUERY_STRING': '', 'HTTP_PAYPAL_TRANSMISSION_TIME': '2022-01-09T10:43:40Z', 'wsgi.multithread': False, 'HTTP_HTTP_X_FORWARDED_FOR': '173.0.80.117', 'HTTP_X_REAL_IP': '173.0.80.117', 'RAW_URI': '/payCycle/paypalCycleNotify', 'HTTP_PAYPAL_AUTH_VERSION': 'v2', 'gunicorn.socket': '<socket.socket fd=51, family=AddressFamily.AF_INET, type=SocketKind.SOCK_STREAM, proto=0, laddr=(127.0.0.1, 8082), raddr=(127.0.0.1, 58060)>', 'SERVER_PORT': '8082'}
  391. json_obj = json.loads(json_agreement_str)
  392. paypal_body = json_obj.get('resource')
  393. billing_agreement_id = paypal_body.get('billing_agreement_id')
  394. amount = paypal_body.get('amount')
  395. if not billing_agreement_id:
  396. return HttpResponse('success')
  397. nowTime = int(time.time())
  398. transmission_id = header.get('HTTP_PAYPAL_TRANSMISSION_ID',None)
  399. transmission_time = header.get('HTTP_PAYPAL_TRANSMISSION_TIME',None)
  400. webhook_id = '6TS30758D98835230'
  401. cert_url = header.get('HTTP_PAYPAL_CERT_URL',None)
  402. transmission_sig = header.get('HTTP_PAYPAL_TRANSMISSION_SIG',None)
  403. auth_algo = header.get('HTTP_PAYPAL_AUTH_ALGO',None)
  404. resource_type = json_obj.get('resource_type')
  405. # return HttpResponse(resource_type)
  406. transmission_id = 'f42509f0-71ff-11ec-a473-05e6d85b61e7'
  407. transmission_time = '2022-01-10T10:27:46Z'
  408. webhook_id = '3J888119TD851704M'
  409. cert_url = 'https://api.sandbox.paypal.com/v1/notifications/certs/CERT-360caa42-fca2a594-7a8abba8'
  410. transmission_sig = 'R6sBDhsoq5+FRQHWe+8tSeKJMlRDnt9F2SlWlWVVEfDu9mvQ0zKl74bwcN1zMbvH4o7fWVNbwkcPW70/t4O0YBsj9BcMwL8hDxcuWuHp20RBzaI2dlBpdPEke19wr/fhJKGZCDYuvptV2RJGCSePBn3gKs7hkY5ribELPDqHuajlgVxMmoXm/+CHrMmPo6gSGgTuEMzEn4/ENuj3uJoCkcYqsFx3tUHg6eakUvQ+vYAyflRx9hX7QXEQHp15PWLgGzHkm9zGmnX6YoG5keo5MbJEYh9LfHJjmHmHVErvOtHebJxfTEDZwGoqw+WHr3KqnP4L1gaUj7XIXsQzbiFTBg=='
  411. auth_algo = 'SHA256withRSA'
  412. resource_type = 'sale'
  413. self.get_plan_desc('P-4CG284532S612303METMEINY')
  414. if resource_type == 'sale' and paypal_body.get('state') == 'completed':
  415. # paypalrestsdk.configure(PAYPAL_CRD)
  416. # response = paypalrestsdk.WebhookEvent.verify(
  417. # transmission_id, transmission_time, webhook_id, json_agreement_str, cert_url, transmission_sig, auth_algo)
  418. response = True
  419. if response:
  420. try:
  421. agreement_id = paypal_body.get('billing_agreement_id')
  422. order_qs = Order_Model.objects.filter(agreement_id=agreement_id, status=1)
  423. if not order_qs:
  424. return HttpResponse('failss')
  425. order_list = order_qs.values("UID", "channel", "commodity_code", "rank", "isSelectDiscounts",
  426. "userID__userID","uid_bucket_id",
  427. "userID__username",'plan_id','addTime','desc','payType','currency','commodity_type')
  428. plan_id = order_list[0]['plan_id']
  429. # plan_cycle = self.get_plan_desc(plan_id)
  430. # 订阅续费订单(如果查到的本地订单已经付过了且包中的完成周期数`不是0, 则说明是续费订单, 本地可以新建一个订单标记是续费的)
  431. nowTime = int(time.time())
  432. if(order_list[0]['addTime']+600 > nowTime):
  433. return HttpResponse('success')
  434. userid = order_list[0]['userID__userID']
  435. username = order_list[0]['userID__username']
  436. UID = order_list[0]['UID']
  437. channel = order_list[0]['channel']
  438. rank = order_list[0]['rank']
  439. smqs = Store_Meal.objects.filter(id=rank). \
  440. values("day", "bucket_id", "bucket__storeDay", "expire")
  441. bucketId = smqs[0]['bucket_id']
  442. if not smqs.exists():
  443. return HttpResponse('fail')
  444. # ##
  445. ubqs = UID_Bucket.objects.filter(uid=UID).values("id", "bucket_id", "bucket__storeDay",
  446. "bucket__region",
  447. "endTime", "use_status")
  448. expire = smqs[0]['expire']
  449. # if order_list[0]['isSelectDiscounts'] == 1:
  450. # expire = smqs[0]['expire'] * 2
  451. # 是否有促销
  452. # nowTime = int(time.time())
  453. # promotion = PromotionRuleModel.objects.filter(status=1, startTime__lte=nowTime,
  454. # endTime__gte=nowTime).values('id', 'ruleConfig')
  455. # if promotion.exists():
  456. # promotion_rule_id = promotion[0]['id']
  457. # expire = expire * 2
  458. with transaction.atomic():
  459. if ubqs.exists():
  460. ubq = ubqs[0]
  461. if ubq['use_status'] == 1 and ubq['bucket_id'] == bucketId: # 套餐使用中并且相同套餐叠加过期时间
  462. endTime = CommonService.calcMonthLater(expire, ubq['endTime'])
  463. UID_Bucket.objects.filter(id=ubq['id']).update \
  464. (uid=UID, channel=channel, bucket_id=bucketId,
  465. endTime=endTime, updateTime=nowTime)
  466. else: # 已过期或者不相同的套餐加入未使用的关联套餐表
  467. has_unused = Unused_Uid_Meal.objects.filter(uid=UID, bucket_id=bucketId).values("id")
  468. # nums = 2 if order_list[0]['isSelectDiscounts'] == 1 else 1
  469. # if promotion.exists():
  470. nums = 1
  471. if has_unused.exists():
  472. Unused_Uid_Meal.objects.filter(id=has_unused[0]['id']).update(num=F('num') + nums)
  473. else:
  474. Unused_Uid_Meal.objects.create(uid=UID, channel=channel, addTime=nowTime, num=nums,
  475. expire=smqs[0]['expire'], bucket_id=bucketId)
  476. UID_Bucket.objects.filter(id=ubq['id']).update(has_unused=1)
  477. uid_bucket_id = ubq['id']
  478. else:
  479. endTime = CommonService.calcMonthLater(expire)
  480. ub_cqs = UID_Bucket.objects.create \
  481. (uid=UID, channel=channel, bucket_id=bucketId, endTime=endTime, addTime=nowTime,
  482. updateTime=nowTime, use_status=1)
  483. uid_bucket_id = ub_cqs.id
  484. dvq = Device_Info.objects.filter(UID=UID, vodPrimaryUserID='', vodPrimaryMaster='')
  485. if dvq.exists():
  486. dvq_set_update_dict = {
  487. 'vodPrimaryUserID': userid,
  488. 'vodPrimaryMaster': username
  489. }
  490. dvq.update(**dvq_set_update_dict)
  491. # uid_main_exist = UIDMainUser.objects.filter(UID=UID)
  492. # if not uid_main_exist.exists():
  493. # uid_main_dict = {
  494. # 'UID': UID,
  495. # 'user_id': userid
  496. # }
  497. # UIDMainUser.objects.create(**uid_main_dict)
  498. orderID = CommonService.createOrderID()
  499. Order_Model.objects.create(orderID=orderID, UID=UID, channel=channel, userID_id=userid,
  500. desc=order_list[0]['desc'], payType=order_list[0]['payType'], payTime=nowTime,
  501. price=amount.get('total'), currency=order_list[0]['currency'], addTime=nowTime, updTime=nowTime,
  502. pay_url='', isSelectDiscounts=0,
  503. commodity_code=order_list[0]['commodity_code'], commodity_type=order_list[0]['commodity_type'],
  504. rank_id=rank, paymentID='', coupon_id='',uid_bucket_id=uid_bucket_id,status=1,agreement_id=agreement_id,plan_id=order_list[0]['plan_id'])
  505. datetime = time.strftime("%Y-%m-%d", time.localtime())
  506. sys_msg_text_list = ['温馨提示:尊敬的客户,您的' + UID + '设备在' + datetime + '已成功续订云存套餐',
  507. 'Dear customer,you already subscribed the cloud storage package successfully for device ' + UID + ' on ' + time.strftime(
  508. "%b %dth,%Y", time.localtime())]
  509. if order_list[0]['payType'] == 1:
  510. lang = 'en'
  511. else:
  512. lang = 'cn'
  513. CloudStorage.CloudStorageView.do_vod_msg_Notice(self, UID, channel, userid, lang,
  514. sys_msg_text_list, 'SMS_219738485')
  515. return HttpResponse('success')
  516. except Exception as e:
  517. print(e)
  518. return HttpResponse('fail')
  519. return HttpResponse('fail')
  520. def get_plan_desc(self,plan_id):
  521. paypalrestsdk.configure(PAYPAL_CRD)
  522. billing_plan = paypalrestsdk.BillingPlan.find(plan_id)
  523. print("Got Billing Plan Details for Billing Plan[%s]" % (billing_plan.id))
  524. exit()