HttpUtils.py 3.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. #coding=utf-8
  2. import hashlib
  3. import json
  4. import random
  5. import requests
  6. import time
  7. from collections import OrderedDict
  8. from Crypto.PublicKey import RSA
  9. from Crypto.Hash import MD5, SHA1, SHA256
  10. from Crypto.Signature import PKCS1_v1_5 as Signature_PKC
  11. import base64
  12. from requests_toolbelt.multipart.encoder import MultipartEncoder
  13. # 接口调用地址,
  14. # 正式环境:https://oapi.acsign.cn
  15. # 沙箱环境域名:https://prev.acsign.cn
  16. #构建post请求
  17. class HttpUtils(object):
  18. # 构建请求头
  19. @staticmethod
  20. def doPOST(url, reqBodyData, appId, appKey, pathstr=None, file_key=None, file_name=None):
  21. accept = "*/*"
  22. # 请求的与实体对应的MIME信息
  23. contentType = "multipart/form-data; charset=UTF-8"
  24. # 对请求的url进行签名
  25. accountsApiUrl = url
  26. # 毫米时间戳获取
  27. t = time.time()
  28. # 毫秒级时间戳
  29. _timestamp = str(round(t * 1000) + 1000 * 60)
  30. # 按照阿拉伯字符排序
  31. jsonstr = json.dumps(reqBodyData, sort_keys=True,separators=(',',':'), ensure_ascii=False)
  32. data = dict()
  33. data["appId"] = appId
  34. data["timestamp"] = _timestamp
  35. data["bizData"] = jsonstr
  36. #计算md5值
  37. m = hashlib.md5()
  38. m.update(jsonstr.encode('utf-8'))
  39. # 二进制数据字符串值
  40. md5_str = m.hexdigest()
  41. sign_str = '%s%s%s%s' % (jsonstr, md5_str, appId, _timestamp)
  42. # 打印签名值
  43. private_keyBytes = base64.b64decode(appKey)
  44. rsakey = RSA.importKey(private_keyBytes)
  45. signer = Signature_PKC.new(rsakey)
  46. # 根据SHA256算法处理签名内容data
  47. sha_data = SHA1.new(sign_str.encode("utf-8"))
  48. # 私钥进行签名
  49. signature = base64.b64encode(signer.sign(sha_data))
  50. if(pathstr != None):
  51. m = MultipartEncoder(
  52. fields={
  53. 'appId': appId,
  54. 'bizData': jsonstr,
  55. 'timestamp': _timestamp,
  56. 'Content-Type': 'application/octet-stream',
  57. 'type': 'application/octet-stream',
  58. file_key: (file_name, open(pathstr, 'rb'), 'application/octet-stream')
  59. },
  60. boundary='-----------------------------' + str(random.randint(1e28, 1e29 - 1)))
  61. else:
  62. m = MultipartEncoder(
  63. fields={
  64. 'appId': appId,
  65. 'bizData': jsonstr,
  66. 'timestamp': _timestamp,
  67. 'Content-Type': 'application/octet-stream',
  68. 'type': 'application/octet-stream'
  69. },
  70. boundary='-----------------------------' + str(random.randint(1e28, 1e29 - 1)))
  71. #添加文件
  72. # 构建请求头
  73. headers = {
  74. 'Content-Type': contentType,
  75. 'Accept': accept,
  76. 'sign': signature
  77. }
  78. headers['Content-Type'] = m.content_type
  79. r = requests.post(accountsApiUrl, data=m, headers=headers)
  80. return r.text