PaymentCycle.py 39 KB

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