InAppPurchaseController.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232
  1. # @Author : Rocky
  2. # @File : InAppPurchaseController.py
  3. # @Time : 2024/6/21 9:10
  4. import time
  5. import itunesiap
  6. from django.db.models import Q
  7. from django.views import View
  8. from Controller.CheckUserData import DataValid
  9. from Model.models import Order_Model, Store_Meal, Device_Info, UID_Bucket, Unused_Uid_Meal, AiService, Device_User, \
  10. SysMsgModel
  11. from Object.AWS.S3Email import S3Email
  12. from Object.AliSmsObject import AliSmsObject
  13. from Object.RedisObject import RedisObject
  14. from Service.CommonService import CommonService
  15. class InAppPurchaseView(View):
  16. def get(self, request, *args, **kwargs):
  17. request.encoding = 'utf-8'
  18. operation = kwargs.get('operation')
  19. return self.validation(request.GET, request, operation)
  20. def post(self, request, *args, **kwargs):
  21. request.encoding = 'utf-8'
  22. operation = kwargs.get('operation')
  23. return self.validation(request.POST, request, operation)
  24. def validation(self, request_dict, request, operation):
  25. if operation == 'AppStoreServerNotifications': # App Store服务器通知
  26. pass
  27. token_code, user_id, response = CommonService.verify_token_get_user_id(request_dict, request)
  28. if token_code != 0:
  29. return response.json(token_code)
  30. if operation == 'verifyTransaction': # 获取商品列表
  31. return self.verify_transaction(user_id, request_dict, response)
  32. @classmethod
  33. def verify_transaction(cls, user_id, request_dict, response):
  34. """
  35. 认证交易
  36. @param user_id: 用户id
  37. @param request_dict: 请求参数
  38. @request_dict receipt: 收据
  39. @param response: 响应对象
  40. @return: response
  41. """
  42. receipt = request_dict.get('receipt', None)
  43. uid = request_dict.get('uid', None)
  44. lang = request_dict.get('lang', 'en')
  45. channel = request_dict.get('channel', None)
  46. # redis加锁,防止订单重复
  47. redis_obj = RedisObject()
  48. redis_key = uid + 'in_app_purchase'
  49. is_lock = redis_obj.CONN.setnx(redis_key, 1)
  50. redis_obj.CONN.expire(redis_key, 60)
  51. if not is_lock:
  52. return response.json(5)
  53. try:
  54. device_info_qs = Device_Info.objects.filter(userID_id=user_id, UID=uid, isShare=False, isExist=1).values(
  55. 'vodPrimaryUserID',
  56. 'vodPrimaryMaster')
  57. if not device_info_qs.exists():
  58. return response.json(12)
  59. device_info_qs = Device_Info.objects.filter(Q(UID=uid), ~Q(vodPrimaryUserID='')).values('vodPrimaryUserID')
  60. if device_info_qs.exists():
  61. if device_info_qs[0]['vodPrimaryUserID'] != user_id:
  62. return response.json(10033)
  63. order_id = CommonService.createOrderID()
  64. verify_response = itunesiap.verify(receipt, env=itunesiap.env.sandbox)
  65. print(verify_response.receipt.in_app[0]['product_id']) # response.receipt.last_in_app.product_id
  66. product_id = verify_response.receipt.in_app[0]['product_id']
  67. pay_type = 4
  68. now_time = int(time.time())
  69. store_qs = Store_Meal.objects.filter(
  70. product_id=product_id, lang__lang=lang, is_show=0).\
  71. values(
  72. 'id', 'currency', 'price', 'lang__content', 'day', 'commodity_type', 'lang__title', 'expire',
  73. 'commodity_code', 'discount_price', 'bucket__mold', 'cycle_config_id', 'is_ai')
  74. if not store_qs.exists():
  75. return response.json(173)
  76. rank_id = store_qs[0]['id']
  77. bucket_id = store_qs[0]['bucket_id']
  78. currency = store_qs[0]['currency']
  79. price = store_qs[0]['price']
  80. is_ai = store_qs[0]['is_ai']
  81. expire = store_qs[0]['expire']
  82. end_time = CommonService.calcMonthLater(expire)
  83. content = store_qs[0]['lang__content']
  84. commodity_code = store_qs[0]['commodity_code']
  85. commodity_type = store_qs[0]['commodity_type']
  86. order_type = 1 if is_ai else 0
  87. store_meal_qs = Store_Meal.objects.filter(id=rank_id, lang__lang='cn', is_show=0).\
  88. values('lang__title', 'lang__content')
  89. if store_meal_qs.exists():
  90. store_meal_name = store_meal_qs[0]['lang__title'] + '-' + store_meal_qs[0]['lang__content']
  91. else:
  92. store_meal_name = '未知套餐'
  93. # 查询设备是否已开过云存
  94. use_flag = True
  95. uid_bucket_qs = UID_Bucket.objects.filter(uid=uid).\
  96. values('id', 'bucket_id', 'bucket__region', 'endTime', 'use_status')
  97. if uid_bucket_qs.exists():
  98. uid_bucket = uid_bucket_qs.first()
  99. uid_bucket_id = uid_bucket['id']
  100. # 叠加相同套餐的过期时间
  101. if uid_bucket['use_status'] == 1 and uid_bucket['endTime'] > now_time:
  102. Unused_Uid_Meal.objects.create(
  103. uid=uid, channel=channel, addTime=now_time, order_id=order_id, expire=expire, is_ai=is_ai,
  104. bucket_id=bucket_id)
  105. UID_Bucket.objects.filter(id=uid_bucket_id).update(has_unused=1)
  106. use_flag = False
  107. # 更新套餐的过期时间
  108. else:
  109. UID_Bucket.objects.filter(id=uid_bucket_id).update(
  110. channel=channel, bucket_id=bucket_id, endTime=end_time, updateTime=now_time, use_status=1,
  111. orderId=order_id)
  112. else:
  113. uid_bucket = UID_Bucket.objects.create(
  114. uid=uid, channel=channel, bucket_id=bucket_id, endTime=end_time, use_status=1, orderId=order_id,
  115. addTime=now_time, updateTime=now_time)
  116. uid_bucket_id = uid_bucket.id
  117. # 开通AI服务
  118. if is_ai and use_flag:
  119. ai_service = AiService.objects.filter(uid=uid, channel=channel)
  120. # 有正在使用的套餐,叠加套餐时间,否则创建
  121. if ai_service.exists():
  122. ai_service.update(updTime=now_time, use_status=1, orders_id=order_id, endTime=end_time)
  123. else:
  124. AiService.objects.create(
  125. uid=uid, channel=channel, detect_status=1, use_status=1, orders_id=order_id,
  126. addTime=now_time, updTime=now_time, endTime=end_time)
  127. Order_Model.objects.create(
  128. orderID=order_id, UID=uid, channel=channel, userID_id=user_id, desc=content, payType=pay_type,
  129. payTime=now_time, price=price, currency=currency, addTime=now_time, updTime=now_time,
  130. order_type=order_type, commodity_code=commodity_code, commodity_type=commodity_type, rank_id=rank_id,
  131. ai_rank_id=1, status=1, create_vod=1, store_meal_name=store_meal_name, uid_bucket_id=uid_bucket_id)
  132. # 发送云存开通信息
  133. date_time = time.strftime("%Y-%m-%d", time.localtime())
  134. # 如果存在序列号,消息提示用序列号
  135. device_info_qs = Device_Info.objects.filter(UID=uid).values('serial_number', 'Type')
  136. serial_number = device_info_qs[0]['serial_number']
  137. device_type = device_info_qs[0]['Type']
  138. if serial_number:
  139. device_name = CommonService.get_full_serial_number(uid, serial_number, device_type)
  140. else:
  141. device_name = uid
  142. sys_msg_text_list = [
  143. '温馨提示:尊敬的客户,您的{}设备在{}已成功购买云存套餐'.format(device_name, date_time),
  144. 'Dear customer,you already subscribed the cloud storage package successfully for device {} on '.
  145. format(device_name, time.strftime('%b %dth,%Y', time.localtime()))]
  146. cls.do_vod_msg_notice(uid, user_id, lang, sys_msg_text_list)
  147. redis_obj.del_data(redis_key)
  148. return response.json(0)
  149. except Exception as e:
  150. redis_obj.del_data(redis_key)
  151. return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
  152. @classmethod
  153. def do_vod_msg_notice(cls, uid, user_id, lang, sys_msg_text_list):
  154. """
  155. 发送云存开通信息
  156. @param uid: uid
  157. @param user_id: 用户id
  158. @param lang: 语言
  159. @param sys_msg_text_list: 消息列表
  160. @return: response
  161. """
  162. if lang == 'cn':
  163. sys_msg_text = sys_msg_text_list[0]
  164. else:
  165. sys_msg_text = sys_msg_text_list[1]
  166. now_time = int(time.time())
  167. create_data = {
  168. 'userID_id': user_id,
  169. 'msg': sys_msg_text,
  170. 'addTime': now_time,
  171. 'updTime': now_time,
  172. 'uid': uid,
  173. 'eventType': 0
  174. }
  175. SysMsgModel.objects.create(**create_data)
  176. # 不接收邮件用户
  177. if user_id == '167015836969813800138000':
  178. return
  179. user_qs = Device_User.objects.filter(userID=user_id)
  180. if user_qs.exists():
  181. user = user_qs.first()
  182. username = user.username
  183. data_valid = DataValid()
  184. if data_valid.email_validate(username):
  185. S3Email().faEmail(sys_msg_text, username)
  186. elif data_valid.mobile_validate(username):
  187. # 如果存在序列号,消息提示用序列号
  188. device_info_qs = Device_Info.objects.filter(UID=uid).values('serial_number', 'Type')
  189. if device_info_qs.exists():
  190. serial_number = device_info_qs[0]['serial_number']
  191. device_type = device_info_qs[0]['Type']
  192. if serial_number:
  193. device_name = CommonService.get_full_serial_number(uid, serial_number, device_type)
  194. else:
  195. device_name = uid
  196. params = '{"devname":"%s","submittime":"%s"}' % (
  197. device_name, time.strftime("%Y-%m-%d", time.localtime()))
  198. cls.send_message(username, params, 'SMS_219738485')
  199. @staticmethod
  200. def send_message(phone, params, temp_msg):
  201. """
  202. 发送手机消息
  203. @param phone: 用户名
  204. @param params: 消息参数
  205. @param temp_msg: sms码
  206. """
  207. sign_ms = '周视'
  208. ali_sms = AliSmsObject()
  209. ali_sms.send_code_sms_cloud(phone=phone, params=params, sign_name=sign_ms, temp_msg=temp_msg)