|
"""
|
|
Google API相关功能模块 - 提供Google API的调用和验证功能
|
|
"""
|
|
import requests
|
|
|
|
def validate_api_key(api_key):
|
|
"""
|
|
验证Google API密钥是否有效
|
|
|
|
Args:
|
|
api_key (str): 需要验证的Google API密钥
|
|
|
|
Returns:
|
|
dict: 包含验证结果的字典,包括:
|
|
- success (bool): API密钥验证成功为True,失败为False
|
|
- return_message (str): 验证响应的具体消息,成功时为空字符串,失败时为错误详情
|
|
- balance (float): 账户余额,固定为0
|
|
- states (str): 账户状态,付费版或免费版
|
|
"""
|
|
url = "https://generativelanguage.googleapis.com/v1beta/models/gemini-1.5-pro:generateContent"
|
|
|
|
params = {
|
|
"key": api_key
|
|
}
|
|
|
|
payload = {
|
|
"contents": [
|
|
{
|
|
"parts": [{"text": "Hello"}]
|
|
}
|
|
],
|
|
"generationConfig": {
|
|
"maxOutputTokens": 1
|
|
}
|
|
}
|
|
|
|
try:
|
|
response = requests.post(url, params=params, json=payload)
|
|
|
|
if response.status_code == 200:
|
|
states = check_paid_account(api_key)
|
|
|
|
return {
|
|
"success": True,
|
|
"return_message": "200: Success!",
|
|
"balance": 0,
|
|
"states": states
|
|
}
|
|
else:
|
|
return_message = ""
|
|
try:
|
|
error_data = response.json()
|
|
if "error" in error_data:
|
|
return_message = error_data["error"].get("message", "")
|
|
if "details" in error_data["error"]:
|
|
for detail in error_data["error"]["details"]:
|
|
if detail.get("errorMessage"):
|
|
return_message += f" {detail['errorMessage']}"
|
|
return_message = f"{response.status_code}: {return_message}"
|
|
except:
|
|
return_message = f"{response.status_code}: {response.text or f'HTTP错误'}"
|
|
|
|
return {
|
|
"success": False,
|
|
"return_message": return_message,
|
|
"balance": 0,
|
|
"states": ""
|
|
}
|
|
except Exception as e:
|
|
error_str = str(e)
|
|
print(f"验证API密钥时出错: {error_str}")
|
|
return {
|
|
"success": False,
|
|
"return_message": f"500: 请求异常: {error_str}",
|
|
"balance": 0,
|
|
"states": ""
|
|
}
|
|
|
|
def check_paid_account(api_key):
|
|
"""
|
|
检查Google API密钥是否为付费账户
|
|
|
|
Args:
|
|
api_key (str): Google API密钥
|
|
|
|
Returns:
|
|
str: 账户状态,付费版返回"Paid",免费版返回"Free"
|
|
"""
|
|
try:
|
|
imagen_url = "https://generativelanguage.googleapis.com/v1beta/models/imagen-3.0-generate-002:predict"
|
|
params = {"key": api_key}
|
|
payload = {
|
|
"instances": [{"prompt": "Hi"}]
|
|
}
|
|
|
|
timeout = 3
|
|
|
|
try:
|
|
response = requests.post(imagen_url, params=params, json=payload, timeout=timeout)
|
|
|
|
if response.status_code == 200:
|
|
return "Paid"
|
|
else:
|
|
return "Free"
|
|
|
|
except requests.exceptions.Timeout:
|
|
return "Paid"
|
|
except Exception:
|
|
return "Free"
|
|
|
|
except Exception as e:
|
|
print(f"检查账户类型时出错: {str(e)}")
|
|
return "Free" |