如何获取Microsoft Translator API的身份验证令牌?

时间:2017-03-06 12:16:50

标签: php curl bing-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的例子,但它们已经过时了。

如何获得微软识别我的密钥的AuthenticationToken / achieve?

2 个答案:

答案 0 :(得分:0)

您正在传递订阅密钥错误 - 订阅密钥应该在标头(Ocp-Apim-Subscription-Key)中传递,还是作为URL中的查询字符串参数传递?订阅密钥=

您应该使用Azure认知服务仪表板生成的Key1或Key2。

仅供参考 - M $已将令牌生成器用于测试目的,这应该可以为您提供哪些键用于以下目的的线索: http://docs.microsofttranslator.com/oauth-token.html

这是一个工作的PHP脚本,它将字符串从EN转换为FR(它基于一个过时的WP插件,名为Wp-Slug-Translate by BoLiQuan,我为此目的进行了修改) :

&#13;
&#13;
<?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?");
?>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

也可以在网址中添加密钥。

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

但请将其留在CURLOPT_POSTFIELDS