PaymentCycle.py 46 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841
  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)
  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 create_vod(self, uid, expire, is_ai, now_time, channel, bucket_id, order_id, userid, username):
  145. ubqs = UID_Bucket.objects.filter(uid=uid).values("id", "endTime", "use_status")
  146. end_time = CommonService.calcMonthLater(expire)
  147. use_flag = True
  148. with transaction.atomic():
  149. if ubqs.exists():
  150. ubq = ubqs[0]
  151. uid_bucket_id = ubq['id']
  152. if ubq['use_status'] == 1 and ubq['endTime'] > now_time: # 套餐使用中并且未过期,加入未使用的关联套餐表
  153. Unused_Uid_Meal.objects.create(uid=uid, channel=channel, addTime=now_time, is_ai=is_ai,
  154. order_id=order_id, expire=expire, bucket_id=bucket_id)
  155. UID_Bucket.objects.filter(id=uid_bucket_id).update(has_unused=1)
  156. use_flag = False
  157. else: # 云存服务已过期则重新开通云存服务
  158. UID_Bucket.objects.filter(id=uid_bucket_id).update(uid=uid, channel=channel,
  159. bucket_id=bucket_id,
  160. endTime=end_time,
  161. updateTime=now_time,
  162. use_status=1,
  163. orderId=order_id)
  164. else:
  165. ub_cqs = UID_Bucket.objects.create \
  166. (uid=uid, channel=channel, bucket_id=bucket_id, endTime=end_time, addTime=now_time,
  167. updateTime=now_time, use_status=1, orderId=order_id)
  168. uid_bucket_id = ub_cqs.id
  169. dvq = Device_Info.objects.filter(UID=uid, vodPrimaryUserID='', vodPrimaryMaster='')
  170. if dvq.exists():
  171. dvq_set_update_dict = {
  172. 'vodPrimaryUserID': userid,
  173. 'vodPrimaryMaster': username
  174. }
  175. dvq.update(**dvq_set_update_dict)
  176. # 开通AI服务
  177. if is_ai and use_flag:
  178. ai_service = AiService.objects.filter(uid=uid, channel=channel)
  179. if ai_service.exists(): # 有正在使用的套餐,套餐结束时间保存为套餐有效期
  180. ai_service.update(updTime=now_time, use_status=1, orders_id=order_id, endTime=end_time)
  181. else:
  182. AiService.objects.create(uid=uid, channel=channel, detect_status=1, addTime=now_time,
  183. updTime=now_time, endTime=end_time, use_status=1, orders_id=order_id)
  184. return uid_bucket_id
  185. def do_paypal_cycle_return(self, request_dict, response):
  186. lang = request_dict.get('lang', 'en')
  187. token = request_dict.get('token', None)
  188. logger = logging.getLogger('pay')
  189. logger.info('--------进入paypay首次订阅付款回调--------')
  190. logger.info(request_dict)
  191. paypalrestsdk.configure(PAYPAL_CRD)
  192. billing_agreement = paypalrestsdk.BillingAgreement()
  193. billing_agreement_response = billing_agreement.execute(token)
  194. if billing_agreement_response.error:
  195. logger.info('----付款失败----')
  196. logger.info(billing_agreement_response.error)
  197. red_url = "{SERVER_DOMAIN_SSL}web/paid2/fail.html".format(SERVER_DOMAIN_SSL=SERVER_DOMAIN_SSL)
  198. if lang != 'cn':
  199. red_url = "{SERVER_DOMAIN_SSL}web/paid2/en_fail.html".format(SERVER_DOMAIN_SSL=SERVER_DOMAIN_SSL)
  200. return HttpResponseRedirect(red_url)
  201. orderID = billing_agreement_response.description
  202. state = billing_agreement_response.state
  203. nowTime = int(time.time())
  204. promotion_rule_id = ''
  205. logger.info('----订阅详情----')
  206. logger.info(billing_agreement_response)
  207. agreement_id = billing_agreement_response.id
  208. order_qs = Order_Model.objects.filter(orderID=orderID, status=0)
  209. order_list = order_qs.values("UID", "channel", "commodity_code", "rank", "isSelectDiscounts",
  210. "userID__userID",
  211. "userID__username", 'coupon_id')
  212. if not orderID:
  213. logger.info('----订阅订单号失效----')
  214. red_url = "{SERVER_DOMAIN_SSL}web/paid2/fail.html".format(SERVER_DOMAIN_SSL=SERVER_DOMAIN_SSL)
  215. if lang != 'cn':
  216. red_url = "{SERVER_DOMAIN_SSL}web/paid2/en_fail.html".format(SERVER_DOMAIN_SSL=SERVER_DOMAIN_SSL)
  217. return HttpResponseRedirect(red_url)
  218. UID = order_list[0]['UID']
  219. if state != 'Active':
  220. order_qs.update(status=2, promotion_rule_id=promotion_rule_id)
  221. logger.info('----UID:{UID},用户名:{last_time} {first_time}首次订阅付款失败----'.format
  222. (UID=UID,
  223. last_time=billing_agreement_response.payer.payer_info.last_name,
  224. first_time=billing_agreement_response.payer.payer_info.first_time,
  225. ))
  226. logger.info('billing_agreement_state')
  227. logger.info(state)
  228. red_url = "{SERVER_DOMAIN_SSL}web/paid2/fail.html".format(SERVER_DOMAIN_SSL=SERVER_DOMAIN_SSL)
  229. if lang != 'cn':
  230. red_url = "{SERVER_DOMAIN_SSL}web/paid2/en_fail.html".format(SERVER_DOMAIN_SSL=SERVER_DOMAIN_SSL)
  231. return HttpResponseRedirect(red_url)
  232. try:
  233. userid = order_list[0]['userID__userID']
  234. username = order_list[0]['userID__username']
  235. channel = order_list[0]['channel']
  236. rank = order_list[0]['rank']
  237. smqs = Store_Meal.objects.filter(id=rank).values("day", "bucket_id", "bucket__storeDay", "expire", "is_ai")
  238. bucketId = smqs[0]['bucket_id']
  239. if not smqs.exists():
  240. logger.info('----订阅套餐失效----')
  241. red_url = "{SERVER_DOMAIN_SSL}web/paid2/fail.html".format(SERVER_DOMAIN_SSL=SERVER_DOMAIN_SSL)
  242. if lang != 'cn':
  243. red_url = "{SERVER_DOMAIN_SSL}web/paid2/en_fail.html".format(SERVER_DOMAIN_SSL=SERVER_DOMAIN_SSL)
  244. return HttpResponseRedirect(red_url)
  245. # ##
  246. ubqs = UID_Bucket.objects.filter(uid=UID).values("id", "bucket_id", "bucket__storeDay", "bucket__region",
  247. "endTime", "use_status")
  248. expire = smqs[0]['expire']
  249. is_ai = smqs[0]['is_ai']
  250. if order_list[0]['isSelectDiscounts'] == 1:
  251. expire = smqs[0]['expire'] * 2
  252. # 是否有促销
  253. promotion = PromotionRuleModel.objects.filter(status=1, startTime__lte=nowTime,
  254. endTime__gte=nowTime).values('id', 'ruleConfig')
  255. if promotion.exists():
  256. promotion_rule_id = promotion[0]['id']
  257. expire = expire * 2
  258. endTime = CommonService.calcMonthLater(expire)
  259. use_flag = True
  260. with transaction.atomic():
  261. if ubqs.exists():
  262. ubq = ubqs[0]
  263. uid_bucket_id = ubq['id']
  264. if ubq['use_status'] == 1 and ubq['endTime'] > nowTime: # 套餐使用中并且未过期,加入未使用的关联套餐表
  265. Unused_Uid_Meal.objects.create(uid=UID, channel=channel, addTime=nowTime, is_ai=is_ai,
  266. order_id=orderID, expire=expire, bucket_id=bucketId)
  267. update_status = UID_Bucket.objects.filter(id=uid_bucket_id).update(has_unused=1)
  268. use_flag = False
  269. else: # 云存服务已过期则重新开通云存服务
  270. update_status = UID_Bucket.objects.filter(id=uid_bucket_id).update(uid=UID, channel=channel,
  271. bucket_id=bucketId,
  272. endTime=endTime,
  273. updateTime=nowTime,
  274. use_status=1,
  275. orderId=orderID)
  276. else:
  277. ub_cqs = UID_Bucket.objects.create \
  278. (uid=UID, channel=channel, bucket_id=bucketId, endTime=endTime, addTime=nowTime,
  279. updateTime=nowTime, use_status=1, orderId=orderID)
  280. update_status = True
  281. uid_bucket_id = ub_cqs.id
  282. dvq = Device_Info.objects.filter(UID=UID, vodPrimaryUserID='', vodPrimaryMaster='')
  283. if dvq.exists():
  284. dvq_set_update_dict = {
  285. 'vodPrimaryUserID': userid,
  286. 'vodPrimaryMaster': username
  287. }
  288. dvq.update(**dvq_set_update_dict)
  289. # 开通AI服务
  290. if is_ai and use_flag:
  291. ai_service = AiService.objects.filter(uid=UID, channel=channel)
  292. if ai_service.exists(): # 有正在使用的套餐,套餐结束时间保存为套餐有效期
  293. ai_service.update(updTime=nowTime, use_status=1, orders_id=orderID, endTime=endTime)
  294. else:
  295. AiService.objects.create(uid=UID, channel=channel, detect_status=1, addTime=nowTime,
  296. updTime=nowTime, endTime=endTime, use_status=1, orders_id=orderID)
  297. # uid_main_exist = UIDMainUser.objects.filter(UID=UID)
  298. # if not uid_main_exist.exists():
  299. # uid_main_dict = {
  300. # 'UID': UID,
  301. # 'user_id': userid
  302. # }
  303. # UIDMainUser.objects.create(**uid_main_dict)
  304. # 核销coupon
  305. if order_list[0]['coupon_id']:
  306. CouponModel.objects.filter(id=order_list[0]['coupon_id']).update(use_status=2, update_time=nowTime)
  307. logger.info(
  308. 'uid:{},uid_bucket_id:{},update_status:{},order_id:{}'.format(UID, uid_bucket_id, update_status,
  309. orderID))
  310. order_qs.update(status=1, updTime=nowTime, uid_bucket_id=uid_bucket_id, create_vod=1, payTime=nowTime,
  311. promotion_rule_id=promotion_rule_id, agreement_id=agreement_id)
  312. # 如果存在序列号,消息提示用序列号
  313. device_name = CommonService.query_serial_with_uid(uid=UID)
  314. datetime = time.strftime("%Y-%m-%d", time.localtime())
  315. sys_msg_text_list = [
  316. '温馨提示:尊敬的客户,您的' + device_name + '设备在' + datetime + '已成功订阅云存套餐',
  317. 'Dear customer, you have now successfully subscribed to the cloud storage plan for device ' + device_name + ' on ' + time.strftime(
  318. "%b %dth,%Y", time.localtime())]
  319. CloudStorage.CloudStorageView().do_vod_msg_notice(UID, channel, userid, lang, sys_msg_text_list,
  320. 'SMS_219738485')
  321. # return response.json(0)
  322. red_url = "{SERVER_DOMAIN_SSL}web/paid2/success.html".format(SERVER_DOMAIN_SSL=SERVER_DOMAIN_SSL)
  323. if lang != 'cn':
  324. red_url = "{SERVER_DOMAIN_SSL}web/paid2/en_success.html".format(SERVER_DOMAIN_SSL=SERVER_DOMAIN_SSL)
  325. logger.info('{UID}成功开通paypal自动续费:----'.format(UID=UID))
  326. return HttpResponseRedirect(red_url)
  327. except Exception as e:
  328. print(repr(e))
  329. logger.info('do_paypal_cycle_return支付失败:----')
  330. logger.info('{UID}开通paypal自动续费失败'.format(UID=UID))
  331. logger.info("错误行数:{errLine}".format(errLine=e.__traceback__.tb_lineno))
  332. logger.info(repr(e))
  333. if order_qs:
  334. order_qs.update(status=10, promotion_rule_id=promotion_rule_id)
  335. red_url = "{SERVER_DOMAIN_SSL}web/paid2/fail.html".format(SERVER_DOMAIN_SSL=SERVER_DOMAIN_SSL)
  336. if lang != 'cn':
  337. red_url = "{SERVER_DOMAIN_SSL}web/paid2/en_fail.html".format(SERVER_DOMAIN_SSL=SERVER_DOMAIN_SSL)
  338. return HttpResponseRedirect(red_url)
  339. def do_paypal_webhook_notify(self, request_dict, request, response):
  340. PAY_LOGGER.info('--------进入周期扣款钩子--------')
  341. if not request.body:
  342. PAY_LOGGER.info('PayPal周期扣款失败---缺失请求体')
  343. return HttpResponse('fail', status=500)
  344. json_agreement_str = request.body.decode("utf-8")
  345. json_obj = json.loads(json_agreement_str)
  346. header = request.META
  347. paypal_body = json_obj.get('resource')
  348. PAY_LOGGER.info('----请求体数据:{}----'.format(json_agreement_str))
  349. PAY_LOGGER.info('----请求头数据:{}----'.format(header))
  350. try:
  351. transmission_id = header.get('HTTP_PAYPAL_TRANSMISSION_ID', None)
  352. transmission_time = header.get('HTTP_PAYPAL_TRANSMISSION_TIME', None)
  353. cert_url = header.get('HTTP_PAYPAL_CERT_URL', None)
  354. transmission_sig = header.get('HTTP_PAYPAL_TRANSMISSION_SIG', None)
  355. auth_algo = header.get('HTTP_PAYPAL_AUTH_ALGO', None)
  356. event_type = json_obj.get('event_type')
  357. summary = json_obj.get('summary')
  358. resource_type = json_obj.get('resource_type')
  359. agreement_id = paypal_body.get('billing_agreement_id')
  360. paypal_transaction_id = paypal_body.get('id')
  361. amount = paypal_body.get('amount')
  362. fee = paypal_body['transaction_fee']['value']
  363. PaypalWebHookEventInsert = {
  364. 'webhook_event_id': json_obj.get('id'),
  365. 'resource_type': json_obj.get('resource_type'),
  366. 'event_type': 1,
  367. 'summary': summary,
  368. 'trade_no': paypal_transaction_id,
  369. 'resource': json_agreement_str,
  370. 'created_time': int(time.time()),
  371. }
  372. if event_type != 'PAYMENT.SALE.COMPLETED':
  373. PAY_LOGGER.info('----event_type异常:{}----'.format(event_type))
  374. if resource_type == 'sale' and paypal_body.get('state') == 'completed':
  375. paypalrestsdk.configure(PAYPAL_CRD)
  376. response = paypalrestsdk.WebhookEvent.verify(
  377. transmission_id, transmission_time, PAYPAL_WEB_HOOK_ID, json_agreement_str, cert_url,
  378. transmission_sig, auth_algo)
  379. if not response:
  380. PAY_LOGGER.info('PayPal周期扣款失败---签名验证失败')
  381. return HttpResponse('Fail', status=500)
  382. else:
  383. PAY_LOGGER.info('PayPal周期扣款失败,付款状态有误,resource_type:{},state:{}----'.
  384. format(resource_type, paypal_body.get('state')))
  385. return HttpResponse('Fail', status=500)
  386. nowTime = int(time.time())
  387. if not agreement_id:
  388. # 记录钩子日志
  389. PaypalWebHookEvent.objects.create(**PaypalWebHookEventInsert)
  390. # 普通支付,更新paypal交易id
  391. paymentID = paypal_body.get('parent_payment')
  392. if paymentID and paypal_transaction_id:
  393. # 查询客户地区信息,地区跟服务器配置不匹配,返回500
  394. order_qs = Order_Model.objects.filter(paymentID=paymentID).values('UID', 'userID__region_country',
  395. 'create_vod', 'orderID',
  396. 'channel', 'rank__is_ai',
  397. 'rank__expire',
  398. 'rank__bucket__id',
  399. 'isSelectDiscounts',
  400. 'userID__username',
  401. 'userID__userID', 'coupon_id')
  402. if not order_qs.exists():
  403. PAY_LOGGER.info('PayPal周期扣款失败---根据paymentID查询订单数据不存在')
  404. return HttpResponse('Fail', status=500)
  405. # 判断用户地区是否跟服务器地区匹配
  406. uid = order_qs[0]['UID']
  407. country_id = order_qs[0]['userID__region_country']
  408. if not self.config_match_region(uid, country_id):
  409. return HttpResponse('Fail', status=500)
  410. if order_qs[0]['create_vod']:
  411. order_qs.update(status=1, trade_no=paypal_transaction_id, updTime=nowTime, fee=fee)
  412. else:
  413. # 是否有促销
  414. expire = order_qs[0]['rank__expire']
  415. isSelectDiscounts = order_qs[0]['isSelectDiscounts']
  416. is_ai = order_qs[0]['rank__is_ai']
  417. channel = order_qs[0]['channel']
  418. bucketId = order_qs[0]['rank__bucket__id']
  419. userid = order_qs[0]['userID__userID']
  420. username = order_qs[0]['userID__username']
  421. order_id = order_qs[0]['orderID']
  422. coupon_id = order_qs[0]['coupon_id']
  423. promotion = PromotionRuleModel.objects.filter(status=1, startTime__lte=nowTime,
  424. endTime__gte=nowTime).values('id', 'ruleConfig')
  425. if promotion.exists():
  426. promotion_rule_id = promotion[0]['id']
  427. expire = expire * 2
  428. else:
  429. promotion_rule_id = ''
  430. if isSelectDiscounts:
  431. expire = expire * 2
  432. uid_bucket_id = self.create_vod(uid, expire, is_ai, nowTime, channel, bucketId, order_id,
  433. userid, username)
  434. order_qs.update(status=1, trade_no=paypal_transaction_id, updTime=nowTime,
  435. uid_bucket_id=uid_bucket_id, create_vod=1, fee=fee,
  436. promotion_rule_id=promotion_rule_id, agreement_id=agreement_id)
  437. # 核销coupon
  438. if coupon_id:
  439. CouponModel.objects.filter(id=coupon_id).update(use_status=2, update_time=nowTime)
  440. PAY_LOGGER.info('PayPal周期扣款成功---更新交易id:{}'.format(paypal_transaction_id))
  441. return HttpResponse('success')
  442. else:
  443. PAY_LOGGER.info('PayPal周期扣款失败---paymentID:{}或paypal_transaction_id:{}为空'.
  444. format(paymentID, paypal_transaction_id))
  445. return HttpResponse('fail', status=500)
  446. billing_agreement = paypalrestsdk.BillingAgreement.find(agreement_id)
  447. PAY_LOGGER.info('billing_agreement:{}'.format(billing_agreement))
  448. # 记录钩子日志
  449. PaypalWebHookEventInsert['agreement_desc'] = repr(billing_agreement)
  450. PaypalWebHookEventInsert['agreement_id'] = agreement_id
  451. PaypalWebHookEventInsert['orderID'] = billing_agreement.description
  452. paypal_webhook_event_qs = PaypalWebHookEvent.objects.create(**PaypalWebHookEventInsert)
  453. # 查询订单数据
  454. order_id = billing_agreement.description
  455. order_qs = Order_Model.objects.filter(orderID=order_id).values('UID', 'channel', 'commodity_code', 'rank',
  456. 'isSelectDiscounts', 'plan_id', 'desc',
  457. 'payType', 'currency', 'addTime',
  458. 'commodity_type', 'updTime', 'order_type',
  459. 'userID__userID', 'uid_bucket_id',
  460. 'userID__username', 'userID__region_country',
  461. 'create_vod', 'coupon_id')
  462. if not order_qs.exists():
  463. PAY_LOGGER.info('PayPal周期扣款失败---根据order_id查询订单数据不存在')
  464. return HttpResponse('fail', status=500)
  465. # 判断用户地区是否跟服务器地区匹配
  466. uid = order_qs[0]['UID']
  467. country_id = order_qs[0]['userID__region_country']
  468. if not self.config_match_region(uid, country_id):
  469. return HttpResponse('Fail', status=500)
  470. UID = order_qs[0]['UID']
  471. isSelectDiscounts = order_qs[0]['isSelectDiscounts']
  472. coupon_id = order_qs[0]['coupon_id']
  473. userid = order_qs[0]['userID__userID']
  474. username = order_qs[0]['userID__username']
  475. channel = order_qs[0]['channel']
  476. rank = order_qs[0]['rank']
  477. store_meal_qs = Store_Meal.objects.filter(id=rank).values("bucket_id", "expire", "is_ai")
  478. if not store_meal_qs.exists():
  479. PAY_LOGGER.info('{} PayPal周期扣款失败---套餐数据不存在'.format(UID))
  480. return HttpResponse('fail', status=500)
  481. expire = store_meal_qs[0]['expire']
  482. is_ai = store_meal_qs[0]['is_ai']
  483. bucketId = store_meal_qs[0]['bucket_id']
  484. # PayPal周期扣款首次扣款
  485. if billing_agreement.agreement_details.cycles_completed == '0':
  486. if order_qs[0]['create_vod']:
  487. order_qs.update(status=1, trade_no=paypal_transaction_id, updTime=nowTime, fee=fee)
  488. else:
  489. # 是否有促销
  490. promotion = PromotionRuleModel.objects.filter(status=1, startTime__lte=nowTime,
  491. endTime__gte=nowTime).values('id', 'ruleConfig')
  492. if promotion.exists():
  493. promotion_rule_id = promotion[0]['id']
  494. expire = expire * 2
  495. else:
  496. promotion_rule_id = ''
  497. if isSelectDiscounts:
  498. expire = expire * 2
  499. uid_bucket_id = self.create_vod(UID, expire, is_ai, nowTime, channel, bucketId, order_id,
  500. userid, username)
  501. order_qs.update(status=1, trade_no=paypal_transaction_id, updTime=nowTime,
  502. uid_bucket_id=uid_bucket_id, create_vod=1, fee=fee,
  503. promotion_rule_id=promotion_rule_id, agreement_id=agreement_id)
  504. # 核销coupon
  505. if coupon_id:
  506. CouponModel.objects.filter(id=coupon_id).update(use_status=2, update_time=nowTime)
  507. PAY_LOGGER.info('{} PayPal周期扣款首次扣款成功'.format(UID))
  508. return HttpResponse('success')
  509. if order_qs[0]['addTime'] + 9200 > nowTime: # 避免续费订单重复支付
  510. PAY_LOGGER.info('{} PayPal周期扣款失败---续费订单已创建'.format(UID))
  511. return HttpResponse('success')
  512. desc = order_qs[0]['desc']
  513. pay_type = order_qs[0]['payType']
  514. commodity_code = order_qs[0]['commodity_code']
  515. commodity_type = order_qs[0]['commodity_type']
  516. plan_id = order_qs[0]['plan_id']
  517. order_type = order_qs[0]['order_type']
  518. endTime = CommonService.calcMonthLater(expire)
  519. use_flag = True
  520. orderID = CommonService.createOrderID()
  521. ubqs = UID_Bucket.objects.filter(uid=UID).values("id", "endTime", "use_status")
  522. with transaction.atomic():
  523. if ubqs.exists():
  524. ubq = ubqs[0]
  525. uid_bucket_id = ubq['id']
  526. if ubq['use_status'] == 1 and ubq['endTime'] > nowTime: # 套餐使用中并且未过期
  527. Unused_Uid_Meal.objects.create(uid=UID, channel=channel, addTime=nowTime, is_ai=is_ai,
  528. order_id=orderID, expire=expire, bucket_id=bucketId)
  529. update_status = UID_Bucket.objects.filter(id=ubq['id']).update(has_unused=1)
  530. use_flag = False
  531. else: # 已过期或者不相同的套餐加入未使用的关联套餐表
  532. update_status = UID_Bucket.objects.filter(id=uid_bucket_id).update(uid=UID, channel=channel,
  533. bucket_id=bucketId,
  534. endTime=endTime,
  535. updateTime=nowTime,
  536. use_status=1,
  537. orderId=orderID)
  538. else:
  539. ub_cqs = UID_Bucket.objects.create(uid=UID, channel=channel, bucket_id=bucketId, endTime=endTime,
  540. addTime=nowTime, updateTime=nowTime, use_status=1,
  541. orderId=orderID)
  542. uid_bucket_id = ub_cqs.id
  543. update_status = True
  544. PAY_LOGGER.info(
  545. 'uid:{},uid_bucket_id:{},update_status:{},order_id:{}'.format(UID, uid_bucket_id, update_status,
  546. orderID))
  547. dvq = Device_Info.objects.filter(UID=UID, vodPrimaryUserID='', vodPrimaryMaster='')
  548. if dvq.exists():
  549. dvq_set_update_dict = {
  550. 'vodPrimaryUserID': userid,
  551. 'vodPrimaryMaster': username
  552. }
  553. dvq.update(**dvq_set_update_dict)
  554. store_meal_qs = Store_Meal.objects.filter(id=rank, lang__lang='cn', is_show=0).values('lang__title',
  555. 'lang__content')
  556. if store_meal_qs.exists():
  557. store_meal_name = store_meal_qs[0]['lang__title'] + '-' + store_meal_qs[0]['lang__content']
  558. else:
  559. store_meal_name = '未知套餐'
  560. Order_Model.objects.create(orderID=orderID, UID=UID, channel=channel, userID_id=userid,
  561. desc=desc, payType=pay_type, payTime=nowTime,
  562. price=amount.get('total'),
  563. currency=order_qs[0]['currency'], addTime=nowTime,
  564. updTime=nowTime, order_type=order_type,
  565. pay_url='', isSelectDiscounts=0, fee=fee,
  566. commodity_code=commodity_code, create_vod=1,
  567. commodity_type=commodity_type, rank_id=rank, paymentID='',
  568. coupon_id='', uid_bucket_id=uid_bucket_id, status=1,
  569. agreement_id=agreement_id, store_meal_name=store_meal_name,
  570. plan_id=plan_id, ai_rank_id=1, trade_no=paypal_transaction_id)
  571. # 开通AI服务
  572. if is_ai and use_flag:
  573. ai_service = AiService.objects.filter(uid=uid, channel=channel)
  574. if ai_service.exists(): # 有正在使用的套餐,套餐结束时间保存为套餐有效期
  575. ai_service.update(updTime=nowTime, use_status=1, orders_id=orderID, endTime=endTime)
  576. else:
  577. AiService.objects.create(uid=uid, channel=channel, detect_status=1, addTime=nowTime,
  578. updTime=nowTime, endTime=endTime, use_status=1, orders_id=orderID)
  579. # 如果存在序列号,消息提示用序列号
  580. device_name = CommonService.query_serial_with_uid(uid=UID)
  581. datetime = time.strftime("%Y-%m-%d", time.localtime())
  582. sys_msg_text_list = [
  583. '温馨提示:尊敬的客户,您的' + device_name + '设备在' + datetime + '已成功续订云存套餐',
  584. 'Dear customer,you already subscribed the cloud storage package successfully for device ' + device_name + ' on ' + time.strftime(
  585. "%b %dth,%Y", time.localtime())]
  586. if pay_type == 1:
  587. lang = 'en'
  588. else:
  589. lang = 'cn'
  590. CloudStorage.CloudStorageView().do_vod_msg_notice(UID, channel, userid, lang,
  591. sys_msg_text_list, 'SMS_219738485')
  592. # 更新agreement
  593. billing_agreement_update_attributes = [
  594. {
  595. "op": "replace",
  596. "path": "/",
  597. "value": {
  598. "description": orderID,
  599. }
  600. }
  601. ]
  602. update_status = billing_agreement.replace(billing_agreement_update_attributes)
  603. # 记录新订单号和更新状态
  604. PaypalWebHookEvent.objects.filter(id=paypal_webhook_event_qs.id).update(newOrderID=orderID,
  605. update_status=update_status)
  606. PAY_LOGGER.info('{} PayPal周期扣款成功'.format(UID))
  607. return HttpResponse('success')
  608. except Exception as e:
  609. PAY_LOGGER.info('PayPal周期扣款异常: errLine:{}, errMsg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  610. return HttpResponse('fail', status=500)
  611. @staticmethod
  612. def config_match_region(uid, country_id):
  613. """
  614. 判断用户地区是否跟服务器地区匹配
  615. @param uid: uid
  616. @param country_id: 国家表id
  617. @return: bool
  618. """
  619. country_qs = CountryModel.objects.filter(id=country_id).values('region_id')
  620. # 不确定用户地区信息,默认美洲
  621. if not country_qs.exists():
  622. if CONFIG_INFO == CONFIG_EUR:
  623. PAY_LOGGER.info('PayPal周期扣款失败---不确定地区的用户请求欧洲服,uid:{},country_id:{}'.format(uid, country_id))
  624. return False
  625. else:
  626. return True
  627. region_id = country_qs[0]['region_id']
  628. PAY_LOGGER.info('uid{}的用户地区信息: country_id:{}, region_id:{}'.format(uid, country_id, region_id))
  629. if (CONFIG_INFO == CONFIG_US and region_id == 4) or (CONFIG_INFO == CONFIG_EUR and region_id != 4):
  630. PAY_LOGGER.info('PayPal周期扣款失败---服务器跟用户地区不匹配')
  631. return False
  632. return True
  633. def do_subscription_break_notify(self, request_dict, request, response):
  634. logger = logging.getLogger('pay')
  635. logger.info('--------进入订阅失败,付款失败,暂停--------')
  636. json_agreement_str = request.body.decode("utf-8")
  637. json_obj = json.loads(json_agreement_str)
  638. header = request.META
  639. paypal_body = json_obj.get('resource')
  640. logger.info('----主体信息----')
  641. logger.info(json_agreement_str)
  642. logger.info('----进入订阅失败头部信息----')
  643. logger.info(header)
  644. try:
  645. transmission_id = header.get('HTTP_PAYPAL_TRANSMISSION_ID', None)
  646. transmission_time = header.get('HTTP_PAYPAL_TRANSMISSION_TIME', None)
  647. cert_url = header.get('HTTP_PAYPAL_CERT_URL', None)
  648. transmission_sig = header.get('HTTP_PAYPAL_TRANSMISSION_SIG', None)
  649. auth_algo = header.get('HTTP_PAYPAL_AUTH_ALGO', None)
  650. event_type = json_obj.get('event_type')
  651. summary = json_obj.get('summary')
  652. resource_type = json_obj.get('resource_type')
  653. paypal_transaction_id = paypal_body.get('id')
  654. amount = paypal_body.get('amount')
  655. # self.get_plan_desc('P-4CG284532S612303METMEINY')
  656. paypalrestsdk.configure(PAYPAL_CRD)
  657. response = paypalrestsdk.WebhookEvent.verify(
  658. transmission_id, transmission_time, PAYPAL_WEB_HOOK_ID_TWO, json_agreement_str, cert_url,
  659. transmission_sig, auth_algo)
  660. logger.info('----验证签名----')
  661. logger.info(response)
  662. if not response:
  663. return HttpResponse('Fail', status=500)
  664. event_type_code = 0
  665. billing_agreement_id = ''
  666. if event_type == 'PAYMENT.SALE.COMPLETED':
  667. event_type_code = 1
  668. billing_agreement_id = paypal_body.get('billing_agreement_id')
  669. elif event_type == 'PAYMENT.SALE.REVERSED':
  670. billing_agreement_id = paypal_body.get('billing_agreement_id')
  671. event_type_code = 2
  672. elif event_type == 'BILLING.SUBSCRIPTION.CANCELLED':
  673. billing_agreement_id = paypal_body.get('id')
  674. event_type_code = 3
  675. elif event_type == 'BILLING.SUBSCRIPTION.SUSPENDED':
  676. billing_agreement_id = paypal_body.get('id')
  677. event_type_code = 4
  678. elif event_type == 'BILLING.SUBSCRIPTION.PAYMENT.FAILED':
  679. billing_agreement_id = paypal_body.get('id')
  680. event_type_code = 5
  681. elif event_type == 'PAYMENT.SALE.REFUNDED':
  682. billing_agreement_id = paypal_body.get('billing_agreement_id')
  683. event_type_code = 6
  684. PaypalWebHookEventInsert = {
  685. 'webhook_event_id': json_obj.get('id'),
  686. 'resource_type': resource_type,
  687. 'event_type': event_type_code,
  688. 'summary': summary,
  689. 'trade_no': paypal_transaction_id,
  690. 'resource': json_agreement_str,
  691. 'created_time': int(time.time()),
  692. }
  693. if not billing_agreement_id:
  694. # 记录钩子日志
  695. PaypalWebHookEvent.objects.create(**PaypalWebHookEventInsert)
  696. return HttpResponse('success')
  697. billing_agreement = paypalrestsdk.BillingAgreement.find(billing_agreement_id)
  698. # 记录钩子日志
  699. PaypalWebHookEventInsert['agreement_desc'] = repr(billing_agreement)
  700. PaypalWebHookEventInsert['agreement_id'] = billing_agreement_id
  701. PaypalWebHookEventInsert['orderID'] = billing_agreement.description
  702. PaypalWebHookEvent.objects.create(**PaypalWebHookEventInsert)
  703. return HttpResponse('success')
  704. except Exception as e:
  705. print(e)
  706. logger.info('----进入订阅失败----')
  707. logger.info('do_paypal_webhook_notify支付失败:----')
  708. logger.info("错误行数:{errLine}".format(errLine=e.__traceback__.tb_lineno))
  709. logger.info(repr(e))
  710. return HttpResponse('fail', status=500)
  711. def get_plan_desc(self, plan_id):
  712. paypalrestsdk.configure(PAYPAL_CRD)
  713. billing_plan = paypalrestsdk.BillingPlan.find(plan_id)
  714. print("Got Billing Plan Details for Billing Plan[%s]" % (billing_plan.id))
  715. exit()
  716. class payCycle(View):
  717. def get(self, request, *args, **kwargs):
  718. request.encoding = 'utf-8'
  719. operation = kwargs.get('operation')
  720. return self.validation(request.GET, request, operation)
  721. def post(self, request, *args, **kwargs):
  722. request.encoding = 'utf-8'
  723. operation = kwargs.get('operation')
  724. return self.validation(request.POST, request, operation)
  725. def validation(self, request_dict, request, operation):
  726. response = ResponseObject()
  727. token = request_dict.get('token', None)
  728. # 设备主键uid
  729. tko = TokenObject(token)
  730. response.lang = tko.lang
  731. if tko.code != 0:
  732. return response.json(tko.code)
  733. userID = tko.userID
  734. if operation is None:
  735. return response.json(444, 'error path')
  736. elif operation == 'queryPayCycle': # paypal成功订阅回调
  737. return self.do_query_pay_cycle(request_dict, userID, response)
  738. elif operation == 'cancelPayCycle': # 取消自动续费
  739. return self.do_cancel_pay_cycle(request_dict, userID, response)
  740. def do_query_pay_cycle(self, request_dict, userID, response):
  741. lang = request_dict.get('lang', 'en')
  742. uid = request_dict.get('uid', None)
  743. orderObject = Order_Model.objects.filter(userID=userID, status=1, rank__lang__lang=lang).annotate(
  744. rank__title=F('rank__lang__title'), rank__content=F('rank__lang__content'))
  745. if uid:
  746. orderObject = orderObject.filter(UID=uid)
  747. orderObject = orderObject.filter(~Q(agreement_id=''))
  748. if not orderObject.exists():
  749. return response.json(0, {'data': [], 'count': 0})
  750. orderQuery = orderObject.values("orderID", "UID", "channel", "desc", "price", "currency",
  751. "addTime",
  752. "updTime", "paypal", "rank__day", "payType",
  753. "rank__price", "status",
  754. "rank__lang__content", "rank__lang__title", "rank__currency",
  755. "rank_id", "rank__expire", "agreement_id").order_by('addTime')
  756. new_data = []
  757. values = []
  758. for d in orderQuery:
  759. if d['agreement_id'] not in values:
  760. new_data.append(d)
  761. values.append(d['agreement_id'])
  762. count = len(new_data)
  763. return response.json(0, {'data': new_data, 'count': count})
  764. def do_cancel_pay_cycle(self, request_dict, userID, response):
  765. orderID = request_dict.get('orderID', 'None')
  766. orderObject = Order_Model.objects.filter(orderID=orderID)
  767. orderObject = orderObject.filter(~Q(agreement_id='')).values("agreement_id")
  768. if not orderObject.exists():
  769. return response.json(800)
  770. paypalrestsdk.configure(PAYPAL_CRD)
  771. BILLING_AGREEMENT_ID = orderObject[0]['agreement_id']
  772. try:
  773. billing_agreement = paypalrestsdk.BillingAgreement.find(BILLING_AGREEMENT_ID)
  774. if billing_agreement.state != 'Active':
  775. Order_Model.objects.filter(agreement_id=BILLING_AGREEMENT_ID).update(agreement_id='')
  776. return response.json(0)
  777. cancel_note = {"note": "Canceling the agreement"}
  778. if billing_agreement.cancel(cancel_note):
  779. Order_Model.objects.filter(agreement_id=BILLING_AGREEMENT_ID).update(agreement_id='')
  780. return response.json(0)
  781. else:
  782. return response.json(10052)
  783. except Exception as e:
  784. return response.json(10052)