I have a problem with my Prestashop module. I'm trying to send post with order products in hookActionValidateOrder. But if I get an error in API, or it just not working, the customer "confirm order page" is not loading(because it's waiting for API to answer).
The question is: Can I somehow make request send with WORKERS or jobs. Or should make with ajax code and pass it to the "confirm order page" template, so it would send the request after a user saw a page and it doesn't block with a request. Sorry about my English, I hope you will understand my question
public function hookActionValidateOrder($params)
{
if (Configuration::get('MY_API_STATUS') == 1) {
$id_order = $params['order']->id;
$products = $params['order']->getProducts();
$data = [];
$data['account_id'] = Configuration::get('MY_API_ACCOUNT_ID');
$data['project_id'] = Configuration::get('MY_API_PROJECT_ID');
$data['order_id'] = $id_order;
$productsData = [];
foreach ($products as $productItem) {
$product = array();
$product['order_id'] = $id_order;
$product['project_id'] = $data['project_id'];
$product['account_id'] = $data['account_id'];
$product['product_id'] = $productItem['product_id'];
$product['product_cost'] = Product::getPriceStatic($productItem['product_id']);
$product['quantity'] = $productItem['product_quantity'];
$productsData[] = $product;
}
$data['products'] = $productsData;
$returned = static::sendData($this->orderHookUrl, $data);
}
return;
}
this is the sendData code
private function sendData($url, $dataJson)
{
$payload = json_encode($dataJson);
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLINFO_HEADER_OUT, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json', 'Content-Length: ' . Tools::strlen($payload)));
$result = curl_exec($ch);
curl_close($ch);
return json_decode($result, true);
}
The question how to do that without blocking a hook, so customer can see a confirm page without waiting for respond from api.
Related
The code down below was implemented by me to retrieve specific details from LinkedIn accounts and save them to the database. Although they are retrieving correctly data is not saving to the database correctly. Not sure something wrong with my query. Please have a look at my coding and point out the issue. Any sort of help would be really appreciated.
<?php
session_start();
$client_id = "";
$client_secret = "";
$redirect_uri = "http://localhost:8888/Exercise/callback.php";
$csrf_token = random_int(1111111, 9999999);
$scopes = "r_basicprofile%20r_emailaddress";
function curl($url, $parameters)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $parameters);
curl_setopt($ch, CURLOPT_POST, 1);
$headers = [];
$headers[] = "Content-Type: application/x-www-form-urlencoded";
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$result = curl_exec($ch);
return $result;
}
function getCallback()
{
$client_id = "";
$client_secret = "";
$redirect_uri = "http://localhost:8888/Exercise/callback.php";
$csrf_token = random_int(1111111, 9999999);
$scopes = "r_basicprofile%20r_emailaddress";
if (isset($_REQUEST['code'])) {
$code = $_REQUEST['code'];
$url = "https://www.linkedin.com/oauth/v2/accessToken";
$params = [
'client_id' => $client_id,
'client_secret' => $client_secret,
'redirect_uri' => $redirect_uri,
'code' => $code,
'grant_type' => 'authorization_code',
];
$accessToken = curl($url,http_build_query($params));
$accessToken = json_decode($accessToken)->access_token;
$url = "https://api.linkedin.com/v1/people/~:(id,firstName,lastName,pictureUrls::(original),headline,publicProfileUrl,location,industry,positions,email-address )?format=json&oauth2_access_token=" . $accessToken;
$user = file_get_contents($url, false);
$User = json_decode(post_curl($url)); // Request user information on received token
$query = "INSERT INTO `linkedti_scheduler`.`users`
(`userid`,
`firstName`,
`lastName`,
`emailAddress`,
`position`,
`location`,
`profileURL`,
`headline`)
VALUES
('$id',
'$firstName',
'$lastName',
'$emailAddress',
'$position',
'$location',
'$profileURL',
'$headline')";
mysqli_query($connection,$query);
return (json_decode($user));
}
}
?>
You need to reference the fields using the $User object like this:
$User = json_decode(post_curl($url)); // Request user information on received token
$query = "INSERT INTO `linkedti_scheduler`.`users`
(`userid`,
`firstName`,
`lastName`,
`emailAddress`,
`position`,
`location`,
`profileURL`,
`headline`)
VALUES
('$id',
'$User->firstName',
'$User->lastName',
'$User->emailAddress',
'$User->position',
'$User->location',
'$User->profileURL',
'$User->headline')";
Also, be warned that you are not using an MySQL escaping here -- I suggest using a prepared query to prevent any issues with single quotes:
https://secure.php.net/manual/en/mysqli.quickstart.prepared-statements.php
I have the following JavaScript that sends parameters to a PHP file:
function getOutput()
{
$.ajax({
url:'myPHPFile.php',
data:{APIKey:$APIKey,Password:$APIPass,Alias:$Alias,DataCenter:$DataCenter},
type:'POST',
complete: function (response) {
$('#output').html(response.responseText);
},
error: function ()
{
$('#output').html('Bummer: there was an error!');
}
});
return response.responseText;
}`
Which changes the following HTML to the output of the PHP file:
test
Here is the PHP
<?php
// echo nl2br("\nIntializing api.php \n");
// DATA SECTION
$APIKey = $_POST["APIKey"];
$APIPass = $_POST["Password"];
$AccountAlias = $_POST["Alias"];
$dataCenter = $_POST["DataCenter"];
$data = array(
"APIKey" => $APIKey,
"Password" => $APIPass,
);
$url_send = 'https://api.ctl.io/REST/Auth/Logon/';
$json_data = json_encode($data);
function sendPostData($url, $post, $cook = null){
// echo "Beginning sendPostData($url, $post, $cook)";
$ch = curl_init($url);
$headers= array('Accept: application/json','Content-Type: application/json');
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS,$post);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
if (!empty($cook))
{
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Accept: application/json','Content-Type: application/json','Cookie:'.$cook));
}
$result = curl_exec($ch);
curl_close($ch); // Seems like good practice
return $result;
};
$myresult = sendPostData($url_send, $json_data);
// print_r ($myresult);
$decodedresult = json_decode($myresult);
// print_r ($decodedresult);
'/reply-(.*?)-private/';
preg_match_all('/Tier3(.*?)path=/', $myresult, $matches);
$cookies = array();
foreach($matches[0] as $item)
{
parse_str($item, $cookie);
$cookies = array_merge($cookies, $cookie);
}
$prefix = 'Tier3.API.Cookie=';
$cookie = implode(" ",$matches[0]);
// Call the customer server list
$data = array(
'AccountAlias' => $AccountAlias,
'Location' => $dataCenter
);
$data_url = 'https://api.ctl.io/REST/Server/GetAllServersForAccountHierarchy/';
$data_string = json_encode($data);
$dataResult = sendPostData($data_url,$data_string, $cookie);
print_r($dataResult);
return $dataResult;
`
How can I get the $dataResult PHP array into a javascript variable so I can parse it? It is a big JSON response from an API.
Thanks.
Ajax calls are (normally) asynchronous, this means that the return response.responseText; will be executed immediately and should even raise an error related to response being undefined.
You'll have the response in the complete event of the ajax call and is inside there where you should go on with the execution of the script. jQuery will parse the JSON automatically and response will be the resulting object.
At the other side, the PHP script should just print the result of json_encode() and nothing else in order for the response to be valid JSON.
I'm currently using whateverorigin.org in some javascript to retrieve a URL as a JSON object because a 3rd party site hasn't made one of their functions available via their JSON API.
I'd like to remove this dependancy from my website as whateverorigin.org breaks the HTTPS/SSL browser checks for secure content because it's a clear http call.
Has anyone done this? I haven't found an example of it anywhere.
Thanks in advance for a response!
Ok, so since I first typed up this question, I've now already found some examples and cobbled together a working proxy function in php... Feel free to use it for your own purposes!
<?php
// Sourced from: http://stackoverflow.com/questions/2511410/curl-follow-location-error
function curl_exec_follow(/*resource*/ &$ch, /*int*/ $redirects = 20, /*bool*/ $curlopt_header = false) {
if ((!ini_get('open_basedir') && !ini_get('safe_mode')) || $redirects < 1) {
curl_setopt($ch, CURLOPT_HEADER, $curlopt_header);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, $redirects > 0);
curl_setopt($ch, CURLOPT_MAXREDIRS, $redirects);
return curl_exec($ch);
} else {
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FORBID_REUSE, false);
do {
$data = curl_exec($ch);
if (curl_errno($ch))
break;
$code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if ($code != 301 && $code != 302)
break;
$header_start = strpos($data, "\r\n")+2;
$headers = substr($data, $header_start, strpos($data,"\r\n\r\n", $header_start)+2-$header_start);
if (!preg_match("!\r\n(?:Location|URI): *(.*?) *\r\n!",$headers, $matches))
break;
curl_setopt($ch, CURLOPT_URL, $matches[1]);
} while (--$redirects);
if (!$redirects)
trigger_error('Too many redirects. When following redirects, libcurl hit the maximum amount.', E_USER_WARNING);
if (!$curlopt_header)
$data = substr($data, strpos($data, "\r\n\r\n")+4);
return $data;
}
}
header('Content-Type: application/json');
$retrieveurl = curl_init(urldecode($_GET['url']));
$callbackname = $_GET['callback'];
$htmldata = curl_exec_follow($retrieveurl);
if (curl_error($retrieveurl))
die(curl_error($retrieveurl));
$status = curl_getinfo($retrieveurl, CURLINFO_HTTP_CODE);
curl_close($retrieveurl);
$data = array('contents' => $htmldata, 'status' => $status);
$jsonresult = json_encode($data);
echo $callbackname . '(' . $jsonresult . ')';
?>
Hope this helps someone!
I'm having an issue trying to submit a form for a medical website to determine a user's name based on their registration number or their national ID number. An example Registration Number is MPS0753602
Site in question: http://isystems.hpcsa.co.za/iregister/
I can do an initial query to generate the second input form which is generated using a dopostback when clicking on one of the options, in this case clicking on "Registration Number". My issue is that if I fill in all the fields as examined by FireCurl I get a server error, even if I fill them in identically. I think it has something to do with the Javascript on the page.
My code:
<?php
// Specify a cookie file
$cookiefile = '/var/www/hpcsa/cookies.txt';
$client = new Login($cookiefile);
// Retrieve page first to store cookies
$page = file_get_contents("http://isystems.hpcsa.co.za/iregister/");
// scrape __VIEWSTATE value
$start = strpos($page, '__VIEWSTATE" value="') + 20;
$end = strpos($page, '"', $start);
$viewstate = substr($page, $start, $end - $start);
// scrape __EVENTVALIDATION value
$start = strpos($page, '__EVENTVALIDATION" value="') + 26;
$end = strpos($page, '"', $start);
$eventvalidation = substr($page, $start, $end - $start);
// Do our actual query
$form_data = array(
'SearchChkb$0' => 'on',
'__EVENTARGUMENT' => '',
'__EVENTTARGET' => '',
'__EVENTVALIDATION' => $eventvalidation,
'__LASTFOCUS' => '',
'__VIEWSTATE' => $viewstate,
'rgReg_No' => 'rbReg_NoExact',
'txtReg_No' => 'MPS0753602'
);
$page = $client -> get("http://isystems.hpcsa.co.za/iregister/", $form_data);
echo($page);
// cURL wrapper class
class Login {
private $_cookiefile;
public function __construct($cookiefile) {
if (!is_writable($cookiefile)) {
throw new Exception('Cannot write cookiefile: ' . $cookiefile);
}
$this -> _cookiefile = $cookiefile;
}
public function get($url, $data = false) {
// Setup cURL
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_REFERER, 'http://isystems.hpcsa.co.za/iregister/');
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_AUTOREFERER, true);
curl_setopt($ch, CURLOPT_MAXREDIRS, 10);
// Is there data to post
if (!empty($data)) {
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
}
return curl_exec($ch);
}
}
?>
I have a task to find a way to stop using the php curl, and I have to use only javascript without jQuery.
This was my php file and it was called by another ajax:
$jsonData = json_decode(file_get_contents('php://input'));
$url ='https://api.#######.com/####'; // this is not my website, just using their api
$ch = curl_init();
$data = array(
'text' => $jsonData,
'from' => 'eng',
'to' => 'fra'
);
$data_encoded = json_encode($data);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json',
'Authorization: SECRET apikey=###'));
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_encoded);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
$result = curl_exec($ch);
echo $result;
This is my new ajax but i get this error: NS_ERROR_FAILURE: Failure
function getTranslation(a_data,from,to)
{
var json_array = {};
var url = 'https://api.#####.com/#####';
var xmlhttp;
json_array = { 'text': a_data,
'from' : 'eng',
'to' : 'fra' };
var json_data = JSON.stringify(json_array);
console.log(json_data);
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("POST", url, false);
xmlhttp.setRequestHeader("Content-type","application/json");
xmlhttp.setRequestHeader("Authorization","SECRET apiKey=###");
xmlhttp.send();
json_parsed = JSON.parse(xmlhttp.responseText);
return json_parsed.translation;
}
If i missed something please let me know I will add more details.
This sounds like it is a result of javascript's same origin policy.
You will need to use techniques likes CORS or JSONp to get around this. The link above has more details.