I'm trying to connect Woocommerce to Unleashed and have the code for it below. It consistently fails authorisation. It requires a HMAC-SHA256 signature to be generated.
add_action('init', 'register_product');
function register_product(){
register_post_type('product', [
'label' => 'Products Greyville',
'public' => true,
'capability_type' => 'post'
]);
}
function get_products_from_unleashed(){
$current_page = ( ! empty($_POST['current_page']) ) ? $_POST['current_page'] : 1;
$products = [];
$results = wp_remote_get('https://api.unleashedsoftware.com/products/?page=' . $current_page . '&per_page=50');
}
$apiId = "***";
$apiKey = "***";
function getSignature($request, $key) {
return base64_encode(hash_hmac('sha256', $request, $key, true));
}
function getCurl($id, $key, $signature, $endpoint, $requestUrl, $format) {
global $api;
$curl = curl_init($api . $endpoint . $requestUrl);
curl_setopt($curl, CURLOPT_FRESH_CONNECT, true);
curl_setopt($curl, CURLINFO_HEADER_OUT, true);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($curl, CURLOPT_HTTPHEADER, array(
"Content-Type: application/$format",
"Accept: application/$format",
"api-auth-id: $id",
"api-auth-signature: $signature"));
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_TIMEOUT, 20);
// these options allow us to read the error message sent by the API
curl_setopt($curl, CURLOPT_FAILONERROR, false);
curl_setopt($curl, CURLOPT_HTTP200ALIASES, range(400, 599));
return $curl;
}
function get($id, $key, $endpoint, $request, $format) {
$requestUrl = "";
if (!empty($request)) $requestUrl = "?$request";
try {
// calculate API signature
$signature = getSignature($request, $key);
// create the curl object
$curl = getCurl($id, $key, $signature, $endpoint, $requestUrl, $format);
// GET something
$curl_result = curl_exec($curl);
error_log($curl_result);
curl_close($curl);
return $curl_result;
}
catch (Exception $e) {
error_log('Error: ' + $e);
}
}
Please also see: https://apidocs.unleashedsoftware.com/PHP
And: https://apidocs.unleashedsoftware.com/AuthenticationHelp
Related
I have a problem in getting access token. After getting auth code, when I called my get_access_token it returns "invalid_client" error. I researched about it but nothing helped me. Please, look at my code and help me to solve this problem. Thank you in advance.
Here is my code:
public function get_access_token($zoho_code)
{
$headers = array(
);
$taskurl = 'https://accounts.zoho.com/oauth/v2/token';
$cdata = array(
'code' => $zoho_code,
'grant_type' => 'authorization_code',
'client_id' => $this->client_id,
'client_secret' => $this->client_secret_id,
'redirect_uri' => 'http://localhost/callback.php',
'scope' => 'ZohoMail.accounts.UPDATE,ZohoMail.accounts.READ,ZohoMail.partner.organization.READ,ZohoMail.partner.organization.UPDATE,ZohoMail.organization.accounts.CREATE,ZohoMail.organization.accounts.UPDATE,ZohoMail.organization.accounts.READ,ZohoMail.organization.domains.CREATE,ZohoMail.organization.domains.UPDATE,ZohoMail.organization.domains.DELETE,ZohoMail.organization.domains.READ',
'state' => '55555sfdfsdfgbcv',
);
$curlresult = $this->docurl($taskurl, $cdata, $headers);
return $curlresult;
}
public function docurl($taskurl, $cdata, $headers, $method = 'post',$sendjson=true) {
$ch = curl_init();
if ($method == 'get') {
if ($cdata) {
$query = '?' . http_build_query($cdata);
$taskurl .= $query;
}
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'GET');
} elseif ($method == 'delete') {
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'DELETE');
} elseif ($method == 'put') {
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
} elseif ($method == 'patch') {
if($sendjson) $cdata = json_encode($cdata);
curl_setopt($ch, CURLOPT_POSTFIELDS, $cdata);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PATCH');
} else {
if($sendjson) $cdata = json_encode($cdata);
curl_setopt($ch, CURLOPT_POSTFIELDS, $cdata);
}
curl_setopt($ch, CURLOPT_URL, $taskurl);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
$res = curl_exec($ch);
$information = curl_getinfo($ch);
print_r($information);
print_r($cdata);
curl_close($ch);
$resj = json_decode($res);
return $resj;
}
If I read your code correctly, you are sending your client_secret as part of a POST request body encoded as JSON.
You should make a POST request with application/x-www-form-urlencoded body and you should include the Authorization header with the client_secret encoded in the Basic scheme. For more info, see the OAuth2 RFC.
You need to change accounts.zoho.com according to your data centre. For example accounts.zoho.in for India. You can see this in the URL of your Zoho web app. It is written in their docs link.
I keep getting NULL in my response while trying to pull images for products. Making a request for list of products works fine. I'm using the version 2 of the Bigcommerce API. What am I missing?
My code is below:
$product_id = 82;
$organizationAccount = array(
"username" => "stores/xxxx",
"user_token" => "xxxxx"
);
$resource = 'http://api.bigcommerce.com/stores/xxxx/api/v2/products/'.$product_id.'/images.json';
$response = sendRequest($resource, 'GET', 'user_token'); //This gives null
Send Request function
function sendRequest($url, $method, $userToken, $postFields = null, $queryData = null){
$curlHandle = curl_init();
curl_setopt($curlHandle, CURLOPT_RETURNTRANSFER, true);
if( $method == "PUT" ){
curl_setopt($curlHandle, CURLOPT_HEADER, true);
}
curl_setopt($curlHandle, CURLOPT_CUSTOMREQUEST, $method);
$httpHeader = array('Content-Type: application/json');
$url = (strpos($url, "http") !== false ) ? str_replace("http", "https", $url) : "https://" . $url;
if ($method == "POST" || $method == "PUT" || $method == "DELETE") {
curl_setopt($curlHandle, CURLOPT_URL, $url);
curl_setopt($curlHandle, CURLOPT_POST, true);
curl_setopt($curlHandle, CURLOPT_POSTFIELDS, $postFields);
} elseif ($method == "GET") {
$url = (is_null($queryData)) ? $url : $url . "?" . http_build_query($queryData);
curl_setopt($curlHandle, CURLOPT_URL, $url);
}
if (!is_null($userToken)) {
$httpHeader[] = 'X-Auth-Client: ' . BC_CLIENT_ID; //Client id
$httpHeader[] = 'X-Auth-Token: ' . $userToken;
//curl_setopt($curlHandle);
curl_setopt($curlHandle, CURLOPT_HTTPHEADER, $httpHeader);
}
$response = curl_exec($curlHandle);
return json_decode($response, true);
}
the mistake was from the endpoint url it is supposed to be
$resource = 'http://api.bigcommerce.com/stores/xxxx/v2/products/'.$product_id.'/images.json';
thanks
I am trying to sign in with google plus Api in my web app.
I searched on it from https://developers.google.com/oauthplayground/https://developers.google.com/oauthplayground/
and I applied them.
When I request to https://www.googleapis.com/oauth2/v3/token , it returns
{ "error": "internal_failure", "error_description": "Unsupported content with type: multipart/form-data; boundary=----------------------------5dd1639f2986" }
I am putting my code snippets which are doing the request (as client id and secret as star)
I dont understand it, maybe you can help.
if(isset($_GET['code'])) {
// try to get an access token
$code = $_GET['code'];
$url = 'https://www.googleapis.com/oauth2/v3/token';
$params = array(
"code" => $code,
"client_id" => "************************",
"client_secret" => "************************",
"redirect_uri" => "http://localhost/googleplus/oauth2callback.php",
"grant_type" => "authorization_code"
);
$json=CallAPI('POST',$url,$params);
and my CALLAPI function
function CallAPI($method, $url, $data = false)
{
$curl = curl_init();
switch ($method)
{
case "POST":
curl_setopt($curl, CURLOPT_POST, 1);
if ($data)
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
break;
case "PUT":
curl_setopt($curl, CURLOPT_PUT, 1);
break;
default:
if ($data){
$url = sprintf("%s?%s", $url, http_build_query($data));
echo $url;
}
}
// Optional Authentication:
curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($curl, CURLOPT_USERPWD, "username:password");
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($curl);
curl_close($curl);
return $result;
}
You request is correct but missing something
the content type is not multipart/form-data should be application/x-www-form-urlencoded instead
I had very similar problem using OAuth2.0 to access Gmail from iOS app. Indeed Ahmad's suggestion is correct I'll expand it:
When you POST using HTTP there is a header field 'Content-Type:'. Looks like in your case it had default value of 'multipart/form-data' which is for binary data. For Google API OAuth2.0 make sure you set it to 'application/x-www-form-urlencoded'.
You can see this value in the example given here:
https://developers.google.com/identity/protocols/OAuth2InstalledApp#handlingtheresponse
You can read more about those two values for 'Content-Type' here:
application/x-www-form-urlencoded or multipart/form-data?
In my iOS framework I had to make a call to customize this HTTP header. Unfortunately I'm not familiar with PHP so hope that helps.
I had a very similar problem. I was finally able to resolve it by adding some elements to the HTTP header ("Content-Type" and "Content-Length") and manually constructing the url (so I can use 0 for "Content-Length").
$id_token = $_POST['id_token'];
$url = 'https://www.googleapis.com/oauth2/v3/tokeninfo?id_token='.$id_token;
$options = [
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_POST => 1,
CURLOPT_HTTPHEADER => array( "Content-Length: 0", "Content-Type: application/x-www-form-urlencoded"),
CURLOPT_SSL_VERIFYHOST => false,
CURLOPT_SSL_VERIFYPEER => false,
];
$curlObj = curl_init();
curl_setopt_array($curlObj, $options);
$returnData = curl_exec($curlObj);
if (curl_errno($curlObj)) {
//error message
$returnData = curl_error($curlObj);
}
echo $returnData;
if(isset($_REQUEST['code'])){
$ch =curl_init();
$auth_url = "https://www.googleapis.com/oauth2/v4/token";
$post = array(
'code' =>$_REQUEST['code'],
'client_id' => '**************',
'client_secret' => '************',
'redirect_uri' => 'http://localhost/prakash/redirect.php',
'grant_type' => 'authorization_code'
);
$postText = http_build_query($post);
$options = array(
CURLOPT_URL =>$auth_url,
CURLOPT_POST => true,
CURLOPT_SSL_VERIFYPEER =>false,
CURLOPT_RETURNTRANSFER =>true,
CURLOPT_POSTFIELDS => $postText
);
//print_r($ch);
curl_setopt_array($ch, $options);
$returnData = curl_exec($ch);
print_r($returnData);
curl_close($ch);
exit;
}else{
print_r($_REQUEST);
exit;
}
<?php
/**
*Class to instantiate different api connections
*
* #author Adam Bilsing <adambilsing#gmail.com>
*/
class connection
{
/**
*public and private variables
*
* #var string stores data for the class
*/
static public $path;
static private $user;
static private $token;
static private $headers;
/**
* Sets $_path, $_user, $_token, $_headers upon class instantiation
*
* #param $user, $path, $token required for the class
* #return void
*/
public function __construct($user, $path, $token) {
$path = explode('/api/v2/', $path);
$this->_path = $path[0];
$this->_user = $user;
$this->_token = $token;
$encodedToken = base64_encode($this->_user.":".$this->_token);
$authHeaderString = 'Authorization: Basic ' . $encodedToken;
$this->_headers = array($authHeaderString, 'Accept: application/json','Content-Type: application/json');
}
public static function http_parse_headers( $header )
{
$retVal = array();
$fields = explode("\r\n", preg_replace('/\x0D\x0A[\x09\x20]+/', ' ', $header));
foreach( $fields as $field ) {
if( preg_match('/([^:]+): (.+)/m', $field, $match) ) {
$match[1] = preg_replace('/(?<=^|[\x09\x20\x2D])./e', 'strtoupper("\0")', strtolower(trim($match[1])));
if( isset($retVal[$match[1]]) ) {
$retVal[$match[1]] = array($retVal[$match[1]], $match[2]);
} else {
$retVal[$match[1]] = trim($match[2]);
}
}
}
if ($retVal['X-Bc-Apilimit-Remaining'] <= 100) {
sleep(300);
}
}
public function error($body, $url, $json, $type) {
global $error;
if (isset($json)) {
$results = json_decode($body, true);
$results = $results[0];
$results['type'] = $type;
$results['url'] = $url;
$results['payload'] = $json;
$error = $results;
} else {
$results = json_decode($body, true);
$results = $results[0];
$results['type'] = $type;
$results['url'] = $url;
$error = $results;
}
}
/**
* Performs a get request to the instantiated class
*
* Accepts the resource to perform the request on
*
* #param $resource string $resource a string to perform get on
* #return results or var_dump error
*/
public function get($resource) {
$url = $this->_path . '/api/v2' . $resource;
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_HTTPHEADER, $this->_headers);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_VERBOSE, 1);
curl_setopt($curl, CURLOPT_HEADER, 1);
curl_setopt($curl, CURLOPT_HTTPGET, 1);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
$response = curl_exec($curl);
$http_status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
$header_size = curl_getinfo($curl, CURLINFO_HEADER_SIZE);
$headers = substr($response, 0, $header_size);
$body = substr($response, $header_size);
self::http_parse_headers($headers);
curl_close ($curl);
if ($http_status == 200) {
$results = json_decode($body, true);
return $results;
} else {
$this->error($body, $url, null, 'GET');
}
}
/**
* Performs a put request to the instantiated class
*
* Accepts the resource to perform the request on, and fields to be sent
*
* #param string $resource a string to perform get on
* #param array $fields an array to be sent in the request
* #return results or var_dump error
*/
public function put($resource, $fields) {
$url = $this->_path . '/api/v2' . $resource;
$json = json_encode($fields);
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_HTTPHEADER, $this->_headers);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_VERBOSE, 1);
curl_setopt($curl, CURLOPT_HEADER, 1);
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "PUT");
curl_setopt($curl, CURLOPT_POSTFIELDS, $json);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
$response = curl_exec($curl);
$http_status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
$header_size = curl_getinfo($curl, CURLINFO_HEADER_SIZE);
$headers = substr($response, 0, $header_size);
$body = substr($response, $header_size);
self::http_parse_headers($headers);
curl_close($curl);
if ($http_status == 200) {
$results = json_decode($body, true);
return $results;
} else {
$this->error($body, $url, $json, 'PUT');
}
}
/**
* Performs a post request to the instantiated class
*
* Accepts the resource to perform the request on, and fields to be sent
*
* #param string $resource a string to perform get on
* #param array $fields an array to be sent in the request
* #return results or var_dump error
*/
public function post($resource, $fields) {
global $error;
$url = $this->_path . '/api/v2' . $resource;
$json = json_encode($fields);
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_HTTPHEADER, $this->_headers);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_VERBOSE, 1);
curl_setopt($curl, CURLOPT_HEADER, 1);
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($curl, CURLOPT_POSTFIELDS, $json);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
$response = curl_exec ($curl);
$http_status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
$header_size = curl_getinfo($curl, CURLINFO_HEADER_SIZE);
$headers = substr($response, 0, $header_size);
$body = substr($response, $header_size);
self::http_parse_headers($headers);
curl_close ($curl);
if ($http_status == 201) {
$results = json_decode($body, true);
return $results;
} else {
$this->error($body, $url, $json, 'POST');
}
}
/**
* Performs a delete request to the instantiated class
*
* Accepts the resource to perform the request on
*
* #param string $resource a string to perform get on
* #return proper response or var_dump error
*/
public function delete($resource) {
$url = $this->_path . '/api/v2' . $resource;
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_HTTPHEADER, $this->_headers);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_VERBOSE, 1);
curl_setopt($curl, CURLOPT_HEADER, 1);
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "DELETE");
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
$response = curl_exec($curl);
$http_status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
$header_size = curl_getinfo($curl, CURLINFO_HEADER_SIZE);
$headers = substr($response, 0, $header_size);
$body = substr($response, $header_size);
self::http_parse_headers($headers);
curl_close ($curl);
if ($http_status == 204) {
return $http_status . ' DELETED';
} else {
$this->error($body, $url, null, 'DELETE');
}
}
}
?>
get('RESOURCE');
$store->delete('RESOURCE');
$store->post('RESOURCE', $fields);
$store->put('RESOURCE', $fields);
?>
If i run these code i m getting error like this
( ! ) Deprecated: preg_replace(): The /e modifier is deprecated, use preg_replace_callback instead in D:\wamp\www\Bigcommerce\connection.php on line 39
Notice: Undefined variable: fields in D:\wamp\www\Bigcommerce\singlepage.php on line 5
any one pls help me to solve this problem
I am trying to use the Bing Translation API, but I am confused.
There seems to be much possibilities (old and new ones) but I don't understand what I have to do.
Can someone please help me?
I want to send a HTTP Request like http://api.microsofttranslator.com/V2/Ajax.svc/Translate?appId=<AppId>&to=de&text=World and get the translation. Where to get the AppId?
What I have done so far:
Signed in for the free API useage (https://datamarket.azure.com/dataset/bing/microsofttranslator)
Created an App: https://datamarket.azure.com/developer/applications
Now I have the Client_ID and Client_Secret and also I have a account key (visible here https://datamarket.azure.com/account)
What to do now?
Thanks a lot or any help!
AppID is deprecated. How you need perform following steps:
Register you clientID, clientSecter in https://datamarket.azure.com
Then you code must getting access token for login BingTranslator API
Read more details instrustions on http://msdn.microsoft.com/en-us/library/dd576287.aspx
NB Microsoft Translator has been replaced by Bing Translate, which does not appear to have a readily-available API.
Follow the links on http://api.microsofttranslator.com. The API takes an access token in the appid parameter. See the section "Obtaining an access token" in the documentation to learn how to get that token.
Feel free to use this instructions (if you're using php):
Define your keys
$apis['azure']['id'] = 123456789
$apis['azure']['key'] = 'abcde123456';
Classes and functions
class AccessTokenAuthentication {
function getTokens($grantType, $scopeUrl, $clientID, $clientSecret, $authUrl){
try {
$ch = curl_init();
$paramArr = array (
'grant_type' => $grantType,
'scope' => $scopeUrl,
'client_id' => $clientID,
'client_secret' => $clientSecret
);
$paramArr = http_build_query($paramArr);
curl_setopt($ch, CURLOPT_URL, $authUrl);
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, $paramArr);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$strResponse = curl_exec($ch);
$curlErrno = curl_errno($ch);
if($curlErrno){
$curlError = curl_error($ch);
throw new Exception($curlError);
}
curl_close($ch);
$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 {
function curlRequest($url, $authHeader, $postData=''){
$ch = curl_init();
curl_setopt ($ch, CURLOPT_URL, $url);
curl_setopt ($ch, CURLOPT_HTTPHEADER, array($authHeader,"Content-Type: text/xml"));
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, False);
if($postData) {
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
}
$curlResponse = curl_exec($ch);
$curlErrno = curl_errno($ch);
if ($curlErrno) {
$curlError = curl_error($ch);
throw new Exception($curlError);
}
curl_close($ch);
return $curlResponse;
}
function xmlLanguageCodes($languageCodes) {
$requestXml = '<ArrayOfstring xmlns="http://schemas.microsoft.com/2003/10/Serialization/Arrays" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">';
if(sizeof($languageCodes) > 0){
foreach($languageCodes as $codes) {
$requestXml .= "<string>$codes</string>";
}
} else {
throw new Exception('$languageCodes array is empty.');
}
$requestXml .= '</ArrayOfstring>';
return $requestXml;
}
function xmlTranslateArray($fromLanguage,$toLanguage,$contentType,$inputStrArr) {
$requestXml = "<TranslateArrayRequest>".
"<AppId/>".
"<From>$fromLanguage</From>".
"<Options>" .
"<Category xmlns=\"http://schemas.datacontract.org/2004/07/Microsoft.MT.Web.Service.V2\" />" .
"<ContentType xmlns=\"http://schemas.datacontract.org/2004/07/Microsoft.MT.Web.Service.V2\">$contentType</ContentType>" .
"<ReservedFlags xmlns=\"http://schemas.datacontract.org/2004/07/Microsoft.MT.Web.Service.V2\" />" .
"<State xmlns=\"http://schemas.datacontract.org/2004/07/Microsoft.MT.Web.Service.V2\" />" .
"<Uri xmlns=\"http://schemas.datacontract.org/2004/07/Microsoft.MT.Web.Service.V2\" />" .
"<User xmlns=\"http://schemas.datacontract.org/2004/07/Microsoft.MT.Web.Service.V2\" />" .
"</Options>" .
"<Texts>";
foreach ($inputStrArr as $inputStr) {
$requestXml .= "<string xmlns=\"http://schemas.microsoft.com/2003/10/Serialization/Arrays\">$inputStr</string>";
}
$requestXml .= "</Texts>".
"<To>$toLanguage</To>" .
"</TranslateArrayRequest>";
return $requestXml;
}
}
function get_language_names($locale="en") {
global $list, $apis;
try {
$clientID = $apis['azure']['id'];
$clientSecret = $apis['azure']['key'];
$authUrl = "https://datamarket.accesscontrol.windows.net/v2/OAuth2-13/";
$scopeUrl = "http://api.microsofttranslator.com";
$grantType = "client_credentials";
$authObj = new AccessTokenAuthentication();
$accessToken = $authObj->getTokens($grantType, $scopeUrl, $clientID, $clientSecret, $authUrl);
$authHeader = "Authorization: Bearer ". $accessToken;
foreach($list['translate'] as $k=>$iso) {
$languageCodes[] = $k;
}
$url = "http://api.microsofttranslator.com/V2/Http.svc/GetLanguageNames?locale=$locale";
$translatorObj = new HTTPTranslator();
$requestXml = $translatorObj->xmlLanguageCodes($languageCodes);
$curlResponse =$translatorObj->curlRequest($url, $authHeader, $requestXml);
$xmlObj = simplexml_load_string($curlResponse);
$i=0;
foreach($xmlObj->string as $language) {
$result[$languageCodes[$i]] = (string)$language;
$i++;
}
return $result;
} catch (Exception $e) {
echo "Exception: " . $e->getMessage() . PHP_EOL;
}
}
function get_translate($array, $from, $to, $html=false) {
global $apis;
try {
$clientID = $apis['azure']['id'];
$clientSecret = $apis['azure']['key'];
$authUrl = "https://datamarket.accesscontrol.windows.net/v2/OAuth2-13/";
$scopeUrl = "http://api.microsofttranslator.com";
$grantType = "client_credentials";
$authObj = new AccessTokenAuthentication();
$accessToken = $authObj->getTokens($grantType, $scopeUrl, $clientID, $clientSecret, $authUrl);
$authHeader = "Authorization: Bearer ". $accessToken;
$fromLanguage = $from;
$toLanguage = $to;
$inputStrArr = array_values($array);
if($html) {
$contentType = 'text/html';
foreach($inputStrArr as $k=>$item) {
$inputStrArr[$k] = htmlentities($inputStrArr[$k]);
}
} else {
$contentType = 'text/plain';
}
$translatorObj = new HTTPTranslator();
$requestXml = $translatorObj->xmlTranslateArray($fromLanguage,$toLanguage,$contentType,$inputStrArr);
$translateUrl = "http://api.microsofttranslator.com/v2/Http.svc/TranslateArray";
$curlResponse = $translatorObj->curlRequest($translateUrl, $authHeader, $requestXml);
$xmlObj = simplexml_load_string($curlResponse);
foreach($xmlObj->TranslateArrayResponse as $translatedArrObj){
$result[] = (string)$translatedArrObj->TranslatedText;
}
return $result;
} catch (Exception $e) {
echo "Exception: " . $e->getMessage() . PHP_EOL;
}
}
function get_translate_single($input, $from, $to, $html=false) {
global $apis;
try {
$clientID = $apis['azure']['id'];
$clientSecret = $apis['azure']['key'];
$authUrl = "https://datamarket.accesscontrol.windows.net/v2/OAuth2-13/";
$scopeUrl = "http://api.microsofttranslator.com";
$grantType = "client_credentials";
$authObj = new AccessTokenAuthentication();
$accessToken = $authObj->getTokens($grantType, $scopeUrl, $clientID, $clientSecret, $authUrl);
$authHeader = "Authorization: Bearer ". $accessToken;
$fromLanguage = $from;
$toLanguage = $to;
if($html) {
$contentType = 'text/html';
$input = htmlentities($input);
} else {
$contentType = 'text/plain';
}
# params
$params = "text=".urlencode($input)."&to=".$toLanguage."&from=".$fromLanguage;
$translateUrl = "http://api.microsofttranslator.com/v2/Http.svc/Translate?".$params;
# object
$translatorObj = new HTTPTranslator();
$curlResponse = $translatorObj->curlRequest($translateUrl, $authHeader);
# interprets a string of XML into an object.
$xmlObj = simplexml_load_string($curlResponse);
foreach((array)$xmlObj[0] as $val){
$result = $val;
}
return $result;
} catch (Exception $e) {
echo "Exception: " . $e->getMessage() . PHP_EOL;
}
}
The calls
echo get_translate_single('horse', 'en', 'es'); //this will print 'caballo'
or
echo get_translate(array('horse', 'house'), 'en', 'es'); //this will print array('caballo', 'casa')
That's it, have fun and remember to follow the terms of service.