PaymentCycle.py 34 KB

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