PaymentCycle.py 50 KB

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