首页 > 解决方案 > 文本翻译 API | 微软天青 | 总是错误 401000

问题描述

我尝试测试 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."}}"

错误在哪里?我应该在开发者门户等上启用任何设置吗?

标签: azurephp-curlmicrosoft-translatorbing-translator-api

解决方案


也许这会有所帮助。在官方文档中,您可以找到 CURL 请求的两个示例。两者的区别在于,第二个也有参数region。在我的情况下,只有第二个请求有效。也许区域参数是必不可少的。


推荐阅读