CloudStorage.py 101 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. import base64
  4. import datetime
  5. import json
  6. import logging
  7. import sys
  8. import time
  9. import ssl
  10. from decimal import Decimal
  11. from itertools import groupby
  12. from operator import itemgetter
  13. from urllib.parse import quote, parse_qs, unquote
  14. import boto3
  15. import jwt
  16. import paypalrestsdk
  17. from django.db import transaction
  18. from django.db.models import Q, F
  19. from django.http import JsonResponse, HttpResponseRedirect, HttpResponse
  20. from django.views.generic.base import View
  21. from Ansjer.config import SERVER_DOMAIN, PAYPAL_CRD, SERVER_DOMAIN_SSL, AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, \
  22. AWS_ARN, OAUTH_ACCESS_TOKEN_SECRET
  23. from Controller.CheckUserData import DataValid
  24. from Controller.CloudPhoto.CloudServiceController import CloudServiceController
  25. from Controller.PaymentCycle import Paypal
  26. from Model.models import Device_Info, Order_Model, Store_Meal, VodHlsModel, UID_Bucket, StsCrdModel, \
  27. ExperienceContextModel, Pay_Type, CDKcontextModel, Device_User, SysMsgModel, Unused_Uid_Meal, PromotionRuleModel, \
  28. VideoPlaybackTimeModel, CouponModel, VodBucketModel, VodHlsSummary
  29. from Object.AWS.AmazonS3Util import AmazonS3Util
  30. from Object.AWS.S3Email import S3Email
  31. from Object.AliPayObject import AliPayObject
  32. from Object.AliSmsObject import AliSmsObject
  33. from Object.RedisObject import RedisObject
  34. from Object.ResponseObject import ResponseObject
  35. from Object.TokenObject import TokenObject
  36. from Object.UidTokenObject import UidTokenObject
  37. from Object.WechatPayObject import WechatPayObject
  38. from Object.m3u8generate import PlaylistGenerator
  39. from Service.CommonService import CommonService
  40. from Service.PayService import PaymentService
  41. from Service.VodHlsService import SplitVodHlsObject
  42. ssl._create_default_https_context = ssl._create_unverified_context
  43. LOGGER = logging.getLogger('info')
  44. # 设备信息添加
  45. class CloudStorageView(View):
  46. def get(self, request, *args, **kwargs):
  47. request.encoding = 'utf-8'
  48. operation = kwargs.get('operation')
  49. return self.validation(request.GET, request, operation)
  50. def post(self, request, *args, **kwargs):
  51. request.encoding = 'utf-8'
  52. operation = kwargs.get('operation')
  53. return self.validation(request.POST, request, operation)
  54. def validation(self, request_dict, request, operation):
  55. lang = request_dict.get('lang', 'en')
  56. response = ResponseObject(lang)
  57. if operation is None:
  58. return response.json(444, 'error path')
  59. elif operation == 'dopaypalcallback': # paypal支付回调
  60. return self.do_pay_by_paypal_callback(request_dict, response)
  61. elif operation == 'doalicallback': # 阿里支付回调
  62. return self.do_pay_by_ali_callback(request_dict, response)
  63. elif operation == 'dowechatnotify': # 微信支付回调
  64. return self.do_pay_by_wechat_callback(request, response)
  65. elif operation == 'getsignsts': # 设备调用,获取sts令牌
  66. ip = CommonService.get_ip_address(request)
  67. return self.do_get_sign_sts(request_dict, ip, response)
  68. elif operation == 'storeplaylist': # 设备调用,设备把视频上传到s3,同时把视频数据信息传给服务器,服务器存储播放内容
  69. return self.do_store_playlist(request_dict, response)
  70. elif operation == 'signplaym3u8': # 根据sts播放m3u8 视频流
  71. return self.do_sign_play_m3u8(request_dict, response)
  72. elif operation == 'payOK': # 支付成功
  73. return self.do_pay_ok(request_dict)
  74. elif operation == 'vodMsgEnd': # 云存到期续费提醒 提前1天
  75. return self.do_vod_msg_end(response)
  76. elif operation == 'doRefund': # 退款
  77. return self.do_refund(request_dict, response)
  78. else:
  79. token = request_dict.get('token', None)
  80. # 设备主键uid
  81. tko = TokenObject(token)
  82. if tko.code != 0:
  83. return response.json(tko.code)
  84. user_id = tko.userID
  85. if operation == 'createpayorder': # 创建支付订单
  86. ip = CommonService.get_ip_address(request)
  87. return self.do_create_pay_order(request_dict, user_id, ip, response)
  88. elif operation == 'changevodstatus': # 修改云存状态,传送两个url,即getsignsts接口和storeplaylist接口
  89. return self.do_change_vod_status(request_dict, user_id, response)
  90. elif operation == 'queryvodlist': # 获取视频播放列表
  91. return self.do_query_vod_list(request_dict, user_id, response)
  92. elif operation == 'commoditylist': # 查询套餐列表
  93. return self.do_commodity_list(request_dict, user_id, response)
  94. elif operation == 'queryorder': # 查询订单列表
  95. return self.do_query_order(request_dict, user_id, response)
  96. elif operation == 'experienceorder': # 生成体验订单
  97. return self.do_experience_order(request_dict, user_id, response)
  98. elif operation == 'experiencereset': # 重置设备云存体验
  99. return self.do_experience_reset(request_dict, response)
  100. elif operation == 'deletevodlist': # 删除播放列表
  101. return self.delete_vod_list(request_dict, user_id, response)
  102. elif operation == 'devicecommodity': # 设备关联套餐列表
  103. return self.device_commodity(request_dict, user_id, response)
  104. elif operation == 'switchdevicecommodity': # 提前使用设备关联套餐
  105. return self.switch_device_commodity(request_dict, user_id, response)
  106. elif operation == 'hasvod': # APP的回放界面,日历表显示当天有无录像
  107. return self.has_vod(request_dict, user_id, response)
  108. elif operation == 'videoPlaybackTime': # 记录app播放时间
  109. return self.video_playback_time(request_dict, user_id, response)
  110. else:
  111. return response.json(414)
  112. @staticmethod
  113. def do_query_order(request_dict, user_id, response): # 查询订单列表
  114. """
  115. 查询订单列表
  116. @param request_dict: 请求数据
  117. @request_dict status: uid
  118. @request_dict page: 通道
  119. @request_dict line: 支付类型
  120. @request_dict uid: 套餐id
  121. @param user_id: 用户id
  122. @param response: 响应
  123. @return: response
  124. """
  125. status = request_dict.get('status', None)
  126. page = request_dict.get('page', None)
  127. line = request_dict.get('line', None)
  128. uid = request_dict.get('uid', None)
  129. if not all([page, line]):
  130. return response.json(444)
  131. page = int(page)
  132. line = int(line)
  133. order_qs = Order_Model.objects.filter(userID_id=user_id)
  134. if status:
  135. order_qs = order_qs.filter(status=status)
  136. # 筛选指定设备id的订单
  137. if uid:
  138. order_qs = order_qs.filter(UID=uid)
  139. if not order_qs.exists():
  140. return response.json(173)
  141. count = order_qs.count()
  142. order_list = order_qs[(page - 1) * line:page * line].values("orderID", "UID", "channel", "desc", "price",
  143. "currency", "addTime", "updTime", "endTime",
  144. "pay_url", "payType", "status", "commodity_type",
  145. "commodity_code")
  146. data = []
  147. now_time = int(time.time())
  148. for order in order_list:
  149. if order['status'] == 0:
  150. if order['addTime'] + 3600 < now_time:
  151. order['status'] = 3
  152. device_info_qs = Device_Info.objects.filter(userID_id=user_id, UID=order['UID']).values('id', 'Type')
  153. order['did'] = device_info_qs[0]['id'] if device_info_qs.exists() else ''
  154. order['Type'] = device_info_qs[0]['Type'] if device_info_qs.exists() else ''
  155. data.append(order)
  156. return response.json(0, {'data': data, 'count': count})
  157. @staticmethod
  158. def do_commodity_list(request_dict, user_id, response): # 查询套餐列表
  159. """
  160. 查询套餐列表
  161. @param user_id: 用户id
  162. @param request_dict: 请求数据
  163. @request_dict mold: 存储区域类型
  164. @request_dict uid: uid
  165. @request_dict lang: 语言
  166. @param response: 响应
  167. @return: response
  168. """
  169. mold = request_dict.get('mold', None)
  170. uid = request_dict.get('uid', None)
  171. lang = request_dict.get('lang', 'en')
  172. if not all([uid]):
  173. return response.json(444)
  174. now_time = int(time.time())
  175. # DVR/NVR设备暂不返回云存套餐列表
  176. device_info_qs = Device_Info.objects.filter(Q(UID=uid), Q(Type__lte=4) | Q(Type=10001))
  177. if device_info_qs.exists():
  178. return response.json(0)
  179. store_qs = Store_Meal.objects.filter(Q(lang__lang=lang), Q(is_show=0), ~Q(pay_type='11')) # 过滤激活码、隐藏套餐
  180. experience_context_qs = ExperienceContextModel.objects.filter(uid=uid, experience_type=0)
  181. if mold:
  182. store_qs = store_qs.filter(bucket__mold=mold)
  183. # 没体验过的设备只返回体验套餐,体验过的不返回体验套餐
  184. if experience_context_qs.exists():
  185. store_qs = store_qs.filter(~Q(pay_type='10'))
  186. else:
  187. store_qs = store_qs.filter(pay_type='10')
  188. store_qs = store_qs.annotate(title=F('lang__title'), content=F('lang__content'),
  189. discount_content=F('lang__discount_content'))
  190. store_qs = store_qs.order_by('sort').values("id", "title", "content", "price", "day", "currency",
  191. "bucket__storeDay",
  192. "bucket__bucket", "bucket__area", "commodity_code",
  193. "commodity_type", "is_discounts", "virtual_price", "expire",
  194. "discount_price", "discount_content", "symbol", "cycle_config_id")
  195. if not store_qs.exists():
  196. return response.json(0)
  197. store_list = list(store_qs)
  198. store_list.sort(key=itemgetter('bucket__area'))
  199. res = []
  200. coupon_qs = '' if not user_id else CloudServiceController.get_user_coupon_list(user_id)
  201. for area, items in groupby(store_list, key=itemgetter('bucket__area')):
  202. items_list = list(items)
  203. for item in items_list:
  204. pay_type_qs = Pay_Type.objects.filter(store_meal=item['id']).values("id", "payment")
  205. item['pay_type'] = list(pay_type_qs)
  206. item['is_pay_cycle'] = 1 if item['cycle_config_id'] else 0
  207. del item['cycle_config_id']
  208. item['isCoupon'] = False if not coupon_qs or not coupon_qs.exists() else \
  209. CloudStorageView.check_user_coupon_is_available(coupon_qs, item['id'])
  210. res_c = {'area': area, 'items': items_list}
  211. res.append(res_c)
  212. # 是否促销
  213. promotion_rule_qs = PromotionRuleModel.objects.filter(status=1, startTime__lte=now_time,
  214. endTime__gte=now_time).values('id', 'ruleConfig',
  215. 'ruleName',
  216. 'startTime', 'endTime',
  217. 'ruleDesc')
  218. if promotion_rule_qs.exists():
  219. promotion = {
  220. 'is_promotion': 1,
  221. 'promotionStartTime': promotion_rule_qs[0]['startTime'],
  222. 'promotionEndTime': promotion_rule_qs[0]['endTime'],
  223. 'promotionName': json.loads(promotion_rule_qs[0]['ruleName']).get(lang, ''),
  224. 'promotionDesc': json.loads(promotion_rule_qs[0]['ruleDesc']).get(lang, ''),
  225. 'nowTime': now_time
  226. }
  227. else:
  228. promotion = {
  229. 'is_promotion': 0
  230. }
  231. result = {
  232. 'meals': res,
  233. 'extra':
  234. {
  235. 'cloud_banner': SERVER_DOMAIN + 'web/images/cloud_cn_banner.png',
  236. 'cloud_en_baner': SERVER_DOMAIN_SSL + 'web/images/cloud_en_banner.png'
  237. },
  238. 'promotion': promotion,
  239. }
  240. return response.json(0, result)
  241. @staticmethod
  242. def check_user_coupon_is_available(coupon_qs, combo_id):
  243. """
  244. 查看用户优惠券是否可用
  245. @param coupon_qs: 优惠券列表
  246. @param combo_id: 套餐id
  247. @return:
  248. """
  249. if not coupon_qs.exists():
  250. return False
  251. result = False
  252. for item in coupon_qs:
  253. if result:
  254. break
  255. combo_list = CloudServiceController.get_combo_list(0, item['coupon_config__id'])
  256. if not combo_list:
  257. continue
  258. if combo_id in combo_list:
  259. result = True
  260. return result
  261. @staticmethod
  262. def do_sign_play_m3u8(request_dict, response): # 根据sts播放m3u8 视频流
  263. """
  264. 获取m3u8视频流
  265. @param request_dict: 请求数据
  266. @request_dict uid: uid_token
  267. @request_dict channel: 通道
  268. @request_dict time: 播放列表名字时间戳
  269. @param response: 响应
  270. @return: response
  271. """
  272. uid_token = request_dict.get('uid', None)
  273. channel = request_dict.get('channel', None)
  274. start_time = request_dict.get('time', None)
  275. if not all([uid_token, channel, start_time]):
  276. return response.json(444)
  277. uid = jwt.decode(uid_token, OAUTH_ACCESS_TOKEN_SECRET, algorithms='HS256').get('uid', '')
  278. now_time = int(time.time())
  279. split_vod_hls_obj = SplitVodHlsObject()
  280. vod_hls_qs = split_vod_hls_obj.get_vod_hls_data(uid=uid, channel=channel, start_time=start_time,
  281. end_time__gte=now_time).values("sec", "fg", "bucket_id",
  282. 'start_time')
  283. if not vod_hls_qs.exists():
  284. return response.json(173)
  285. bucket_id = vod_hls_qs[0]['bucket_id']
  286. vod_bucket_qs = VodBucketModel.objects.filter(id=bucket_id).values('bucket', 'region', 'mold')
  287. if not vod_bucket_qs.exists():
  288. return response.json(173)
  289. bucket_region = vod_bucket_qs[0]['region']
  290. bucket_name = vod_bucket_qs[0]['bucket']
  291. mold = vod_bucket_qs[0]["mold"]
  292. fg = int(vod_hls_qs[0]['fg'])
  293. s3_obj = AmazonS3Util(
  294. AWS_ACCESS_KEY_ID[mold],
  295. AWS_SECRET_ACCESS_KEY[mold],
  296. bucket_region
  297. )
  298. playlist_entries = []
  299. # ts_count = fg & 0xf
  300. # fg 64位整型,低四位代表ts文件总数,然后进行位运算,一次移四位,每四位转为十进制即为当前ts文件的秒数
  301. for i in range(15):
  302. shift = (i + 1) * 4
  303. duration = (fg >> shift) & 0xf
  304. if duration > 0:
  305. ts_file = '{uid}/vod{channel}/{time}/ts{i}.ts'.format(uid=uid, channel=channel, time=start_time, i=i)
  306. response_url = s3_obj.generate_file_obj_url(bucket_name, ts_file)
  307. playlist_entries.append({
  308. 'name': response_url,
  309. 'duration': duration,
  310. })
  311. playlist = PlaylistGenerator(playlist_entries).generate()
  312. response = HttpResponse(playlist)
  313. response['Content-Type'] = 'application/octet-stream'
  314. response['Content-Disposition'] = 'attachment;filename="play.m3u8"'
  315. return response
  316. @staticmethod
  317. def do_get_sign_sts(request_dict, ip, response): # 获取sts令牌
  318. """
  319. 获取sts令牌
  320. @param request_dict: 请求数据
  321. @param ip: ip地址
  322. @request_dict uidToken: uid_token
  323. @param response: 响应
  324. @return: response
  325. """
  326. uid_token = request_dict.get('uidToken', None)
  327. uid_obj = UidTokenObject(uid_token)
  328. if uid_obj.flag is False:
  329. return response.json(444, 'uidToken')
  330. uid = uid_obj.UID
  331. channel = uid_obj.channel
  332. now_time = int(time.time())
  333. try:
  334. uid_bucket_qs = UID_Bucket.objects.filter(uid=uid, endTime__gte=now_time, channel=channel).values(
  335. "bucket__mold",
  336. "bucket__bucket",
  337. "bucket__endpoint",
  338. "bucket__region",
  339. "endTime").order_by(
  340. 'addTime')
  341. if not uid_bucket_qs.exists():
  342. res = {'code': 405, 'msg': 'Not purchased or expired!'}
  343. return HttpResponse(json.dumps(res, ensure_ascii=False), content_type="application/json,charset=utf-8")
  344. # 亚马逊 s3 sts
  345. sts_crd_qs = StsCrdModel.objects.filter(uid=uid, channel=channel).values("addTime", "data")
  346. if sts_crd_qs.exists():
  347. end_time = int(sts_crd_qs[0]["addTime"]) + 5000
  348. if end_time > now_time:
  349. res = json.loads(sts_crd_qs[0]["data"])
  350. return JsonResponse(status=200, data=res)
  351. storage = '{uid}/vod{channel}/'.format(uid=uid, channel=channel)
  352. bucket_name = uid_bucket_qs[0]['bucket__bucket']
  353. endpoint = uid_bucket_qs[0]['bucket__endpoint']
  354. region_id = uid_bucket_qs[0]['bucket__region']
  355. try:
  356. aws_access_key_id = AWS_ACCESS_KEY_ID[uid_bucket_qs[0]["bucket__mold"]]
  357. aws_secret_access_key = AWS_SECRET_ACCESS_KEY[uid_bucket_qs[0]["bucket__mold"]]
  358. aws_arn = AWS_ARN[uid_bucket_qs[0]["bucket__mold"]]
  359. except:
  360. res = {'code': 404, 'msg': 'mold not exists!'}
  361. return HttpResponse(json.dumps(res, ensure_ascii=False), content_type="application/json,charset=utf-8")
  362. boto3_sts = boto3.client(
  363. 'sts',
  364. aws_access_key_id=aws_access_key_id,
  365. aws_secret_access_key=aws_secret_access_key,
  366. region_name=region_id
  367. )
  368. policy = {
  369. "Version": "2012-10-17",
  370. "Statement": [
  371. {
  372. "Effect": "Allow",
  373. "Action": "s3:*",
  374. "Resource": ["{aws_arn}:::{bucket_name}/{uid_channel}*".
  375. format(aws_arn=aws_arn, bucket_name=bucket_name, uid_channel=storage)]
  376. }
  377. ]
  378. }
  379. response = boto3_sts.get_federation_token(
  380. Name='{role_name}'.format(role_name=uid + '_' + str(channel)),
  381. Policy=json.dumps(policy),
  382. DurationSeconds=7200
  383. )
  384. res = {
  385. 'AccessKeyId': response['Credentials']['AccessKeyId'],
  386. 'AccessKeySecret': response['Credentials']['SecretAccessKey'],
  387. 'SessionToken': response['Credentials']['SessionToken'],
  388. 'Expiration': response['Credentials']['Expiration'],
  389. 'expire': 900,
  390. 'endpoint': endpoint,
  391. 'bucket_name': bucket_name,
  392. 'arn': response['FederatedUser']['Arn'],
  393. 'code': 0,
  394. 'storage': storage,
  395. 'endTime': uid_bucket_qs[0]['endTime'],
  396. 'ip': ip,
  397. 'region': region_id,
  398. 'bucket_mold': uid_bucket_qs[0]['bucket__mold']
  399. }
  400. if sts_crd_qs.exists():
  401. sts_crd_qs.update(data=json.dumps(res, default=str), addTime=now_time)
  402. else:
  403. StsCrdModel.objects.create(uid=uid, channel=channel, data=json.dumps(res, default=str),
  404. addTime=now_time, type=1)
  405. return JsonResponse(status=200, data=res)
  406. except Exception as e:
  407. return response.json(500, repr(e))
  408. @staticmethod
  409. def do_query_vod_list(request_dict, user_id, response): # 获取视频播放列表
  410. """
  411. 获取视频播放列表
  412. @param request_dict: 请求数据
  413. @param user_id: 用户id
  414. @request_dict startTime: 开始时间
  415. @request_dict endTime: 结束时间
  416. @request_dict uid: uid
  417. @request_dict channel: 通道
  418. @param response: 响应
  419. @return: response
  420. """
  421. logger = logging.getLogger('info')
  422. into_time = int(time.time())
  423. start_time = request_dict.get('startTime', None)
  424. end_time = request_dict.get('endTime', None)
  425. uid = request_dict.get('uid', None)
  426. channel = request_dict.get('channel', None)
  427. if not all([uid, channel, start_time, end_time]):
  428. return response.json(444)
  429. if uid == 'UWE2ZJ52SE4FX75U111A':
  430. logger.info({
  431. "intoTime": into_time,
  432. })
  433. device_info_qs = Device_Info.objects.filter(userID_id=user_id, UID=uid, isShare=False).values(
  434. 'vodPrimaryUserID',
  435. 'vodPrimaryMaster')
  436. if not device_info_qs.exists():
  437. return response.json(12)
  438. device_info_qs_time_over = int(time.time())
  439. if uid == 'UWE2ZJ52SE4FX75U111A':
  440. logger.info({
  441. "intoTime": into_time,
  442. "dvQsModelOverTime": device_info_qs_time_over,
  443. })
  444. if device_info_qs[0]['vodPrimaryUserID'] != user_id:
  445. return response.json(10034)
  446. now_time = int(time.time())
  447. uid_bucket_qs = UID_Bucket.objects.filter(uid=uid, endTime__gte=now_time, channel=channel).values(
  448. 'bucket_id').order_by('addTime')
  449. if not uid_bucket_qs.exists():
  450. return response.json(10030)
  451. uid_bucket_qs_time_over = int(time.time())
  452. logger.info({
  453. "intoTime": into_time,
  454. "dvQsModelOverTime": device_info_qs_time_over,
  455. "UidBucketModelOverTime": uid_bucket_qs_time_over,
  456. })
  457. split_vod_hls_obj = SplitVodHlsObject()
  458. vod_hls_qs = split_vod_hls_obj.get_vod_hls_data(uid=uid, channel=channel,
  459. end_time__gte=now_time,
  460. start_time__range=(start_time, end_time),
  461. ) \
  462. .values("id", "start_time", "sec", "fg", "bucket_id")
  463. vod_play_list = []
  464. if not vod_hls_qs.exists():
  465. return response.json(0, vod_play_list)
  466. # 不用关联外键查询,因为会查询非常慢
  467. vod_bucket_qs = VodBucketModel.objects.values()
  468. regroup_bucket_qs = {}
  469. for bucket_dict in vod_bucket_qs:
  470. regroup_bucket_qs[bucket_dict['id']] = bucket_dict
  471. vod_hls_qs_time_over = int(time.time())
  472. logger.info({
  473. "intoTime": into_time,
  474. "dvQsModelOverTime": device_info_qs_time_over,
  475. "UidBucketModelOverTime": uid_bucket_qs_time_over,
  476. "vodHlsModelOverTime": vod_hls_qs_time_over,
  477. })
  478. bucket_mold = regroup_bucket_qs[vod_hls_qs[0]['bucket_id']]['mold']
  479. bucket_region = regroup_bucket_qs[vod_hls_qs[0]['bucket_id']]['region']
  480. aws_access_key_id = AWS_ACCESS_KEY_ID[bucket_mold]
  481. aws_secret_access_key = AWS_SECRET_ACCESS_KEY[bucket_mold]
  482. s3_obj = AmazonS3Util(aws_access_key_id, aws_secret_access_key, bucket_region)
  483. uid_token = TokenObject().encryption(data={'uid': uid})
  484. aws_object_over_time = int(time.time())
  485. logger.info({
  486. "intoTime": into_time,
  487. "dvQsModelOverTime": device_info_qs_time_over,
  488. "UidBucketModelOverTime": uid_bucket_qs_time_over,
  489. "vodHlsModelOverTime": vod_hls_qs_time_over,
  490. "awsObjectOverTime": aws_object_over_time,
  491. })
  492. for vod in vod_hls_qs:
  493. bucket_name = regroup_bucket_qs[vod['bucket_id']]['bucket']
  494. thumbs_png = '{uid}/vod{channel}/{time}/Thumb.jpeg'.format(uid=uid, channel=channel, time=vod['start_time'])
  495. response_url = s3_obj.generate_file_obj_url(bucket_name, thumbs_png)
  496. vod_url = '{server_domain}cloudstorage/signplaym3u8?' \
  497. 'uid={uid}&channel={channel}&time={time}&sign=tktktktk'. \
  498. format(server_domain=SERVER_DOMAIN_SSL, uid=uid_token, channel=channel, time=vod['start_time'])
  499. ts_num = int(vod['fg']) & 0xf
  500. vod_play_list.append({
  501. 'start_time': vod['start_time'],
  502. 'sign_url': vod_url,
  503. 'thumb': response_url,
  504. 'sec': vod['sec'],
  505. 'ts_num': ts_num,
  506. 'vod_id': vod['id'],
  507. })
  508. vod_play_list = sorted(vod_play_list, key=lambda item: -item['start_time'])
  509. generate_presigned_over_time = int(time.time())
  510. if uid == 'UWE2ZJ52SE4FX75U111A':
  511. logger.info({
  512. "intoTime": into_time,
  513. "dvQsModelOverTime": device_info_qs_time_over,
  514. "UidBucketModelOverTime": uid_bucket_qs_time_over,
  515. "vodHlsModelOverTime": vod_hls_qs_time_over,
  516. "awsObjectOverTime": aws_object_over_time,
  517. "generatePresignedOverTime": generate_presigned_over_time,
  518. })
  519. return response.json(0, vod_play_list)
  520. @staticmethod
  521. def do_store_playlist(request_dict, response):
  522. """
  523. 存储设备上传云存信息数据
  524. @param request_dict: 请求数据
  525. @request_dict uidToken: uid_token
  526. @request_dict time: 播放列表名字时间戳
  527. @request_dict sec: 秒数
  528. @request_dict fg: ts个数,时间描述片段数
  529. @param response: 响应
  530. @return: response
  531. """
  532. uid_token = request_dict.get('uidToken', None)
  533. start_time = request_dict.get('time', None)
  534. sec = request_dict.get('sec', None)
  535. fg = request_dict.get('fg', None)
  536. if not all([uid_token, start_time, sec]):
  537. return response.json(0)
  538. uid_obj = UidTokenObject(uid_token)
  539. if uid_obj.flag is False:
  540. return response.json(444, 'uidToken')
  541. try:
  542. sec = int(sec)
  543. uid = uid_obj.UID
  544. channel = uid_obj.channel
  545. now_time = int(time.time())
  546. uid_bucket_qs = UID_Bucket.objects.filter(uid=uid, endTime__gte=now_time, channel=channel).values(
  547. "bucket__mold",
  548. "bucket__bucket",
  549. "bucket__endpoint",
  550. "bucket__region",
  551. "status",
  552. "bucket__storeDay",
  553. "bucket__id").order_by(
  554. 'addTime')
  555. if not uid_bucket_qs.exists():
  556. return response.json(10030)
  557. # 判断设备是否开启云存
  558. uid_bucket = uid_bucket_qs.first()
  559. store_day = uid_bucket['bucket__storeDay']
  560. bucket_id = uid_bucket['bucket__id']
  561. end_time = int(start_time) + store_day * 86400
  562. if uid_bucket['status'] != 1:
  563. return response.json(10, {'msg': '设备未开启云存'})
  564. # 保存云存信息数据
  565. # 创建旧表数据
  566. VodHlsModel.objects.create(
  567. uid=uid,
  568. channel=channel,
  569. time=start_time,
  570. endTime=end_time,
  571. bucket_id=bucket_id,
  572. fg=fg,
  573. sec=sec,
  574. )
  575. # 创建分表数据
  576. split_vod_hls_obj = SplitVodHlsObject()
  577. vod_vo, week = split_vod_hls_obj.creat_vod_hls_data(uid=uid, channel=channel, start_time=start_time,
  578. end_time=end_time, bucket_id=bucket_id, fg=fg, sec=sec)
  579. split_vod_hls_obj.cloud_vod_hls_tag(vod_vo.id, week, uid, start_time)
  580. end_time_stamp = datetime.datetime.fromtimestamp(int(start_time))
  581. end_time_str = datetime.datetime(end_time_stamp.year, end_time_stamp.month, 1)
  582. end_time_stamp = CommonService.str_to_timestamp(end_time_str.strftime('%Y-%m-%d %H:%M:%S'))
  583. vod_hls_sum_qs = VodHlsSummary.objects.filter(uid=uid, time=end_time_stamp)
  584. if vod_hls_sum_qs.exists():
  585. vod_hls_sum = vod_hls_sum_qs.first()
  586. vod_hls_sum.upload_frequency += 1
  587. vod_hls_sum.upload_duration += sec
  588. vod_hls_sum.updated_time = now_time
  589. vod_hls_sum.save()
  590. else:
  591. VodHlsSummary.objects.create(uid=uid, time=end_time_stamp, created_time=now_time, updated_time=now_time,
  592. upload_duration=sec, upload_frequency=1)
  593. res = {'code': 0, 'msg': '存储成功'}
  594. return HttpResponse(json.dumps(res, ensure_ascii=False), content_type='application/json,charset=utf-8')
  595. except Exception as e:
  596. return response.json(500, repr(e))
  597. @staticmethod
  598. def do_change_vod_status(request_dict, user_id, response): # 修改云存状态
  599. """
  600. 修改云存状态
  601. @param request_dict: 请求数据
  602. @param user_id: 用户id
  603. @request_dict uid: uid
  604. @request_dict status: 套餐状态
  605. @request_dict channel: 通道
  606. @param response: 响应
  607. @return: response
  608. """
  609. uid = request_dict.get('uid', None)
  610. status = request_dict.get('status', None)
  611. channel = request_dict.get('channel', None)
  612. domain_name = request_dict.get('domain_name', None)
  613. if not all([uid, status, channel]):
  614. return response.json(444, 'uid,status,channel')
  615. device_info_qs = Device_Info.objects.filter(userID_id=user_id, UID=uid, isShare=False, isExist=1).values(
  616. 'vodPrimaryUserID')
  617. if not device_info_qs.exists() or device_info_qs[0]['vodPrimaryUserID'] != user_id:
  618. return response.json(12)
  619. uid_bucket_qs = UID_Bucket.objects.filter(channel=channel, uid=uid)
  620. if not uid_bucket_qs.exists():
  621. return response.json(10030)
  622. now_time = int(time.time())
  623. if now_time > uid_bucket_qs[0].endTime:
  624. return response.json(10031)
  625. uid_bucket_qs.update(status=status)
  626. if status == 0:
  627. return response.json(0)
  628. uid_obj = UidTokenObject()
  629. uid_obj.generate(data={'uid': uid, 'channel': channel})
  630. # 欧洲域名固定返回欧洲域名
  631. urls = SERVER_DOMAIN_SSL
  632. if domain_name in ['api.zositeche.com', 'api.loocam3.com', 'common.neutral3.com']:
  633. urls = 'https://api.zositeche.com/'
  634. uid_tk_url = '{}cloudstorage/getsignsts?uidToken={}'.format(urls, uid_obj.token)
  635. store_hls_url = '{}cloudstorage/storeplaylist?uidToken={}'.format(urls, uid_obj.token)
  636. return response.json(0, {'uidTkUrl': uid_tk_url, 'storeHlsUrl': store_hls_url})
  637. @staticmethod
  638. def do_pay_error():
  639. response = HttpResponse()
  640. response.content = PaymentService.get_pay_error_content()
  641. return response
  642. @staticmethod
  643. def do_pay_ok(request_dict): # 支付成功
  644. """
  645. 支付成功
  646. @param request_dict: 请求数据
  647. @request_dict paytype: 支付类型
  648. @request_dict lang: 语言
  649. @return: response
  650. """
  651. lang = request_dict.get('lang', 'en')
  652. pay_type = request_dict.get('paytype', None)
  653. response = HttpResponse()
  654. response.content = PaymentService.get_pay_ok_content(lang, pay_type)
  655. return response
  656. def do_pay_by_ali_callback(self, request_dict, response): # 阿里支付回调
  657. """
  658. 阿里支付回调
  659. @param request_dict: 请求数据
  660. @request_dict out_trade_no: 订单id
  661. @request_dict sign: 语言
  662. @request_dict trade_status: 语言
  663. @request_dict passback_params: 语言
  664. @param response: 响应
  665. @return: response
  666. """
  667. request_dict = request_dict.dict()
  668. pass_back_params = request_dict["passback_params"]
  669. signature = request_dict["sign"]
  670. request_dict.pop('sign')
  671. order_id = request_dict['out_trade_no']
  672. trade_status = request_dict["trade_status"]
  673. if not all([pass_back_params, signature, order_id, trade_status]):
  674. return response.json(444)
  675. parmap = dict([(k, v[0]) for k, v in parse_qs(unquote(pass_back_params)).items()])
  676. lang = parmap["lang"]
  677. order_qs = Order_Model.objects.filter(orderID=order_id, status=0)
  678. if not order_qs.exists():
  679. return response.json(173)
  680. # redis加锁,防止订单重复
  681. redis_obj = RedisObject()
  682. is_lock = redis_obj.CONN.setnx(order_id + 'do_notify', 1)
  683. redis_obj.CONN.expire(order_id + 'do_notify', 60)
  684. if not is_lock:
  685. return response.json(5)
  686. promotion_rule_id = ''
  687. try:
  688. # 验证阿里支付链接
  689. ali_pay_obj = AliPayObject()
  690. alipay = ali_pay_obj.conf()
  691. success = alipay.verify(request_dict, signature)
  692. if success and trade_status in ("TRADE_SUCCESS", "TRADE_FINISHED"):
  693. order_list = order_qs.values("UID", "channel", "commodity_code", "rank", "isSelectDiscounts",
  694. "userID__userID", "userID__username", "coupon_id")
  695. userid = order_list[0]['userID__userID']
  696. username = order_list[0]['userID__username']
  697. uid = order_list[0]['UID']
  698. channel = order_list[0]['channel']
  699. rank = order_list[0]['rank']
  700. store_qs = Store_Meal.objects.filter(id=rank).values("day", "bucket_id", "bucket__storeDay", "expire")
  701. bucket_id = store_qs[0]['bucket_id']
  702. if not store_qs.exists():
  703. return response.json(173)
  704. uiu_bucket_qs = UID_Bucket.objects.filter(uid=uid).values("id", "bucket_id", "bucket__storeDay",
  705. "bucket__region", "endTime", "use_status")
  706. expire = store_qs[0]['expire']
  707. if order_list[0]['isSelectDiscounts'] == 1:
  708. expire = store_qs[0]['expire'] * 2
  709. # 是否有促销
  710. now_time = int(time.time())
  711. promotion = PromotionRuleModel.objects.filter(status=1, startTime__lte=now_time,
  712. endTime__gte=now_time).values('id', 'ruleConfig')
  713. if promotion.exists():
  714. promotion_rule_id = promotion[0]['id']
  715. expire = expire * 2
  716. with transaction.atomic():
  717. if uiu_bucket_qs.exists():
  718. uid_bucket = uiu_bucket_qs.first()
  719. if uid_bucket['use_status'] == 1 and uid_bucket['bucket_id'] == bucket_id: # 套餐使用中并且相同套餐叠加过期时间
  720. end_time = CommonService.calcMonthLater(expire, uid_bucket['endTime'])
  721. UID_Bucket.objects.filter(id=uid_bucket['id']).update(uid=uid, channel=channel,
  722. bucket_id=bucket_id, endTime=end_time,
  723. updateTime=now_time)
  724. else: # 已过期或者不相同的套餐加入未使用的关联套餐表
  725. unused_uid_qs = Unused_Uid_Meal.objects.filter(uid=uid, bucket_id=bucket_id)
  726. nums = 2 if order_list[0]['isSelectDiscounts'] == 1 else 1
  727. if promotion.exists():
  728. nums = nums + 1
  729. if unused_uid_qs.exists():
  730. unused_uid_qs.update(num=F('num') + nums)
  731. else:
  732. Unused_Uid_Meal.objects.create(uid=uid, channel=channel, addTime=now_time, num=nums,
  733. expire=store_qs[0]['expire'], bucket_id=bucket_id)
  734. UID_Bucket.objects.filter(id=uid_bucket['id']).update(has_unused=1)
  735. uid_bucket_id = uid_bucket['id']
  736. else:
  737. end_time = CommonService.calcMonthLater(expire)
  738. uid_bucket = UID_Bucket.objects.create(uid=uid, channel=channel, bucket_id=bucket_id,
  739. endTime=end_time, addTime=now_time, updateTime=now_time,
  740. use_status=1)
  741. uid_bucket_id = uid_bucket.id
  742. device_info_qs = Device_Info.objects.filter(UID=uid, vodPrimaryUserID='', vodPrimaryMaster='')
  743. if device_info_qs.exists():
  744. dvq_set_update_dict = {
  745. 'vodPrimaryUserID': userid,
  746. 'vodPrimaryMaster': username
  747. }
  748. device_info_qs.update(**dvq_set_update_dict)
  749. # 核销coupon
  750. if order_list[0]['coupon_id']:
  751. CouponModel.objects.filter(id=order_list[0]['coupon_id']).update(use_status=2,
  752. update_time=now_time)
  753. order_qs.update(status=1, updTime=now_time, uid_bucket_id=uid_bucket_id,
  754. promotion_rule_id=promotion_rule_id)
  755. date_time = time.strftime("%Y-%m-%d", time.localtime())
  756. # 如果存在序列号,消息提示用序列号
  757. device_info_qs = Device_Info.objects.filter(UID=uid).values('serial_number', 'Type')
  758. serial_number = device_info_qs[0]['serial_number']
  759. device_type = device_info_qs[0]['Type']
  760. if serial_number:
  761. device_name = CommonService.get_full_serial_number(uid, serial_number, device_type)
  762. else:
  763. device_name = uid
  764. sys_msg_text_list = [
  765. '温馨提示:尊敬的客户,您的' + device_name + '设备在' + date_time + '已成功购买云存套餐',
  766. 'Dear customer,you already subscribed the cloud storage package successfully for device ' + device_name + ' on ' + time.strftime(
  767. "%b %dth,%Y", time.localtime())]
  768. self.do_vod_msg_notice(uid, channel, userid, lang, sys_msg_text_list, 'SMS_219738485')
  769. red_url = "{}web/paid2/success.html".format(SERVER_DOMAIN_SSL)
  770. if lang != 'cn':
  771. red_url = red_url.replace('success.html', 'en_success.html')
  772. redis_obj.del_data(key=order_id + 'do_notify')
  773. return HttpResponseRedirect(red_url)
  774. return response.json(0, signature)
  775. except Exception as e:
  776. logger = logging.getLogger('info')
  777. logger.info('alipay----notify---------')
  778. logger.info(repr(e))
  779. logger.info(sys.exc_info())
  780. logger.info('alipay支付失败:----')
  781. logger.info("错误行数:{errLine}".format(errLine=e.__traceback__.tb_lineno))
  782. logger.info(repr(e))
  783. if order_qs:
  784. order_qs.update(status=10, promotion_rule_id=promotion_rule_id)
  785. redis_obj.del_data(key=order_id + 'do_notify')
  786. red_url = "{}web/paid2/fail.html".format(SERVER_DOMAIN_SSL)
  787. if lang != 'cn':
  788. red_url = red_url.replace('fail.html', 'en_fail.html')
  789. return HttpResponseRedirect(red_url)
  790. def do_pay_by_paypal_callback(self, request_dict, response): # paypal支付回调
  791. """
  792. paypal支付回调
  793. @param request_dict: 请求数据
  794. @request_dict paymentId: 支付id
  795. @request_dict PayerID: 支付人id
  796. @request_dict orderID: 订单id
  797. @request_dict lang: 语言
  798. @param response: 响应
  799. @return: response
  800. """
  801. logger = logging.getLogger('info')
  802. logger.info('---------进入paypal异步回调')
  803. payment_id = request_dict.get('paymentId', None)
  804. payer_id = request_dict.get('PayerID', None)
  805. order_id = request_dict.get('orderID', None)
  806. lang = request_dict.get('lang', 'en')
  807. if not all([payer_id, payment_id]):
  808. return response.json(444)
  809. logger.info("paymentID={paymentId},payerID={PayerID}".format(paymentId=payment_id, PayerID=payer_id))
  810. # redis加锁,防止订单重复
  811. redis_obj = RedisObject()
  812. is_lock = redis_obj.CONN.setnx(order_id + 'do_notify', 1)
  813. redis_obj.CONN.expire(order_id + 'do_notify', 60)
  814. if not is_lock:
  815. return response.json(5)
  816. order_qs = Order_Model.objects.filter(orderID=order_id, status=0)
  817. if not order_qs.exists():
  818. return response.json(173)
  819. promotion_rule_id = ''
  820. try:
  821. if not order_id:
  822. red_url = "{}web/paid2/fail.html".format(SERVER_DOMAIN_SSL)
  823. if lang != 'cn':
  824. red_url = red_url.replace('fail.html', 'en_fail.html')
  825. return HttpResponseRedirect(red_url)
  826. paypalrestsdk.configure(PAYPAL_CRD)
  827. payment = paypalrestsdk.Payment.find(payment_id)
  828. logger.info("payment------")
  829. logger.info(payment)
  830. payers = payment.execute({"payer_id": payer_id})
  831. logger.info(payers)
  832. if not payers:
  833. red_url = "{}web/paid2/fail.html".format(SERVER_DOMAIN_SSL)
  834. if lang != 'cn':
  835. red_url = red_url.replace('fail.html', 'en_fail.html')
  836. redis_obj.del_data(key=order_id + 'do_notify')
  837. return HttpResponseRedirect(red_url)
  838. order_list = order_qs.values("UID", "channel", "commodity_code", "rank", "isSelectDiscounts",
  839. "userID__userID", "userID__username", "coupon_id")
  840. userid = order_list[0]['userID__userID']
  841. username = order_list[0]['userID__username']
  842. uid = order_list[0]['UID']
  843. channel = order_list[0]['channel']
  844. rank = order_list[0]['rank']
  845. store_qs = Store_Meal.objects.filter(id=rank).values("day", "bucket_id", "bucket__storeDay", "expire")
  846. bucket_id = store_qs[0]['bucket_id']
  847. if not store_qs.exists():
  848. return response.json(173)
  849. uid_bucket_qs = UID_Bucket.objects.filter(uid=uid).values("id", "bucket_id", "bucket__storeDay",
  850. "bucket__region", "endTime", "use_status")
  851. expire = store_qs[0]['expire']
  852. if order_list[0]['isSelectDiscounts'] == 1:
  853. expire = store_qs[0]['expire'] * 2
  854. # 是否有促销
  855. now_time = int(time.time())
  856. promotion_rule_qs = PromotionRuleModel.objects.filter(status=1, startTime__lte=now_time,
  857. endTime__gte=now_time).values('id', 'ruleConfig')
  858. if promotion_rule_qs.exists():
  859. promotion_rule_id = promotion_rule_qs[0]['id']
  860. expire = expire * 2
  861. with transaction.atomic():
  862. if uid_bucket_qs.exists():
  863. uid_bucket = uid_bucket_qs.first()
  864. if uid_bucket['use_status'] == 1 and uid_bucket['bucket_id'] == bucket_id: # 套餐使用中并且相同套餐叠加过期时间
  865. end_time = CommonService.calcMonthLater(expire, uid_bucket['endTime'])
  866. UID_Bucket.objects.filter(id=uid_bucket['id']).update(uid=uid, channel=channel,
  867. endTime=end_time,
  868. bucket_id=bucket_id, updateTime=now_time)
  869. else: # 已过期或者不相同的套餐加入未使用的关联套餐表
  870. unused_uid_qs = Unused_Uid_Meal.objects.filter(uid=uid, bucket_id=bucket_id)
  871. nums = 2 if order_list[0]['isSelectDiscounts'] == 1 else 1
  872. if promotion_rule_qs.exists():
  873. nums = nums + 1
  874. if unused_uid_qs.exists():
  875. unused_uid_qs.update(num=F('num') + nums)
  876. else:
  877. Unused_Uid_Meal.objects.create(uid=uid, channel=channel, addTime=now_time, num=nums,
  878. expire=store_qs[0]['expire'], bucket_id=bucket_id)
  879. UID_Bucket.objects.filter(id=uid_bucket['id']).update(has_unused=1)
  880. uid_bucket_id = uid_bucket['id']
  881. else:
  882. end_time = CommonService.calcMonthLater(expire)
  883. uid_bucket = UID_Bucket.objects.create(uid=uid, channel=channel, bucket_id=bucket_id,
  884. endTime=end_time, addTime=now_time, updateTime=now_time,
  885. use_status=1)
  886. uid_bucket_id = uid_bucket.id
  887. device_info_qs = Device_Info.objects.filter(UID=uid, vodPrimaryUserID='', vodPrimaryMaster='')
  888. if device_info_qs.exists():
  889. dvq_set_update_dict = {
  890. 'vodPrimaryUserID': userid,
  891. 'vodPrimaryMaster': username
  892. }
  893. device_info_qs.update(**dvq_set_update_dict)
  894. # 核销coupon
  895. if order_list[0]['coupon_id']:
  896. CouponModel.objects.filter(id=order_list[0]['coupon_id']).update(use_status=2, update_time=now_time)
  897. order_qs.update(status=1, updTime=now_time, uid_bucket_id=uid_bucket_id,
  898. promotion_rule_id=promotion_rule_id)
  899. date_time = time.strftime("%Y-%m-%d", time.localtime())
  900. # 如果存在序列号,消息提示用序列号
  901. device_info_qs = Device_Info.objects.filter(UID=uid).values('serial_number', 'Type')
  902. serial_number = device_info_qs[0]['serial_number']
  903. device_type = device_info_qs[0]['Type']
  904. if serial_number:
  905. device_name = CommonService.get_full_serial_number(uid, serial_number, device_type)
  906. else:
  907. device_name = uid
  908. sys_msg_text_list = [
  909. '温馨提示:尊敬的客户,您的' + device_name + '设备在' + date_time + '已成功购买云存套餐',
  910. 'Dear customer,you already subscribed the cloud storage package successfully for device ' + device_name + ' on ' + time.strftime(
  911. "%b %dth,%Y", time.localtime())]
  912. self.do_vod_msg_notice(uid, channel, userid, lang, sys_msg_text_list, 'SMS_219738485')
  913. red_url = "{}web/paid2/success.html".format(SERVER_DOMAIN_SSL)
  914. if lang != 'cn':
  915. red_url = red_url.replace('success.html', 'en_success.html')
  916. redis_obj.del_data(key=order_id + 'do_notify')
  917. return HttpResponseRedirect(red_url)
  918. except Exception as e:
  919. logger.info('paypal支付失败:----')
  920. logger.info("错误行数:{errLine}".format(errLine=e.__traceback__.tb_lineno))
  921. logger.info(repr(e))
  922. if order_qs:
  923. order_qs.update(status=10, promotion_rule_id=promotion_rule_id)
  924. red_url = "{}web/paid2/fail.html".format(SERVER_DOMAIN_SSL)
  925. if lang != 'cn':
  926. red_url = red_url.replace('fail.html', 'en_fail.html')
  927. redis_obj.del_data(key=order_id + 'do_notify')
  928. return HttpResponseRedirect(red_url)
  929. def do_pay_by_wechat_callback(self, request, response): # 微信支付回调
  930. """
  931. 查询套餐列表
  932. @param request: 请求体
  933. @request_dict result_code: 业务结果
  934. @request_dict out_trade_no: 商户订单号
  935. @request_dict lang: 语言
  936. @param response: 响应
  937. @return: response
  938. """
  939. logger = logging.getLogger('info')
  940. pay = WechatPayObject()
  941. data = pay.weixinpay_call_back(request.body)
  942. attach = data["attach"]
  943. parmap = dict([(k, v[0]) for k, v in parse_qs(unquote(attach)).items()])
  944. lang = parmap["lang"]
  945. trade_status = data['result_code'] # 业务结果 SUCCESS/FAIL
  946. order_id = data['out_trade_no'] # 商户订单号
  947. if not all([attach, trade_status, order_id]):
  948. return response.json(444)
  949. logger.info(order_id)
  950. order_qs = Order_Model.objects.filter(orderID=order_id, status=0)
  951. if not order_qs.exists():
  952. return response.json(173)
  953. # redis加锁,防止订单重复
  954. redis_obj = RedisObject()
  955. is_lock = redis_obj.CONN.setnx(order_id + 'do_notify', 1)
  956. redis_obj.CONN.expire(order_id + 'do_notify', 60)
  957. if not is_lock:
  958. return response.json(5)
  959. promotion_rule_id = ''
  960. try:
  961. if trade_status == "SUCCESS":
  962. check_sign = pay.get_notifypay(data)
  963. if not check_sign:
  964. return HttpResponse(pay.xml_to_dict({'return_code': 'FAIL', 'return_msg': '签名失败'}))
  965. order_list = order_qs.values("UID", "channel", "commodity_code", "rank", "isSelectDiscounts",
  966. "userID__userID", "userID__username", "status", "coupon_id")
  967. logger.info(order_list[0]['UID'])
  968. userid = order_list[0]['userID__userID']
  969. username = order_list[0]['userID__username']
  970. uid = order_list[0]['UID']
  971. channel = order_list[0]['channel']
  972. rank = order_list[0]['rank']
  973. store_qs = Store_Meal.objects.filter(id=rank).values("day", "bucket_id", "bucket__storeDay", "expire")
  974. bucket_id = store_qs[0]['bucket_id']
  975. if not store_qs.exists():
  976. return HttpResponse(pay.xml_to_dict({'return_code': 'FAIL', 'return_msg': '套餐不存在'}))
  977. uid_bucket_qs = UID_Bucket.objects.filter(uid=uid).values("id", "bucket_id", "bucket__storeDay",
  978. "bucket__region", "endTime", "use_status")
  979. expire = store_qs[0]['expire']
  980. if order_list[0]['isSelectDiscounts'] == 1:
  981. expire = store_qs[0]['expire'] * 2
  982. # 是否有促销
  983. now_time = int(time.time())
  984. promotion_rule_qs = PromotionRuleModel.objects.filter(status=1, startTime__lte=now_time,
  985. endTime__gte=now_time).values('id', 'ruleConfig')
  986. if promotion_rule_qs.exists():
  987. promotion_rule_id = promotion_rule_qs[0]['id']
  988. expire = expire * 2
  989. with transaction.atomic():
  990. if uid_bucket_qs.exists():
  991. uid_bucket = uid_bucket_qs.first()
  992. if uid_bucket['use_status'] == 1 and uid_bucket['bucket_id'] == bucket_id: # 套餐使用中并且相同套餐叠加过期时间
  993. end_time = CommonService.calcMonthLater(expire, uid_bucket['endTime'])
  994. UID_Bucket.objects.filter(id=uid_bucket['id']).update(uid=uid, channel=channel,
  995. bucket_id=bucket_id,
  996. endTime=end_time, updateTime=now_time)
  997. else: # 已过期或者不相同的套餐加入未使用的关联套餐表
  998. unused_uid_qs = Unused_Uid_Meal.objects.filter(uid=uid, bucket_id=bucket_id)
  999. nums = 2 if order_list[0]['isSelectDiscounts'] == 1 else 1
  1000. if promotion_rule_qs.exists():
  1001. nums = nums + 1
  1002. if unused_uid_qs.exists():
  1003. unused_uid_qs.update(num=F('num') + nums)
  1004. else:
  1005. Unused_Uid_Meal.objects.create(uid=uid, channel=channel, addTime=now_time, num=nums,
  1006. expire=store_qs[0]['expire'], bucket_id=bucket_id)
  1007. UID_Bucket.objects.filter(id=uid_bucket['id']).update(has_unused=1)
  1008. uid_bucket_id = uid_bucket['id']
  1009. else:
  1010. end_time = CommonService.calcMonthLater(expire)
  1011. uid_bucket = UID_Bucket.objects.create(uid=uid, channel=channel, bucket_id=bucket_id,
  1012. endTime=end_time, addTime=now_time,
  1013. updateTime=now_time, use_status=1)
  1014. uid_bucket_id = uid_bucket.id
  1015. device_info_qs = Device_Info.objects.filter(UID=uid, vodPrimaryUserID='', vodPrimaryMaster='')
  1016. if device_info_qs.exists():
  1017. dvq_set_update_dict = {
  1018. 'vodPrimaryUserID': userid,
  1019. 'vodPrimaryMaster': username
  1020. }
  1021. device_info_qs.update(**dvq_set_update_dict)
  1022. # 核销coupon
  1023. if order_list[0]['coupon_id']:
  1024. CouponModel.objects.filter(id=order_list[0]['coupon_id']).update(use_status=2,
  1025. update_time=now_time)
  1026. order_qs.update(status=1, updTime=now_time, uid_bucket_id=uid_bucket_id,
  1027. promotion_rule_id=promotion_rule_id)
  1028. date_time = time.strftime("%Y-%m-%d", time.localtime())
  1029. # 如果存在序列号,消息提示用序列号
  1030. device_info_qs = Device_Info.objects.filter(UID=uid).values('serial_number', 'Type')
  1031. serial_number = device_info_qs[0]['serial_number']
  1032. device_type = device_info_qs[0]['Type']
  1033. if serial_number:
  1034. device_name = CommonService.get_full_serial_number(uid, serial_number, device_type)
  1035. else:
  1036. device_name = uid
  1037. sys_msg_text_list = [
  1038. '温馨提示:尊敬的客户,您的' + device_name + '设备在' + date_time + '已成功购买云存套餐',
  1039. 'Dear customer,you already subscribed the cloud storage package successfully for device ' + device_name + ' on ' + time.strftime(
  1040. "%b %dth,%Y", time.localtime())]
  1041. self.do_vod_msg_notice(uid, channel, userid, lang, sys_msg_text_list, 'SMS_219738485')
  1042. redis_obj.del_data(key=order_id + 'do_notify')
  1043. return HttpResponse("<xml>\
  1044. <return_code><![CDATA[SUCCESS]]></return_code>\
  1045. <return_msg><![CDATA[OK]]></return_msg>\
  1046. </xml>")
  1047. else:
  1048. order_qs.update(status=10, promotion_rule_id=promotion_rule_id)
  1049. return HttpResponse(pay.xml_to_dict({'return_code': 'FAIL', 'return_msg': '参数格式校验错误'}))
  1050. except Exception as e:
  1051. logger.info('wechat支付失败:----')
  1052. logger.info("错误行数:{errLine}".format(errLine=e.__traceback__.tb_lineno))
  1053. logger.info(repr(e))
  1054. if order_qs:
  1055. order_qs.update(status=10, promotion_rule_id=promotion_rule_id)
  1056. redis_obj.del_data(key=order_id + 'do_notify')
  1057. return HttpResponse(pay.xml_to_dict({'return_code': 'FAIL', 'return_msg': repr(e)}))
  1058. @staticmethod
  1059. def do_create_pay_order(request_dict, user_id, ip, response): # 创建支付订单
  1060. """
  1061. 创建支付订单
  1062. @param request_dict: 请求数据
  1063. @param user_id: 用户id
  1064. @param ip: ip地址
  1065. @request_dict uid: uid
  1066. @request_dict channel: 通道
  1067. @request_dict pay_type: 支付类型
  1068. @request_dict rank: 套餐id
  1069. @request_dict is_select_discount: 用户是否选择了第二年优惠
  1070. @request_dict coupon_id: 优惠券id
  1071. @request_dict lang: 语言
  1072. @param response: 响应
  1073. @return: response
  1074. """
  1075. logger = logging.getLogger('info')
  1076. uid = request_dict.get('uid', None)
  1077. channel = request_dict.get('channel', None)
  1078. pay_type = request_dict.get('pay_type', None)
  1079. rank = request_dict.get('rank', None)
  1080. is_select_discount = request_dict.get('is_select_discount', 0)
  1081. coupon_id = request_dict.get('coupon_id', 0)
  1082. lang = request_dict.get('lang', 'en')
  1083. if not all([uid, channel, pay_type, rank]):
  1084. return response.json(444)
  1085. pay_type = int(pay_type)
  1086. device_info_qs = Device_Info.objects.filter(userID_id=user_id, UID=uid, isShare=False, isExist=1).values(
  1087. 'vodPrimaryUserID',
  1088. 'vodPrimaryMaster')
  1089. if not device_info_qs.exists():
  1090. return response.json(12)
  1091. device_info_qs = Device_Info.objects.filter(Q(UID=uid), ~Q(vodPrimaryUserID='')).values('vodPrimaryUserID')
  1092. if device_info_qs.exists():
  1093. if device_info_qs[0]['vodPrimaryUserID'] != user_id:
  1094. return response.json(10033)
  1095. now_time = int(time.time())
  1096. store_qs = Store_Meal.objects.filter(id=rank, pay_type=pay_type, lang__lang=lang, is_show=0). \
  1097. values('currency', 'price', 'lang__content', 'day', 'commodity_type', 'lang__title', 'expire',
  1098. 'commodity_code', 'discount_price', 'bucket__mold', 'cycle_config_id')
  1099. if not store_qs.exists():
  1100. return response.json(173)
  1101. store_meal_qs = Store_Meal.objects.filter(id=rank, lang__lang='cn', is_show=0).values('lang__title',
  1102. 'lang__content')
  1103. if store_meal_qs.exists():
  1104. store_meal_name = store_meal_qs[0]['lang__title'] + '-' + store_meal_qs[0]['lang__content']
  1105. else:
  1106. store_meal_name = '未知套餐'
  1107. currency = store_qs[0]['currency']
  1108. price = store_qs[0]['price']
  1109. if is_select_discount == '1':
  1110. price = float(store_qs[0]['price']) + float(store_qs[0]['discount_price'])
  1111. content = store_qs[0]['lang__content']
  1112. commodity_code = store_qs[0]['commodity_code']
  1113. commodity_type = store_qs[0]['commodity_type']
  1114. is_mold = 1 if store_qs[0]['bucket__mold'] == 0 else 0 # 判断国内外
  1115. order_qs = Order_Model.objects.filter(UID=uid, rank__bucket__mold=is_mold)
  1116. if order_qs.exists():
  1117. if is_mold == 1:
  1118. return response.json(10060)
  1119. return response.json(10041)
  1120. order_id = CommonService.createOrderID()
  1121. # 优惠券
  1122. if coupon_id:
  1123. coupon_qs = CouponModel.objects.filter(id=coupon_id, use_status=0, distribute_time__lte=now_time,
  1124. valid_time__gt=now_time).values("id", "coupon_config__type",
  1125. "coupon_config__coupon_discount")
  1126. if not coupon_qs.exists():
  1127. return response.json(10049)
  1128. price = Decimal(price)
  1129. coupon_discount = Decimal(coupon_qs[0]['coupon_config__coupon_discount'])
  1130. if coupon_qs[0]['coupon_config__type'] == 1: # 打折
  1131. price = coupon_discount / 10 * price
  1132. elif coupon_qs[0]['coupon_config__type'] == 2: # 抵扣
  1133. price = price - coupon_discount
  1134. price = float(price)
  1135. if price < 0 or price == 0 or price < 0.01:
  1136. price = 0.01
  1137. price = round(price, 2)
  1138. if pay_type == 1:
  1139. # 订阅周期扣款
  1140. if store_qs[0]['cycle_config_id']:
  1141. # 查询是否有订阅过,活跃状态
  1142. check_has_subscribe = Paypal.checkSubscriptions(user_id, uid, rank)
  1143. if not check_has_subscribe:
  1144. return response.json(10050)
  1145. sub_info = Paypal.subscriptions(store_info=store_qs[0], lang=lang, orderID=order_id, price=price)
  1146. if not sub_info:
  1147. return response.json(10048)
  1148. Order_Model.objects.create(orderID=order_id, UID=uid, channel=channel, userID_id=user_id,
  1149. desc=content, payType=pay_type, payTime=now_time,
  1150. price=price, currency=currency, addTime=now_time, updTime=now_time,
  1151. pay_url=sub_info['url'], isSelectDiscounts=is_select_discount,
  1152. commodity_code=commodity_code, commodity_type=commodity_type,
  1153. rank_id=rank, plan_id=sub_info['plan_id'], coupon_id=coupon_id, ai_rank_id=1,
  1154. store_meal_name=store_meal_name)
  1155. return response.json(0, {"redirectUrl": sub_info['url'], "orderID": order_id})
  1156. # 正常扣款
  1157. call_clc_url = "{}web/paid2/fail.html".format(SERVER_DOMAIN_SSL)
  1158. if lang != 'cn':
  1159. call_clc_url = call_clc_url.replace('fail.html', 'en_fail.html')
  1160. call_sub_url = "{}cloudstorage/dopaypalcallback?orderID={}&lang={}".format(SERVER_DOMAIN_SSL, order_id,
  1161. lang)
  1162. paypalrestsdk.configure(PAYPAL_CRD)
  1163. payment = paypalrestsdk.Payment({
  1164. "intent": "sale",
  1165. "payer": {"payment_method": "paypal"},
  1166. "redirect_urls": {"return_url": call_sub_url, "cancel_url": call_clc_url},
  1167. "transactions": [{
  1168. "item_list": {"items": [
  1169. {"name": "Cloud video", "sku": "1", "price": price, "currency": "USD", "quantity": 1}]},
  1170. "amount": {"total": price, "currency": currency},
  1171. "description": content}]})
  1172. if not payment.create():
  1173. return response.json(10, payment.error)
  1174. logger.info('paypal创建订单返回----------')
  1175. logger.info(payment)
  1176. payment_id = payment['id'] # 获取paymentID
  1177. for link in payment.links:
  1178. if link.rel == "approval_url":
  1179. approval_url = str(link.href)
  1180. Order_Model.objects.create(orderID=order_id, UID=uid, channel=channel, userID_id=user_id,
  1181. desc=content, payType=pay_type, payTime=now_time,
  1182. price=price, currency=currency, addTime=now_time, updTime=now_time,
  1183. pay_url=approval_url, isSelectDiscounts=is_select_discount,
  1184. commodity_code=commodity_code, commodity_type=commodity_type,
  1185. rank_id=rank, paymentID=payment_id, coupon_id=coupon_id, ai_rank_id=1,
  1186. store_meal_name=store_meal_name)
  1187. return response.json(0, {"redirectUrl": approval_url, "orderID": order_id})
  1188. return response.json(10, 'generate_order_false')
  1189. elif pay_type == 2:
  1190. try:
  1191. ali_pay_obj = AliPayObject()
  1192. alipay = ali_pay_obj.conf()
  1193. subject = store_qs[0]['lang__title'] + store_qs[0]['lang__content']
  1194. order_string = alipay.api_alipay_trade_wap_pay(
  1195. out_trade_no=order_id,
  1196. total_amount=price,
  1197. subject=subject,
  1198. return_url="{}web/paid2/success.html".format(SERVER_DOMAIN_SSL),
  1199. notify_url="{}cloudstorage/doalicallback".format(SERVER_DOMAIN_SSL),
  1200. quit_url="{}web/paid2/fail.html".format(SERVER_DOMAIN_SSL),
  1201. passback_params=quote("lang=" + lang)
  1202. )
  1203. except Exception as e:
  1204. print(repr(e))
  1205. return response.json(10, repr(e))
  1206. else:
  1207. if order_string:
  1208. redirect_url = ali_pay_obj.alipay_prefix + order_string
  1209. Order_Model.objects.create(orderID=order_id, UID=uid, channel=channel, userID_id=user_id,
  1210. desc=content, payType=pay_type, payTime=now_time,
  1211. price=price, currency=currency, addTime=now_time, updTime=now_time,
  1212. pay_url=redirect_url, isSelectDiscounts=is_select_discount,
  1213. commodity_code=commodity_code, commodity_type=commodity_type,
  1214. rank_id=rank, coupon_id=coupon_id, ai_rank_id=1,
  1215. store_meal_name=store_meal_name)
  1216. return JsonResponse(status=200, data={'result_code': 0, 'reason': 'success',
  1217. 'result': {"redirectUrl": redirect_url, "orderID": order_id},
  1218. 'error_code': 0})
  1219. else:
  1220. return response.json(10, '生成订单错误.')
  1221. elif pay_type == 3:
  1222. pay = WechatPayObject()
  1223. notify_url = "{}cloudstorage/dowechatnotify".format(SERVER_DOMAIN_SSL)
  1224. content = CommonService.Package_Type(0, content) # 云存套餐
  1225. # 获取参数
  1226. parameter_dict = pay.get_parameter(order_id, content, float(price) * 100, ip, notify_url,
  1227. quote("lang=" + lang))
  1228. print('parameter_dict', parameter_dict)
  1229. # parameter_dict 参数中获取MWEB_URL 调转页面在路径后面添加redirect_url
  1230. # 统一调用接口
  1231. response = pay.re_finall(orderid=order_id)
  1232. if not response:
  1233. return response.json(10, '生成订单错误.')
  1234. # 回调函数
  1235. Order_Model.objects.create(orderID=order_id, UID=uid, channel=channel, userID_id=user_id,
  1236. desc=content, payType=pay_type, payTime=now_time,
  1237. price=price, currency=currency, addTime=now_time, updTime=now_time,
  1238. pay_url=notify_url, isSelectDiscounts=is_select_discount,
  1239. commodity_code=commodity_code, commodity_type=commodity_type, rank_id=rank,
  1240. ai_rank_id=1, store_meal_name=store_meal_name)
  1241. return JsonResponse(status=200, data={'result_code': 0, 'reason': 'success',
  1242. 'result': response,
  1243. 'orderId': order_id,
  1244. 'error_code': 0})
  1245. def do_experience_order(self, request_dict, user_id, response): # 生成体验订单
  1246. """
  1247. 生成体验订单
  1248. @param request_dict: 请求数据
  1249. @param user_id: 用户id
  1250. @request_dict uid: uid
  1251. @request_dict channel: 通道
  1252. @request_dict commodity_code: 套餐规格码
  1253. @request_dict pay_type: 支付类型
  1254. @request_dict rank: 存储套餐id
  1255. @request_dict cdk: 激活码
  1256. @request_dict lang: 语言
  1257. @param response: 响应
  1258. @return: response
  1259. """
  1260. uid = request_dict.get('uid', None)
  1261. channel = request_dict.get('channel', None)
  1262. commodity_code = request_dict.get('commodity_code', '')
  1263. pay_type = int(request_dict.get('pay_type', None))
  1264. rank = request_dict.get('rank', None)
  1265. cdk = request_dict.get('cdk', None)
  1266. lang = request_dict.get('lang', 'en')
  1267. if uid is None:
  1268. return response.json(444, 'uid.')
  1269. redis_obj = RedisObject()
  1270. is_lock = redis_obj.CONN.setnx(uid + 'do_experience_order', 1)
  1271. redis_obj.CONN.expire(uid + 'do_experience_order', 60)
  1272. logger = logging.getLogger('info')
  1273. if not is_lock:
  1274. return response.json(5)
  1275. if pay_type == 10: # 判断是否已体验过套餐
  1276. experience_context_qs = ExperienceContextModel.objects.filter(uid=uid, experience_type=0)
  1277. if experience_context_qs.exists():
  1278. return response.json(5)
  1279. if cdk is not None and pay_type == 11:
  1280. cdk_qs = CDKcontextModel.objects.filter(cdk=cdk).values('is_activate', 'rank__id', 'rank__commodity_code')
  1281. if not cdk_qs.exists():
  1282. return response.json(10040)
  1283. if cdk_qs[0]['is_activate'] == 1:
  1284. return response.json(10039)
  1285. rank = cdk_qs[0]['rank__id']
  1286. commodity_code = cdk_qs[0]['rank__commodity_code']
  1287. if not all([channel, pay_type, rank]):
  1288. redis_obj.del_data(key=uid + 'do_experience_order')
  1289. return response.json(444, 'channel, pay_type, rank')
  1290. device_info_qs = Device_Info.objects.filter(Q(UID=uid), ~Q(vodPrimaryUserID='')).values('vodPrimaryUserID')
  1291. if device_info_qs.exists():
  1292. if device_info_qs[0]['vodPrimaryUserID'] != user_id:
  1293. if pay_type == 10:
  1294. return response.json(10035)
  1295. if pay_type == 11:
  1296. return response.json(10036)
  1297. device_info_qs = Device_Info.objects.filter(userID_id=user_id, UID=uid, isShare=False, isExist=1)
  1298. if not device_info_qs.exists():
  1299. return response.json(12)
  1300. order_id = CommonService.createOrderID()
  1301. now_time = int(time.time())
  1302. store_qs = Store_Meal.objects.filter(id=rank, lang__lang=lang, is_show=0).values("day", "bucket_id",
  1303. "bucket__storeDay", "expire",
  1304. 'lang__content', 'price',
  1305. 'currency', 'commodity_type')
  1306. if not store_qs.exists():
  1307. return response.json(173)
  1308. bucket_id = store_qs[0]['bucket_id']
  1309. uid_bucket_qs = UID_Bucket.objects.filter(uid=uid).values("id", "bucket_id", "bucket__storeDay",
  1310. "bucket__region", "endTime", "use_status")
  1311. expire = store_qs[0]['expire']
  1312. try:
  1313. with transaction.atomic():
  1314. if uid_bucket_qs.exists():
  1315. uid_bucket = uid_bucket_qs.first()
  1316. if uid_bucket['use_status'] == 1 and uid_bucket['bucket_id'] == bucket_id: # 套餐使用中并且相同套餐叠加过期时间
  1317. end_time = CommonService.calcMonthLater(expire, uid_bucket['endTime'])
  1318. UID_Bucket.objects.filter(id=uid_bucket['id']).update(uid=uid, channel=channel,
  1319. bucket_id=bucket_id,
  1320. endTime=end_time, updateTime=now_time)
  1321. else: # 已过期或者不相同的套餐加入未使用的关联套餐表
  1322. unused_uid_qs = Unused_Uid_Meal.objects.filter(uid=uid, bucket_id=bucket_id)
  1323. nums = 1
  1324. if unused_uid_qs.exists():
  1325. unused_uid_qs.update(num=F('num') + nums)
  1326. else:
  1327. Unused_Uid_Meal.objects.create(uid=uid, channel=channel, addTime=now_time, num=nums,
  1328. expire=store_qs[0]['expire'], bucket_id=bucket_id)
  1329. UID_Bucket.objects.filter(id=uid_bucket['id']).update(has_unused=1)
  1330. uid_bucket_id = uid_bucket['id']
  1331. else:
  1332. end_time = CommonService.calcMonthLater(expire)
  1333. uid_bucket = UID_Bucket.objects.create(uid=uid, channel=channel, bucket_id=bucket_id,
  1334. endTime=end_time, addTime=now_time, updateTime=now_time,
  1335. use_status=1)
  1336. uid_bucket_id = uid_bucket.id
  1337. store_meal_qs = Store_Meal.objects.filter(id=rank, lang__lang='cn', is_show=0).values('lang__title',
  1338. 'lang__content')
  1339. if store_meal_qs.exists():
  1340. store_meal_name = store_meal_qs[0]['lang__title'] + '-' + store_meal_qs[0]['lang__content']
  1341. else:
  1342. store_meal_name = '未知套餐'
  1343. Order_Model.objects.create(orderID=order_id, UID=uid, channel=channel, userID_id=user_id,
  1344. desc=store_qs[0]['lang__content'], payType=pay_type, payTime=now_time,
  1345. price=store_qs[0]['price'], currency=store_qs[0]['currency'],
  1346. addTime=now_time,
  1347. updTime=now_time,
  1348. pay_url="体验版", store_meal_name=store_meal_name,
  1349. commodity_code=commodity_code, commodity_type=store_qs[0]['commodity_type'],
  1350. rank_id=rank, status=1, uid_bucket_id=uid_bucket_id, ai_rank_id=1)
  1351. device_user_qs = Device_User.objects.filter(userID=user_id).values('username')
  1352. device_info_qs = Device_Info.objects.filter(UID=uid, vodPrimaryUserID='', vodPrimaryMaster='')
  1353. if device_info_qs.exists():
  1354. dvq_set_update_dict = {
  1355. 'vodPrimaryUserID': user_id,
  1356. 'vodPrimaryMaster': device_user_qs[0]['username']
  1357. }
  1358. device_info_qs.update(**dvq_set_update_dict)
  1359. sms = 'SMS_219738485'
  1360. date_time = time.strftime("%Y-%m-%d", time.localtime())
  1361. # 如果存在序列号,消息提示用序列号
  1362. device_info_qs = Device_Info.objects.filter(UID=uid).values('serial_number', 'Type')
  1363. serial_number = device_info_qs[0]['serial_number']
  1364. device_type = device_info_qs[0]['Type']
  1365. if serial_number:
  1366. device_name = CommonService.get_full_serial_number(uid, serial_number, device_type)
  1367. else:
  1368. device_name = uid
  1369. sys_msg_text_list = [
  1370. '温馨提示:尊敬的客户,您的' + device_name + '设备在' + date_time + '已成功购买云存套餐',
  1371. 'Dear customer,you already subscribed the cloud storage package successfully for device ' + device_name + ' on ' + time.strftime(
  1372. "%b %dth,%Y", time.localtime())]
  1373. return_url = "{}cloudstorage/payOK?lang={}".format(SERVER_DOMAIN_SSL, lang)
  1374. if pay_type == 10:
  1375. ExperienceContextModel.objects.create(
  1376. experience_type=0,
  1377. uid=uid,
  1378. do_time=now_time
  1379. )
  1380. return_url = "{}cloudstorage/payOK?paytype=10&lang={}".format(SERVER_DOMAIN_SSL, lang)
  1381. date_time = time.strftime("%Y-%m-%d", time.localtime())
  1382. sys_msg_text_list = [
  1383. '温馨提示:尊敬的客户,您的' + device_name + '设备在' + date_time + '已成功开通云存体验套餐',
  1384. 'Dear customer,you already subscribed the free trial cloud storage service successfully for device ' + device_name + ' on ' + time.strftime(
  1385. "%b %dth,%Y", time.localtime())]
  1386. sms = 'SMS_222870823'
  1387. if pay_type == 11:
  1388. update_dict = {'is_activate': 1, 'order': order_id}
  1389. CDKcontextModel.objects.filter(cdk=cdk).update(**update_dict)
  1390. return_url = "{}cloudstorage/payOK?paytype=11&lang={}".format(SERVER_DOMAIN_SSL, lang)
  1391. date_time = time.strftime("%Y-%m-%d", time.localtime())
  1392. sys_msg_text_list = [
  1393. '温馨提示:尊敬的客户,您的' + device_name + '设备在' + date_time + '已成功兑换云存套餐',
  1394. 'Dear customer, you already redeemed for the cloud storage package successfully for device ' + device_name + ' on ' + time.strftime(
  1395. "%b %dth,%Y", time.localtime())]
  1396. sms = 'SMS_219748439'
  1397. self.do_vod_msg_notice(uid, channel, user_id, lang, sys_msg_text_list, sms)
  1398. result = return_url
  1399. redis_obj.del_data(key=uid + 'do_experience_order')
  1400. return response.json(0, result)
  1401. except Exception as e:
  1402. logger.info('出错了~体验云存异常,errLine:{}, errMsg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  1403. redis_obj.del_data(key=uid + 'do_experience_order')
  1404. return response.json(474)
  1405. @staticmethod
  1406. def do_experience_reset(request_dict, response): # 重置设备云存体验
  1407. """
  1408. 重置设备云存体验
  1409. @param request_dict: 请求数据
  1410. @request_dict id: 关联套餐id
  1411. @param response: 响应
  1412. @return: response
  1413. """
  1414. bucket_id = request_dict.get("id", None)
  1415. uid_bucket_qs = UID_Bucket.objects.filter(id=bucket_id)
  1416. if uid_bucket_qs.exists():
  1417. experience_context_qs = ExperienceContextModel.objects.filter(uid=uid_bucket_qs[0].uid)
  1418. if experience_context_qs.exists():
  1419. experience_context_qs.delete()
  1420. Order_Model.objects.filter(uid_bucket_id=bucket_id).delete()
  1421. uid_bucket_qs.delete()
  1422. else:
  1423. return response.json(10007)
  1424. else:
  1425. return response.json(0, '重置云存体验失败')
  1426. return response.json(0, '重置云存体验成功')
  1427. @staticmethod
  1428. def delete_vod_list(request_dict, user_id, response): # 删除播放列表
  1429. """
  1430. 删除播放列表
  1431. @param request_dict: 请求数据
  1432. @param user_id: 用户id
  1433. @request_dict uid: uid
  1434. @request_dict vod_id_list: 云存视频id列表
  1435. @param response: 响应
  1436. @return: response
  1437. """
  1438. uid = request_dict.get('uid', None)
  1439. vod_id_list = request_dict.get('vod_id_list', None)
  1440. is_del_all = request_dict.get('is_del_all', 0)
  1441. if not all([uid, vod_id_list]):
  1442. return response.json(444)
  1443. device_info_qs = Device_Info.objects.filter(userID_id=user_id, UID=uid, isShare=False, isExist=1).values(
  1444. 'vodPrimaryUserID')
  1445. if not device_info_qs.exists() or device_info_qs[0]['vodPrimaryUserID'] != user_id:
  1446. return response.json(12)
  1447. vod_id_list = json.loads(vod_id_list)
  1448. try:
  1449. if is_del_all == 1:
  1450. VodHlsModel.objects.filter(uid=uid).delete()
  1451. # 删除vod_hls分表数据
  1452. split_vod_hls_obj = SplitVodHlsObject()
  1453. split_vod_hls_obj.del_vod_hls_data(uid=uid)
  1454. else:
  1455. if type(vod_id_list).__name__ != 'list':
  1456. return response.json(444)
  1457. VodHlsModel.objects.filter(id__in=vod_id_list).delete()
  1458. # 删除vod_hls分表数据
  1459. split_vod_hls_obj = SplitVodHlsObject()
  1460. split_vod_hls_obj.del_vod_hls_data(id__in=vod_id_list)
  1461. except Exception as e:
  1462. return response.json(424, repr(e))
  1463. else:
  1464. return response.json(0)
  1465. @staticmethod
  1466. def device_commodity(request_dict, user_id, response): # 设备关联套餐列表
  1467. """
  1468. 设备关联套餐列表
  1469. @param request_dict: 请求数据
  1470. @param user_id: 用户id
  1471. @request_dict uid: uid
  1472. @request_dict lang: 语言
  1473. @param response: 响应
  1474. @return: response
  1475. """
  1476. uid = request_dict.get('uid', None)
  1477. lang = request_dict.get('lang', 'en')
  1478. if not uid:
  1479. return response.json(444)
  1480. device_info_qs = Device_Info.objects.filter(userID_id=user_id, UID=uid, isShare=False, isExist=1).values(
  1481. 'vodPrimaryUserID', 'serial_number', 'Type')
  1482. if not device_info_qs.exists() or device_info_qs[0]['vodPrimaryUserID'] != user_id:
  1483. return response.json(12)
  1484. now_time = int(time.time())
  1485. bucket_id_list = []
  1486. store_list = []
  1487. uid_bucket_qs = UID_Bucket.objects.filter(uid=uid, endTime__gte=now_time).values("id", "uid", "bucket__content",
  1488. "use_status", "endTime",
  1489. "has_unused", "bucket__id")
  1490. if not uid_bucket_qs:
  1491. return response.json(10030)
  1492. # 如果存在序列号返回完整序列号
  1493. device_id = uid
  1494. serial_number = device_info_qs[0]['serial_number']
  1495. device_type = device_info_qs[0]['Type']
  1496. if serial_number:
  1497. device_id = CommonService.get_full_serial_number(uid, serial_number, device_type)
  1498. uid_bucket_qs[0]['uid'] = device_id
  1499. uid_bucket_qs[0]['storage'] = 0
  1500. has_unused = uid_bucket_qs[0]['has_unused']
  1501. del uid_bucket_qs[0]['has_unused']
  1502. store_list.append(uid_bucket_qs[0])
  1503. bucket_id_list.append(uid_bucket_qs[0]['bucket__id'])
  1504. if has_unused == 1:
  1505. unused_uid_qs = Unused_Uid_Meal.objects.filter(uid=uid).annotate(unused_id=F('id')).values("unused_id",
  1506. "uid",
  1507. "bucket__content",
  1508. "num",
  1509. "bucket__id",
  1510. "expire")
  1511. month = 'month' if lang != 'cn' else '个月'
  1512. for unused_uid in unused_uid_qs:
  1513. storage_time = unused_uid['num'] * unused_uid['expire']
  1514. if lang != 'cn' and storage_time > 1: # 英文大于一个月使用复数
  1515. month += 's'
  1516. storage = str(storage_time) + month
  1517. unused_dict = {
  1518. "id": unused_uid['unused_id'],
  1519. "uid": device_id,
  1520. "bucket__content": unused_uid['bucket__content'],
  1521. "use_status": 0,
  1522. "endTime": 0,
  1523. "bucket__id": unused_uid['bucket__id'],
  1524. "storage": storage,
  1525. }
  1526. store_list.append(unused_dict)
  1527. bucket_id_list.append(unused_uid['bucket__id'])
  1528. store_qs = Store_Meal.objects.filter(bucket__id__in=bucket_id_list, lang__lang=lang).annotate(
  1529. title=F('lang__title'), content=F('lang__content')).values('lang__content', 'lang__lang',
  1530. 'bucket__id', 'lang__title')
  1531. for index, value in enumerate(store_list):
  1532. for store in store_qs:
  1533. if value['bucket__id'] == store['bucket__id']:
  1534. value['bucket__content'] = store['lang__title'] + '-' + store['lang__content']
  1535. return response.json(0, list(store_list))
  1536. @staticmethod
  1537. def switch_device_commodity(request_dict, user_id, response): # 提前使用设备关联套餐
  1538. """
  1539. 提前使用设备关联套餐
  1540. @param request_dict: 请求数据
  1541. @param user_id: 用户id
  1542. @request_dict uid: uid
  1543. @request_dict switch_commodity_id: 未使用关联套餐id
  1544. @param response: 响应
  1545. @return: response
  1546. """
  1547. uid = request_dict.get('uid', None)
  1548. unused_id = request_dict.get('switch_commodity_id', None)
  1549. if not all([uid, unused_id]):
  1550. return response.json(444)
  1551. device_info_qs = Device_Info.objects.filter(userID_id=user_id, UID=uid, isShare=False, isExist=1).values(
  1552. 'vodPrimaryUserID')
  1553. if not device_info_qs.exists() or device_info_qs[0]['vodPrimaryUserID'] != user_id:
  1554. return response.json(12)
  1555. # 切换设备套餐关联
  1556. using_uid_bucket_qs = UID_Bucket.objects.filter(uid=uid, has_unused=1).values("id", "uid", "endTime",
  1557. "bucket__content", "addTime")
  1558. unused_uid_bucket_qs = Unused_Uid_Meal.objects.filter(id=unused_id).values("id", "uid", "channel", "addTime",
  1559. "expire", "num", "bucket_id")
  1560. if not unused_uid_bucket_qs.exists() or not using_uid_bucket_qs.exists():
  1561. return response.json(10030)
  1562. unused_uid_bucket = unused_uid_bucket_qs.first()
  1563. now_time = int(time.time())
  1564. try:
  1565. with transaction.atomic():
  1566. count_unused = Unused_Uid_Meal.objects.filter(uid=uid).count()
  1567. has_unused = 1 if count_unused > 1 else 0
  1568. end_time = CommonService.calcMonthLater(unused_uid_bucket['expire'] * unused_uid_bucket['num'])
  1569. UID_Bucket.objects.filter(uid=uid).update(channel=unused_uid_bucket['channel'], endTime=end_time,
  1570. bucket_id=unused_uid_bucket['bucket_id']
  1571. , updateTime=now_time, use_status=1,
  1572. has_unused=has_unused)
  1573. Unused_Uid_Meal.objects.filter(id=unused_id).delete()
  1574. StsCrdModel.objects.filter(uid=uid).delete() # 删除sts记录
  1575. # VodHlsModel.objects.filter(uid=uid).delete() # 删除播放列表,后期数据量多时应该考虑延后删除
  1576. return response.json(0)
  1577. except Exception:
  1578. return response.json(474)
  1579. @staticmethod
  1580. def has_vod(request_dict, user_id, response):
  1581. """
  1582. 云存日期
  1583. @param request_dict: 请求数据
  1584. @param user_id: 用户id
  1585. @request_dict uid: uid
  1586. @request_dict channel: 通道
  1587. @param response: 响应
  1588. @return: response
  1589. """
  1590. uid = request_dict.get('uid', None)
  1591. channel = request_dict.get('channel', 1)
  1592. if not uid:
  1593. return response.json(444)
  1594. device_info_qs = Device_Info.objects.filter(userID_id=user_id, UID=uid, isShare=False).values(
  1595. 'vodPrimaryUserID',
  1596. 'vodPrimaryMaster')
  1597. if not device_info_qs.exists():
  1598. return response.json(12)
  1599. if device_info_qs[0]['vodPrimaryUserID'] != user_id:
  1600. return response.json(10034)
  1601. now_time = int(time.time())
  1602. uid_bucket_qs = UID_Bucket.objects.filter(uid=uid, endTime__gte=now_time, channel=channel).values(
  1603. 'bucket_id').order_by(
  1604. 'addTime')
  1605. if not uid_bucket_qs.exists():
  1606. return response.json(10030)
  1607. # vod_hls_qs = VodHlsModel.objects.extra(select={'date': "FROM_UNIXTIME(time,'%%Y-%%m-%%d')"}).values(
  1608. # 'date').filter(uid=uid, endTime__gte=now_time, channel=channel).annotate(count=Count('time')).order_by(
  1609. # '-date')[:31]
  1610. split_vod_hls_obj = SplitVodHlsObject()
  1611. vod_hls_qs = split_vod_hls_obj.get_vod_hls_date(uid=uid, end_time__gte=now_time, channel=channel)
  1612. had_vod_list = []
  1613. for vod in vod_hls_qs:
  1614. had_vod_list.append({
  1615. 'timestamp': CommonService.str_to_timestamp(vod['date'], '%Y-%m-%d'),
  1616. 'vod_count': vod['count'],
  1617. 'date_format': vod['date'],
  1618. })
  1619. had_vod_list = sorted(had_vod_list, key=lambda item: -item['timestamp'])[:31]
  1620. return response.json(0, had_vod_list)
  1621. @staticmethod
  1622. def video_playback_time(request_dict, user_id, response):
  1623. """
  1624. 存储视频播放数据
  1625. @param request_dict: 请求数据
  1626. @param user_id: 用户id
  1627. @request_dict parms: 参数列表
  1628. @param response: 响应
  1629. @return: response
  1630. """
  1631. params = request_dict.get('parms', None)
  1632. if not params:
  1633. return response.json(444)
  1634. try:
  1635. params = eval(params)
  1636. bulk = []
  1637. for parm in params:
  1638. parm['userID'] = user_id
  1639. # 解密uid
  1640. for i in range(1, 4):
  1641. parm['uid'] = base64.b64decode(parm['uid'])
  1642. parm['uid'] = parm['uid'].decode('utf-8')
  1643. parm['uid'] = parm['uid'][i:-i]
  1644. video_playback_time = VideoPlaybackTimeModel(**parm)
  1645. bulk.append(video_playback_time)
  1646. VideoPlaybackTimeModel.objects.bulk_create(bulk)
  1647. return response.json(0)
  1648. except Exception as e:
  1649. print(e)
  1650. return response.json(500, repr(e))
  1651. def do_vod_msg_notice(self, uid, channel, user_id, lang, sys_msg_text_list, sms): # 云存操作系统消息
  1652. """
  1653. 云存操作系统消息
  1654. @param uid: uid
  1655. @param channel: 通道
  1656. @param user_id: 用户id
  1657. @param lang: 语言
  1658. @param sys_msg_text_list: 消息列表
  1659. @param sms: sms码
  1660. @return: response
  1661. """
  1662. try:
  1663. logger = logging.getLogger('log')
  1664. logger.info('进来了')
  1665. if lang == 'cn':
  1666. sys_msg_text = sys_msg_text_list[0]
  1667. else:
  1668. sys_msg_text = sys_msg_text_list[1]
  1669. now_time = int(time.time())
  1670. create_data = {'userID_id': user_id, 'msg': sys_msg_text, 'addTime': now_time,
  1671. 'updTime': now_time, 'uid': uid, 'eventType': 0}
  1672. SysMsgModel.objects.create(**create_data)
  1673. user_qs = Device_User.objects.filter(userID=user_id)
  1674. if user_qs.exists():
  1675. user = user_qs.first()
  1676. username = user.username
  1677. data_valid = DataValid()
  1678. if data_valid.email_validate(username):
  1679. S3Email().faEmail(sys_msg_text, username)
  1680. elif data_valid.mobile_validate(username):
  1681. # 如果存在序列号,消息提示用序列号
  1682. device_info_qs = Device_Info.objects.filter(UID=uid).values('serial_number', 'Type')
  1683. if device_info_qs.exists():
  1684. serial_number = device_info_qs[0]['serial_number']
  1685. device_type = device_info_qs[0]['Type']
  1686. if serial_number:
  1687. device_name = CommonService.get_full_serial_number(uid, serial_number, device_type)
  1688. else:
  1689. device_name = uid
  1690. params = '{"devname":"%s","submittime":"%s"}' % (
  1691. device_name, time.strftime("%Y-%m-%d", time.localtime()))
  1692. self.send_message(username, params, sms)
  1693. logger.info('出去了')
  1694. except Exception as e:
  1695. return repr(e)
  1696. def do_vod_msg_end(self, response): # 云存到期续费提醒 提前3天
  1697. """
  1698. 云存到期续费提醒
  1699. @param response: 响应
  1700. @return: response
  1701. """
  1702. now_time = int(time.time())
  1703. # 过期前第7天提示一次
  1704. uid_bucket_qs = UID_Bucket.objects.filter(
  1705. Q(endTime__gt=now_time + 3600 * 144) & Q(endTime__lte=(now_time + 3600 * 168))).values('id', 'uid',
  1706. 'bucket__area',
  1707. 'channel', 'endTime')
  1708. self.do_vod_msg(now_time, uid_bucket_qs)
  1709. # 过期前第3天提示一次
  1710. uid_bucket_qs = UID_Bucket.objects.filter(
  1711. Q(endTime__gt=now_time + 3600 * 48) & Q(endTime__lte=(now_time + 3600 * 72))).values('id', 'uid',
  1712. 'bucket__area',
  1713. 'channel', 'endTime')
  1714. self.do_vod_msg(now_time, uid_bucket_qs)
  1715. return response.json(0)
  1716. def do_vod_msg(self, now_time, qs):
  1717. """
  1718. 云存到期续费提醒
  1719. @param now_time: 现在时间
  1720. @param qs: 查询集
  1721. @return: response
  1722. """
  1723. msg_list = []
  1724. ids = []
  1725. for item in qs:
  1726. ids.append(item['id'])
  1727. order_qs = Order_Model.objects.filter(uid_bucket_id__in=ids).values('userID_id', 'uid_bucket_id')
  1728. for item in qs:
  1729. for order in order_qs:
  1730. if item['id'] == order['uid_bucket_id']:
  1731. # 如果存在序列号,消息提示用序列号
  1732. uid = item['uid']
  1733. device_info_qs = Device_Info.objects.filter(UID=uid).values('serial_number', 'Type')
  1734. serial_number = device_info_qs[0]['serial_number']
  1735. device_type = device_info_qs[0]['Type']
  1736. if serial_number and device_type == 101:
  1737. device_name = CommonService.get_full_serial_number(uid, serial_number, device_type)
  1738. else:
  1739. device_name = uid
  1740. if item['bucket__area'] == 'cn':
  1741. sys_msg_text = "温馨提示:尊敬的客户,您%s设备的云存套餐将在%s到期" % (
  1742. device_name, time.strftime("%Y-%m-%d", time.localtime(item['endTime'])))
  1743. else:
  1744. sys_msg_text = 'Dear customer,the cloud storage package for your device %s will expire on %s' % \
  1745. (device_name, time.strftime('%m-%d-%y', time.localtime(item['endTime'])))
  1746. msg_list.append(SysMsgModel(
  1747. userID_id=order['userID_id'],
  1748. addTime=now_time,
  1749. updTime=now_time,
  1750. uid=item['uid'],
  1751. eventType=0,
  1752. msg=sys_msg_text,
  1753. status=0
  1754. ))
  1755. SysMsgModel.objects.bulk_create(msg_list)
  1756. user_qs = Device_User.objects.filter(userID=order['userID_id'])
  1757. if user_qs.exists():
  1758. user = user_qs.first()
  1759. username = user.username
  1760. data_valid = DataValid()
  1761. if data_valid.email_validate(username):
  1762. S3Email().faEmail(sys_msg_text, username)
  1763. elif data_valid.mobile_validate(username):
  1764. params = u'{"devname":"%s","submittime":"%s"}' % (
  1765. device_name, time.strftime("%Y-%m-%d", time.localtime(item['endTime'])))
  1766. self.send_message(username, params, 'SMS_219748440')
  1767. @staticmethod
  1768. def send_message(phone, params, temp_msg):
  1769. """
  1770. 发送手机消息
  1771. @param phone: 用户名
  1772. @param params: 消息参数
  1773. @param temp_msg: sms码
  1774. """
  1775. sign_ms = '周视'
  1776. ali_sms = AliSmsObject()
  1777. ali_sms.send_code_sms_cloud(phone=phone, params=params, sign_name=sign_ms, temp_msg=temp_msg)
  1778. @staticmethod
  1779. def do_refund(request_dict, response):
  1780. """
  1781. 退款
  1782. @param request_dict: 请求数据
  1783. @request_dict orderID: 订单id
  1784. @request_dict refund_amount: 退款金额
  1785. @param response: 响应
  1786. @return: response
  1787. """
  1788. order_id = request_dict.get('orderID', None) # 商户订单号
  1789. refund_amount = request_dict.get('refund_amount', None) # 退款金额
  1790. if not all([order_id, refund_amount]):
  1791. return response.json(444)
  1792. try:
  1793. order_qs = Order_Model.objects.filter(orderID=order_id) \
  1794. .values('status', 'payType', 'price', 'refunded_amount',
  1795. 'currency', 'paymentID', 'trade_no')
  1796. if not order_qs.exists():
  1797. return response.json(173)
  1798. # 支付状态不为支付成功和退款失败和部分退款
  1799. status = order_qs[0]['status']
  1800. if status != 1 and status != 4 and status != 6:
  1801. return response.json(805)
  1802. refund_amount = float(refund_amount)
  1803. now_time = int(time.time())
  1804. pay_type = order_qs[0]['payType']
  1805. price = order_qs[0]['price'] # 订单金额
  1806. refunded_amount = order_qs[0]['refunded_amount'] # 已退款金额
  1807. currency = order_qs[0]['currency'] # 货币
  1808. # 判断是否符合付款条件
  1809. if refunded_amount == float(price): # 已全额退款
  1810. return response.json(805)
  1811. if refund_amount + refunded_amount > float(price): # 退款金额超出订单价格
  1812. return response.json(805)
  1813. # 部分退款标识
  1814. is_partial_refund = True if (float(price) > refund_amount + refunded_amount) else False
  1815. out_request_no = str(time.strftime('%Y%m%d%H%M%S', time.localtime(now_time))) # 退款请求号
  1816. # 根据支付类型处理退款
  1817. if pay_type == 1: # PayPal
  1818. payment_id = order_qs[0]['paymentID'] # PayPal PAYMENT_ID
  1819. trade_no = order_qs[0]['trade_no']
  1820. sale_id = ''
  1821. paypalrestsdk.configure(PAYPAL_CRD)
  1822. if payment_id:
  1823. payment = paypalrestsdk.Payment.find(payment_id)
  1824. related_resources = payment['transactions'][0]['related_resources']
  1825. if not related_resources:
  1826. return response.json(805)
  1827. sale = related_resources[0]['sale']
  1828. # 没退款过 'state' 不为 'completed' 或 已退款过但 'state' 不为 'partially_refunded'
  1829. if (refunded_amount == 0 and sale['state'] != 'completed') or (
  1830. refunded_amount != 0 and sale['state'] != 'partially_refunded'):
  1831. return response.json(805)
  1832. sale_id = sale['id']
  1833. sale_id = sale_id if sale_id else trade_no
  1834. paypal_sale = paypalrestsdk.Sale.find(sale_id)
  1835. if not paypal_sale or paypal_sale['state'] != 'completed':
  1836. return response.json(805)
  1837. refund = paypal_sale.refund({
  1838. 'amount': {
  1839. 'total': refund_amount,
  1840. 'currency': currency
  1841. }
  1842. })
  1843. refund_success = True if refund.success() else False
  1844. elif pay_type == 2: # 支付宝
  1845. ali_pay_obj = AliPayObject()
  1846. alipay = ali_pay_obj.conf()
  1847. refund_response = alipay.api_alipay_trade_refund(refund_amount=refund_amount, out_trade_no=order_id,
  1848. out_request_no=out_request_no)
  1849. refund_success = True if (refund_response['code'] == '10000') else False
  1850. elif pay_type == 3: # 微信
  1851. wechat_pay_obj = WechatPayObject()
  1852. refund_fee = int(refund_amount * 100) # 退款金额,单位为分,只能为整数
  1853. success = wechat_pay_obj.refund(out_trade_no=order_id, out_refund_no=out_request_no,
  1854. total_fee=refund_fee, refund_fee=refund_fee)
  1855. refund_success = True if success else False
  1856. else: # 不支持退款的支付类型
  1857. return response.json(805)
  1858. # 更新订单状态和已退款金额
  1859. update_dict = {'updTime': now_time}
  1860. if refund_success:
  1861. update_dict['status'] = 6 if is_partial_refund else 5
  1862. update_dict['refunded_amount'] = refunded_amount + refund_amount
  1863. else:
  1864. update_dict['status'] = 4
  1865. order_qs.update(**update_dict)
  1866. return response.json(0)
  1867. except Exception as e:
  1868. logger = logging.getLogger('info')
  1869. logger.info('异常详情,errLine:{}, errMsg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  1870. return response.json(500, repr(e))