Как я могу получить токен аутентификации для Microsoft Translator API?

Я хочу получить токен аутентификации для Microsoft Translator API. Это мой код:

<?php

//1. initialize cURL
$ch = curl_init();

//2. set options

//Set to POST request
curl_setopt($ch, CURLOPT_POST,1);

// URL to send the request to
curl_setopt($ch, CURLOPT_URL, 'https://api.cognitive.microsoft.com/sts/v1.0/issueToken');

//return instead of outputting directly
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

//whether to include header in the output. here set to false
curl_setopt($ch, CURLOPT_HEADER, 0);

//pass my subscription key
curl_setopt($ch, CURLOPT_POSTFIELDS,array(Subscription-Key => '<my-key>'));

//CURLOPT_SSL_VERIFYPEER- Set to false to stop verifying certificate
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

//3. Execute the request and fetch the response. check for errors
$output = curl_exec($ch);

if ($output === FALSE) {
echo "cURL Error" . curl_error($ch);
}

//4. close and free up the curl handle
curl_close($ch);

//5. display raw output
print_r($output);?>

это дает мне следующую ошибку:
{«statusCode»: 401, «message»: «Доступ запрещен из-за отсутствующего ключа подписки. Обязательно включайте ключ подписки при выполнении запросов к API.» }

это может означать, что ключ недействителен в соответствии с веб-сайтом ниже, но я убедился, что ключ действителен на том же веб-сайте.

http://docs.microsofttranslator.com/oauth-token.html

В Интернете я нашел несколько примеров того, как получить маркер аутентификации, но они устарели.

Как я могу получить AuthenticationToken / добиться того, чтобы Microsoft распознала мой ключ?

1

Решение

Вы неправильно передаете ключ подписки —
Ключ подписки должен передаваться в заголовке (Ocp-Apim-Subscription-Key) или в качестве параметра строки запроса в URL-адресе? Subscription-Key =

И вы должны использовать Key1 или Key2, сгенерированные панелью мониторинга когнитивных служб Azure.

FYI — M $ сделал генератор токенов доступным для тестирования, это должно дать вам подсказку, какие ключи используются для каких целей:
http://docs.microsofttranslator.com/oauth-token.html

Вот рабочий скрипт PHP, который переводит строку из EN в FR (он основан на устаревшем плагине WP под названием Wp-Slug-Translate от BoLiQuan, который я модифицировал для этой цели):

<?php

define("CLIENTID",'<client-name>'); // client name/id
define("CLIENTSECRET",'<client-key>'); // Put key1 or key 2 here
define("SOURCE","en");
define("TARGET","fr");class WstHttpRequest
{
function curlRequest($url, $header = array(), $postData = ''){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
if(!empty($header)){
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
}
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
if(!empty($postData)){
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, is_array($postData) ? http_build_query($postData) : $postData);
}
$curlResponse = curl_exec($ch);
curl_close($ch);
return $curlResponse;
}
}

class WstMicrosoftTranslator extends WstHttpRequest
{
private $_clientID = CLIENTID;
private $_clientSecret = CLIENTSECRET;
private $_fromLanguage = SOURCE;
private $_toLanguage = TARGET;

private $_grantType = "client_credentials";
private $_scopeUrl = "http://api.microsofttranslator.com";
private $_authUrl = "https://api.cognitive.microsoft.com/sts/v1.0/issueToken";

// added subscription-key
private function _getTokens(){
try{
$header = array('Ocp-Apim-Subscription-Key: '.$this->_clientSecret);
$postData = array(
'grant_type' => $this->_grantType,
'scope' => $this->_scopeUrl,
'client_id' => $this->_clientID,
'client_secret' => $this->_clientSecret
);
$response = $this->curlRequest($this->_authUrl, $header, $postData);
if (!empty($response))
return $response;
}
catch(Exception $e){
echo "Exception-" . $e->getMessage();
}
}

function translate($inputStr){
$params = "text=" . rawurlencode($inputStr) . "&from=" . $this->_fromLanguage . "&to=" . $this->_toLanguage;
$translateUrl = "http://api.microsofttranslator.com/v2/Http.svc/Translate?$params";
$accessToken = $this->_getTokens();
$authHeader = "Authorization: Bearer " . $accessToken;
$header = array($authHeader, "Content-Type: text/xml");
$curlResponse = $this->curlRequest($translateUrl, $header);

$xmlObj = simplexml_load_string($curlResponse);
$translatedStr = '';
foreach((array)$xmlObj[0] as $val){
$translatedStr = $val;
}
return $translatedStr;
}

}

function bing_translator($string) {
$wst_microsoft= new WstMicrosoftTranslator();
return $wst_microsoft->translate($string);
}

echo bing_translator("How about translating this?");
?>
0

Другие решения

Добавьте свой ключ также в URL.

curl_setopt($ch, CURLOPT_URL, 'https://api.cognitive.microsoft.com/sts/v1.0/issueToken?Subscription-Key={your key}');

Но оставь это и в CURLOPT_POSTFIELDS,

0