PaymentCycle.py 49 KB

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