Gemini API本地运行正常,部署到共享服务器后提示地区不支持求助
问题:Gemini API 部署到共享主机后提示“用户位置不支持”错误
本地用PHP调用免费版Gemini API完全正常,但部署到共享主机服务器后,无论访问者从哪里访问(即使是纽约),系统都会返回以下错误:
{"error":"Gemini API operation failed: operation=models/gemini-pro:generateContent, status_code=400, response={\n "error": {\n "code": 400,\n "message": "User location is not supported for the API use.",\n "status": "FAILED_PRECONDITION"\n }\n}\n"}
相关PHP代码如下:
<?php require 'vendor/autoload.php'; use GeminiAPI\Client; use GeminiAPI\Enums\MimeType; use GeminiAPI\Resources\Parts\ImagePart; use GeminiAPI\Resources\Parts\TextPart; // Path to the image containing the voucher $imagePath = "PATH"; // API key for accessing Gemini API $apiKey = 'MY_API_KEY'; $client = new Client($apiKey); // Read the image file content and encode it in base64 $imageData = base64_encode(file_get_contents($imagePath)); // Prompt to provide context for content generation $prompt = "MY_PROMPT"; try { // Send the image and text to Gemini API for processing $response = $client->geminiProVision()->generateContent( new TextPart($prompt), new ImagePart(MimeType::IMAGE_JPEG, $imageData) ); // Extract the JSON response $content = $response->text(); // Return the JSON data echo extractJSON($content); } catch (Exception $e) { // If an error occurs, return an error message echo json_encode(['error' => $e->getMessage()]); } function extractJSON($string) { $pattern = '/\{(.*?)\}/s'; // pattern to match preg_match($pattern, $string, $matches); // perform the match if (isset($matches[0])) { return $matches[0]; // return the first captured group } else { return "{}"; // return null if no match found } } ?>
解决方案
- 核查共享主机服务器IP归属地:Gemini API是根据请求发起的服务器IP判断位置,而非访问者的IP。共享主机可能使用了Gemini不支持地区的IP(如部分东南亚、非洲地区),可在主机上执行
curl ipinfo.io查看IP所属地区,或直接联系主机商确认服务器节点位置。 - 添加代理中转请求:若主机IP不在支持列表内,可在代码中配置代理,让请求通过Gemini支持地区的IP发送。修改Client初始化代码即可:
注意代理IP需属于Gemini支持的地区(如美国、欧盟、新加坡等)。// 初始化Client时配置代理 $client = new Client($apiKey, [ 'proxy' => 'http://your-us-or-eu-proxy:port', // 替换为支持地区的代理地址 ]); - 更换符合要求的主机服务商:若上述方法无效,直接更换服务器IP位于Gemini支持地区的共享主机,比如美国、新加坡节点的服务商。
- 检查API密钥权限限制:免费版Gemini API可能存在地区绑定或IP访问限制,登录Google Cloud控制台查看你的API密钥是否设置了访问地域限制,确保未禁止当前主机IP的访问。
内容的提问来源于stack exchange,提问作者Meem Alif
相关产品推荐
相关产品推荐

