我尝试测试 Microsoft Translator API Text v3.0 但因 401 访问被拒绝而失败。我使用 PHP 7.3 执行标准 cURL 请求(HTTP POST)。
$key = "************************"; // secret key here (from the Azure Portal)
$host = "https://api.cognitive.microsofttranslator.com";
$path = "/translate?api-version=3.0";
$params = "&to=en&from=bg";
$text = "За мен лично хора, които задават такива въпроси са несъобразителни.";
$requestBody = array(
array(
'Text' => $text,
),
);
$content = json_encode($requestBody);
if (!function_exists('com_create_guid')) {
function com_create_guid()
{
return sprintf('%04x%04x-%04x-%04x-%04x-%04x%04x%04x',
mt_rand(0, 0xffff), mt_rand(0, 0xffff),
mt_rand(0, 0xffff),
mt_rand(0, 0x0fff) | 0x4000,
mt_rand(0, 0x3fff) | 0x8000,
mt_rand(0, 0xffff), mt_rand(0, 0xffff), mt_rand(0, 0xffff)
);
}
}
$curl_headers = array(
'Content-type: application/json',
'Content-length: ' . strlen($content),
'Ocp-Apim-Subscription-Key: ' . $key,
'X-ClientTraceId: ' . com_create_guid()
);
$url = $host . $path . $params;
$ch = curl_init();
$curl_content = array('content', $content);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, $curl_headers);
//curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
//curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_POSTFIELDS, $content);
// Receive server response ...
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
//curl_setopt($ch, CURLINFO_HEADER_OUT, TRUE);
$result = curl_exec($ch);
//dd(curl_getinfo($ch, CURLINFO_HEADER_OUT));
if (curl_exec($ch) === false) {
dd(curl_error($ch));
}
Laravel 5.6,代码放在api.php
路由文件中。
响应代码:
"{"error":{"code":401000,"message":"The request is not authorized because credentials are missing or invalid."}}"
错误在哪里?我应该在开发者门户等上启用任何设置吗?