Test.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. """
  4. @Copyright (C) ansjer cop Video Technology Co.,Ltd.All rights reserved.
  5. @AUTHOR: ASJRD018
  6. @NAME: Ansjer
  7. @software: PyCharm
  8. @DATE: 2018/5/22 13:58
  9. @Version: python3.6
  10. @MODIFY DECORD:ansjer dev
  11. @file: Test.py
  12. @Contact: chanjunkai@163.com
  13. """
  14. from django.views.generic.base import View
  15. import os
  16. '''
  17. http://192.168.136.40:8077/Test
  18. '''
  19. from Object.ResponseObject import ResponseObject
  20. from Ansjer.config import BASE_DIR
  21. import json
  22. from alipay import AliPay
  23. import time
  24. import apns2
  25. # 测试接口sdk
  26. class Test(View):
  27. def get(self, request, *args, **kwargs):
  28. request_dict = request.GET
  29. # return self.do_apns(request_dict)
  30. # return self.do_get_putOss_url(request.GET)
  31. # from django.http import JsonResponse
  32. # return JsonResponse(status=200,data={
  33. # 'code': 173,
  34. # 'msg': 'data is not exist'})
  35. test_push_type = request_dict.get('test_push_type')
  36. if test_push_type == 'jpush':
  37. return self.jgPush(request)
  38. elif test_push_type == 'fcm':
  39. return self.do_fcm_push(request)
  40. elif test_push_type == 'apns':
  41. return self.do_apns(request.GET)
  42. return self.do_gcm_push(request)
  43. return self.do_alipay_query_status()
  44. def do_alipay_query_status(self):
  45. response = ResponseObject()
  46. # app_private_key_string = open(BASE_DIR + '/Ansjer/file/alipay/alipay_private_2048.pem').read()
  47. # alipay_public_key_string = open(BASE_DIR + '/Ansjer/file/alipay/alipay_public_2048.pem').read()
  48. app_private_key_string = open(BASE_DIR + '/Ansjer/file/alipay/zosi_alipay_private_2048.pem').read()
  49. alipay_public_key_string = open(BASE_DIR + '/Ansjer/file/alipay/zosi_alipay_public_2048.pem').read()
  50. alipay = AliPay(
  51. # appid="2016092200569234",
  52. appid="2019041663958142",
  53. app_notify_url=None, # the default notify path
  54. app_private_key_string=app_private_key_string,
  55. alipay_public_key_string=alipay_public_key_string,
  56. sign_type="RSA2", # RSA or RSA2
  57. debug=False # False by default
  58. )
  59. # check order status
  60. print("now sleep 3s")
  61. # time.sleep(3)
  62. result = alipay.api_alipay_trade_query(out_trade_no="20190424085757859937")
  63. if result.get("trade_status", "") == "TRADE_SUCCESS":
  64. paid = True
  65. print(paid)
  66. return response.json(0)
  67. else:
  68. print("not paid...")
  69. return response.json(404)
  70. def do_fcm_push(self, request):
  71. rg_id = request.GET.get('rg_id', '')
  72. serverKey = request.GET.get('serverKey', '')
  73. push_type = request.GET.get('push_type', None)
  74. # Send to single device.
  75. from pyfcm import FCMNotification
  76. # OR initialize with proxies
  77. # proxy_dict = {
  78. # "http": "http://127.0.0.1",
  79. # "https": "http://127.0.0.1",
  80. # }
  81. # push_service = FCMNotification(api_key="<api-key>", proxy_dict=proxy_dict)
  82. push_service = FCMNotification(api_key=serverKey)
  83. # Your api-key can be gotten from: https://console.firebase.google.com/project/<project-name>/settings/cloudmessaging
  84. registration_id = rg_id
  85. message_title = "Zosi Smart(xxxx 007)"
  86. now_time = int(time.time())
  87. data = {"alert": "Motion ", "event_time": now_time, "event_type": "51", "msg": "",
  88. "received_at": now_time, "sound": "sound.aif", "uid": "98UXAA8BRPA35VAL111A", "zpush": "1"}
  89. # message_body = json.dumps(data)
  90. message_body = '警告:Motion Channel:1 日期:{tt}'.format(
  91. tt=str(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(time.time()))))
  92. print(message_body)
  93. from var_dump import var_dump
  94. if push_type == '1':
  95. var_dump('1111111')
  96. result = push_service.single_device_data_message(registration_id=registration_id, data_message=data)
  97. elif push_type == '2':
  98. var_dump('22222222')
  99. result = push_service.notify_single_device(registration_id=registration_id, message_title=message_title,
  100. message_body=message_body, data_message=data)
  101. else:
  102. var_dump('333333')
  103. result = push_service.notify_single_device(registration_id=registration_id, message_title=message_title,
  104. message_body=message_body)
  105. from var_dump import var_dump
  106. var_dump(result)
  107. response = ResponseObject()
  108. return response.json(0, result)
  109. def do_apns(self, request_dict):
  110. token_val = request_dict.get('token_val', None)
  111. pem_path = os.path.join(BASE_DIR, 'Ansjer/file/apns_pem/apns-dev2.pem')
  112. # pem_path = os.path.join(BASE_DIR, 'Ansjer/file/apns_pem/apns-loocamccloud.pem')
  113. print(pem_path)
  114. response = ResponseObject()
  115. try:
  116. n_time = int(time.time())
  117. cli = apns2.APNSClient(mode="dev", client_cert=pem_path,
  118. password='111111')
  119. push_data = {"alert": "Motion ", "event_time": n_time, "event_type": 51, "msg": "",
  120. "received_at": n_time, "sound": "sound.aif", "uid": 'XFDJUHUIOKJHYTGSFFDR', "zpush": "1", "channel": 1}
  121. alert = apns2.PayloadAlert(body='通道:1 uid:XFDJUHUIOKJHYTGSFFDR', title='ansjer')
  122. payload = apns2.Payload(alert=alert, custom=push_data)
  123. n = apns2.Notification(payload=payload, priority=apns2.PRIORITY_LOW)
  124. res = cli.push(n=n, device_token=token_val, topic='com.ansjer.loocamccloud')
  125. # assert res.status_code == 200, res.reason
  126. # assert res.apns_id
  127. if res.status_code == 200:
  128. return response.json(0)
  129. else:
  130. return response.json(404, res.reason)
  131. except Exception as e:
  132. return response.json(10, repr(e))
  133. def do_get_putOss_url(self, request_dict):
  134. import oss2
  135. obj_name = request_dict.get('obj_name', '')
  136. # 阿里云主账号AccessKey拥有所有API的访问权限,风险很高。强烈建议您创建并使用RAM账号进行API访问或日常运维,请登录 https://ram.console.aliyun.com 创建RAM账号。
  137. auth = oss2.Auth('LTAIyMkGfEdogyL9', '71uIjpsqVOmF7DAITRyRuc259jHOjO')
  138. # Endpoint以杭州为例,其它Region请按实际情况填写。
  139. bucket = oss2.Bucket(auth, 'oss-cn-shenzhen.aliyuncs.com', 'apg')
  140. # 设置此签名URL在60秒内有效。
  141. url = bucket.sign_url('PUT', obj_name, 7200)
  142. response = ResponseObject()
  143. return response.json(0, url)
  144. def do_gcm_push(self, request):
  145. import json
  146. import requests
  147. response = ResponseObject()
  148. rg_id = request.GET.get('rg_id', '')
  149. serverKey = request.GET.get('serverKey', '')
  150. if not rg_id or not serverKey:
  151. return response.json(444)
  152. now_time = int(time.time())
  153. data = {"alert": "Motion ", "event_time": now_time, "event_type": "51", "msg": "",
  154. "received_at": now_time, "sound": "sound.aif", "uid": "XFDJUHUIOKJHYTGSFFDR", "zpush": "1"}
  155. json_data = {
  156. "collapse_key": "WhatYouWant",
  157. "data": data,
  158. "delay_while_idle": False,
  159. "time_to_live": 3600,
  160. "registration_ids": [rg_id]
  161. }
  162. url = 'https://android.googleapis.com/gcm/send'
  163. data = json.dumps(json_data).encode('utf-8')
  164. headers = {'Content-Type': 'application/json', 'Authorization': 'key=%s' % serverKey}
  165. req = requests.post(url, data, headers=headers)
  166. response = ResponseObject()
  167. return response.json(0)
  168. def jgPush(self, request):
  169. response = ResponseObject()
  170. devToken = request.GET.get('devToken', '')
  171. app_key = request.GET.get('app_key', '')
  172. master_secret = request.GET.get('master_secret', '')
  173. import jpush as jpush
  174. # 此处换成各自的app_key和master_secret
  175. _jpush = jpush.JPush(app_key, master_secret)
  176. push = _jpush.create_push()
  177. # if you set the logging level to "DEBUG",it will show the debug logging.
  178. _jpush.set_logging("DEBUG")
  179. # push.audience = jpush.all_
  180. n_time = int(time.time())
  181. event_type = 51
  182. push.audience = jpush.registration_id(devToken)
  183. push_data = {"alert": "Motion ", "event_time": n_time, "event_type": event_type, "msg": "",
  184. "received_at": n_time, "sound": "sound.aif", "uid": 'xoxoxoxoxoxoxoxoxoxo', "zpush": "1"}
  185. android = jpush.android(alert="Hello, Android msg", priority=1, style=1, alert_type=1, big_text='ssssssssssssssssss',
  186. extras=push_data,title='fffff')
  187. push.notification = jpush.notification(android=android)
  188. push.platform = jpush.all_
  189. try:
  190. push.send()
  191. except Exception as e:
  192. print("Exception")
  193. return response.json(10, repr(e))
  194. return response.json(0)
  195. def post(self, request, *args, **kwargs):
  196. response = ResponseObject()
  197. data = request.POST.dict()
  198. signature = data["sign"]
  199. data.pop('sign')
  200. print(json.dumps(data))
  201. print(signature)
  202. # verify
  203. app_private_key_string = open(BASE_DIR + '/Controller/alipay_private_2048.pem').read()
  204. alipay_public_key_string = open(BASE_DIR + '/Controller/alipay_public_2048.pem').read()
  205. alipay = AliPay(
  206. appid="2016092200569234",
  207. app_notify_url=None, # the default notify path
  208. app_private_key_string=app_private_key_string,
  209. alipay_public_key_string=alipay_public_key_string,
  210. sign_type="RSA2", # RSA or RSA2
  211. debug=False # False by default
  212. )
  213. success = alipay.verify(data, signature)
  214. if success and data["trade_status"] in ("TRADE_SUCCESS", "TRADE_FINISHED"):
  215. print("trade succeed")
  216. return response.json(0, signature)
  217. # 修改 资源改变
  218. def put(self, request):
  219. response = ResponseObject()
  220. return response.json(0, '')
  221. # 修改 属性改变
  222. def PATCH(self, request):
  223. response = ResponseObject()
  224. return response.json(0)
  225. # 删除
  226. def delete(self, request):
  227. response = ResponseObject()
  228. return response.json(0)
  229. def validation(self, request_dict, *args, **kwargs):
  230. response = ResponseObject()
  231. return response.json(0)