UnicomObject.py 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256
  1. # -*- encoding: utf-8 -*-
  2. """
  3. @File : UnicomObject.py
  4. @Time : 2022/6/17 11:03
  5. @Author : stephen
  6. @Email : zhangdongming@asj6.wecom.work
  7. @Software: PyCharm
  8. """
  9. import base64
  10. import json
  11. import requests
  12. from Crypto.Cipher import AES
  13. from decimal import Decimal
  14. from Object.utils import SM3Util
  15. from Ansjer.config import unicomAppUrl, unicomAppId, unicomAppSecret, unicomTenantId, \
  16. unicomEncodeKey, unicomIvKey, unicomUserName, unicomPassword, unicomPushKey
  17. from Object.utils.SymmetricCryptoUtil import AESencrypt
  18. """
  19. 联通4Gapi
  20. 具体参数查看接口文档
  21. https://www.showdoc.com.cn/unicomJYHapi/8158648460007467
  22. """
  23. class UnicomObjeect:
  24. def __init__(self):
  25. self.appUrl = unicomAppUrl
  26. self.appId = unicomAppId
  27. self.appSecret = unicomAppSecret
  28. self.tenantId = unicomTenantId
  29. self.encodeKey = unicomEncodeKey
  30. self.ivKey = unicomIvKey
  31. self.username = unicomUserName
  32. self.password = unicomPassword
  33. self.pushKey = unicomPushKey
  34. self.headers = {'Tenant': self.tenantId, 'content-type': 'application/x-www-form-urlencoded'}
  35. # pip install snowland-smx
  36. def createSign(self, reverse=False, **sign_params):
  37. """
  38. 调用接口(API)时需要对请求参数进行签名(sign)验证,
  39. 算法:
  40. 根据参数名称将你的所有请求参数按照字母先后顺序排序: key = value & key = value,对除签名外的所有请求参数按
  41. key
  42. 做的升序排列。
  43. 如:将
  44. foo = 1, bar = 2, baz = 3
  45. 排序为
  46. bar = 2, baz = 3, foo = 1
  47. 参数名和参数值链接后,得到拼装字符串(注意:参数名与参数值左右两边不能包含空格)
  48. bar = 2 & baz = 3 & foo = 1
  49. pushkey拼接到参数字符尾部进行
  50. SM3
  51. 加密,再转化成大写,格式是
  52. (SM3(key1=value1 & key2=value2 &...& key= pushKey)).upcase
  53. @param reverse:
  54. @param sign_params:
  55. @return:
  56. """
  57. dict_2 = dict(sorted(sign_params.items(), key=lambda item: item[0], reverse=reverse))
  58. data_list = []
  59. for item in dict_2.items():
  60. if item[0] and item[1]:
  61. data_list.append("{}={}".format(item[0], item[1]))
  62. val = '&'.join(data_list)
  63. push_key = '&key={}'.format(self.pushKey)
  64. val = val + push_key
  65. return SM3Util.Hash_sm3(val).upper()
  66. def get_login_authorization(self):
  67. """
  68. 获取登录授权
  69. 注意登录认证Authorization和登录后的请求认证不一样
  70. 算法:appId+":"+appSecret base64转码生成 前面加Basic
  71. @return: "Basic " + base64_data
  72. """
  73. voucher = self.appId + ':' + self.appSecret
  74. base64_data = str(base64.b64encode(voucher.encode("utf-8")), "utf-8")
  75. return "Basic " + base64_data
  76. def get_encode_password(self):
  77. """
  78. 获取对称加密
  79. @return: encrypt_pwd
  80. """
  81. aes = AESencrypt(self.encodeKey.encode('utf-8'), AES.MODE_CBC, self.ivKey.encode('utf-8'),
  82. paddingMode="ZeroPadding",
  83. characterSet='utf-8')
  84. encrypt_pwd = aes.encryptFromString(self.password)
  85. return encrypt_pwd
  86. def generate_token(self):
  87. """
  88. 生成令牌
  89. @return: token
  90. """
  91. url = self.appUrl + '/auc/oauth/token'
  92. pwd = self.get_encode_password()
  93. body = {'username': self.username, 'password': pwd, 'grant_type': 'password', 'scope': 'server'}
  94. headers = self.headers
  95. headers['Authorization'] = self.get_login_authorization()
  96. response_data = requests.post(url, data=body, headers=headers)
  97. response_data = json.loads(response_data.text)
  98. return response_data['access_token']
  99. def refresh_token(self, refresh_token):
  100. """
  101. 刷新令牌
  102. @param refresh_token:
  103. @return:
  104. """
  105. url = self.appUrl + '/auc/oauth/token?grant_type=refresh_token'
  106. body = {'refresh_token': refresh_token, 'grant_type': 'refresh_token'}
  107. headers = self.headers
  108. headers['Authorization'] = self.get_login_authorization()
  109. response_data = requests.post(url, data=body, headers=headers)
  110. return response_data.text
  111. def business_unify_headers(self):
  112. """
  113. 业务统一headers
  114. 在请求头中增加key为Authorization,value为"Bearer " + token
  115. @return: headers
  116. """
  117. token = self.generate_token()
  118. headers = self.headers
  119. headers['Authorization'] = 'Bearer ' + token
  120. return headers
  121. # 业务api 注意 get与post 请求数据类型不同 post使用:application/json
  122. def verify_device(self, **re_params):
  123. """
  124. 验证设备
  125. @param re_params:
  126. @return:
  127. """
  128. url = self.appUrl + '/platform/api/device/verify-device'
  129. return requests.get(url, params=re_params, headers=self.business_unify_headers())
  130. def query_device_status(self, **re_params):
  131. """
  132. 查询设备状态
  133. @param re_params:
  134. @return:
  135. """
  136. url = self.appUrl + '/platform/api/device/device-status'
  137. return requests.get(url, params=re_params, headers=self.business_unify_headers())
  138. def update_device_state(self, **re_data):
  139. """
  140. 修改设备状态
  141. @param re_data:
  142. @return:
  143. """
  144. url = self.appUrl + '/platform/api/device/device-state'
  145. headers = self.business_unify_headers()
  146. headers['content-type'] = 'application/json'
  147. return requests.post(url, data=json.dumps(re_data), headers=headers)
  148. def query_device_usage_history(self, **re_params):
  149. """
  150. 查询设备用量历史
  151. @param re_params:
  152. @return:
  153. """
  154. url = self.appUrl + '/platform/api/usage/device-usage-history'
  155. return requests.get(url, params=re_params, headers=self.business_unify_headers())
  156. def query_current_renew_list_usage_details(self, **re_params):
  157. """
  158. 查询设备当前队列用量详情
  159. @param re_params:
  160. @return:
  161. """
  162. url = self.appUrl + '/platform/api/usage/current-renewlist-usage-details'
  163. return requests.get(url, params=re_params, headers=self.business_unify_headers())
  164. def get_device_batch_detail(self, **re_data):
  165. """
  166. 查询设备当前队列用量详情
  167. @return:
  168. """
  169. url = self.appUrl + '/platform/api/device/batch-detail'
  170. headers = self.business_unify_headers()
  171. headers['content-type'] = 'application/json'
  172. return requests.post(url, data=json.dumps(re_data), headers=headers)
  173. def query_package_list(self, **re_params):
  174. """
  175. 查询套餐列表
  176. @return:
  177. """
  178. url = self.appUrl + '/platform/api/package/list'
  179. return requests.get(url, params=re_params, headers=self.business_unify_headers())
  180. def query_renewal_list(self, **re_params):
  181. """
  182. 续费套餐列表
  183. @param re_params:
  184. @return:
  185. """
  186. url = self.appUrl + '/platform/api/package/list'
  187. return requests.get(url, params=re_params, headers=self.business_unify_headers())
  188. def async_buy_package(self, **re_data):
  189. """
  190. 查询设备当前队列用量详情
  191. @return:
  192. """
  193. url = self.appUrl + '/platform/api/package/async-buy-package'
  194. headers = self.business_unify_headers()
  195. headers['content-type'] = 'application/json'
  196. return requests.post(url, data=json.dumps(re_data), headers=headers)
  197. if __name__ == '__main__':
  198. price = '12.13'
  199. print(float(price))
  200. discount = '6'
  201. dd = Decimal(price) - Decimal(discount)
  202. print(dd.quantize(Decimal('0.00')))
  203. unicom_api = UnicomObjeect()
  204. data = {'foo': 1, 'bar': 2, 'baz': 3}
  205. print(unicom_api.createSign(**data))
  206. # result = unicom_api.generate_token()
  207. # result = unicom_api.refresh_token('5d0c0f30-99bd-4f17-9614-3524495b05d4')
  208. params = {'iccid': '89860620170009628001'}
  209. response = unicom_api.verify_device(**params)
  210. # response = unicom_api.query_device_status(**params)
  211. # response = unicom_api.update_device_state(**params)
  212. # response = unicom_api.query_device_usage_history(**params)
  213. # response = unicom_api.query_current_renew_list_usage_details(**params)
  214. # unicom_api.get_device_batch_detail()
  215. # response = unicom_api.query_package_list(**params)
  216. # response = unicom_api.query_renewal_list(**params)
  217. if response.status_code == 200:
  218. res_dict = json.loads(response.text)
  219. print(res_dict)
  220. response_json = {
  221. "success": True,
  222. "msg": "操作成功",
  223. "code": 0,
  224. "data": {
  225. "iccid": "8986062018007784202",
  226. "completeIccid": "89860620180077842020",
  227. "status": 1
  228. }
  229. }
  230. print(response_json['data']['iccid'])
  231. print(response.status_code)