CloudStorage.py 125 KB

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