PaymentCycle.py 49 KB

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