Goal:
Log into processor's site using their API and store the success response into COOKIEs and SESSIONs on my site.
What almost works:
jQuery(document).ready(function($){
$.ajax({
type: 'POST',
url: '{url-to-api-call}',
xhrFields: {
withCredentials: true
},
dataType: 'text',
data: 'Email={email}&GuestSessionToken={token}&Password={pass}&Format=JSON&RememberMe=true',
processData: false,
crossDomain: true,
success: function (res) { console.log('success'); },
error: function (jqXHR, textStatus, ex) {
console.log('error');
}
});
});
Why it doesn't work:
I'm unable to store the response to COOKIEs and SESSIONs.
What I would like to work:
$url = {url-to-api};
$curl = curl_init();
$curl_post_data = array(
'Email' => $fields['user_email'],
'GuestSessionToken' => $_COOKIE['SessionToken'],
'Password' => $fields['user_pass'],
'Format' => "JSON",
'RememberMe' => "true"
);
curl_setopt($curl,CURLOPT_URL,$url);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl,CURLOPT_RETURNTRANSFER,true);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $curl_post_data);
curl_setopt($curl,CURLOPT_CONNECTTIMEOUT,5);
curl_setopt($curl, CURLOPT_TIMEOUT, 90);
$content = curl_exec($curl);
curl_close($curl);
$content_array = json_decode($content, true);
if ($content_array['StatusCode'] == 'OK') {
$fields['UserId'] = $content_array['Data']['UserId'];
$fields['SessionID'] = $content_array['Data']['ID'];
$fields['SessionToken'] = $content_array['Data']['Token'];
return true;
} else {
$errors->add( 'error', 'Unable to sign in.' );
return false;
}
Why it doesn't work:
This will return a success response that I can use to set the COOKIEs and SESSIONs, but it will not log the user into the processor's site.
Why I think it doesn't work:
The ajax call wouldn't sign the user in until I added the xhrFields part. I think if I could find a cURL equivalent for the xhrFields part, I would be all set.
Thanks in advance!
My duct tape fix.
<?php
// If signin form is submitted and signin cURL was successful.
echo (isset($fields['signin_script'])) ? $fields['signin_script'] : "";
function processor_signin(&$fields, &$errors) {
$url = '{url-to-api-call}';
$curl = curl_init();
$curl_post_data = array(
'Email' => $fields['user_email'],
'GuestSessionToken' => $_COOKIE['SessionToken'],
'Password' => $fields['user_pass'],
'Format' => "JSON",
'RememberMe' => "true"
);
curl_setopt($curl,CURLOPT_URL,$url);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl,CURLOPT_RETURNTRANSFER,true);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $curl_post_data);
curl_setopt($curl,CURLOPT_CONNECTTIMEOUT,5);
curl_setopt($curl, CURLOPT_TIMEOUT, 90);
$content = curl_exec($curl);
curl_close($curl);
$content_array = json_decode($content, true);
if ($content_array['StatusCode'] == 'OK') {
$fields['UserId'] = $content_array['Data']['UserId'];
$fields['SessionID'] = $content_array['Data']['ID'];
$fields['SessionID'] = $content_array['Data']['ID'];
$fields['SessionToken'] = $content_array['Data']['Token'];
// Duct tape fix
$fields['signin_script'] = "
<script>
jQuery(document).ready(function($){
$.ajax({
type: 'POST',
url: '{url-to-api-call}',
xhrFields: {
withCredentials: true
},
dataType: 'text',
data: '
Email=".$fields['user_email']."
&GuestSessionToken=".$_COOKIE['SessionToken']."
&Password=".$fields['user_pass']."
&Format=JSON
&RememberMe=true',
processData: false,
crossDomain: true,
success: function (res) { console.log('signin success'); },
error: function (jqXHR, textStatus, ex) {
console.log('signin error');
}
});
});
</script>
";
return true;
} else {
$errors->add( 'error', 'Unable to sign in.' );
return false;
}
}
?>
Maybe you are logged in but you are not storing the cookies.
So you need to parse the headers and in the end store all cookies. In proceeding requests you need to send back all cookies that you retrieved before.
Here is an example how to retrieve the cookies and other headers from the server:
public function sendRequest(HttpRequest $request)
{
...
curl_setopt($ch, CURLOPT_HTTPHEADER, $request->getHeaders());
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADERFUNCTION, [$this, 'fetchHeader']);
...
$content = curl_exec($ch);
...
}
/**
* #param resource $ch - curl handle
* #param string $header
*
* #return int
*/
private function fetchHeader($ch, $header)
{
$headerParts = explode(': ', $header, 2);
if (2 === count($headerParts)) {
$headerName = strtolower($headerParts[0]);
if ('set-cookie' === $headerName) {
$this->responseHeaders[$headerName][] = trim($headerParts[1]);
return strlen($header);
}
$this->responseHeaders[$headerName] = trim($headerParts[1]);
}
return strlen($header);
}
Related
If there is an error in the js/send_to_telegram.php file, then the error script will work. How to do it?
jQuery("form").submit(function () {
var form_data = jQuery(this).serialize();
jQuery.ajax({
type: "POST",
url: "js/send_to_telegram.php",
data: form_data,
success: function (result) {
donemodal.style.display = "block";
},
error: function (jqXHR, exception) {
errormodal.style.display = "block";
}
});
});
in js/send_to_telegram.php the following code:
$token = "5306003979:AAEPK2NhlxW";
$chat_id = "497358";
$txt = htmlspecialchars($_POST["text"]);
$sendToTelegram = fopen("https://api.telegram.org/bot{$token}/sendMessage?chat_id={$chat_id}&parse_mode=html&text={$txt}","r");
Now, even if you enter the wrong token in $sendToTelegram, it returns success. How to get error if token is wrong?
Short answer: It doesn't use API response status code unless you tell him does that. What if we sent multiple HTTP requests and got different status codes? Which of them should be used?
Solution: This is what you need:
<?php
function post($url, $fields = []) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
if (is_array($fields) && count($fields)) {
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($fields));
}
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
curl_close($ch);
return json_decode($result);
}
$response = post("https://api.telegram.org/bot{$token}/sendMessage", [
'chat_id' => $chat_id,
'text' => $txt,
]);
if ($response->ok) {
echo '{"message": "ok"}';
} else {
http_response_code(500);
echo '{"message": "Something went wrong"}';
}
may I ask how to track the specific event with the event tracking ActiveCampaign code?`
For example, if I want to track button clicks on my own website, how do I add on in this php sample code here.
Thank you.
<?php
// initializes a cURL session
$curl = curl_init();
// changes the cURL session behavior with options
curl_setopt($curl, CURLOPT_URL, "https://trackcmp.net/event");
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, array(
"actid" => "Actid",
"key" => "Key",
"event" => "EVENT NAME",
"eventdata" => "Button click login",
"visit" => json_encode(array(
// If you have an email address, assign it here.
"email" => "",
)),
));
//execute
$result = curl_exec($curl);
if ($result !== false) {
$result = json_decode($result);
if ($result->success) {
echo 'Success! ';
} else {
echo 'Error! ';
}
echo $result->message;
} else {
echo 'cURL failed to run: ', curl_error($curl);
}
};
?>`
You will have to use AJAX and send a request to execute this segment of code on all the buttons you want to track the click event.
$(".tracked-button").on('click', function () {
// fire the AJAX request on button click
$.ajax({
type: "POST",
url: 'YOUR URL',
dataType: 'json',
headers: {},
data: {}
})
.done(function (response) {
// if you want to do something on success
})
.fail(function (xhr, status, error) {
// if you want to do something on error
});
});
I'm a newbie when it comes to using PHP curl and ajax
I've been asked to do the following (an image is attached for your consideration).. there are the requirements
initially I tried sending request with jquery ajax but it was not working here is the code:
function sendAPI(){
$.ajax({
url: "https://someurl.com/api/page/index",
headers: {
'x-api-key':"[API KEY GIVEN BY THE COMPANY]",
'Content-Type':'application/json'
},
method: 'POST',
dataType: 'jsonp',
data: {
id: "7001345730",
recordNo: "1000000000",
recordDate: "2017-12-12",
phone: "+966555555555",
extension: "1234",
email: "feras#test.com",
managerName: "Amjad",
managerPhone: "+966555555555",
managerMobile: "+966555555555"
},
success: function(data){
console.log('lllk');
console.log('succes: ' + data);
},
error: function(XMLHttpRequest, textStatus, errorThrown){
console.log("textStatus: ", textStatus);
console.log("errorThrown: ", errorThrown);
}
});
}
sendAPI();
I get the following error message displayed on my console
Please note: I tried both json and jsonp dataType but same result
textStatus: error
errorThrown: error
Afterwards I tried php curl but I am getting the error on that too.
here is php curl code:
$id ="7001345730";
$recordNo = "1000000000" ;
$recordIssueDate = "2017-12-12" ;
$phone = "+966555555555" ;
$extension = "1234" ;
$email = "feras#test.com" ;
$managerName = "Adeel Essa" ;
$managerPhone = "+966555555555" ;
$managerMobile = "+966555555555";
$data = array(
"id" => $id,
"recordNo" => $recordNo,
"recordIssueDate" => $recordIssueDate,
"phone" => $phone,
"extension" => $extension,
"email" => $email,
"managerName" => $managerName,
"managerPhone" => $managerPhone,
"managerMobile" => $managerMobile,
);
$ch = curl_init('https://someurl.com/api/page/index');
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-Type: application/json',
"x-api-key: 56DAAC8KAD-SFOL9267B-B97E1A9E"
]);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
$result = curl_exec($ch); //get return String
echo json_encode($result);
if (curl_error($ch)) {
$error_msg = curl_error($ch);
}
curl_close($ch);
if (isset($error_msg)) {
print_r($error_msg);
}
When I execute the above code I get the following error:
false
Failed to connect to wasl.elm.sa port 443: Timed out
In the end my only question is:
If I am doing right or there is something is missing in my code.
On both JQuery and PHP CURL codes.
If so what do I need to change.
Requirements are also mentioned in the above image
Please Help
I am having an issue with my form. The issue is that when submit is clicked the jQuery does not work within the response.length > 0 statement but however the form is working and importing data but I need it to update the div and load the thank you page instead of acting like its doing nothing :)
It should be response.length > 0 - then load the errors and update div else go to the thank you page
jQuery:
$('#mountianForm').submit(function(e) { // catch the form's submit event
$.ajax({ // create an AJAX call...
data: $(this).serialize(), // get the form data
type: $(this).attr('method'), // GET or POST
url: $(this).attr('action'), // the file to call
success: function(response) { // on success..
if (response.length > 0) {
$('#mountianFormResponse').html(response); // update the DIV
} else {
window.location.href = 'https://example.com/thank-you/';
}
}
});
e.preventDefault();
});
Process Code:
<?php
error_reporting(E_ALL); ini_set('display_errors', 1);
$url = 'https://id.infusionsoft.com/app/form/iframe/formID';
$userAgent = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36';
if (!empty($_GET))
{
$url .= '?'.http_build_query($_GET);
}
$isPOST = !empty($_POST);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
curl_setopt($ch, CURLOPT_USERAGENT, $userAgent);
curl_setopt($ch, CURLOPT_POST, $isPOST);
if ($isPOST)
{
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($_POST));
}
$response = curl_exec($ch);
curl_close($ch);
if(preg_match('/(<ul>.*<\/ul>)/is', $response, $match)){
$match[1];
}else{
$error = "Error";
$file = fopen("mountianProxyerror.php", 'w+'); // Create a new file, or overwrite the existing one.
fwrite($file, $error);
fclose($file);
}
?>
I think you didn't return the response from your process code.
if(preg_match('/(<ul>.*<\/ul>)/is', $response, $match))
{
$match[1];
$resp = array('status' => TRUE,'msg' => 'success','resp' => $response);
}
else
{
$error = "Error";
$file = fopen("mountianProxyerror.php", 'w+'); // Create a new file, or overwrite the existing one.
fwrite($file, $error);
fclose($file);
$resp = array('status' => FALSE,'msg' => 'Failed');
}
echo json_encode($resp);
And in your ajax
$.ajax({ // create an AJAX call...
data: $(this).serialize(), // get the form data
type: $(this).attr('method'), // GET or POST
url: $(this).attr('action'), // the file to call
dataType : 'json',
success: function(response) { // on success..
alert(response.msg);
if (response.status == true) {
$('#mountianFormResponse').html(response.resp);
// Do whatever with the success code
}
else
{
window.location.href = 'https://example.com/thank-you/';
}
}
});
I am using facebook login using oauth. Sometime I am getting proper accessToken or sometime this kind of garbage values in accessToken
{"source":"uni","s":"s","p":{"z":"0","c":"0","i":"287"},"r": {"z":"1","c":"15239"},"node_id":"23.57.77.12"}.
Because of that my next requests to graph API fails. What is that thing and How do I handle this??
I have multiple domains ex. www.example.com, www.example12.com, www.example22.com etc.
I have created app for www.example.com on facebook and using it for all domains using the window.postmessage:
homepage.php (When user click on facebook login button):
if(!window.addEventListener){
window.attachEvent("onclick", processFacebookLogin);
}
else{
window.addEventListener("message", processFacebookLogin, false);
}
var width = 500;
var height = 500;
var left = ((window.innerWidth / 2) - (width / 2)) + window.screenLeft;
var top = ((window.innerHeight / 2) - (height / 2)) + window.screenTop;
winObj = window.open("http://www.example.com/fb-login?currentDomain=www.example12.com", "fbwindow", "height="+width+",width="+height+",top="+top+",left="+left);
function processFacebookLogin(e) {
winObj.close();
if(e.data != "error" && e.data != "missing_param"){
accessToken = e.data;
$.ajax({
async: false,
url: "UrlToProcessFacebookLogin",
type: "POST",
dataType: "json",
data:
{
"medium" :"facebook",
"accessToken" : accessToken
},
success: function(data)
{
//redirect to some another url
}
});
}
}
child window url page contains the following code fbLoginController.php:
The above window.open contains the indexAction url of fbLoginController (I am using Zend Framework):
public function indexAction()
{
$communityDomain = preg_replace('#^https?://#', '', $_GET['community']);
$fbLoginUrl = "https://www.facebook.com/v1.0/dialog/oauth?client_id=FbAppClientId&scope=AllRequiredScopes&auth_type=rerequest&return_scopes=true&display=popup&redirect_uri=http://www.example.com/fb-login/fb-response?community=".$communityDomain;
$this->_redirect($fbLoginUrl);
exit;
}
public function fbResponseAction()
{
$arrParams = $this->_getAllParams();
$code = $arrParams['code'];
$communityDomain = $arrParams['community'];
$grantedScopes = $arrParams['granted_scopes'];
$error = $arrParams['error'];
if(!empty($error))
{
echo "<script>window.opener.postMessage('error', 'http://".$communityDomain."');</script>";
exit;
}
if(empty($communityDomain) || empty($grantedScopes))
{
echo "<script>window.opener.postMessage('missing_param', 'http://".$communityDomain."');</script>";
exit;
}
$curlUrl = "https://graph.facebook.com/v1.0/oauth/access_token?client_id=FbAppClientId&client_secret=FbAppClientSecret&code=" . $code . "&redirect_uri=http://www.example.com/fb-login/fb-response?community=" . $communityDomain;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $curlUrl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_NOSIGNAL, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT,10);
curl_setopt($ch, CURLOPT_TIMEOUT_MS, 5000);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 0);
curl_setopt($ch, CURLOPT_ENCODING, "");
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
curl_setopt($ch, CURLOPT_DNS_USE_GLOBAL_CACHE, 0);
curl_setopt($ch, CURLOPT_POST, 0);
$curlResponse = curl_exec($ch);
$curlError = curl_error($ch);
curl_close($ch);
parse_str($curlResponse,$parsedStr);
echo "<script>window.opener.postMessage('".$parsedStr['access_token']."', 'http://".$communityDomain."');</script>";
exit;
}
for proper understanding I have put each and every line of code in this question.