AiController.py 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784
  1. import logging
  2. import time
  3. from urllib.parse import quote, parse_qs, unquote
  4. import paypalrestsdk
  5. from django.db import transaction
  6. from django.db.models import Q, F, Sum
  7. from django.http import HttpResponseRedirect, HttpResponse
  8. from django.views.generic.base import View
  9. from Ansjer.config import PAYPAL_CRD, SERVER_DOMAIN_SSL, DETECT_PUSH_DOMAINS
  10. from Model.models import Device_Info, Order_Model, ExperienceAiModel, Pay_Type, CDKcontextModel, UidPushModel, \
  11. AiStoreMeal, AiService, UidSetModel
  12. from Object.AliPayObject import AliPayObject
  13. from Object.ETkObject import ETkObject
  14. from Object.RedisObject import RedisObject
  15. from Object.ResponseObject import ResponseObject
  16. from Object.TokenObject import TokenObject
  17. from Object.WechatPayObject import WechatPayObject
  18. from Service.CommonService import CommonService
  19. class AiView(View):
  20. """
  21. AI业务功能
  22. AI套餐,开关,消息列表
  23. """
  24. def get(self, request, *args, **kwargs):
  25. request.encoding = 'utf-8'
  26. operation = kwargs.get('operation')
  27. return self.validation(request.GET, request, operation)
  28. def post(self, request, *args, **kwargs):
  29. request.encoding = 'utf-8'
  30. operation = kwargs.get('operation')
  31. return self.validation(request.POST, request, operation)
  32. def validation(self, request_dict, request, operation):
  33. response = ResponseObject()
  34. if operation is None:
  35. return response.json(444, 'error path')
  36. # 支付回调接口
  37. elif operation == 'doPayPalCallBack': # paypal支付回调
  38. return self.do_pay_by_paypal_callback(request_dict, response)
  39. elif operation == 'doAlipayCallBack': # 支付宝支付回调
  40. return self.do_alipay_callback(request_dict, response)
  41. elif operation == 'doWechatCallBack': # 微信支付回调
  42. return self.do_wechat_callback(request, response)
  43. else:
  44. token = request_dict.get('token', None)
  45. tko = TokenObject(token)
  46. response.lang = tko.lang
  47. if tko.code != 0:
  48. return response.json(tko.code)
  49. user_id = tko.userID
  50. # 套餐相关接口
  51. if operation == 'commoditylist': # 查询套餐列表
  52. return self.do_commodity_list(request_dict, response)
  53. elif operation == 'experienceOrder': # 体验套餐
  54. return self.experience_order(request_dict, user_id, response)
  55. elif operation == 'createpayorder': # 创建支付订单
  56. return self.do_create_pay_order(request_dict, request, user_id, response)
  57. elif operation == 'queryorderlist': # 查询订单列表
  58. return self.query_order_list(request_dict, user_id, response)
  59. elif operation == 'getUsingPackage': # 获取当前使用套餐
  60. return self.get_using_package(request_dict, response)
  61. # 开关相关接口
  62. elif operation == 'getAiStatus': # 获取开关状态
  63. return self.get_ai_status(request_dict, response)
  64. elif operation == 'changeaistatus': # 修改开关状态
  65. return self.do_change_ai_status(request_dict, user_id, response)
  66. else:
  67. return response.json(414)
  68. @staticmethod
  69. def do_commodity_list(request_dict, response):
  70. """
  71. 查询套餐列表
  72. @param request_dict: 请求数据
  73. @request_dict uid: uid
  74. @request_dict lang: 语言
  75. @param response: 响应
  76. @return: response
  77. """
  78. uid = request_dict.get('uid', None)
  79. lang = request_dict.get('lang', 'en')
  80. try:
  81. # DVR/NVR设备暂不返回套餐列表
  82. device_info_qs = Device_Info.objects.filter(Q(UID=uid), Q(Type__lte=4) | Q(Type=10001))
  83. if device_info_qs.exists():
  84. return response.json(0)
  85. # 没体验过的设备只返回体验套餐,体验过的不返回体验套餐
  86. exc_ai_qs = ExperienceAiModel.objects.filter(uid=uid, experience_type=0)
  87. if exc_ai_qs.exists():
  88. ai_meal_qs = AiStoreMeal.objects.filter(~Q(pay_type=10))
  89. else:
  90. ai_meal_qs = AiStoreMeal.objects.filter(pay_type=10)
  91. # 查询套餐数据
  92. ai_meal_qs = ai_meal_qs.filter(is_show=1, lang__lang=lang). \
  93. annotate(ai_meal_id=F('id'), title=F('lang__title'), content=F('lang__content')). \
  94. values('ai_meal_id', 'title', 'content', 'price', 'effective_day', 'currency', 'virtual_price',
  95. 'symbol', 'is_beta')
  96. if not ai_meal_qs.exists():
  97. return response.json(0)
  98. # 查询每种套餐的所有支付方式
  99. ai_meal_list = list(ai_meal_qs)
  100. for ai_meal in ai_meal_list:
  101. pay_type_qs = Pay_Type.objects.filter(aistoremeal=ai_meal['ai_meal_id']).values('id', 'payment')
  102. ai_meal['pay_type'] = list(pay_type_qs)
  103. result = {
  104. 'meals': ai_meal_list,
  105. }
  106. return response.json(0, result)
  107. except Exception as e:
  108. return response.json(500, repr(e))
  109. @staticmethod
  110. def experience_order(request_dict, user_id, response):
  111. """
  112. 体验套餐
  113. @param request_dict: 请求数据
  114. @request_dict uid: uid
  115. @request_dict channel: 通道
  116. @request_dict pay_type: 支付类型
  117. @request_dict rank: 套餐id
  118. @request_dict cdk: 兑换码
  119. @request_dict lang: 语言
  120. @param user_id: 用户id
  121. @param response: 响应
  122. @return: response
  123. """
  124. logger = logging.getLogger('info')
  125. uid = request_dict.get('uid', None)
  126. channel = request_dict.get('channel', None)
  127. pay_type = int(request_dict.get('pay_type', 10))
  128. rank = request_dict.get('rank', None)
  129. cdk = request_dict.get('cdk', None)
  130. lang = request_dict.get('lang', 'en')
  131. # 使用redis设置唯一key加锁
  132. redisObj = RedisObject()
  133. redis_key = uid + 'do_experience_ai_order'
  134. isLock = redisObj.CONN.setnx(redis_key, 1)
  135. redisObj.CONN.expire(redis_key, 60)
  136. if not isLock:
  137. return response.json(5)
  138. try:
  139. if pay_type == 10: # 判断是否已体验过套餐
  140. exc_ai_qs = ExperienceAiModel.objects.filter(uid=uid, experience_type=0)
  141. if exc_ai_qs.exists():
  142. return response.json(5)
  143. if cdk is not None and pay_type == 11: # 兑换码体验
  144. cdk_qs = CDKcontextModel.objects.filter(cdk=cdk).values('is_activate', 'rank__id',
  145. 'rank__commodity_code')
  146. if not cdk_qs.exists():
  147. return response.json(10040)
  148. if cdk_qs[0]['is_activate'] == 1:
  149. return response.json(10039)
  150. rank = cdk_qs[0]['rank__id']
  151. if not all([uid, channel, rank]):
  152. redisObj.del_data(key=redis_key)
  153. return response.json(444)
  154. # 判断是否为主用户操作
  155. device_info_qs = Device_Info.objects.filter(Q(UID=uid) & ~Q(vodPrimaryUserID='')).values('vodPrimaryUserID')
  156. if device_info_qs.exists():
  157. if device_info_qs[0]['vodPrimaryUserID'] != user_id:
  158. if pay_type == 10:
  159. return response.json(10035)
  160. if pay_type == 11:
  161. return response.json(10036)
  162. dv_qs = Device_Info.objects.filter(userID_id=user_id, UID=uid, isShare=False, isExist=1)
  163. if not dv_qs.exists():
  164. return response.json(12)
  165. orderID = CommonService.createOrderID()
  166. nowTime = int(time.time())
  167. ai_store_meal_qs = AiStoreMeal.objects.filter(id=rank, lang__lang=lang, is_show=1). \
  168. values('lang__content', 'price', 'currency', 'effective_day')
  169. if not ai_store_meal_qs.exists():
  170. return response.json(173)
  171. effective_day = ai_store_meal_qs[0]['effective_day']
  172. endTime = int(time.time()) + effective_day * 24 * 60 * 60 # 套餐结束时间
  173. # 查询中文套餐名
  174. ai_cn_store_meal_qs = AiStoreMeal.objects.filter(id=rank, lang__lang='cn', is_show=1). \
  175. values('lang__content', 'lang__title')
  176. if ai_cn_store_meal_qs.exists():
  177. store_meal_name = ai_cn_store_meal_qs[0]['lang__title'] + '-' + ai_cn_store_meal_qs[0]['lang__content']
  178. else:
  179. store_meal_name = '未知套餐'
  180. with transaction.atomic():
  181. # 订单表创建数据
  182. Order_Model.objects.create(orderID=orderID, UID=uid, channel=channel, userID_id=user_id,
  183. desc=ai_store_meal_qs[0]['lang__content'], payType=pay_type, payTime=nowTime,
  184. price=ai_store_meal_qs[0]['price'], currency=ai_store_meal_qs[0]['currency'],
  185. addTime=nowTime, updTime=nowTime, pay_url='AI体验',
  186. store_meal_name=store_meal_name, order_type=1,
  187. rank_id=1, ai_rank_id=rank, status=1)
  188. # ai服务表创建数据
  189. AiService.objects.create(uid=uid, channel=channel, orders_id=orderID, detect_status=1, endTime=endTime,
  190. addTime=nowTime, updTime=nowTime, use_status=1)
  191. logger.info('{}成功开通AI体验,结束时间{}'.format(uid, endTime))
  192. if pay_type == 10:
  193. ExperienceAiModel.objects.create(
  194. experience_type=0,
  195. uid=uid,
  196. do_time=nowTime
  197. )
  198. elif pay_type == 11:
  199. CDKcontextModel.objects.filter(cdk=cdk).update(is_activate=1, order=orderID)
  200. redisObj.del_data(key=redis_key)
  201. pay_ok_url = "{}cloudstorage/payOK?paytype={}&lang={}".format(SERVER_DOMAIN_SSL, pay_type, lang)
  202. return response.json(0, pay_ok_url)
  203. except Exception as e:
  204. print(e)
  205. redisObj.del_data(key=redis_key)
  206. return response.json(474)
  207. def do_create_pay_order(self, request_dict, request, user_id, response):
  208. """
  209. 创建支付订单
  210. @param request_dict: 请求数据
  211. @param request: 请求体
  212. @request_dict uid: uid
  213. @request_dict channel: 通道
  214. @request_dict pay_type: 支付类型
  215. @request_dict rank: 套餐id
  216. @request_dict lang: 语言
  217. @param user_id: 用户id
  218. @param response: 响应
  219. @return: response
  220. """
  221. uid = request_dict.get('uid', None)
  222. channel = request_dict.get('channel', None)
  223. pay_type = int(request_dict.get('pay_type', 1))
  224. rank = request_dict.get('rank', None)
  225. lang = request_dict.get('lang', 'en')
  226. if not all([uid, channel, rank]):
  227. return response.json(444)
  228. try:
  229. # 获取ai套餐数据
  230. ai_sm_qs = AiStoreMeal.objects.filter(id=rank, pay_type=pay_type, is_show=1, lang__lang=lang). \
  231. values('lang__title', 'lang__content', 'currency', 'price')
  232. if not ai_sm_qs.exists():
  233. return response.json(173)
  234. title = ai_sm_qs[0]['lang__title']
  235. content = ai_sm_qs[0]['lang__content']
  236. currency = ai_sm_qs[0]['currency']
  237. price = ai_sm_qs[0]['price']
  238. # 查询中文套餐名
  239. ai_store_meal_qs = AiStoreMeal.objects.filter(id=rank, is_show=1, lang__lang='cn'). \
  240. values('lang__title', 'lang__content')
  241. if ai_store_meal_qs.exists():
  242. store_meal_name = ai_store_meal_qs[0]['lang__title'] + '-' + ai_store_meal_qs[0]['lang__content']
  243. else:
  244. store_meal_name = '未知套餐'
  245. nowTime = int(time.time())
  246. orderID = CommonService.createOrderID()
  247. price = round(float(price), 2)
  248. order_dict = {
  249. 'orderID': orderID,
  250. 'UID': uid,
  251. 'channel': channel,
  252. 'userID_id': user_id,
  253. 'desc': content,
  254. 'payType': pay_type,
  255. 'payTime': nowTime,
  256. 'price': price,
  257. 'currency': currency,
  258. 'addTime': nowTime,
  259. 'updTime': nowTime,
  260. 'ai_rank_id': rank,
  261. 'rank_id': 1,
  262. 'order_type': 1,
  263. 'store_meal_name': store_meal_name
  264. }
  265. # 创建订单数据和返回支付回调链接
  266. if pay_type == 1: # PayPal支付
  267. order_dict['paymentID'], order_dict['pay_url'] = self.create_paypal_payment(lang, orderID, price,
  268. currency, content, response)
  269. res_data = {'redirectUrl': order_dict['pay_url'], 'orderID': orderID}
  270. elif pay_type == 2: # 支付宝
  271. order_dict['pay_url'] = self.create_alipay_payment(lang, orderID, price, title, content, response)
  272. res_data = {'redirectUrl': order_dict['pay_url'], 'orderID': orderID}
  273. elif pay_type == 3: # 微信支付
  274. ip = CommonService.get_ip_address(request)
  275. order_dict['pay_url'], sign_params = self.create_wechat_payment(lang, orderID, price, ip, content,
  276. response)
  277. res_data = {'redirectUrl': order_dict['pay_url'], 'orderID': orderID, 'result': sign_params}
  278. else:
  279. return response.json(444, {'param': 'pay_type'})
  280. Order_Model.objects.create(**order_dict)
  281. return response.json(0, res_data)
  282. except Exception as e:
  283. return response.json(500, repr(e))
  284. @staticmethod
  285. def query_order_list(request_dict, user_id, response):
  286. """
  287. 查询订单列表
  288. @param request_dict: 请求数据
  289. @param user_id: 用户id
  290. @request_dict page: 页数
  291. @request_dict line: 条数
  292. @request_dict uid: uid
  293. @request_dict lang: 语言
  294. @param response: 响应
  295. @return: response
  296. """
  297. page = request_dict.get('page', None)
  298. line = request_dict.get('line', None)
  299. uid = request_dict.get('uid', None)
  300. lang = request_dict.get('lang', 'en')
  301. if not all([page, line]):
  302. return response.json(444, 'page,line')
  303. page, line = int(page), int(line)
  304. try:
  305. order_qs = Order_Model.objects.filter(userID_id=user_id, status=1, order_type=1, ai_rank__lang__lang=lang)
  306. if uid: # 查询指定设备订单
  307. order_qs.filter(UID=uid)
  308. if not order_qs.exists():
  309. return response.json(173)
  310. count = order_qs.count()
  311. order_qs = order_qs.annotate(rank__title=F('ai_rank__lang__title'),
  312. rank__content=F('ai_rank__lang__content'),
  313. rank__day=F('ai_rank__effective_day'), rank__price=F('ai_rank__price'),
  314. rank__expire=F('ai_rank__effective_day'), rank__id=F('ai_rank_id'),
  315. rank__currency=F('ai_rank__currency'))
  316. order_qs = order_qs[(page - 1) * line:page * line].values('orderID', 'UID', 'channel', 'desc', 'price',
  317. 'currency', 'addTime', 'updTime', 'paypal',
  318. 'rank__day', 'payType', 'rank__price', 'status',
  319. 'rank__content', 'rank__title', 'rank__currency',
  320. 'rank__expire', 'ai_rank_id')
  321. order_list = list(order_qs)
  322. data = []
  323. now_time = int(time.time())
  324. uid_list = [order['UID'] for order in order_list]
  325. device_info_qs = Device_Info.objects.filter(userID_id=user_id, UID__in=uid_list).values('id', 'UID', 'Type')
  326. for order in order_list:
  327. if order['status'] == 0:
  328. if order['addTime'] + 3600 < now_time:
  329. order['status'] = 3
  330. for did in device_info_qs:
  331. if order['UID'] == did['UID']:
  332. order['did'] = did['id']
  333. order['Type'] = did['Type']
  334. data.append(order)
  335. return response.json(0, {'data': data, 'count': count})
  336. except Exception as e:
  337. return response.json(500, repr(e))
  338. @staticmethod
  339. def get_using_package(request_dict, response):
  340. """
  341. 获取当前使用套餐
  342. @param request_dict: 请求数据
  343. @request_dict uid: uid
  344. @request_dict lang: 语言
  345. @param response: 响应
  346. @return: response
  347. """
  348. uid = request_dict.get('uid', None)
  349. lang = request_dict.get('lang', 'en')
  350. if not uid:
  351. return response.json(444, 'uid')
  352. try:
  353. ai_service_qs = AiService.objects.filter(uid=uid, use_status=1, orders__ai_rank__lang__lang=lang)
  354. if not ai_service_qs.exists():
  355. return response.json(0, [])
  356. # 计算套餐过期时间
  357. sum_end_time = AiService.objects.filter(Q(uid=uid), ~Q(use_status=2)).aggregate(Sum('endTime'))[
  358. 'endTime__sum']
  359. ai_service_qs = ai_service_qs.order_by('addTime').annotate(
  360. bucket__content=F('orders__ai_rank__lang__title')). \
  361. values('uid', 'use_status', 'bucket__content')
  362. ai_service_data = ai_service_qs[0]
  363. ai_service_data['endTime'] = sum_end_time
  364. # 如果存在序列号返回完整序列号
  365. device_info_qs = Device_Info.objects.filter(UID=uid).values('serial_number', 'Type')
  366. serial_number = device_info_qs[0]['serial_number']
  367. device_type = device_info_qs[0]['Type']
  368. if serial_number:
  369. ai_service_data['serial_number'] = CommonService.get_full_serial_number(uid, serial_number, device_type)
  370. return response.json(0, [ai_service_data])
  371. except Exception as e:
  372. return response.json(500, repr(e))
  373. @staticmethod
  374. def get_ai_status(request_dict, response):
  375. """
  376. 获取AI开关状态
  377. @param request_dict: 请求数据
  378. @request_dict uid: uid
  379. @param response: 响应
  380. @return: response
  381. """
  382. uid = request_dict.get('uid', None)
  383. if not uid:
  384. return response.json(444)
  385. try:
  386. ai_server_qs = AiService.objects.filter(uid=uid, use_status=1).values('detect_status', 'detect_group')
  387. if not ai_server_qs.exists():
  388. return response.json(173)
  389. res = {
  390. 'detect_status': ai_server_qs[0]['detect_status'],
  391. 'detect_group': ai_server_qs[0]['detect_group'],
  392. }
  393. return response.json(0, {'data': res})
  394. except Exception as e:
  395. return response.json(500, repr(e))
  396. @staticmethod
  397. def do_change_ai_status(request_dict, user_id, response):
  398. """
  399. 修改AI开关状态
  400. @param request_dict: 请求数据
  401. @request_dict token_val: 设备验证令牌
  402. @request_dict appBundleId: app包id
  403. @request_dict app_type: app类型
  404. @request_dict push_type: 推送类型
  405. @request_dict status: 开关状态, 0: 关, 1: 开
  406. @request_dict m_code: 手机唯一标识
  407. @request_dict uid: uid
  408. @request_dict lang: 语言
  409. @request_dict tz: 时区
  410. @request_dict detect_group: 检测类型
  411. @request_dict interval: 推送间隔
  412. @param user_id: 用户id
  413. @param response: 响应
  414. @return: response
  415. """
  416. token_val = request_dict.get('token_val', None)
  417. appBundleId = request_dict.get('appBundleId', None)
  418. app_type = request_dict.get('app_type', None)
  419. push_type = request_dict.get('push_type', None)
  420. status = request_dict.get('status', None)
  421. m_code = request_dict.get('m_code', None)
  422. uid = request_dict.get('uid', None)
  423. lang = request_dict.get('lang', 'en')
  424. tz = request_dict.get('tz', '0')
  425. detect_group = request_dict.get('detect_group', None)
  426. interval = request_dict.get('interval', None)
  427. if not all([appBundleId, app_type, token_val, uid, m_code, status]):
  428. return response.json(444, 'appBundleId, app_type, token_val, uid,m_code, status')
  429. # 如果传空上来,就默认为0
  430. tz = '0' if tz == '' else tz.replace('GMT', '')
  431. try:
  432. ai_service_qs = AiService.objects.filter(uid=uid, use_status=1)
  433. if not ai_service_qs.exists():
  434. return response.json(10053)
  435. nowTime = int(time.time())
  436. endTime = ai_service_qs.values('endTime')[0]['endTime']
  437. if nowTime > endTime:
  438. return response.json(10054)
  439. # 查询设备是否属于该用户
  440. device_info_qs = Device_Info.objects.filter(userID_id=user_id, UID=uid)
  441. if not device_info_qs.exists():
  442. return response.json(14)
  443. status = int(status)
  444. nowTime = int(time.time())
  445. uid_set_qs = UidSetModel.objects.filter(uid=uid)
  446. if uid_set_qs.exists():
  447. uid_set_id = uid_set_qs[0].id
  448. interval = uid_set_qs[0].new_detect_interval if not interval else interval
  449. qs_data = {
  450. 'updTime': nowTime,
  451. }
  452. if interval:
  453. qs_data['detect_interval'] = int(interval)
  454. qs_data['detect_group'] = detect_group if detect_group else ''
  455. uid_set_qs.update(**qs_data)
  456. else:
  457. qs_data = {
  458. 'uid': uid,
  459. 'addTime': nowTime,
  460. 'updTime': nowTime,
  461. 'device_type': device_info_qs[0].Type
  462. }
  463. if interval:
  464. qs_data['detect_interval'] = int(interval)
  465. qs_data['detect_group'] = detect_group if detect_group else ''
  466. # 添加设备配置
  467. uid_set_qs = UidSetModel.objects.create(**qs_data)
  468. uid_set_id = uid_set_qs.id
  469. qs_data['detect_status'] = status # ai开关状态
  470. ai_service_qs.update(**qs_data)
  471. thing_name = CommonService.query_serial_with_uid(uid) # 存在序列号则为使用序列号作为物品名
  472. topic_name = 'ansjer/generic/{}'.format(thing_name)
  473. if status == 0: # 关闭
  474. # mqtt通知设备关闭AI识别功能
  475. msg = {'commandType': 'AIDisable'}
  476. req_success = CommonService.req_publish_mqtt_msg(thing_name, topic_name, msg)
  477. if not req_success:
  478. return response.json(10044)
  479. return response.json(0)
  480. elif status == 1: # 开启
  481. # 更新或创建uid_push数据
  482. uid_push_qs = UidPushModel.objects.filter(userID_id=user_id, m_code=m_code, uid_set__uid=uid)
  483. uid_push_data = {
  484. 'appBundleId': appBundleId,
  485. 'app_type': app_type,
  486. 'push_type': push_type,
  487. 'token_val': token_val,
  488. 'updTime': nowTime,
  489. 'lang': lang,
  490. 'tz': tz
  491. }
  492. if uid_push_qs.exists():
  493. uid_push_qs.update(**uid_push_data)
  494. else:
  495. uid_push_data['uid_set_id'] = uid_set_id
  496. uid_push_data['userID_id'] = user_id
  497. uid_push_data['m_code'] = m_code
  498. uid_push_data['addTime'] = nowTime
  499. UidPushModel.objects.create(**uid_push_data)
  500. etkObj = ETkObject(etk='')
  501. etk = etkObj.encrypt(uid)
  502. # mqtt通知设备开启AI识别功能
  503. aiIdentificationUrl = '{}AiService/identification'.format(DETECT_PUSH_DOMAINS)
  504. msg = {
  505. 'commandType': 'AIEnable',
  506. 'payload': {
  507. 'etk': etk,
  508. 'endTime': endTime,
  509. 'aiIdentificationUrl': aiIdentificationUrl,
  510. }
  511. }
  512. req_success = CommonService.req_publish_mqtt_msg(thing_name, topic_name, msg)
  513. if not req_success:
  514. return response.json(10044)
  515. return response.json(0, {'aiIdentificationUrl': aiIdentificationUrl, 'endTime': endTime, 'etk': etk})
  516. except Exception as e:
  517. return response.json(500, repr(e))
  518. @staticmethod
  519. def create_paypal_payment(lang, orderID, price, currency, content, response):
  520. cancel_url = CommonService.get_payment_status_url(lang, 'fail')
  521. call_sub_url = "{}AiService/doPayPalCallBack?orderID={}&lang={}".format(SERVER_DOMAIN_SSL, orderID, lang)
  522. paypalrestsdk.configure(PAYPAL_CRD)
  523. payment = paypalrestsdk.Payment({
  524. "intent": "sale",
  525. "payer": {"payment_method": "paypal"},
  526. "redirect_urls": {"return_url": call_sub_url, "cancel_url": cancel_url},
  527. "transactions": [{
  528. "item_list": {"items": [
  529. {"name": "Cloud video", "sku": "1", "price": price, "currency": "USD", "quantity": 1}]},
  530. "amount": {"total": price, "currency": currency},
  531. "description": content}]})
  532. if not payment.create(): # 创建失败
  533. return response.json(10, payment.error)
  534. paymentID = payment['id'] # 获取paymentID
  535. for link in payment.links:
  536. if link.rel == "approval_url":
  537. pay_url = str(link.href)
  538. return paymentID, pay_url
  539. return response.json(10, 'create_ai_order_failed')
  540. @staticmethod
  541. def create_alipay_payment(lang, orderID, price, title, content, response):
  542. aliPayObj = AliPayObject()
  543. alipay = aliPayObj.conf()
  544. subject = title + content
  545. order_string = alipay.api_alipay_trade_wap_pay(
  546. out_trade_no=orderID,
  547. total_amount=price,
  548. subject=subject,
  549. return_url="{}web/paid2/success.html".format(SERVER_DOMAIN_SSL),
  550. notify_url="{}AiService/doAlipayCallBack".format(SERVER_DOMAIN_SSL),
  551. quit_url="{}web/paid2/fail.html".format(SERVER_DOMAIN_SSL),
  552. passback_params=quote("lang=" + lang)
  553. )
  554. if not order_string:
  555. return response.json(10, '生成订单错误.')
  556. return aliPayObj.alipay_prefix + order_string
  557. @staticmethod
  558. def create_wechat_payment(lang, orderID, price, ip, content, response):
  559. pay = WechatPayObject()
  560. pay_url = "{}AiService/doWechatCallBack".format(SERVER_DOMAIN_SSL)
  561. # 统一调用接口
  562. pay.get_parameter(orderID, content, float(price) * 100, ip, pay_url, quote("lang=" + lang))
  563. sign_params = pay.re_finall(orderid=orderID)
  564. if not sign_params:
  565. return response.json(10, '生成订单错误.')
  566. return pay_url, sign_params
  567. def do_pay_by_paypal_callback(self, request_dict, response):
  568. logger = logging.getLogger('info')
  569. logger.info('AI订单---paypal支付回调')
  570. paymentId = request_dict.get('paymentId', None)
  571. PayerID = request_dict.get('PayerID', None)
  572. orderID = request_dict.get('orderID', None)
  573. lang = request_dict.get('lang', 'en')
  574. if not orderID:
  575. pay_failed_url = CommonService.get_payment_status_url(lang, 'fail')
  576. return HttpResponseRedirect(pay_failed_url)
  577. logger.info("paymentID: {}, payerID: {}".format(paymentId, PayerID))
  578. # redis加锁,防止订单重复
  579. redisObj = RedisObject()
  580. isLock = redisObj.CONN.setnx(orderID + 'do_notify', 1)
  581. redisObj.CONN.expire(orderID + 'do_notify', 60)
  582. if not isLock:
  583. return response.json(5)
  584. try:
  585. order_qs = Order_Model.objects.filter(orderID=orderID, status=0)
  586. if not order_qs.exists():
  587. return response.json(173)
  588. paypalrestsdk.configure(PAYPAL_CRD)
  589. payment = paypalrestsdk.Payment.find(paymentId)
  590. logger.info("payment: {}".format(payment))
  591. payer = payment.execute({"payer_id": PayerID})
  592. logger.info('payres: {}'.format(payer))
  593. if not payer:
  594. pay_failed_url = CommonService.get_payment_status_url(lang, 'fail')
  595. redisObj.del_data(key=orderID + 'do_notify')
  596. return HttpResponseRedirect(pay_failed_url)
  597. return self.payment_success(orderID, lang, order_qs, redisObj)
  598. except Exception as e:
  599. logger.info('AI订单paypal支付回调异常:{}'.format(repr(e)))
  600. order_qs.update(status=10)
  601. pay_failed_url = CommonService.get_payment_status_url(lang, 'fail')
  602. redisObj.del_data(key=orderID + 'do_notify')
  603. return HttpResponseRedirect(pay_failed_url)
  604. def do_alipay_callback(self, request_dict, response): # 支付宝支付回调
  605. logger = logging.getLogger('info')
  606. logger.info('AI订单---支付宝支付回调')
  607. try:
  608. data = request_dict.dict()
  609. passback_params = data['passback_params']
  610. parmap = dict([(k, v[0]) for k, v in parse_qs(unquote(passback_params)).items()])
  611. lang = parmap['lang']
  612. signature = data['sign']
  613. data.pop('sign')
  614. orderID = data['out_trade_no']
  615. # redis加锁,防止订单重复
  616. redisObj = RedisObject()
  617. isLock = redisObj.CONN.setnx(orderID + 'do_notify', 1)
  618. redisObj.CONN.expire(orderID + 'do_notify', 60)
  619. if not isLock:
  620. return response.json(5)
  621. order_qs = Order_Model.objects.filter(orderID=orderID, status=0)
  622. if not order_qs.exists():
  623. return response.json(173)
  624. aliPayObj = AliPayObject()
  625. alipay = aliPayObj.conf()
  626. success = alipay.verify(data, signature)
  627. if not success or data["trade_status"] not in ("TRADE_SUCCESS", "TRADE_FINISHED"):
  628. return response.json(0, signature)
  629. return self.payment_success(orderID, lang, order_qs, redisObj)
  630. except Exception as e:
  631. logger.info('AI订单支付宝支付回调异常:{}'.format(repr(e)))
  632. order_qs.update(status=10)
  633. redisObj.del_data(key=orderID + 'do_notify')
  634. pay_failed_url = CommonService.get_payment_status_url(lang, 'fail')
  635. redisObj.del_data(key=orderID + 'do_notify')
  636. return HttpResponseRedirect(pay_failed_url)
  637. def do_wechat_callback(self, request, response): # 微信支付回调
  638. logger = logging.getLogger('info')
  639. logger.info('AI订单---微信支付回调')
  640. try:
  641. pay = WechatPayObject()
  642. data = pay.weixinpay_call_back(request.body)
  643. attach = data["attach"]
  644. parmap = dict([(k, v[0]) for k, v in parse_qs(unquote(attach)).items()])
  645. lang = parmap['lang']
  646. trade_status = data['result_code'] # 业务结果 SUCCESS/FAIL
  647. orderID = data['out_trade_no'] # 商户订单号
  648. order_qs = Order_Model.objects.filter(orderID=orderID, status=0)
  649. if not order_qs.exists():
  650. return response.json(173)
  651. if trade_status != 'SUCCESS':
  652. order_qs.update(status=10)
  653. return HttpResponse(pay.xml_to_dict({'return_code': 'FAIL'}))
  654. check_sign = pay.get_notifypay(data)
  655. if not check_sign:
  656. return HttpResponse(pay.xml_to_dict({'return_code': 'FAIL', 'return_msg': '签名失败'}))
  657. # redis加锁,防止订单重复
  658. redisObj = RedisObject()
  659. isLock = redisObj.CONN.setnx(orderID + 'do_notify', 1)
  660. redisObj.CONN.expire(orderID + 'do_notify', 60)
  661. if not isLock:
  662. return response.json(5)
  663. return self.payment_success(self, orderID, lang, order_qs, redisObj, True)
  664. except Exception as e:
  665. order_qs.update(status=10)
  666. redisObj.del_data(key=orderID + 'do_notify')
  667. return HttpResponse(pay.xml_to_dict({'return_code': 'FAIL', 'return_msg': repr(e)}))
  668. def payment_success(self, orderID, lang, order_qs, redisObj, is_wechat_pay=False):
  669. nowTime = int(time.time())
  670. order_list = order_qs.values("UID", "channel", "commodity_code", "ai_rank__effective_day", "isSelectDiscounts",
  671. "userID__userID", "userID__username", "coupon_id")
  672. userid = order_list[0]['userID__userID']
  673. username = order_list[0]['userID__username']
  674. UID = order_list[0]['UID']
  675. channel = order_list[0]['channel']
  676. effective_day = order_list[0]['ai_rank__effective_day']
  677. ai_service_qs = AiService.objects.filter(Q(uid=UID), Q(channel=channel), Q(use_status=1))
  678. ai_service_dict = {'orders_id': orderID,
  679. 'uid': UID,
  680. 'channel': channel,
  681. 'detect_status': 1,
  682. 'addTime': nowTime,
  683. 'updTime': nowTime,
  684. }
  685. if ai_service_qs.exists(): # 有正在使用的套餐,套餐结束时间保存为套餐有效期
  686. ai_service_dict['endTime'] = effective_day * 24 * 60 * 60
  687. else:
  688. ai_service_dict['use_status'] = 1
  689. ai_service_dict['endTime'] = nowTime + effective_day * 24 * 60 * 60
  690. with transaction.atomic():
  691. # 更新设备主用户
  692. Device_Info.objects.filter(UID=UID, vodPrimaryUserID='', vodPrimaryMaster=''). \
  693. update(vodPrimaryUserID=userid, vodPrimaryMaster=username)
  694. # 更新订单数据,返回支付成功url
  695. order_qs.update(status=1, updTime=nowTime)
  696. # 创建AiService数据
  697. AiService.objects.create(**ai_service_dict)
  698. pay_success_url = CommonService.get_payment_status_url(lang, 'success')
  699. redisObj.del_data(key=orderID + 'do_notify')
  700. if is_wechat_pay:
  701. return HttpResponse("<xml>\
  702. <return_code><![CDATA[SUCCESS]]></return_code>\
  703. <return_msg><![CDATA[OK]]></return_msg>\
  704. </xml>")
  705. else:
  706. return HttpResponseRedirect(pay_success_url)