Spaces:
Running
Running
import hmac | |
import hashlib | |
import base64 | |
import requests | |
from datetime import datetime, timezone | |
class BearerTokenGenerator: | |
def __init__(self, secret_key, secret_auth_prefix, path, base_url, api_version): | |
self.secret_key = secret_key | |
self.secret_auth_prefix = secret_auth_prefix | |
self.path = path | |
self.base_url = base_url | |
self.api_version = api_version | |
def generate_signature(self, to_sign): | |
hmac_obj = hmac.new(self.secret_key, to_sign, hashlib.sha256) | |
return base64.b64encode(hmac_obj.digest()).decode('utf-8') | |
def get_bearer_token(self, body): | |
# 获取当前UTC时间戳 | |
timestamp = datetime.now(timezone.utc).strftime('%Y-%m-%dT%H:%M:%SZ') | |
prefix = f"POST:{self.path}:{timestamp}\n".encode('utf-8') | |
# 生成签名 | |
signature = self.generate_signature(prefix + body) | |
# 编码secretAuthPrefix | |
encoded_secret_auth_prefix = base64.b64encode(self.secret_auth_prefix).decode('utf-8') | |
# 构建Bearer Token | |
bearer_token = f"Bearer {encoded_secret_auth_prefix}.{signature}" | |
return bearer_token, timestamp | |
def make_request(self, body): | |
bearer_token, timestamp = self.get_bearer_token(body) | |
headers = { | |
"Date": timestamp, | |
"Client-time-zone": "-04:00", | |
"Authorization": bearer_token, | |
"User-Agent": f"ChatOn_Android/{self.api_version}", | |
"Accept-Language": "en-US", | |
"X-Cl-Options": "hb", | |
"Content-Type": "application/json; charset=UTF-8" | |
} | |
response = requests.post(self.base_url + self.path, headers=headers, data=body) | |
return response.text | |
# 示例使用 | |
if __name__ == "__main__": | |
secret_key = bytes([14, 94, 79, 102, 38, 245, 11, 65, 100, 43, 115, 94, 15, 241, 14, 16, 66, 129, 248, 226, 98, 109, 235, 60, 62, 41, 78, 29, 72, 181, 47, 8]) | |
secret_auth_prefix = bytes([252, 137, 185, 155, 127, 94, 106, 81, 69, 242, 189, 184, 26, 228, 174, 239]) | |
path = "/chats/stream" | |
base_url = "https://example.com/api" # 替换为实际的BaseURL | |
api_version = "1.0" | |
body = '{"key": "value"}'.encode('utf-8') | |
generator = BearerTokenGenerator(secret_key, secret_auth_prefix, path, base_url, api_version) | |
response = generator.make_request(body) | |
print(response) | |