IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

Bibliothèques et frameworks PHP Discussion :

[Web Service] API Microsoft Translate


Sujet :

Bibliothèques et frameworks PHP

  1. #1
    Membre du Club
    Profil pro
    Inscrit en
    Novembre 2005
    Messages
    78
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Novembre 2005
    Messages : 78
    Points : 48
    Points
    48
    Par défaut [Web Service] API Microsoft Translate
    Bonjour à tous,

    Je penses être u bon endroit pour poster cette message. dans le cas contraire veuillez d'avance m'en excuser.

    Ca fait quelques heure que j'essaie désespérément d'utiliser l'API Microsoft Translate qui, contrairement à celle de google, est gratuite.
    J'ai trouvé beaucoup de chose sur internet plus contradictoire les unes que les autres et je ne m'en sort vraiment pas.

    J'ai bien créé un compte. J'ai récupéré 3 clé :
    1 - Clé de compte primaire
    2 - ID client
    3 - Secret du client

    Pour le secret du client je ne suis pas sur d'avoir fait la bonne manip ... mais j'ai bien récupéré quelque chose (j'ai cliquer sur un lien perdu au fin fond du footer du site "Enregistrement de votre application" et j'ai renseigné mon id client pour récupéré un id secret).

    Ensuite, en recoupant un peut les informations que j'ai pu trouvé sur différents site j'ai l'impression qu'il faut aujourd'hui récupérer un token avant de pouvoir utiliser l'API. C'est la que tout ce complique ! L'url que j'ai trouvé semble ne pas fonctionner !!
    Pour info voici mon code pour la récupération du token :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    $authURL = 'http://datamarket.accesscontrol.windows.net/v2/OAuth2-13&grant_type=client_credentials&client_id='.urlencode(API_CLIENT_BING).'&client_secret='.urlencode(API_CLIENT_SECRET_BING).'&scope=http://api.microsofttranslator.com';
     
    $chpre = curl_init();
    curl_setopt($chpre, CURLOPT_URL, $authURL );
    curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
    $xpre = curl_exec($chpre);
     
    print_r($xpre);

    n'arrivant même pas a récupéré le token je n'ai pas été plus loin...

    Quelqu'un pourrait-t-il m'aider ou même mieux, me donner un exemple simple du code à utiliser pour traduire un simple texte avec cette api svp (le basic du basic, sans gestion d'erreur ni rien...) ?

  2. #2
    Membre du Club
    Profil pro
    Inscrit en
    Novembre 2005
    Messages
    78
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Novembre 2005
    Messages : 78
    Points : 48
    Points
    48
    Par défaut
    Désolé pourl e dérangement j'ai fini par m'en sortir (mais j'ai plus de cheveux ) ... voila mon code pour ceux que ça intéresse :

    Les classes :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    <?php 
    class AccessTokenAuthentication {
        /*
         * 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);
                }
                return $objResponse->access_token;
            } catch (Exception $e) {
                echo "Exception-".$e->getMessage();
            }
        }
    }
     
    /*
     * Class:HTTPTranslator
     * 
     * Processing the translator request.
     */
    Class HTTPTranslator {
        /*
         * Create and execute the HTTP CURL request.
         *
         * @param string $url        HTTP Url.
         * @param string $authHeader Authorization Header string.
         * @param string $postData   Data to post.
         *
         * @return string.
         *
         */
        function curlRequest($url, $authHeader, $postData=''){
            //Initialize the Curl Session.
            $ch = curl_init();
            //Set the Curl url.
            curl_setopt ($ch, CURLOPT_URL, $url);
            //Set the HTTP HEADER Fields.
            curl_setopt ($ch, CURLOPT_HTTPHEADER, array($authHeader,"Content-Type: text/xml"));
            //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);
            if($postData) {
                //Set HTTP POST Request.
                curl_setopt($ch, CURLOPT_POST, TRUE);
                //Set data to POST in HTTP "POST" Operation.
                curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
            }
            //Execute the  cURL session.
            $curlResponse = 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 a cURL session.
            curl_close($ch);
            return $curlResponse;
        }
     
        /*
         * Create Request XML Format.
         *
         * @param string $languageCode  Language code
         *
         * @return string.
         */
        function createReqXML($languageCode) {
            //Create the Request XML.
            $requestXml = '<ArrayOfstring xmlns="http://schemas.microsoft.com/2003/10/Serialization/Arrays" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">';
            if($languageCode) {
                $requestXml .= "<string>$languageCode</string>";
            } else {
                throw new Exception('Language Code is empty.');
            }
            $requestXml .= '</ArrayOfstring>';
            return $requestXml;
        }
    }
     
    class BingTraduction {
     
    	public function translate($inputStr, $to = 'en', $from = 'fr'){
    		try {
    			//Client ID of the application.
    			$clientID       = API_CLIENT_BING;
    			//Client Secret key of the application.
    			$clientSecret = API_CLIENT_SECRET_BING;
    			//OAuth Url.
    			$authUrl      = "https://datamarket.accesscontrol.windows.net/v2/OAuth2-13/";
    			//Application Scope Url
    			$scopeUrl     = "http://api.microsofttranslator.com";
    			//Application grant type
    			$grantType    = "client_credentials";
     
    			//Create the AccessTokenAuthentication object.
    			$authObj      = new AccessTokenAuthentication();
    			//Get the Access token.
    			 $accessToken  = $authObj->getTokens($grantType, $scopeUrl, $clientID, $clientSecret, $authUrl);
    			//Create the authorization Header string.
    			$authHeader = "Authorization: Bearer ". $accessToken;
     
    			//Create the Translator Object.
    			$translatorObj = new HTTPTranslator();
     
     
    			//HTTP Detect Method URL.
    			$detectMethodUrl = "http://api.microsofttranslator.com/V2/Http.svc/Translate?text=".urlencode($inputStr)."&from=".$from."&to=".$to;
    			//Call the curlRequest.
    			$strResponse = $translatorObj->curlRequest($detectMethodUrl, $authHeader);
     
    			return $strResponse;
    		}catch(Exception $e){
    			return "Erreur de traduction : ".$e->getMessage();
    		}
    	}
    }

    L'utilisation :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
     
    $bt = new BingTraduction();
    echo $bt->translate('Bonjour', 'en', 'fr');

Discussions similaires

  1. [Web Service][API Google Maps] Ne fonctionne pas en ligne
    Par PRACH dans le forum Bibliothèques et frameworks
    Réponses: 4
    Dernier message: 07/12/2009, 10h30
  2. Réponses: 1
    Dernier message: 03/03/2009, 11h09
  3. [Web Service] Api Client HTTP
    Par ksven dans le forum Bibliothèques et frameworks
    Réponses: 2
    Dernier message: 19/02/2009, 16h43
  4. Réponses: 3
    Dernier message: 05/12/2008, 11h59

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo