Search code examples
phpcurlbing-translator-api

How can I get an Authentication Token for Microsoft Translator API?


I want to get an Authentication Token for the Microsoft Translator API. This is my code:

<?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);


?>

it gives me the following error: { "statusCode": 401, "message": "Access denied due to missing subscription key. Make sure to include subscription key when making requests to an API." }

which could mean that the key is invalid according to the website below, but I ensured the key is valid on the same website.

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

I did find some examples online on how to get the Authenticationtoken, but they are outdated.

How can I get the AuthenticationToken/achieve that microsoft recognises my key?


Solution

  • You're passing the subscription-key wrong - The subscription key should passed in the header (Ocp-Apim-Subscription-Key) or as a querystring parameter in the URL ?Subscription-Key=

    And you should use Key1 or Key2 generated by the Azure cognitive service dashboard.

    FYI - M$ has made a token generator available for testing purposes, this should give you a clue which keys are used for which purpose: http://docs.microsofttranslator.com/oauth-token.html

    Here's a working PHP script which translates a string from EN to FR (it's based on an outdated WP plugin called Wp-Slug-Translate by BoLiQuan which I've modified for this purpose):

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