PaymentCycle.py 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719
  1. from Ansjer.config import PAYPAL_CRD, SERVER_DOMAIN, SERVER_DOMAIN_SSL, PAYPAL_WEB_HOOK_ID, PAYPAL_WEB_HOOK_ID_TWO
  2. from Model.models import PayCycleConfigModel, Order_Model, Store_Meal, UID_Bucket, PromotionRuleModel, \
  3. Unused_Uid_Meal, Device_Info, CouponModel, Order_Model, PaypalWebHookEvent
  4. from Service.CommonService import CommonService
  5. from django.http import JsonResponse, HttpResponseRedirect, HttpResponse
  6. import requests
  7. import time
  8. import sys
  9. from Object.TokenObject import TokenObject
  10. from Object.UidTokenObject import UidTokenObject
  11. from Object.ResponseObject import ResponseObject
  12. import paypalrestsdk
  13. from paypalrestsdk import BillingAgreement
  14. from django.views.generic.base import View
  15. from django.db import transaction
  16. from Controller import CloudStorage
  17. from django.db.models import Q, F, Count
  18. from paypalrestsdk.notifications import WebhookEvent
  19. import logging
  20. import json
  21. from paypalrestsdk import BillingPlan
  22. import datetime as date_time
  23. # 周期扣款相关
  24. class Paypal:
  25. # 检查是否有重复订阅
  26. def checkSubscriptions(userID, uid, rank):
  27. hasOrder = Order_Model.objects.filter(UID=uid, rank=rank)
  28. hasOrder = hasOrder.filter(~Q(agreement_id='')).values('agreement_id', 'orderID').order_by('-addTime')[0:1]
  29. if not hasOrder.exists():
  30. return True
  31. paypalrestsdk.configure(PAYPAL_CRD)
  32. billing_agreement = paypalrestsdk.BillingAgreement.find(hasOrder[0]['agreement_id'])
  33. if billing_agreement.state == 'Active':
  34. return False
  35. return True
  36. def subscriptions(store_info, lang, orderID, price):
  37. logger = logging.getLogger('pay')
  38. cycle_config = PayCycleConfigModel.objects.filter(id=store_info['cycle_config_id']).values()
  39. if not cycle_config:
  40. logger.info('----创建订阅失败----')
  41. logger.info('订阅配置失败')
  42. return False
  43. cal_url = "{SERVER_DOMAIN_SSL}web/paid2/fail.html".format(SERVER_DOMAIN_SSL=SERVER_DOMAIN_SSL)
  44. if lang != 'cn':
  45. cal_url = "{SERVER_DOMAIN_SSL}web/paid2/en_fail.html".format(SERVER_DOMAIN_SSL=SERVER_DOMAIN_SSL)
  46. return_url = "{SERVER_DOMAIN_SSL}payCycle/paypalCycleReturn?lang={lang}". \
  47. format(SERVER_DOMAIN_SSL=SERVER_DOMAIN_SSL, lang=lang)
  48. # call_sub_url = "http://binbin.uicp.vip/cloudstorage/dopaypalcallback?orderID={orderID}".format(
  49. # SERVER_DOMAIN_SSL=SERVER_DOMAIN_SSL, orderID=orderID)
  50. # exit(price)
  51. BillingPlan = {
  52. "description": orderID,
  53. "merchant_preferences": {
  54. "auto_bill_amount": "YES",
  55. "cancel_url": cal_url, # 取消协议url
  56. "initial_fail_amount_action": "CANCEL",
  57. "max_fail_attempts": "1", # 允许的最大失败付款尝试次数
  58. "return_url": return_url, # 客户批准协议的url
  59. # "notify_url": "http://www.notify.com", #通知客户协议已创建的 URL。只读并保留供将来使用。
  60. "setup_fee": {
  61. "currency": store_info['currency'],
  62. "value": price,
  63. }
  64. },
  65. "name": store_info['lang__content'],
  66. "payment_definitions": [
  67. {
  68. "amount": {
  69. "currency": store_info['currency'],
  70. "value": store_info['price']
  71. },
  72. # "charge_models": [
  73. # {
  74. # "amount": {
  75. # "currency": "USD",
  76. # "value": "20"
  77. # },
  78. # "type": "TAX" #税金
  79. # }
  80. # ],
  81. "cycles": cycle_config[0]['cycles'],
  82. "frequency": cycle_config[0]['frequency'],
  83. "frequency_interval": cycle_config[0]['frequencyInterval'],
  84. "name": store_info['lang__title'],
  85. "type": "REGULAR"
  86. },
  87. ],
  88. "type": "INFINITE",
  89. }
  90. paypalrestsdk.configure(PAYPAL_CRD)
  91. billing_plan = paypalrestsdk.BillingPlan(BillingPlan)
  92. if billing_plan.create():
  93. billing_plan.activate() # 激活
  94. plan_id = billing_plan.id
  95. else:
  96. logger.info('----创建计划失败----')
  97. logger.info(billing_plan.error)
  98. return False
  99. now_time = int(time.time())
  100. if cycle_config[0]['frequency'] == "DAY":
  101. start_date_timestamp = now_time + 86400 - 3600 # 下次扣款为明天,提前1个小时扣款
  102. start_date_str = CommonService.timestamp_to_str(start_date_timestamp, "%Y-%m-%dT%H:%M:%SZ")
  103. elif cycle_config[0]['frequency'] == "MONTH":
  104. start_date_timestamp = CommonService.calcMonthLater(1, now_time) - (5 * 86400) # 下次扣款为下个月提前5天扣款
  105. start_date_str = CommonService.timestamp_to_str(start_date_timestamp, "%Y-%m-%dT%H:%M:%SZ")
  106. # 订阅
  107. billingAgreement = {
  108. "name": store_info['lang__content'],
  109. "description": orderID,
  110. "start_date": start_date_str,
  111. "plan": {
  112. "id": plan_id
  113. },
  114. "payer": {
  115. "payment_method": "paypal"
  116. },
  117. }
  118. billing_agreement = paypalrestsdk.BillingAgreement(billingAgreement)
  119. # print(billing_agreement.create())
  120. if billing_agreement.create():
  121. for link in billing_agreement.links:
  122. if link.rel == "approval_url":
  123. return {"plan_id": plan_id, "url": link.href}
  124. else:
  125. logger.info('----创建订阅失败----')
  126. logger.info(billing_agreement.error)
  127. return False
  128. class PaypalCycleNotify(View):
  129. def get(self, request, *args, **kwargs):
  130. request.encoding = 'utf-8'
  131. operation = kwargs.get('operation')
  132. return self.validation(request.GET, request, operation)
  133. def post(self, request, *args, **kwargs):
  134. request.encoding = 'utf-8'
  135. operation = kwargs.get('operation')
  136. return self.validation(request.POST, request, operation)
  137. def validation(self, request_dict, request, operation):
  138. response = ResponseObject()
  139. if operation is None:
  140. return response.json(444, 'error path')
  141. elif operation == 'paypalCycleReturn': # paypal成功订阅回调
  142. return self.do_paypal_cycle_return(request_dict, response)
  143. elif operation == 'paypalCycleNotify': # paypal 周期付款回调
  144. return self.do_paypal_webhook_notify(request_dict, request, response)
  145. elif operation == 'subscriptionBreakNotify': # paypal 订阅相关回调
  146. return self.do_subscription_break_notify(request_dict, request, response)
  147. def do_paypal_cycle_return(self, request_dict, response):
  148. lang = request_dict.get('lang', 'en')
  149. token = request_dict.get('token', None)
  150. logger = logging.getLogger('pay')
  151. logger.info('--------进入paypay首次订阅付款回调--------')
  152. logger.info(request_dict)
  153. paypalrestsdk.configure(PAYPAL_CRD)
  154. billing_agreement = paypalrestsdk.BillingAgreement()
  155. billing_agreement_response = billing_agreement.execute(token)
  156. if billing_agreement_response.error:
  157. logger.info('----付款失败----')
  158. logger.info(billing_agreement_response.error)
  159. red_url = "{SERVER_DOMAIN_SSL}web/paid2/fail.html".format(SERVER_DOMAIN_SSL=SERVER_DOMAIN_SSL)
  160. if lang != 'cn':
  161. red_url = "{SERVER_DOMAIN_SSL}web/paid2/en_fail.html".format(SERVER_DOMAIN_SSL=SERVER_DOMAIN_SSL)
  162. return HttpResponseRedirect(red_url)
  163. orderID = billing_agreement_response.description
  164. state = billing_agreement_response.state
  165. nowTime = int(time.time())
  166. promotion_rule_id = ''
  167. logger.info('----订阅详情----')
  168. logger.info(billing_agreement_response)
  169. agreement_id = billing_agreement_response.id
  170. order_qs = Order_Model.objects.filter(orderID=orderID, status=0)
  171. order_list = order_qs.values("UID", "channel", "commodity_code", "rank", "isSelectDiscounts",
  172. "userID__userID",
  173. "userID__username", 'coupon_id')
  174. if not orderID:
  175. logger.info('----订阅订单号失效----')
  176. red_url = "{SERVER_DOMAIN_SSL}web/paid2/fail.html".format(SERVER_DOMAIN_SSL=SERVER_DOMAIN_SSL)
  177. if lang != 'cn':
  178. red_url = "{SERVER_DOMAIN_SSL}web/paid2/en_fail.html".format(SERVER_DOMAIN_SSL=SERVER_DOMAIN_SSL)
  179. return HttpResponseRedirect(red_url)
  180. UID = order_list[0]['UID']
  181. if state != 'Active':
  182. order_qs.update(status=2, promotion_rule_id=promotion_rule_id)
  183. logger.info('----UID:{UID},用户名:{last_time} {first_time}首次订阅付款失败----'.format
  184. (UID=UID,
  185. last_time=billing_agreement_response.payer.payer_info.last_name,
  186. first_time=billing_agreement_response.payer.payer_info.first_time,
  187. ))
  188. logger.info('billing_agreement_state')
  189. logger.info(state)
  190. red_url = "{SERVER_DOMAIN_SSL}web/paid2/fail.html".format(SERVER_DOMAIN_SSL=SERVER_DOMAIN_SSL)
  191. if lang != 'cn':
  192. red_url = "{SERVER_DOMAIN_SSL}web/paid2/en_fail.html".format(SERVER_DOMAIN_SSL=SERVER_DOMAIN_SSL)
  193. return HttpResponseRedirect(red_url)
  194. try:
  195. userid = order_list[0]['userID__userID']
  196. username = order_list[0]['userID__username']
  197. channel = order_list[0]['channel']
  198. rank = order_list[0]['rank']
  199. smqs = Store_Meal.objects.filter(id=rank). \
  200. values("day", "bucket_id", "bucket__storeDay", "expire")
  201. bucketId = smqs[0]['bucket_id']
  202. if not smqs.exists():
  203. logger.info('----订阅套餐失效----')
  204. red_url = "{SERVER_DOMAIN_SSL}web/paid2/fail.html".format(SERVER_DOMAIN_SSL=SERVER_DOMAIN_SSL)
  205. if lang != 'cn':
  206. red_url = "{SERVER_DOMAIN_SSL}web/paid2/en_fail.html".format(SERVER_DOMAIN_SSL=SERVER_DOMAIN_SSL)
  207. return HttpResponseRedirect(red_url)
  208. # ##
  209. ubqs = UID_Bucket.objects.filter(uid=UID).values("id", "bucket_id", "bucket__storeDay", "bucket__region",
  210. "endTime", "use_status")
  211. expire = smqs[0]['expire']
  212. if order_list[0]['isSelectDiscounts'] == 1:
  213. expire = smqs[0]['expire'] * 2
  214. # 是否有促销
  215. promotion = PromotionRuleModel.objects.filter(status=1, startTime__lte=nowTime,
  216. endTime__gte=nowTime).values('id', 'ruleConfig')
  217. if promotion.exists():
  218. promotion_rule_id = promotion[0]['id']
  219. expire = expire * 2
  220. with transaction.atomic():
  221. if ubqs.exists():
  222. ubq = ubqs[0]
  223. if ubq['use_status'] == 1 and ubq['bucket_id'] == bucketId: # 套餐使用中并且相同套餐叠加过期时间
  224. endTime = CommonService.calcMonthLater(expire, ubq['endTime'])
  225. UID_Bucket.objects.filter(id=ubq['id']).update \
  226. (uid=UID, channel=channel, bucket_id=bucketId,
  227. endTime=endTime, updateTime=nowTime)
  228. else: # 已过期或者不相同的套餐加入未使用的关联套餐表
  229. has_unused = Unused_Uid_Meal.objects.filter(uid=UID, bucket_id=bucketId).values("id")
  230. nums = 2 if order_list[0]['isSelectDiscounts'] == 1 else 1
  231. if promotion.exists():
  232. nums = nums + 1
  233. if has_unused.exists():
  234. Unused_Uid_Meal.objects.filter(id=has_unused[0]['id']).update(num=F('num') + nums)
  235. else:
  236. Unused_Uid_Meal.objects.create(uid=UID, channel=channel, addTime=nowTime, num=nums,
  237. expire=smqs[0]['expire'], bucket_id=bucketId)
  238. UID_Bucket.objects.filter(id=ubq['id']).update(has_unused=1)
  239. uid_bucket_id = ubq['id']
  240. else:
  241. endTime = CommonService.calcMonthLater(expire)
  242. ub_cqs = UID_Bucket.objects.create \
  243. (uid=UID, channel=channel, bucket_id=bucketId, endTime=endTime, addTime=nowTime,
  244. updateTime=nowTime, use_status=1)
  245. uid_bucket_id = ub_cqs.id
  246. dvq = Device_Info.objects.filter(UID=UID, vodPrimaryUserID='', vodPrimaryMaster='')
  247. if dvq.exists():
  248. dvq_set_update_dict = {
  249. 'vodPrimaryUserID': userid,
  250. 'vodPrimaryMaster': username
  251. }
  252. dvq.update(**dvq_set_update_dict)
  253. # uid_main_exist = UIDMainUser.objects.filter(UID=UID)
  254. # if not uid_main_exist.exists():
  255. # uid_main_dict = {
  256. # 'UID': UID,
  257. # 'user_id': userid
  258. # }
  259. # UIDMainUser.objects.create(**uid_main_dict)
  260. # 核销coupon
  261. if order_list[0]['coupon_id']:
  262. CouponModel.objects.filter(id=order_list[0]['coupon_id']).update(use_status=2, update_time=nowTime)
  263. order_qs.update(status=1, updTime=nowTime, uid_bucket_id=uid_bucket_id,
  264. promotion_rule_id=promotion_rule_id, agreement_id=agreement_id)
  265. # 如果存在序列号,消息提示用序列号
  266. device_name = CommonService.query_serial_with_uid(uid=UID)
  267. datetime = time.strftime("%Y-%m-%d", time.localtime())
  268. sys_msg_text_list = ['温馨提示:尊敬的客户,您的' + device_name + '设备在' + datetime + '已成功订阅云存套餐',
  269. 'Dear customer,you already subscribed the cloud storage package successfully for device ' + device_name + ' on ' + time.strftime(
  270. "%b %dth,%Y", time.localtime())]
  271. CloudStorage.CloudStorageView().do_vod_msg_Notice(UID, channel, userid, lang, sys_msg_text_list,
  272. 'SMS_219738485')
  273. # return response.json(0)
  274. red_url = "{SERVER_DOMAIN_SSL}web/paid2/success.html".format(SERVER_DOMAIN_SSL=SERVER_DOMAIN_SSL)
  275. if lang != 'cn':
  276. red_url = "{SERVER_DOMAIN_SSL}web/paid2/en_success.html".format(SERVER_DOMAIN_SSL=SERVER_DOMAIN_SSL)
  277. logger.info('{UID}成功开通paypal自动续费:----'.format(UID=UID))
  278. return HttpResponseRedirect(red_url)
  279. except Exception as e:
  280. print(repr(e))
  281. logger.info('do_paypal_cycle_return支付失败:----')
  282. logger.info('{UID}开通paypal自动续费失败'.format(UID=UID))
  283. logger.info("错误行数:{errLine}".format(errLine=e.__traceback__.tb_lineno))
  284. logger.info(repr(e))
  285. if order_qs:
  286. order_qs.update(status=10, promotion_rule_id=promotion_rule_id)
  287. red_url = "{SERVER_DOMAIN_SSL}web/paid2/fail.html".format(SERVER_DOMAIN_SSL=SERVER_DOMAIN_SSL)
  288. if lang != 'cn':
  289. red_url = "{SERVER_DOMAIN_SSL}web/paid2/en_fail.html".format(SERVER_DOMAIN_SSL=SERVER_DOMAIN_SSL)
  290. return HttpResponseRedirect(red_url)
  291. def do_paypal_webhook_notify(self, request_dict, request, response):
  292. logger = logging.getLogger('pay')
  293. logger.info('--------进入周期扣款钩子--------')
  294. json_agreement_str = request.body.decode("utf-8")
  295. json_obj = json.loads(json_agreement_str)
  296. header = request.META
  297. paypal_body = json_obj.get('resource')
  298. logger.info('----主体信息----')
  299. logger.info(json_agreement_str)
  300. logger.info('----周期扣款头部信息----')
  301. logger.info(header)
  302. try:
  303. transmission_id = header.get('HTTP_PAYPAL_TRANSMISSION_ID', None)
  304. transmission_time = header.get('HTTP_PAYPAL_TRANSMISSION_TIME', None)
  305. cert_url = header.get('HTTP_PAYPAL_CERT_URL', None)
  306. transmission_sig = header.get('HTTP_PAYPAL_TRANSMISSION_SIG', None)
  307. auth_algo = header.get('HTTP_PAYPAL_AUTH_ALGO', None)
  308. event_type = json_obj.get('event_type')
  309. summary = json_obj.get('summary')
  310. resource_type = json_obj.get('resource_type')
  311. billing_agreement_id = paypal_body.get('billing_agreement_id')
  312. paypal_transaction_id = paypal_body.get('id')
  313. amount = paypal_body.get('amount')
  314. if event_type != 'PAYMENT.SALE.COMPLETED':
  315. logger.info('----钩子异常----')
  316. self.find_subscription_transactions(billing_agreement_id)
  317. # self.get_plan_desc('P-4CG284532S612303METMEINY')
  318. if resource_type == 'sale' and paypal_body.get('state') == 'completed':
  319. paypalrestsdk.configure(PAYPAL_CRD)
  320. response = paypalrestsdk.WebhookEvent.verify(
  321. transmission_id, transmission_time, PAYPAL_WEB_HOOK_ID, json_agreement_str, cert_url,
  322. transmission_sig, auth_algo)
  323. logger.info('----验证签名----')
  324. logger.info(response)
  325. if not response:
  326. return HttpResponse('Fail', status=500)
  327. else:
  328. logger.info('----付款状态有误----')
  329. logger.info(resource_type)
  330. logger.info(paypal_body.get('state'))
  331. return HttpResponse('Fail', status=500)
  332. PaypalWebHookEventInsert = {
  333. 'webhook_event_id': json_obj.get('id'),
  334. 'resource_type': json_obj.get('resource_type'),
  335. 'event_type': 1,
  336. 'summary': summary,
  337. 'trade_no': paypal_transaction_id,
  338. 'resource': json_agreement_str,
  339. 'created_time': int(time.time()),
  340. }
  341. if not billing_agreement_id:
  342. # 记录钩子日志
  343. PaypalWebHookEvent.objects.create(**PaypalWebHookEventInsert)
  344. # 普通支付,更新paypal交易id
  345. paymentID = paypal_body.get('parent_payment')
  346. if paymentID and paypal_transaction_id:
  347. Order_Model.objects.filter(paymentID=paymentID).update(
  348. updTime=int(time.time()),
  349. trade_no=paypal_transaction_id
  350. )
  351. logger.info('----paypal_transaction_id----更新成功')
  352. logger.info('----paypal_transaction_id----:')
  353. logger.info(paypal_transaction_id)
  354. return HttpResponse('success')
  355. else:
  356. logger.info('----paymentID and transactions_id某个为空')
  357. logger.info(paymentID)
  358. logger.info(paypal_transaction_id)
  359. return HttpResponse('fail', status=500)
  360. agreement_id = paypal_body.get('billing_agreement_id')
  361. billing_agreement = paypalrestsdk.BillingAgreement.find(agreement_id)
  362. logger.info(type(billing_agreement))
  363. # 记录钩子日志
  364. PaypalWebHookEventInsert['agreement_desc'] = repr(billing_agreement)
  365. PaypalWebHookEventInsert['agreement_id'] = agreement_id
  366. PaypalWebHookEventInsert['orderID'] = billing_agreement.description
  367. PaypalWebHookEvent.objects.create(**PaypalWebHookEventInsert)
  368. # 订阅续费订单(如果完成周期数`==0,则是自动续费第一次扣款。否则说明是续费订单)
  369. if billing_agreement.agreement_details.cycles_completed == '0':
  370. logger.info('----订阅详情----')
  371. logger.info(billing_agreement)
  372. logger.info('订阅续费订单完成周期数==0,结束')
  373. # 更新order表,paypal的商家交易号
  374. Order_Model.objects.filter(orderID=billing_agreement.description).update(
  375. updTime=int(time.time()),
  376. trade_no=paypal_transaction_id
  377. )
  378. return HttpResponse('success')
  379. oldOrderID = billing_agreement.description
  380. order_qs = Order_Model.objects.filter(orderID=oldOrderID, status=1)
  381. if not order_qs:
  382. return HttpResponse('fail', status=500)
  383. order_list = order_qs.values("UID", "channel", "commodity_code", "rank", "isSelectDiscounts",
  384. "userID__userID", "uid_bucket_id",
  385. "userID__username", 'plan_id', 'addTime', 'desc', 'payType', 'currency',
  386. 'commodity_type', 'updTime')
  387. nowTime = int(time.time())
  388. if order_list[0]['addTime'] + 9200 > nowTime: # 避免续费订单重复支付
  389. logger.info('----paypal重复异步回调----')
  390. return HttpResponse('success')
  391. logger.info('----走入订阅过程----')
  392. userid = order_list[0]['userID__userID']
  393. username = order_list[0]['userID__username']
  394. UID = order_list[0]['UID']
  395. channel = order_list[0]['channel']
  396. rank = order_list[0]['rank']
  397. smqs = Store_Meal.objects.filter(id=rank). \
  398. values("day", "bucket_id", "bucket__storeDay", "expire")
  399. bucketId = smqs[0]['bucket_id']
  400. if not smqs.exists():
  401. return HttpResponse('fail', status=500)
  402. # ##
  403. ubqs = UID_Bucket.objects.filter(uid=UID).values("id", "bucket_id", "bucket__storeDay",
  404. "bucket__region",
  405. "endTime", "use_status")
  406. expire = smqs[0]['expire']
  407. # if order_list[0]['isSelectDiscounts'] == 1:
  408. # expire = smqs[0]['expire'] * 2
  409. # 是否有促销
  410. # nowTime = int(time.time())
  411. # promotion = PromotionRuleModel.objects.filter(status=1, startTime__lte=nowTime,
  412. # endTime__gte=nowTime).values('id', 'ruleConfig')
  413. # if promotion.exists():
  414. # promotion_rule_id = promotion[0]['id']
  415. # expire = expire * 2
  416. with transaction.atomic():
  417. if ubqs.exists():
  418. ubq = ubqs[0]
  419. if ubq['use_status'] == 1 and ubq['bucket_id'] == bucketId: # 套餐使用中并且相同套餐叠加过期时间
  420. endTime = CommonService.calcMonthLater(expire, ubq['endTime'])
  421. UID_Bucket.objects.filter(id=ubq['id']).update \
  422. (uid=UID, channel=channel, bucket_id=bucketId,
  423. endTime=endTime, updateTime=nowTime)
  424. else: # 已过期或者不相同的套餐加入未使用的关联套餐表
  425. has_unused = Unused_Uid_Meal.objects.filter(uid=UID, bucket_id=bucketId).values("id")
  426. # nums = 2 if order_list[0]['isSelectDiscounts'] == 1 else 1
  427. # if promotion.exists():
  428. nums = 1
  429. if has_unused.exists():
  430. Unused_Uid_Meal.objects.filter(id=has_unused[0]['id']).update(num=F('num') + nums)
  431. else:
  432. Unused_Uid_Meal.objects.create(uid=UID, channel=channel, addTime=nowTime, num=nums,
  433. expire=smqs[0]['expire'], bucket_id=bucketId)
  434. UID_Bucket.objects.filter(id=ubq['id']).update(has_unused=1)
  435. uid_bucket_id = ubq['id']
  436. else:
  437. endTime = CommonService.calcMonthLater(expire)
  438. ub_cqs = UID_Bucket.objects.create \
  439. (uid=UID, channel=channel, bucket_id=bucketId, endTime=endTime, addTime=nowTime,
  440. updateTime=nowTime, use_status=1)
  441. uid_bucket_id = ub_cqs.id
  442. dvq = Device_Info.objects.filter(UID=UID, vodPrimaryUserID='', vodPrimaryMaster='')
  443. if dvq.exists():
  444. dvq_set_update_dict = {
  445. 'vodPrimaryUserID': userid,
  446. 'vodPrimaryMaster': username
  447. }
  448. dvq.update(**dvq_set_update_dict)
  449. # uid_main_exist = UIDMainUser.objects.filter(UID=UID)
  450. # if not uid_main_exist.exists():
  451. # uid_main_dict = {
  452. # 'UID': UID,
  453. # 'user_id': userid
  454. # }
  455. # UIDMainUser.objects.create(**uid_main_dict)
  456. orderID = CommonService.createOrderID()
  457. Order_Model.objects.create(orderID=orderID, UID=UID, channel=channel, userID_id=userid,
  458. desc=order_list[0]['desc'], payType=order_list[0]['payType'],
  459. payTime=nowTime,
  460. price=amount.get('total'), currency=order_list[0]['currency'],
  461. addTime=nowTime, updTime=nowTime,
  462. pay_url='', isSelectDiscounts=0,
  463. commodity_code=order_list[0]['commodity_code'],
  464. commodity_type=order_list[0]['commodity_type'], rank_id=rank, paymentID='',
  465. coupon_id='', uid_bucket_id=uid_bucket_id, status=1,
  466. agreement_id=agreement_id,
  467. plan_id=order_list[0]['plan_id'], ai_rank_id=1,
  468. trade_no=paypal_transaction_id)
  469. # 如果存在序列号,消息提示用序列号
  470. device_name = CommonService.query_serial_with_uid(uid=UID)
  471. datetime = time.strftime("%Y-%m-%d", time.localtime())
  472. sys_msg_text_list = ['温馨提示:尊敬的客户,您的' + device_name + '设备在' + datetime + '已成功续订云存套餐',
  473. 'Dear customer,you already subscribed the cloud storage package successfully for device ' + device_name + ' on ' + time.strftime(
  474. "%b %dth,%Y", time.localtime())]
  475. if order_list[0]['payType'] == 1:
  476. lang = 'en'
  477. else:
  478. lang = 'cn'
  479. CloudStorage.CloudStorageView().do_vod_msg_Notice(UID, channel, userid, lang,
  480. sys_msg_text_list, 'SMS_219738485')
  481. logger.info('----周期扣款结果----')
  482. logger.info('success')
  483. # 更新agreement
  484. billing_agreement_update_attributes = [
  485. {
  486. "op": "replace",
  487. "path": "/",
  488. "value": {
  489. "description": orderID,
  490. }
  491. }
  492. ]
  493. billing_agreement.replace(billing_agreement_update_attributes)
  494. logger.info('{UID}成功续费paypal:----'.format(UID=UID))
  495. return HttpResponse('success')
  496. except Exception as e:
  497. print(e)
  498. logger.info('----周期扣款钩子失败----')
  499. logger.info('do_paypal_webhook_notify支付失败:----')
  500. logger.info("错误行数:{errLine}".format(errLine=e.__traceback__.tb_lineno))
  501. logger.info(repr(e))
  502. return HttpResponse('fail', status=500)
  503. @staticmethod
  504. def find_subscription_transactions(billing_agreement_id):
  505. """
  506. 列出当前订阅扣款事务
  507. @param billing_agreement_id: 协议id
  508. @return:
  509. """
  510. if not billing_agreement_id:
  511. return False
  512. logger = logging.getLogger('pay')
  513. try:
  514. paypalrestsdk.configure(PAYPAL_CRD)
  515. billing_agreement = paypalrestsdk.BillingAgreement.find(billing_agreement_id)
  516. today = date_time.date.today()
  517. oneday = date_time.timedelta(days=1)
  518. yesterday = today - oneday
  519. start_date = yesterday.strftime('%Y-%m-%d')
  520. end_date = today.strftime('%Y-%m-%d')
  521. transactions = billing_agreement.search_transactions(start_date, end_date)
  522. logger.info('--->列出当前扣款事务{}'.format(transactions))
  523. except Exception as e:
  524. logger.info('出错了~查询订阅的事务异常,errLine:{}, errMsg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  525. def do_subscription_break_notify(self, request_dict, request, response):
  526. logger = logging.getLogger('pay')
  527. logger.info('--------进入订阅失败,付款失败,暂停--------')
  528. json_agreement_str = request.body.decode("utf-8")
  529. json_obj = json.loads(json_agreement_str)
  530. header = request.META
  531. paypal_body = json_obj.get('resource')
  532. logger.info('----主体信息----')
  533. logger.info(json_agreement_str)
  534. logger.info('----进入订阅失败头部信息----')
  535. logger.info(header)
  536. try:
  537. transmission_id = header.get('HTTP_PAYPAL_TRANSMISSION_ID', None)
  538. transmission_time = header.get('HTTP_PAYPAL_TRANSMISSION_TIME', None)
  539. cert_url = header.get('HTTP_PAYPAL_CERT_URL', None)
  540. transmission_sig = header.get('HTTP_PAYPAL_TRANSMISSION_SIG', None)
  541. auth_algo = header.get('HTTP_PAYPAL_AUTH_ALGO', None)
  542. event_type = json_obj.get('event_type')
  543. summary = json_obj.get('summary')
  544. resource_type = json_obj.get('resource_type')
  545. paypal_transaction_id = paypal_body.get('id')
  546. amount = paypal_body.get('amount')
  547. # self.get_plan_desc('P-4CG284532S612303METMEINY')
  548. paypalrestsdk.configure(PAYPAL_CRD)
  549. response = paypalrestsdk.WebhookEvent.verify(
  550. transmission_id, transmission_time, PAYPAL_WEB_HOOK_ID_TWO, json_agreement_str, cert_url,
  551. transmission_sig, auth_algo)
  552. logger.info('----验证签名----')
  553. logger.info(response)
  554. if not response:
  555. return HttpResponse('Fail', status=500)
  556. event_type_code = 0
  557. billing_agreement_id = ''
  558. if event_type == 'PAYMENT.SALE.COMPLETED':
  559. event_type_code = 1
  560. billing_agreement_id = paypal_body.get('billing_agreement_id')
  561. elif event_type == 'PAYMENT.SALE.REVERSED':
  562. billing_agreement_id = paypal_body.get('billing_agreement_id')
  563. event_type_code = 2
  564. elif event_type == 'BILLING.SUBSCRIPTION.CANCELLED':
  565. billing_agreement_id = paypal_body.get('id')
  566. event_type_code = 3
  567. elif event_type == 'BILLING.SUBSCRIPTION.SUSPENDED':
  568. billing_agreement_id = paypal_body.get('id')
  569. event_type_code = 4
  570. elif event_type == 'BILLING.SUBSCRIPTION.PAYMENT.FAILED':
  571. billing_agreement_id = paypal_body.get('id')
  572. event_type_code = 5
  573. elif event_type == 'PAYMENT.SALE.REFUNDED':
  574. billing_agreement_id = paypal_body.get('billing_agreement_id')
  575. event_type_code = 6
  576. PaypalWebHookEventInsert = {
  577. 'webhook_event_id': json_obj.get('id'),
  578. 'resource_type': resource_type,
  579. 'event_type': event_type_code,
  580. 'summary': summary,
  581. 'trade_no': paypal_transaction_id,
  582. 'resource': json_agreement_str,
  583. 'created_time': int(time.time()),
  584. }
  585. if not billing_agreement_id:
  586. # 记录钩子日志
  587. PaypalWebHookEvent.objects.create(**PaypalWebHookEventInsert)
  588. return HttpResponse('success')
  589. billing_agreement = paypalrestsdk.BillingAgreement.find(billing_agreement_id)
  590. # 记录钩子日志
  591. PaypalWebHookEventInsert['agreement_desc'] = repr(billing_agreement)
  592. PaypalWebHookEventInsert['agreement_id'] = billing_agreement_id
  593. PaypalWebHookEventInsert['orderID'] = billing_agreement.description
  594. PaypalWebHookEvent.objects.create(**PaypalWebHookEventInsert)
  595. return HttpResponse('success')
  596. except Exception as e:
  597. print(e)
  598. logger.info('----进入订阅失败----')
  599. logger.info('do_paypal_webhook_notify支付失败:----')
  600. logger.info("错误行数:{errLine}".format(errLine=e.__traceback__.tb_lineno))
  601. logger.info(repr(e))
  602. return HttpResponse('fail', status=500)
  603. def get_plan_desc(self, plan_id):
  604. paypalrestsdk.configure(PAYPAL_CRD)
  605. billing_plan = paypalrestsdk.BillingPlan.find(plan_id)
  606. print("Got Billing Plan Details for Billing Plan[%s]" % (billing_plan.id))
  607. exit()
  608. class payCycle(View):
  609. def get(self, request, *args, **kwargs):
  610. request.encoding = 'utf-8'
  611. operation = kwargs.get('operation')
  612. return self.validation(request.GET, request, operation)
  613. def post(self, request, *args, **kwargs):
  614. request.encoding = 'utf-8'
  615. operation = kwargs.get('operation')
  616. return self.validation(request.POST, request, operation)
  617. def validation(self, request_dict, request, operation):
  618. response = ResponseObject()
  619. token = request_dict.get('token', None)
  620. # 设备主键uid
  621. tko = TokenObject(token)
  622. response.lang = tko.lang
  623. if tko.code != 0:
  624. return response.json(tko.code)
  625. userID = tko.userID
  626. if operation is None:
  627. return response.json(444, 'error path')
  628. elif operation == 'queryPayCycle': # paypal成功订阅回调
  629. return self.do_query_pay_cycle(request_dict, userID, response)
  630. elif operation == 'cancelPayCycle': # 取消自动续费
  631. return self.do_cancel_pay_cycle(request_dict, userID, response)
  632. def do_query_pay_cycle(self, request_dict, userID, response):
  633. lang = request_dict.get('lang', 'en')
  634. uid = request_dict.get('uid', None)
  635. orderObject = Order_Model.objects.filter(userID=userID, status=1, rank__lang__lang=lang).annotate(
  636. rank__title=F('rank__lang__title'), rank__content=F('rank__lang__content'))
  637. if uid:
  638. orderObject = orderObject.filter(UID=uid)
  639. orderObject = orderObject.filter(~Q(agreement_id=''))
  640. if not orderObject.exists():
  641. return response.json(0, {'data': [], 'count': 0})
  642. orderQuery = orderObject.values("orderID", "UID", "channel", "desc", "price", "currency",
  643. "addTime",
  644. "updTime", "paypal", "rank__day", "payType",
  645. "rank__price", "status",
  646. "rank__lang__content", "rank__lang__title", "rank__currency",
  647. "rank_id", "rank__expire", "agreement_id").order_by('addTime')
  648. new_data = []
  649. values = []
  650. for d in orderQuery:
  651. if d['agreement_id'] not in values:
  652. new_data.append(d)
  653. values.append(d['agreement_id'])
  654. count = len(new_data)
  655. return response.json(0, {'data': new_data, 'count': count})
  656. def do_cancel_pay_cycle(self, request_dict, userID, response):
  657. orderID = request_dict.get('orderID', 'None')
  658. orderObject = Order_Model.objects.filter(orderID=orderID)
  659. orderObject = orderObject.filter(~Q(agreement_id='')).values("agreement_id")
  660. if not orderObject.exists():
  661. return response.json(800)
  662. paypalrestsdk.configure(PAYPAL_CRD)
  663. BILLING_AGREEMENT_ID = orderObject[0]['agreement_id']
  664. try:
  665. billing_agreement = paypalrestsdk.BillingAgreement.find(BILLING_AGREEMENT_ID)
  666. if billing_agreement.state != 'Active':
  667. Order_Model.objects.filter(agreement_id=BILLING_AGREEMENT_ID).update(agreement_id='')
  668. return response.json(0)
  669. cancel_note = {"note": "Canceling the agreement"}
  670. if billing_agreement.cancel(cancel_note):
  671. Order_Model.objects.filter(agreement_id=BILLING_AGREEMENT_ID).update(agreement_id='')
  672. return response.json(0)
  673. else:
  674. return response.json(10052)
  675. except Exception as e:
  676. return response.json(10052)