Here is the method provide by Volusion support for ProductSync but the code in C# i want to implement in PHP but how to implement it i don't know.
https://support.volusion.com/hc/en-us/articles/209637767-API-Integration-ProductSync-Developer-
So anyone can help me that how to implement in PHP because i am working on PHP i have no knowledge of C#. I just copy this code in paste in my PHP it give me an error like this
Fatal error: Class 'XMLHTTP' not found in /home/tlztech/public_html/volusion/productSync.php on line 5.
And my code as under.
<?php
$api_url = "http://tebkq.mvlce.servertrust.com/net/WebService.aspx?Login=mylogin&EncryptedPassword=mypass&API_Name=Generic\\Products&SELECT_Columns=p.ProductCode,p.ProductID,p.ProductName,p.StockStatus";
$xml_http = new XMLHTTP();
$xml_http.open("POST", $api_url, false, "", "");
$xml_http.send(null);
$api_response = $xml_http.responseText;
$api_url = "http://tebkq.mvlce.servertrust.com/net/WebService.aspx?Login=mylogin&EncryptedPassword=mypass&Import=Update";
$api_request = "";
$api_request = $api_request + "<?xml version=\"1.0\" encoding=\"utf-8\" ?>";
$api_request = $api_request + "<xmldata>";
$api_request = $api_request + " <Products>";
$api_request = $api_request + " <ProductCode>0001</ProductCode>";
$api_request = $api_request + " <StockStatus>5</StockStatus>";
$api_request = $api_request + " </Products>";
$api_request = $api_request + "</xmldata>";
$xml_http = new XMLHTTP();
$xml_http.open("POST", $api_url, false, "", "");
$xml_http.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8");
$xml_http.setRequestHeader("Content-Action", "Volusion_API");
$xml_http.send(api_request);
$xml_http = $xml_http.responseText;
$api_url = "http://tebkq.mvlce.servertrust.com/net/WebService.aspx?Login=mylogin&EncryptedPassword=mypass&API_Name=Generic\\Products&SELECT_Columns=p.ProductCode,p.ProductID,p.ProductName,p.StockStatus&WHERE_Column=p.ProductCode&WHERE_Value=0002";
$xml_http = new XMLHTTP();
$xml_http.open("POST", $api_url, false, "", "");
$xml_http.send(null);
$api_response = $xml_http.responseText;
?>
You're trying to reference a Microsoft class that doesn't exist in PHP.
I see in your other recent threads that you've tried to call the Volusion API with cURL. This is a valid approach that I use with PHP. There's no need to adapt the C# example into PHP.
Here is a valid example in PHP using cURL and your URL example:
$api_url = "http://tebkq.mvlce.servertrust.com/net/WebService.aspx?Login=mylogin&EncryptedPassword=mypass&Import=Update";
$api_request = '<?xml version="1.0" encoding="utf-8" ?>';
$api_request .= '<xmldata>';
$api_request .= ' <Products>';
$api_request .= ' <ProductCode>0001</ProductCode>';
$api_request .= ' <StockStatus>5</StockStatus>';
$api_request .= ' </Products>';
$api_request .= '</xmldata>';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $api_url);
curl_setopt($ch, CURLOPT_HEADER, FALSE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, $api_request);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type:application/x-www-form-urlencoded; charset=utf-8", "Content-Action:Volusion_API"));
$head = curl_exec($ch);
$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
I think it's because you need to use namespace of you're XMLHTTP class :
$xml_http = new Your\Namespace\XMLHTTP();
because there is no XMLHTTP class in your file. That's why it is not found
Then if you want to use only XMLHTTP() you need to add a use at the beginning of your file:
use <NAMESPACE>;
If this class is from the global namespace just do it like that :
$xml_http = new \XMLHTTP();
Related
I need a local CORS proxy to load images from an external source. These images should be rendered in the canvas object.
For this I use the solution from https://github.com/softius/php-cross-domain-proxy
However no images are loaded but there is an empty response
This is the Part where Images should be rendered in a Canvas Object
loadImages() {
this.images.forEach((value, index) => {
const image = {};
image.img = new Image();
image.img.crossOrigin = 'anonymous';
image.img.src = 'https://cors-anywhere.herokuapp.com/' + value.packshot;
//image.img.src = '/proxy.php?csurl=' + value.packshot;
image.img.onload = (() => {
// some code
});
});
},
this works
https://cors-anywhere.herokuapp.com/http://download.falk-ross.eu/ws/picture/163_06_051_f-2015-nc_01.jpg
this doesn't work /proxy.php?csurl=http://download.falk-ross.eu/ws/picture/163_06_051_f-2015-nc_01.jpg
anyone knows advice?
got it - with many thanks to this greate community. sometimes the solutions comes in when asking the question
<?php
$url = ($_POST['url']) ? $_POST['url'] : $_GET['url'];
$headers = ($_POST['headers']) ? $_POST['headers'] : $_GET['headers'];
$mimeType = ($_POST['mimeType']) ? $_POST['mimeType'] : $_GET['mimeType'];
$session = curl_init($url);
if ($_POST['url']) {
$postvars = '';
while ($element = current($_POST)) {
$postvars .= key($_POST) . '=' . $element . '&';
next($_POST);
}
curl_setopt($session, CURLOPT_POST, true);
curl_setopt($session, CURLOPT_POSTFIELDS, $postvars);
}
curl_setopt($session, CURLOPT_HEADER, $headers == 'true');
curl_setopt($session, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($session, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($session);
if ($mimeType != '') {
header('Content-Type: ' . $mimeType);
}
echo $response;
curl_close($session);
I have read over the documentation many times and tried solutions that I found on the internet and I am struggling to retrieve the data I want from the eBay Shopping API using the GetSingleItem request. I believe I have my headers and xml request set up correctly based on the examples in the documentation but I can't work out how to actually send the request and retrieve the xml response. Can someone help me on the next step please?
How do I actually send the request and retrieve the response?
My headers and xml request look like this:
// Create headers
$headers = array
(
'X-EBAY-API-APP-ID: ' . $app_id,
'X-EBAY-API-SITE-ID: ' . $site_id,
'X-EBAY-API-CALL-NAME: ' . $call_name,
'X-EBAY-API-VERSION: ' . $version,
'X-EBAY-API-REQUEST-ENCODING: ' . $encoding,
);
// Generate XML request
$xml_request = '<?xml version="1.0" encoding="utf-8"?>\n';
$xml_request .= '<GetSingleItemRequest xmlns="urn:ebay:apis:eBLBaseComponents">\n';
$xml_request .= '<ItemID>283814879195</ItemID>\n';
$xml_request .= '<IncludeSelector>Details</IncludeSelector>\n';
$xml_request .= '</GetSingleItemRequest>';
What is the next step?
If it helps, this is my complete code so far that I have tried but I get "Failed to load" when I try to use simplexml_load_string. I have removed my app_id for security also:
<?php
error_reporting(E_ALL);
ini_set('display_errors', '1');
function getItem($itemID) {
$endpoint = 'https://open.api.ebay.com/shopping';
$app_id = 'XXXXXXXXXXX';
$site_id = '3';
$call_name = 'GetSingleItem';
$version = '863';
$encoding = 'xml';
// Create headers to send with CURL request.
$headers = array
(
'X-EBAY-API-APP-ID: ' . $app_id,
'X-EBAY-API-SITE-ID: ' . $site_id,
'X-EBAY-API-CALL-NAME: ' . $call_name,
'X-EBAY-API-VERSION: ' . $version,
'X-EBAY-API-REQUEST-ENCODING: ' . $encoding,
);
// Generate XML request
$xml_request = '<?xml version="1.0" encoding="utf-8"?>\n';
$xml_request .= '<GetSingleItemRequest xmlns="urn:ebay:apis:eBLBaseComponents">\n';
$xml_request .= '<ItemID>283814879195</ItemID>\n';
$xml_request .= '<IncludeSelector>Details</IncludeSelector>\n';
$xml_request .= '</GetSingleItemRequest>';
$session = curl_init($endpoint); // create a curl session
curl_setopt($session, CURLOPT_POST, true); // POST request type
curl_setopt($session, CURLOPT_HTTPHEADER, $headers); // set headers using $headers array
curl_setopt($session, CURLOPT_POSTFIELDS, $xml_request); // set the body of the POST
curl_setopt($session, CURLOPT_RETURNTRANSFER, true); // return values as a string, not to std out
$responsexml = curl_exec($session); // send the request
curl_close($session); // close the session
return $responsexml; // returns a string
}
$itemID = '283814879195';
$resp = simplexml_load_string(getItem($itemID)) or die("Failed to load");
print($resp->Item->ItemID);
?>
I was having the same issue.
I'll be posting my project on my Github publicly once I am done, so here you go.
Note that ItemID is being passed into the function. You can ignore the GET in the first bit of code if you intend on hard coding the itemID.
$ItemID = $_GET['itemid'];
itemDetails($ItemID);
Then
function itemDetails($ItemID) {
$url = 'https://open.api.ebay.com/shopping';
$app_id = '[ADD YOUR APP ID]';
$site_id = '0';
$call_name = 'GetSingleItem';
$version = '863';
$encoding = 'xml';
$xml = "<?xml version=\"1.0\" encoding=\"utf-8\"?>";
$xml.= "<GetSingleItemRequest xmlns=\"urn:ebay:apis:eBLBaseComponents\">";
$xml .= "<ItemID>".$ItemID."</ItemID>";
$xml .= "</GetSingleItemRequest>";
$headers = array(
'X-EBAY-API-APP-ID:'.$app_id,
'X-EBAY-API-SITE-ID:'.$site_id,
'X-EBAY-API-CALL-NAME:'.$call_name,
'X-EBAY-API-VERSION:'.$version,
'X-EBAY-API-REQUEST-ENCODING:'.$encoding,
'Content-type:text/xml;charset=utf-8'
);
$connection = curl_init();
curl_setopt($connection, CURLOPT_URL, $url);
curl_setopt($connection, CURLOPT_HTTPHEADER, $headers);
curl_setopt($connection, CURLOPT_POST, 1);
curl_setopt($connection, CURLOPT_POSTFIELDS, $xml);
curl_setopt($connection, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($connection);
echo $result;
curl_close($connection);
}
Hopefully, this helps!
I'm trying to add a job to the Workflow Max API. I seem to be hitting the API but I keep getting the error message:
Message not in expected format. The following required element was missing - Job/ClientID
I'm sure that the client ID is added but something seems to be wrong. This is the code:
function post_job_to_workflow_max($job_data) {
// configure our connection to the api
$api_token = 'API_KEY';
$acc_key = 'ACC_TOKEN';
$url = 'https://api.workflowmax.com/job.api/add?apiKey=' . $api_token . '&accountKey=' . $acc_key;
// Job data must match the format required by WorkflowMax
// currently accepts XML data
// see: https://www.workflowmax.com/api/job-methods#POST%20add
$xml = new SimpleXMLElement("<Job></Job>");
$xml->addChild('Name', $job_data[0]);
$xml->addChild('Description', $job_data[1]);
$xml->addChild('ClientID', 18754031);
// $clientID = $xml->addChild('Client');
// $clientID->addChild('ID', 18754031);
// $clientID->addChild('Name', "TEST CLIENT");
$xml->addChild('State', 'Planned');
$xml->addChild('StartDate', $job_data[2]);
$xml->addChild('DueDate', $job_data[3]);
// print_r($xml);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $xml->asXML());
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: text/xml',
'Content-Length: ' . strlen($xml->asXML()))
);
$output = curl_exec($ch);
curl_close($ch);
$result = simplexml_load_string($output);
print_r($result);
}
If there's anyone with experience of using WFM, would be good to hear how you approached it.
Thanks
So in answer to my own question, I did finally work this out.
The way I did this was to return the ID of the client from the function I used to post a client to WorkFlow Max. See code:
1) post the client
function post_client_to_workflowmax($client_data) {
// configure our connection to the api
$api_token = 'YOUR_TOKEN';
$acc_key = 'YOUR_KEY';
$url = 'https://api.workflowmax.com/client.api/add?apiKey=' . $api_token . '&accountKey=' . $acc_key;
// Client data must match the format required by WorkflowMax
// currently accepts XML data
// These indexes match up with how the data has been stored
// see: https://www.workflowmax.com/api/client-methods#POST%20add
$xml = new SimpleXMLElement("<Client></Client>");
$xml->addChild('Name', htmlspecialchars($client_data[2]));
$xml->addChild('Email', htmlspecialchars($client_data[9]));
$xml->addChild('Phone', htmlspecialchars($client_data[10]));
$xml->addChild('Address', htmlspecialchars($client_data[3]) . ' ' . htmlspecialchars($client_data[4]));
$xml->addChild('City', htmlspecialchars($client_data[5]));
$xml->addChild('Postcode', htmlspecialchars($client_data[7]));
$xml->addChild('Country', htmlspecialchars($client_data[8]));
$xml->addChild('IsProspect', 'No');
$contacts = $xml->addChild('Contacts');
$contact = $contacts->addChild('Contact');
$name = $contact->addChild('Name', htmlspecialchars($client_data[0]) . ' ' . htmlspecialchars($client_data[1]));
// POST request
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $xml->asXML());
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: text/xml',
'Content-Length: ' . strlen($xml->asXML()))
);
$output = curl_exec($ch);
curl_close($ch);
// Create an array from the data that is sent back from the API
$result = simplexml_load_string($output);
$clientID = NULL;
// here we get the ID created for this client and pass it into the variable $clientID
foreach($result->Client as $k => $v) {
$clientID = $v->ID;
}
return $clientID;
}
We then get that ID passed into our job posting function like so:
2) post a job to WFM
function post_job_to_workflow_max($job_data, $clientID) {
// configure our connection to the api
$api_token = 'YOUR_TOKEN';
$acc_key = 'YOUR_KEY';
$url = 'https://api.workflowmax.com/job.api/add?apiKey=' . $api_token . '&accountKey=' . $acc_key;
// Job data must match the format required by WorkflowMax
// currently accepts XML data
// see: https://www.workflowmax.com/api/job-methods#POST%20add
$xml = new SimpleXMLElement("<Job></Job>");
$xml->addChild('ClientID', $clientID);
$xml->addChild('Name', htmlspecialchars($job_data[0]));
$xml->addChild('Description', htmlspecialchars($job_data[1]));
$xml->addChild('State', 'Planned');
$xml->addChild('StartDate', htmlspecialchars($job_data[2]));
$xml->addChild('DueDate', htmlspecialchars($job_data[3]));
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $xml->asXML());
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: text/xml',
'Content-Length: ' . strlen($xml->asXML()))
);
$output = curl_exec($ch);
curl_close($ch);
$result = simplexml_load_string($output);
}
And then calling these functions looks something like this:
$id = post_client_to_workflowmax($client);
post_job_to_workflow_max($job, $id);
Where $client must be an array of data. This worked for my case but might not work for your particular case so you may need to edit the fields etc.
Hopefully this helps someone who is stuck with the same problem. Not the most elegant code but it gets the job done.
I have the script below written in Ruby. I was wondering is anyone can help me convert it to PHP. I know this is a big ask. I am looking to convert the ruby script to a PHP curl request.
See the link to the documentation https://www.sinch.com/docs/rest-apis/api-documentation/#applicationsignedrequest
The first code is the SAMPLE ruby script. While the second below it is what i have attempted to write in PHP on my own. Without success because i get "Invalid signature error".
require "base64"
require "openssl"
require "time"
require "net/http"
require "uri"
require "json"
to = "+4412345678"
message = "Test sms message"
key = "wwwwwwwwwxxxxxxxx" //Key as supplied by sinch.com
secret = "zzzzzzzyyyyyyyyy" // Secret as supplied by sinch.com
body = "{\"message\":\"" + message + "\"}"
timestamp = Time.now.iso8601
http_verb = "POST"
path = "/v1/sms/" + to
scheme = "Application"
content_type = "application/json"
digest = OpenSSL::Digest.new('sha256')
canonicalized_headers = "x-timestamp:" + timestamp
content_md5 = Base64.encode64(Digest::MD5.digest(body.encode("UTF-8"))).strip
string_to_sign = http_verb + "\n" + content_md5 + "\n" + content_type + "\n" + canonicalized_headers + "\n" + path
signature = Base64.encode64(OpenSSL::HMAC.digest(digest, Base64.decode64(secret), string_to_sign.encode("UTF-8"))).strip
authorization = "Application " + key + ":" + signature
uri = URI.parse("https://messagingApi.sinch.com" + path)
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
http.verify_mode = OpenSSL::SSL::VERIFY_NONE
headers = {"content-type" => "application/json", "x-timestamp" => timestamp, "authorization" => authorization}
request = Net::HTTP::Post.new(uri.request_uri)
request.initialize_http_header(headers)
request.body = body
puts JSON.parse(http.request(request).body)
Below is my script and i have no problem accepting an entirely new script. I am a super ruby rookie. Please help.
$to="+4412345678";
$text="Hello there test message";
$curl_post_data = array(
'Message' => $text
);
$curl_post_data=json_encode($curl_post_data);
$timestamp=date("c");
$key = "wwwwwwwwwwwxxxxxxxxxxx";
$secret = "zzzzzzzzzzzzyyyyyyyyyyy";
$http_verb="POST";
$path = "/v1/sms/".$to."";
$scheme = "Application ";
$content_type = "application/json";
$canonicalized_headers = "x-timestamp:".$timestamp."";
$content_md5=base64_encode( md5($curl_post_data,true) );
$string_to_sign = array(
'http_verb' => $http_verb,
'content_md5' => $content_md5,
'content_type' => $content_type,
'canonicalized_headers' =>$canonicalized_headers
);
$signature = hash_hmac("sha256", $secret,json_encode($string_to_sign));
$authorization = "".$scheme."".$key.":".$signature."";
$service_url = 'https://messagingapi.sinch.com/v1/sms/'.$to.'';
$curl = curl_init($service_url);
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: application/json; charset=UTF-8', 'x-timestamp: '.$timestamp.'','authorization: '.$authorization.''));
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $curl_post_data);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
$curl_response = curl_exec($curl);
$response = json_decode($curl_response);
curl_close($curl);
var_dump($response);
?>
Any help will do please, Stackoverflow has been a useful resource whenever am stuck with something, i hope my question helps others too.
I got it to work, had to rewrite a few things. Anyway, here's a working code for anyone that might need it.
<?php
$to="+4412345678";
$text2="Test sms message from PHP";
$curl_post_data = array(
'message' => $text2
);
$timestamp=date("c");
$key = "wwwwwwwwwwwwwxxxxxxxxxxxxxxx";
$secret ="zzzzzzzzzzzzyyyyyyyyyyyyyy";
$http_verb="POST";
$path = "/v1/sms/".$to."";
$scheme = "Application";
$content_type = "application/json";
$canonicalized_headers = "x-timestamp:".$timestamp."";
$content_md5=md5(json_encode($curl_post_data),true);
$string_to_sign ="".$http_verb."\n".$content_md5."\n".$content_type."\n".$canonicalized_headers."\n".$path."\n";
$signature = hash_hmac("sha256", base64_encode($secret),utf8_encode($string_to_sign) true);
$signature=base64_encode($signature);
$authorization = "".$scheme."".$key.":".$signature."";
$curl_post_data=json_encode($curl_post_data);
$service_url = 'https://messagingapi.sinch.com/v1/sms/'.$to.'';
$curl = curl_init($service_url);
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: application/json; charset=UTF-8','x-timestamp:'.$timestamp.'','authorization:'.$authorization.''));
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $curl_post_data);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
$curl_response = curl_exec($curl);
$response = json_decode($curl_response);
curl_close($curl);
var_dump($response);
?>
Completely working code. Also, thanks to 'Stephen' for basical porting from Ruby to PHP. It saves me a lot of time.
Some notes:
Key should be copied from apps menu of sinch account as is (without any conversion)
String to sign shouldn't contain new line at the end. Also, please check every changes by setting default values from commented code.
In the PHP hash_hmac function cody should be defined before secret (in Ruby arguments should be defined in other order)
If actual headers will contain charset definition - string_to_sign should contain it too. I have deleted them at all.
$key = 'key';
$secret = 'secret';
$message = 'your message';
$phone = '+000000000000';
$body = json_encode(array('message'=>$message));
$timestamp = date("c");
// {{{ test values for checking code (from docs)
/*
$phone="+46700000000";
$key = "5F5C418A0F914BBC8234A9BF5EDDAD97";
$secret ="JViE5vDor0Sw3WllZka15Q==";
$timestamp='2014-06-04T13:41:58Z';
$body = '{"message":"Hello world"}';
*/
// result:
// content-md5 should be 'jANzQ+rgAHyf1MWQFSwvYw=='
// signature should be 'qDXMwzfaxCRS849c/2R0hg0nphgdHciTo7OdM6MsdnM='
// }}}
$path = "/v1/sms/" . $phone;
$content_type = "application/json";
$canonicalized_headers = "x-timestamp:" . $timestamp;
$content_md5 = base64_encode( md5( utf8_encode($body), true ));
$string_to_sign =
"POST\n".
$content_md5."\n".
$content_type."\n".
$canonicalized_headers."\n".
$path;
$signature = base64_encode(hash_hmac("sha256", utf8_encode($string_to_sign), base64_decode($secret), true));
$authorization = "Application " . $key . ":" . $signature;
$curl_post_data=json_encode($curl_post_data);
$service_url = 'https://messagingapi.sinch.com'.$path;
$curl = curl_init($service_url);
curl_setopt($curl, CURLOPT_HTTPHEADER, array(
'content-type: '.$content_type,
'x-timestamp:' . $timestamp,
'authorization:' . $authorization
));
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $curl_post_data);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
$curl_response = curl_exec($curl);
// #todo: checking response / working with results
curl_close($curl);
I have the ZF first old function working before but somehow ZF it was failing, and then i made the unittest module.
I am trying to use the google translation v2 but it never works anymore, did Google stop there service for public use or is it PHP Bug or somewhere else confusing very much.
Always returning 403 with both following functions.
Any idea whats going wrong?
<?php
## Test: How to's
/*
$ php tst.php
403
$ curl http://ajax.googleapis.com/ajax/services/language/translate -d "v=1.0&q=dog&langpair=en|ru" -H "Referer: http://google.com"
{"responseData": null, "responseDetails": "Please use Translate v2. See http://code.google.com/apis/language/translate/overview.html", "responseStatus": 403}sun#sun-M14xR2:/var/www/html/vooyz.com/unittest$
*/
// V1 - Old not working
function googleTranslatePostV1($text, $destLang = 'nl', $srcLang = 'en') {
$url = 'http://ajax.googleapis.com/ajax/services/language/translate';
$http_response = '';
$text = urlencode($text);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_REFERER, !empty($_SERVER["HTTP_REFERER"]) ? $_SERVER["HTTP_REFERER"] : "");
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, "v=1.0&q=" . $text . "&langpair=$srcLang|$destLang");
$http_response = curl_exec($ch);
$json = json_decode($http_response, true);
if ($json['responseStatus'] != '200') {
return $json['responseStatus'];
} else {
return $json['responseData']['translatedText'];
}
curl_close($ch);
}
// V2 - Curl way not working
function googleTranslatePostV2($text, $destLang = 'nl', $srcLang = 'en') {
$url = 'https://www.googleapis.com/language/translate/v2';
$http_response = '';
$text = urlencode($text);
$postArr = array('key' => 'sdfdsfdsfds',
'q' => $text,
'source' => $srcLang,
'target' => $destLang);
$ch = curl_init();
//curl_setopt($ch, CURLOPT_POSTFIELDS,'hl=en&ie=UTF8&text=-->this+is+a+test<--&langpair=en%7Car');
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
curl_setopt($ch, CURLOPT_REFERER, !empty($_SERVER["HTTP_REFERER"]) ? $_SERVER["HTTP_REFERER"] : "");
curl_setopt($ch, CURLOPT_POST,true);
curl_setopt($ch, CURLOPT_POSTFIELDS,$postArr);
$http_response = curl_exec($ch);
var_dump($http_response);
$json = json_decode($http_response, true);
if ($json['responseStatus'] != '200') {
return $json['responseStatus'];
} else {
return $json['responseData']['translatedText'];
}
curl_close($ch);
}
// V2 - Google way
function googleTranslateV2Method1($text, $destLang = 'nl', $srcLang = 'en') {
require_once 'google/src/Google_Client.php';
require_once 'google/src/contrib/Google_TranslateService.php';
$client = new Google_Client();
$client->setApplicationName('Google Translate PHP Starter Application');
$client->setDeveloperKey('dsfdsfdsf');
$service = new Google_TranslateService($client);
//$langs = $service->languages->listLanguages();
//print "<h1>Languages</h1><pre>" . print_r($langs, true) . "</pre>";
$translations = $service->translations->listTranslations($text, 'hi');
return $translations;
}
echo googleTranslatePostV1("V1: " . "How are you?") . "\n";
echo googleTranslatePostV2("V2: " . "How are you?") . "\n";
echo googleTranslateV2Method1("V2: " . "How are you?") . "\n";
?>
$ curl http://ajax.googleapis.com/ajax/services/language/translate -d "v=1.0&q=dog&langpair=en|ru" -H "Referer: http://google.com"
{"responseData": null, "responseDetails": "Please use Translate v2. See http://code.google.com/apis/language/translate/overview.html", "responseStatus": 403}
http://code.google.com/apis/language/translate/overview.html : Google
Translate API is available as a paid service. See the Pricing and FAQ
pages for details.