PaymentCycle.py 36 KB

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