cURL form post with Javascript & postback ASP.NET - javascript

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);
}
}
?>

Related

Prestashop module remote API request

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.

Sign in with LinkedIn PHP Code issue

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

Message":"There was an error processing the request.","StackTrace":"","ExceptionType" - JQUERY

Here is my code, I keep on getting the same error response.
"{"Message":"There was an error processing the request.","StackTrace":"","ExceptionType":""}"
I can't figure it out. I'm using Eloqua APIs to get basic information such as total number of accounts, landing pages, users, images, etc. It's weird because I tried the API on POSTMAN application and it did work perfectly Screenshot of postman response to the API
PHP
$objetos = array("data/accounts", "data/contacts", "assets/emails", "assets/landingPages", "assets/images", "assets/forms", "system/users", "assets/microsites", "assets/customObjects");
for ($i = 0; $i < 9; $i++){
$url = 'http://secure.p03.eloqua.com/API/REST/1.0/' . $objetos[$i] . '?count=1';
$ch=curl_init();
curl_setopt($ch,CURLOPT_URL,$url);
$headers = array(
'Content-type: application/json',
'Authorization: BASIC "MY TOKEN"'
);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($ch, CURLOPT_CAINFO, getcwd() ."/EloquaApi_lvl1.cer");
curl_setopt($ch, CURLOPT_POST, 0);
curl_setopt($ch, CURLOPT_HTTPGET, 1);
$data[$i] = curl_exec($ch);
curl_close($ch);
}
echo json_encode($data);
?>
JS
function getObjetos(){
$.get("objetos.php", function (data) {
console.log(data);
}, "json").done(function (data) {
console.log(data);
// rest of my code
}
Console
console.log response (click for image)
Try changing the url http://secure.p03.eloqua.com/API/REST/1.0/ to https
Use https://ssl.bing.com/webmaster/api.svc/json/SubmitUrlbatch?apikey=KEY
My full PHP code here
$data = array();
$data['siteUrl'] = 'https://example.com';
$data['urlList'][] = 'https://example.com/news/1';
$ch = curl_init('https://ssl.bing.com/webmaster/api.svc/json/SubmitUrlbatch?apikey=KEY');
curl_setopt_array($ch, array(
CURLOPT_POST => TRUE,
CURLOPT_RETURNTRANSFER => TRUE,
CURLOPT_HTTPHEADER => array(
'Content-Type: application/json',
'charset=utf-8',
'HTTP/1.1'
),
CURLOPT_POSTFIELDS => json_encode($data)
));
$response = curl_exec($ch);

call jquery function in a php while loop

I need to call a jquery function from a php while loop
my code
$msg_body = "Test%20SMS";
while($mobList = mysql_fetch_array($resSet))
{
$mobile = $mobList['mobile'];
if($mobile)
{
?>
<script>
$(document).ready(function()
{
var mob = <?php echo $mobile;?>;
var msgBody = <?php echo $msg_body;?>
var url = "http://example.com/abc.php?msg=TEXT&sendTo="+mob+"&message="+msgBody+"&method=sendMessage";
$.get( url, function( data )
{
alert( "SMS SEND to : "+mob );
});
});
</script>
<?php
}
}
it is running for one time, ie if more than one mobile numbers are there it will execute once and send one sms,
Alert is not working.
I used CURL,
now its OK
if($scm_mobile)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
curl_setopt($ch, CURLOPT_MAXREDIRS, 3);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
$data = curl_exec($ch);
}

Replace whateverorigin.org call with local proxy in php

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!

Categories