PaymentCycle.py 36 KB

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