2012-02-29 3 views
2

Я пытаюсь получить токен доступа для Microsoft Translator API, и это была довольно сложная борьба. Сначала я попытался написать запрос с Ruby и HTTParty, но он не принимал мои параметры. Microsoft предоставила пример в PHP, так что я понял, я мог бы просто использовать, что:cURL POST Запрос API в PHP, не возвращающий значения

http://msdn.microsoft.com/en-us/library/hh454950.aspx#phpexample

код был скопирован прямо с сайта Microsoft - Я просто добавил в моих переменных и называется функцией в конце:

<?php 

/* 
* Get the access token. 
* 
* @param string $grantType Grant type. 
* @param string $scopeUrl  Application Scope URL. 
* @param string $clientID  Application client ID. 
* @param string $clientSecret Application client ID. 
* @param string $authUrl  Oauth Url. 
* 
* @return string. 
*/ 
function getTokens($grantType, $scopeUrl, $clientID, $clientSecret, $authUrl){ 
    try { 
     //Initialize the Curl Session. 
     $ch = curl_init(); 
     //Create the request Array. 
     $paramArr = array (
      'grant_type' => $grantType, 
      'scope'   => $scopeUrl, 
      'client_id'  => $clientID, 
      'client_secret' => $clientSecret 
     ); 
     //Create an Http Query.// 
     $paramArr = http_build_query($paramArr); 
     //Set the Curl URL. 
     curl_setopt($ch, CURLOPT_URL, $authUrl); 
     //Set HTTP POST Request. 
     curl_setopt($ch, CURLOPT_POST, TRUE); 
     //Set data to POST in HTTP "POST" Operation. 
     curl_setopt($ch, CURLOPT_POSTFIELDS, $paramArr); 
     //CURLOPT_RETURNTRANSFER- TRUE to return the transfer as a string of the return value of curl_exec(). 
     curl_setopt ($ch, CURLOPT_RETURNTRANSFER, TRUE); 
     //CURLOPT_SSL_VERIFYPEER- Set FALSE to stop cURL from verifying the peer's certificate. 
     curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); 
     //Execute the cURL session. 
     $strResponse = curl_exec($ch); 
     //Get the Error Code returned by Curl. 
     $curlErrno = curl_errno($ch); 
     if($curlErrno){ 
      $curlError = curl_error($ch); 
      throw new Exception($curlError); 
     } 
     //Close the Curl Session. 
     curl_close($ch); 
     //Decode the returned JSON string. 
     $objResponse = json_decode($strResponse); 
     if ($objResponse->error){ 
      throw new Exception($objResponse->error_description); 
     } 
     $finalresponse = $objResponse->access_token; 
     return $finalresponse; 

    } catch (Exception $e) { 
     echo "Exception-".$e->getMessage(); 
    } 

} 

    $grant = "client_credentials" 
$scope = "http://api.microsofttranslator.com"; 
$secret = "8Bo0SET1W8lmDgfV/l7FLEKUWRDXCEZrvTgv9tSH3Bs="; 
    $client = "globalchatapp" 
$auth = "https://datamarket.accesscontrol.windows.net/v2/OAuth2-13/"; 


getTokens($grant, $scope, $client, $secret, $auth); 


?> 

В любом случае, когда я запускаю это (используя PHP 5.3.6), ошибок нет; он не возвращает никакой ценности. Я не очень хорош с PHP, и это может быть что-то очевидное, что я просто не видел, но я изо всех сил пытался с этим ненадолго. Любая помощь будет принята с благодарностью.

Кроме того, если это помогает, здесь был мой оригинальный код Ruby. Я получил ответ от сервера здесь, заявив, что «scope» отсутствует:

require 'httparty' 
scope = "http://api.microsofttranslator.com"; 
secret = "8Bo0SET1W8lmDgfV/l7FLEKUWRDXCEZrvTgv9tSH3Bs="; 
auth = "https://datamarket.accesscontrol.windows.net/v2/OAuth2-13/"; 
client_id = "globalchatapp" 
grant_type = "client_credentials" 

response = HTTParty.post("https://datamarket.accesscontrol.windows.net/v2/OAuth2-13/?&scope=#{scope}&secret=#{secret}&client_id=#{client_id}&grant_type=#{grant_type}", :body => {:key => :value}) 
puts response 

Еще раз спасибо!

+0

Возможно, указывая очевидное, но вы, кажется, не захватили возврат 'getTokens()' в любом месте. Вы только что вызвали функцию ... '$ output = getTokens (....); var_dump ($ output); ' –

+0

FYI: нет необходимости в http_build_query. Вы можете передать массив params непосредственно в curlopt POSTFIELDS, и PHP будет обрабатывать кодировку/преобразование для вас. –

+0

@ ryan508: добавьте 'curl_setopt ($ ch, CURLOPT_VERBOSE, TRUE);' там только выше всех других вызовов curl_setopt и дайте нам знать результат (сначала удалив выводимые значения заголовка аутентификации, если они есть, - мы не вам нужно знать свои пароли). –

ответ

0

Сохраните значение, возвращенное getTokens(), переменной и передайте его urldecode() для декодирования %2F и других закодированных символов.

$tokens = getTokens($grant, $scope, $client, $secret, $auth); 
echo urldecode($tokens); 
+0

Эй, забыл принять это как ответ. Извинения за безумную задержку, но ваш код сделал трюк. Еще раз спасибо! – ryan508

Смежные вопросы