impossible to retrieve Paypal information after successful payment - javascript

I am trying to integrate paypal payment on a sales site. the client part works well, the client pays and the money is in the seller account. the second part which allows to recover data such as transaction number, amount, customer address, does not work. yet I use the scripts provided by Paypal.
this file index.php to pay works
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Radiofil</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css"
integrity="sha384-/Y6pD6FV/Vv2HJnA6t+vslU6fwYXjCFtcEpHbNJ0lyAFsXTsjBbfaDjzALeQsN6M"
crossorigin="anonymous">
</head>
<body>
<nav class="navbar navbar-expand-lg navbar-dark bg-primary mb-1">
<a class="navbar-brand" href="#">Boutique Tubes</a>
</nav>
<div class="container">
<h1>Récapitulatif</h1>
<table class="table table-striped">
<thead>
<tr>
<th>Tube</th>
<th>Qte</th>
<th>Prix</th>
</tr>
</thead>
<tbody>
<?php
$user_id = 8000;
$RefBonCommande= '20000';
include('../config/dbconn.php');
$query = mysqli_query($dbconn,"SELECT * FROM detailcde WHERE user_id='$user_id' AND RefBonCommande='$RefBonCommande'") or die (mysqli_error());
while ($row3 = mysqli_fetch_array($query, MYSQLI_NUM)) {
$count = mysqli_num_rows($query);
$numerotube=$row3[3];
$qty= $row3[4];
$totalp = $row3[5];
echo "<tr>";
echo "<td>".$numerotube."</td>";
echo "<td>".$qty."</td>";
echo "<td>".$totalp.'€'."</td>";
}
$query1 = mysqli_query($dbconn,"SELECT * FROM commandes WHERE Refcde='$RefBonCommande' AND adherent1='$user_id'") or die (mysqli_error());
$row4 = mysqli_fetch_array($query1);
$port=$row4['FraisTransport'];
$total=$row4['Total'];
echo "<tr>";
echo "<td>".'Total + port '."</td>";
echo "<td>".'1 '."</td>";
echo "<td>".$total.'€'."</td>";
echo "<tr>";
echo "<td><b><font size = 5>".'Commande de l\'adherent RFL n° '.$user_id."</b></br></td>";
?>
</tbody>
</table>
<!--<p class="text-right">
<div id="paypal-button"></div>
<!--Acheter-->
</p>
</div><!-- /.container -->
<script
src="https://www.paypal.com/sdk/js?client-id=client-id&currency=EUR"> // Required. Replace SB_CLIENT_ID with your sandbox client ID.
paypal.Buttons().render('#paypal-button-container');
// This function displays Smart Payment Buttons on your web page.
</script>
<center>
<div id="paypal-button-container"></div>
</center>
<script>
paypal.Buttons({
createOrder: function(data, actions) {
return actions.order.create({
purchase_units: [{
amount: {
value: <?php echo $total ;?> //'5.60'
}
}]
});
},
onApprove: function(data, actions) {
return actions.order.capture().then(function(details) {
alert('Transaction completed by adherent ' + details.payer.name.given_name);
// Call your server to save the transaction
return fetch('/paypal-transaction-complete', {
method: 'post',
headers: {
'content-type': 'application/json'
},
body: JSON.stringify({
orderID: data.orderID,
payerID: data.payerID
})
});
});
}
}).render('#paypal-button-container');
</script>
</body>
</html>
**the script below does not work**
<!-- language: lang-PHP -->
<?php
require 'vendor/autoload.php';
?>
<script>
// 1. Set up your server to make calls to PayPal
// 1a. Add your client ID and secret
PAYPAL_CLIENT = cliet id';
PAYPAL_SECRET = secret';
// 1b. Point your server to the PayPal API
PAYPAL_OAUTH_API = 'https://api.sandbox.paypal.com/v1/oauth2/token/';
PAYPAL_ORDER_API = 'https://api.sandbox.paypal.com/v2/checkout/orders/';
// 1c. Get an access token from the PayPal API
basicAuth = base64encode(`${ PAYPAL_CLIENT }:${ PAYPAL_SECRET }`);
auth = http.post(PAYPAL_OAUTH_API ,{
headers: {
Accept: `application/json`,
Authorization: `Basic ${ basicAuth }`
},
data: `grant_type=client_credentials`
});
// 2. Set up your server to receive a call from the client
function handleRequest(request, response), {
// 2a. Get the order ID from the request body
orderID = request.body.orderID;
// 3. Call PayPal to capture the order
capture = http.post(PAYPAL_ORDER_API + orderID + '/capture', {
headers: {
Accept: `application/json`,
Authorization: `Bearer ${ auth.access_token }`
}
});
// 4. Save the capture ID to your database
if (!capture.error) {
captureID = capture.purchase_units[0]
.payments.captures[0].id;
database.saveCaptureID(captureID);
}
// 5. Handle any errors from the call
if (capture.error) {
console.error(capture.error);
return response.send(500);
}
// 6. Return a successful response to the client
response.send(200);
}
hello, according to the advice of PHPology I set up the return call URL and of course used the PAYPAL script. I went to the history of IPN messages and I have an HTTP 500 error. I think there may be a syntax error in the PAYPAL script they are specialists in this kind of error.
<?php
function ipn($ipn_data) {
define('SSL_P_URL', 'https://www.paypal.com/cgi-bin/webscr');
define('SSL_SAND_URL', 'https://www.sandbox.paypal.com/cgi-bin/webscr');
$hostname = gethostbyaddr($_SERVER['REMOTE_ADDR']);
if (!preg_match('/paypal\.com$/', $hostname)) {
$ipn_status = 'Validation post isn\'t from PayPal';
if ($ipn_data == true) {
//You can send email as well
}
return false;
}
// parse the paypal URL
$paypal_url = ($_REQUEST['test_ipn'] == 1) ? SSL_SAND_URL : SSL_P_URL;
$url_parsed = parse_url($paypal_url);
$post_string = '';
foreach ($_REQUEST as $field => $value) {
$post_string .= $field . '=' . urlencode(stripslashes($value)) . '&';
}
$post_string.="cmd=_notify-validate"; // append ipn command
// get the correct paypal url to post request to
$paypal_mode_status = $ipn_data; //get_option('im_sabdbox_mode');
if ($paypal_mode_status == true)
$fp = fsockopen('ssl://www.sandbox.paypal.com', "443", $err_num, $err_str, 60);
else
$fp = fsockopen('ssl://www.sandbox.paypal.com', "443", $err_num, $err_str, 60);
$ipn_response = '';
if (!$fp) {
// could not open the connection. If loggin is on, the error message
// will be in the log.
$ipn_status = "fsockopen error no. $err_num: $err_str";
if ($ipn_data == true) {
echo 'fsockopen fail';
}
return false;
} else {
// Post the data back to paypal
fputs($fp, "POST $url_parsed[path] HTTP/1.1\r\n");
fputs($fp, "Host: $url_parsed[host]\r\n");
fputs($fp, "Content-type: application/x-www-form-urlencoded\r\n");
fputs($fp, "Content-length: " . strlen($post_string) . "\r\n");
fputs($fp, "Connection: close\r\n\r\n");
fputs($fp, $post_string . "\r\n\r\n");
// loop through the response from the server and append to variable
while (!feof($fp)) {
$ipn_response .= fgets($fp, 1024);
}
fclose($fp); // close connection
}
// Invalid IPN transaction. Check the $ipn_status and log for details.
if (!preg_match("/VERIFIED/s", $ipn_response)) {
$ipn_status = 'IPN Validation Failed';
if ($ipn_data == true) {
echo 'Validation fail';
print_r($_REQUEST);
}
return false;
} else {
$ipn_status = "IPN VERIFIED";
if ($ipn_data == true) {
echo 'SUCCESS';
print_r($_REQUEST);
}
return true;
}
}
function ipn_response() {
//mail("sobhagya1411#gmail.com","My subject",print_r($request,true));
$ipn_data = true;
if ($this->ipn($_REQUEST)) {
$this->insert_data($_REQUEST);
}
}
function issetCheck($post, $key) {
if (isset($post[$key])) {
$return = $post[$key];
} else {
$return = '';
}
return $return;
}
public function insert_data(){
$post = $_REQUEST;
$item_name= $this->issetCheck($post, 'item_name');
$amount = $this->issetCheck($post, 'mc_gross');
$currency = $this->issetCheck($post, 'mc_currency');
$payer_email = $this->issetCheck($post, 'payer_email');
$first_name = $this->issetCheck($post, 'first_name');
$last_name = $this->issetCheck($post, 'last_name');
$country = $this->issetCheck($post, 'residence_country');
$txn_id = $this->issetCheck($post, 'txn_id');
$txn_type = $this->issetCheck($post, 'txn_type');
$payment_status = $this->issetCheck($post, 'payment_status');
$payment_type = $this->issetCheck($post, 'payment_type');
$payer_id = $this->issetCheck($post, 'payer_id');
$create_date = date('Y-m-d H:i:s');
$payment_date = date('Y-m-d H:i:s');
$paypal_sql = "INSERT INTO ipn_data_tbl (item_name,payer_email,first_name,last_name,amount,currency,country,txn_id,txn_type,payer_id,payment_status,payment_type,create_date,payment_date)
VALUES ($item_name,'$payer_email','$first_name','$last_name','$amount','$currency','$country','$txn_id','$txn_type','$payer_id','$payment_status','$payment_type','$create_date','$payment_date')";
mysql_query($paypal_sql);
}
?>

I solve the problem. Paypal provides scripts that do not work because there are syntax errors. Their explanation of the methods is very obscure. Finally after making some syntax and url modification my php IPN paypal IPN listener software works.
<?php
$charset = "utf-8";
include('../config/dbconn.php');
$deb='je commence';
mysqli_query($dbconn,"INSERT INTO paytest (mess) VALUES ('$deb')");
/* NE RIEN MODIFIER CI-DESSOUS */
// lecture du post de PayPal et ajout de 'cmd'
$req = 'cmd=_notify-validate';
foreach ($_POST as $key => $value) {
$value = trim(urlencode(stripslashes($value)));
$req .= "&$key=$value";
}
//mysqli_query($dbconn,"INSERT INTO paytest (mess) VALUES ('$req')");
// reponse a PayPal pour validation
$header .= "POST /cgi-bin/webscr HTTP/1.1\r\n";
//$header .= "Content-Length: 1028\r\n";
$header .= "Content-Length: " . strlen($req) . "\r\n";
$header .= "Content-Type: application/x-www-form-urlencoded\r\n";
$header .= "Host: www.sandbox.paypal.com\r\n";
$header .= "Connection: close\r\n\r\n";
//$header .= "Host: ipnpb.paypal.com:443\r\n";
$fp = fsockopen ('ssl://www.sandbox.paypal.com', 443, $errno, $errstr, 30);
//$fp = fsockopen ('ipnpb.paypal.com', 443, $errno, $errstr, 30);
mysqli_query($dbconn,"INSERT INTO paytest (mess) VALUES ('fp1')");
mysqli_query($dbconn,"INSERT INTO paytest (mess) VALUES ('$fp')");
// variables
$discount = $_POST['discount'];
$insurance_amount = $_POST['insurance_amount'];
$payer_id = $_POST['payer_id'];
$address_country_code = $_POST['address_country_code'];
$ipn_track_id = $_POST['ipn_track_id'];
$address_zip = $_POST['address_zip'];
$charset = $_POST['charset'];
$payment_gross = $_POST['payment_gross'];
$address_status = $_POST['address_status'];
$shipping_discount = $_POST['shipping_discount'];
$address_street = $_POST['address_street'];
$verify_sign = $_POST['verify_sign'];
$item_name = $_POST['item_name'];
$test_ipn = $_POST['test_ipn'];
$txn_type = $_POST['txn_type'];
$receiver_id = $_POST['receiver_id'];
$payment_fee = $_POST['payment_fee'];
$mc_currency = $_POST['mc_currency'];
$transaction_subject = $_POST['transaction_subject'];
$shipping_method = $_POST['shipping_method'];
$custom = $_POST['custom'];
$protection_eligibility = $_POST['protection_eligibility'];
$address_country = $_POST['address_country'];
$payer_status = $_POST['payer_status'];
$first_name = $_POST['first_name'];
$address_name = $_POST['address_name'];
$mc_gross = $_POST['mc_gross'];
$payment_date = $_POST['payment_date'];
$payment_status = $_POST['payment_status'];
$quantity = $_POST['quantity'];
$business = $_POST['business'];
$item_number = $_POST['item_number'];
$last_name = $_POST['last_name'];
$address_state = $_POST['address_state'];
$txn_id = $_POST['txn_id'];
$mc_fee = $_POST['mc_fee'];
$payment_type = $_POST['payment_type'];
$notify_version = $_POST['notify_version'];
$payer_email = $_POST['payer_email'];
$receiver_email = $_POST['receiver_email'];
$address_city = $_POST['address_city'];
$residence_country = $_POST['residence_country'];
$payment_currency = $_POST['mc_currency'];
$receiver_id = $_POST['receiver_id'];
$num_cart_items = $_POST['num_cart_items'];
mysqli_query($dbconn,"INSERT INTO paytest (mess) VALUES ('$txn_id')");
mysqli_query($dbconn,"INSERT INTO paytest (mess) VALUES ('Date')");
mysqli_query($dbconn,"INSERT INTO paytest (mess) VALUES ('$payment_date')");
$rest = substr($payment_date, 9, 13);
$mois = substr($rest, 0, 3);
$jour = substr($rest, 4, 2);
$an = substr($rest, 8, 4);
$date = $an.'-'.$mois.'-'.$jour;
$date = date_create($date);
$dte = date_format($date,'Y-m-d');
if (!$fp) {
// HTTP ERROR
} else {
fputs ($fp, $header . $req);
fseek($fp, 0);
while (!feof($fp)) {
$res = fgets ($fp, 10024);
//$test=strcmp (trim($res), "VERIFIED");
//if (strcmp ($res, "VERIFIED") == 0) {
if (strcmp (trim($res), "VERIFIED") == 0) {
$deba = 'verifie';
mysqli_query($dbconn,"INSERT INTO paytest (mess) VALUES ('$deba')");
// Envoi du mail
$paypal_sql = "INSERT INTO paiements (payment_id,payment_status,payment_amount,taxe_paypal,payment_currency,payment_date,payer_email)
VALUES ('$txn_id','$payment_status','$mc_gross','$mc_fee','$mc_currency','$dte','$payer_email')";
mysqli_query($dbconn,$paypal_sql);
}
else if (strcmp (trim($res), "INVALID") == 0) {
$debb = 'invalide';
mysqli_query($dbconn,"INSERT INTO paytest (mess) VALUES ('$debb')");
$payment_status = 'INVALID';
$paypal_sql = "INSERT INTO paiements (payment_id,payment_status,payment_amount,taxe_paypal,payment_currency,payment_date,payer_email)
VALUES ('$txn_id','$payment_status','$mc_gross','$mc_fee','$mc_currency','$dte','$payer_email')";
mysqli_query($dbconn,$paypal_sql);
}
}
fclose ($fp);
}
$debc = 'fini';
mysqli_query($dbconn,"INSERT INTO paytest (mess) VALUES ('$debc')");
?>

Related

API receiving Half Data

I have a PHP API but when I send data to it using a post or get request the API receives half data, I don't know what the issue is. this same API works on the localhost but gives error on the Public server.
API sendrequset URL:
https://peer.infusiblecoder.com/android/loanapp/sendrequesttoperson.php?request_is_seen=hjhj&loan_request_code=100&req_status=hjh&request_sender_user_name=ghjgjh&request_reciver_user_name=hjhjh&request_sender_user_id=jkjkj&request_reciver_user_id=hjhj&request_time_stamp=ghhgjhh
And this is my Api sendrequesttoperson.php
<?php
require 'db.php';
if(isset( $_GET["$req_status_db"]) && isset($_GET["$loan_request_code_db"]) && isset($_GET["$request_sender_user_name_db"]) && isset($_GET["$request_reciver_user_name_db"]) && isset($_GET["$request_sender_user_id_db"]) && isset($_GET["$request_reciver_user_id_db"]) && isset($_GET["$request_is_seen_db"]) && isset($_GET["$request_time_stamp_db"])){
$loan_request_code = $_GET["$loan_request_code_db"];
$request_sender_user_name = $_GET["$request_sender_user_name_db"];
$request_reciver_user_name = $_GET["$request_reciver_user_name_db"];
$request_sender_user_id = $_GET["$request_sender_user_id_db"];
$request_reciver_user_id = $_GET["$request_reciver_user_id_db"];
$request_time_stamp = $_GET["$request_time_stamp_db"];
$request_is_seen = $_GET["$request_is_seen_db"];
$req_status = $_GET["$req_status_db"];
$sql = "select * from $table_requests where $loan_request_code_db like '".$loan_request_code."';";
$result = mysqli_query($con, $sql);
$response = array();
if(mysqli_num_rows($result) > 0){
$code = "failed";
$message = "Request already exists";
array_push($response, array("code" => $code, "message" => $message));
echo json_encode($response);
} else {
$sql = "INSERT INTO $table_requests VALUES (NULL,'$loan_request_code','$request_sender_user_name','$request_reciver_user_name','$request_sender_user_id','$request_reciver_user_id','$request_time_stamp','$request_is_seen','$req_status')";
if (mysqli_query($con, $sql)) {
$code = "success";
$message = "Request sent";
array_push($response, array("code" => $code, "message" => $message));
echo json_encode($response);
echo "Request sent successfully";
} else {
$code = "failed";
$message = "Error: " . $sql . "<br>" . mysqli_error($con);
array_push($response, array("code" => $code, "message" => $message));
echo json_encode($response);
}
//$message = "Thank you for registration";
// array_push($response, array("code" => $code, "message" => $message));
// echo json_encode($response);
}
mysqli_close($con);
}else{
$loan_request_code = $_GET["$loan_request_code_db"];
$request_sender_user_name = $_GET["$request_sender_user_name_db"];
$request_reciver_user_name = $_GET["$request_reciver_user_name_db"];
$request_sender_user_id = $_GET["$request_sender_user_id_db"];
$request_reciver_user_id = $_GET["$request_reciver_user_id_db"];
$request_time_stamp = $_GET["$request_time_stamp_db"];
$request_is_seen = $_GET["$request_is_seen_db"];
$req_status = $_GET["$req_status_db"];
$myresponse = 'Enter missing fields_'.$request_sender_user_name."_".$loan_request_code."_".$request_reciver_user_name."_".$request_sender_user_id."_".$request_reciver_user_id."_".$request_time_stamp."_".$request_is_seen."_".$req_status."_";
echo json_encode($myresponse);
}
?>
And this is my db.php file required for the variable names and db connection
<?php
$host = "localhost";
$db_user = "ur5kq7835fnc4";
$db_password ="ch%2#3/^c<1b";
$db_name = "dbhrzz2e49skck";
//Folder Path
$mainpath = "http://192.168.0.101/android/loanapp/";
$profilepic_folder = "profilepics/";
$fileupload_folder="uploadedFiles/";
$fileuploadfullpath_folder="uploadedFiles/";
// loan request statuses {"pending", "rejected","accepted","awaiting money", "paid out", "completed"};
// Table RegisteredUser attributes:
$table_user = "registered_users";
$user_id_db = "user_id";
$firstname_db = "firstname";
$lastname_db = "lastname";
$address_db = "address";
$whatyoupretend_db = "whatyoupretend";
$fieldofactivity_db = "fieldofactivity";
$phone_db = "phone";
$email_db = "email";
$password_db = "password";
$status_db = "status";
$user_img_url_db = "user_img_url";
// Table LoanRequest attributes:
$table_loan_request = "loan_request";
$loan_id_db = "loan_id";
$loan_request_code_db = "loan_request_code";
$user_full_name_db = "user_full_name";
$user_img_url_request_db = "user_img_url_request";
$loan_amount_db = "loan_amount";
$loan_purpose_db = "loan_purpose";
$loan_collateral_db = "loan_collateral";
$loan_market_value_db = "loan_market_value";
$loan_type_db = "loan_type";
$loan_due_date_db = "loan_due_date";
$loan_doc_urls_db = "loan_doc_urls";
$loan_borrowing_rate_db ="loan_borrowing_rate";
$loan_loan_ratio_db ="loan_loan_ratio";
$loan_status_db = "loan_status";
$loan_paid_out_date_db ="loan_paid_out_date";
$loan_duration_db = "loan_duration";
//loan_duration
//loan_paid_out_date
// Table Requests
$table_loan_request = "loan_request";
$loan_id_db = "loan_id";
$loan_request_code_db = "loan_request_code";
$user_full_name_db = "user_full_name";
$user_img_url_request_db = "user_img_url_request";
$loan_amount_db = "loan_amount";
$loan_purpose_db = "loan_purpose";
$loan_collateral_db = "loan_collateral";
$loan_market_value_db = "loan_market_value";
$loan_type_db = "loan_type";
$loan_due_date_db = "loan_due_date";
$loan_doc_urls_db = "loan_doc_urls";
$loan_borrowing_rate_db ="loan_borrowing_rate";
$loan_loan_ratio_db ="loan_loan_ratio";
$loan_status_db = "loan_status";
$loan_lender_id_db = "loan_lender_id";
$loan_paid_out_date_db ="loan_paid_out_date";
$loan_duration_db = "loan_duration";
/*
Table User attributes:
tbname = registered_users
user_id
firstname
lastname
address
whatyoupretend
fieldofactivity
phone
email
password
status [true,false]
user_img_url
*/
/*
Table LoanRequest attributes:
tbname = loan_request
loan_id
loan_request_code
user_full_name
loan_amount
loan_purpose
loan_collateral
loan_market_value
loan_type
loan_due_date
loan_doc_vehicle_id_url
loan_doc_owner_id_url
loan_doc_insurance_url
loan_status
Vehicle ID,Owner´s ID,Insurance
*/
/*
Table Requests attributes:
tbname = requests
request_id
loan_request_code
request_sender_user_name
request_reciver_user_name
request_sender_user_id
request_reciver_user_id
request_time_stamp
request_is_seen
*/
$con = mysqli_connect($host, $db_user,$db_password,$db_name);
if (!$con){
die("connection failed". mysqli_connect_error());
}
/*
else{
echo "connected susscesful";
}
*/
?>
it gives this result
The problem is $_GET["$req_status_db"]
It should be $_GET["req_status_db"]
You will have to remove $ from all the $_GET keys.
Also, you do not have req_status_db as query param in the URL you have shared.

How to embed Javascript function in restful api in php?

I have the following code in one of api files(DispatchJob_Public) and i need ajax here to call the other file(selectDriverForJobResult) after 2 minutes. I can do that in php with sleep(), but that will keep the server busy. Ajax call is at the end of the php code. Can i embed js in api code? Or is there any alternate to do what i am trying to do.
Moreover i have got response from the first file(DispatchJob_Public), but no response from the second file(selectDriverForJobResult) when i called the endpoint in postman. Because the call wasn't made. If the second file was called, it should have return some response. The strange thing is that i get response from second file when i run it in browser. I think that is because the browser supports the javascript but the call made from android to the end point doesn't support that.
Please can i get any solution for this?
<?php
include_once ('connection.php');
include_once ('fcm_notification.php');
//error_reporting(E_ERROR | E_PARSE);
$user_id = $_REQUEST["user_id"];
$customer_name = $_REQUEST["customer_name"];
$group_id_fk = $_REQUEST["group_id_fk"];
$readynow_checkbox = $_REQUEST["readynow_checkbox"];
$job_points = '';
date_default_timezone_set('Australia/Melbourne');
$date = date('Y-m-d H:i:s');
if(strcasecmp($benefits_type, 'Points') == 0){
if(strcasecmp($fixed_price, '') == 0){
$fixed_price_new = $estimated_price;
}else{
$fixed_price_new = $fixed_price;
}
$sql_job_points = "SELECT `points` FROM `hg_job_points` WHERE '$fixed_price_new' BETWEEN `min_price` AND `max_price`";
$res_jobPoints = mysqli_query($conn, $sql_job_points);
$row_job_points = $res_jobPoints->fetch_assoc();
$job_points = $row_job_points["points"];
}
if(strcasecmp($commission_percent, 'Amount') != 0 && strcasecmp($fixed_price, '') != 0){
$commision_price = ($commission_percent / 100) * $fixed_price;
}
//insert job in job table
$sql = "INSERT INTO `hg_jobs`(`customer_name`, `pickup_address`, `dropoff_address`, `customer_phone`, `instruction`,
`via`, `user_id_fk`, `group_id_fk`, `pickup_time`, `flight_no`, `car_type`, `post_time`)
VALUES ('$customer_name', '$pickup_address', '$dropoff_address', '$customer_phone', '$instruction', '$via', '$user_id', '$group_id_fk',
'$pick_time', '$flight_no', '$car_type', '$date')";
if(mysqli_query($conn, $sql)){
//get job id from jobs table
$job_id = $conn->insert_id;
//insert new record in advance job table
$sql_adv = "INSERT INTO `hg_job_details`(`no_of_passenger`, `no_of_bags`, `child_seats`,
`car_type_specific`, `job_type`, `job_price`, `estimated_amount`, `payment_type`, `benefits_type`, `benefit_percent`,
`benefit_amount`, `job_points`, `ready_now_job`, `job_id_fk`)
VALUES ('$passenger','$bags','$child_seats','$car_type_specific','$job_type','$fixed_price', '$estimated_price',
'$payment_type','$benefits_type','$commission_percent','$commision_price', '$job_points', '$readynow_checkbox', '$job_id') ";
$res_adv = mysqli_query($conn, $sql_adv);
if($res_adv){
echo json_encode(Array('message' => 'job success'));
//get black list users
$sql_black = "SELECT blacklist_user_fk FROM hg_black_list WHERE user_id_fk = '$user_id'";
$res_black = mysqli_query($conn,$sql_black);
//if specif type car is any
if(strcasecmp($car_type_specific, 'ANY') == 0){
if ($res_black->num_rows > 0) {
//get all fcm key and send notification (if blacklist table not empty)
$sql = "SELECT ft.fcm_token from hg_user_notify_token ft
JOIN hg_users AS u ON u.user_id = ft.user_id_fk
JOIN hg_car_details AS cd ON u.user_id = cd.user_id_fk
WHERE u.user_id != '$user_id' AND cd.car_type = '$car_type' AND u.user_id !=
(SELECT blacklist_user_fk FROM hg_black_list WHERE user_id_fk = '$user_id') ";
$result = $conn->query($sql);
while ($keys = mysqli_fetch_assoc($result)){
$token = $keys['fcm_token'];
$title = 'HIRENGO';
$message = 'New Job Request Received';
$activity_to_open = 'new job';
sendPushNotification($token, $title, $message,$activity_to_open);
}
}else{
//get all fcm key and send notification (if blacklist table empty)
$sql = "SELECT ft.fcm_token from hg_user_notify_token ft
JOIN hg_users AS u ON u.user_id = ft.user_id_fk
JOIN hg_car_details AS cd ON u.user_id = cd.user_id_fk
WHERE u.user_id != '$user_id' AND cd.car_type = '$car_type'";
$result = $conn->query($sql);
while ($keys = mysqli_fetch_assoc($result)){
$token = $keys['fcm_token'];
$title = 'HIRENGO';
$message = 'New Job Request Received';
$activity_to_open = 'new job';
sendPushNotification($token, $title, $message,$activity_to_open);
}
}
}else{
//if specific car type
if ($res_black->num_rows > 0) {
//get all fcm key and send notification (if blacklist table not empty)
$sql = "SELECT ft.fcm_token from hg_user_notify_token ft
JOIN hg_users AS u ON u.user_id = ft.user_id_fk
JOIN hg_car_details AS cd ON u.user_id = cd.user_id_fk
WHERE u.user_id != '$user_id' AND cd.car_type = '$car_type'
AND cd.car_type_specific = '$car_type_specific' AND u.user_id !=
(SELECT blacklist_user_fk FROM hg_black_list WHERE user_id_fk = '$user_id') ";
$result = $conn->query($sql);
while ($keys = mysqli_fetch_assoc($result)){
$token = $keys['fcm_token'];
$title = 'HIRENGO';
$message = 'New Job Request Received';
$activity_to_open = 'new job';
sendPushNotification($token, $title, $message,$activity_to_open);
}
}else{
//get all fcm key and send notification (if blacklist table empty)
$sql = "SELECT ft.fcm_token from hg_user_notify_token ft
JOIN hg_users AS u ON u.user_id = ft.user_id_fk
JOIN hg_car_details AS cd ON u.user_id = cd.user_id_fk
WHERE u.user_id != '$user_id' AND cd.car_type = '$car_type'
AND cd.car_type_specific = '$car_type_specific'";
$result = $conn->query($sql);
while ($keys = mysqli_fetch_assoc($result)){
$token = $keys['fcm_token'];
$title = 'HIRENGO';
$message = 'New Job Request Received';
$activity_to_open = 'new job';
sendPushNotification($token, $title, $message,$activity_to_open);
}
}
}
?>
<script>
function callDispatch()
{
nIntervId = window.setInterval(myCallback, 5000);
var baseUrl = document.location.origin;
function myCallback()
{
var user_id = '<?=$GLOBALS["user_id"];?>';
var job_id = '<?=$job_id;?>';
$.ajax({
url: baseUrl+'/android/selectDriverForJobResult.php',
type: 'POST',
dataType : 'json',
data: {'user_id': user_id, 'job_id': job_id} ,
success: function(response) {
clearInterval(nIntervId);
var resp = response.toString();
if (resp.includes('true') === true)
{
console.log('true'+ resp);
}
else
{
console.log(resp);
}
},
error: function(response)
{
console.log('Error in ajax'+response.statusText);
clearInterval(nIntervId);
}
});
}
}
callDispatch();
</script>
<?php
}
} else{
echo json_encode(Array('message' => 'error job post'));
}
$conn->close();
?>

JSON_encode not outputting anything

I want to send a query result from one php file to my javascript, I've used an AJAX which seems to work as it is getting data from my BaseClass.php. However when using JSON_encode, it is not outputting anything at all. So I can't work out how to send a query result from one php file(MySQLDao.php) to my BaseClass.php so I am then able to send it to my Javascript file.
My Code:
BaseClass.php:
<?php
error_reporting(E_ALL); ini_set('display_errors', 1);
require("Conn.php");
require("MySQLDao.php");
//$param=$_REQUEST['action'];
//echo json_encode($_GET);
//echo var_dump(json_encode($_GET));
$handle = fopen("php://input", "rb");
$param = $_REQUEST['action'];
while (!feof($handle)) {
$param .= fread($handle, 8192);
}
fclose($handle);
if (empty($param))
{
$returnValue["status"] = false;
$returnValue["title"] = "Error";
$returnValue["message"] = "No Data Recieved paige" .$param ."...";
echo json_encode($returnValue);
return;
}
else
{
$dao = new MySQLDao();
if ($dao->openConnection() == false)
{
$returnValue["status"] = false;
$returnValue["title"] = "Error";
$returnValue["message"] = "Connection Could Not Be Established Between Server And Database";
ob_clean();
echo json_encode($returnValue);
}
else
{
//Decodes data, dont change
$body = json_decode($param, true);
$recieved = $body["data"];
//Gets the result of a query
$result = $dao->getResults($recieved);
}
$dao->closeConnection();
//Return the result of the query
ob_clean();
echo json_encode("param" .$param);
echo json_encode("body" .$body);
echo json_encode("recieved" .$recieved);
echo json_encode("result" .$result);
exit();
}
?>
output for the above echo statements:
"paramgetResults""body""recieved""result"
MySQLDao.php - this file holds the query result that I want to pass to my js
<?php
error_reporting(E_ALL); ini_set('display_errors', 1);
//Class for holding queries
class MySQLDao
{
var $dbhost = null;
var $dbuser = null;
var $dbpass = null;
var $mysqli = null;
var $dbname = null;
var $result = null;
//constructor
function __construct()
{
$this->dbhost = Conn::$dbhost;
$this->dbuser = Conn::$dbuser;
$this->dbpass = Conn::$dbpass;
$this->dbname = Conn::$dbname;
}
//Attempt a connection to the database
public function openConnection()
{
//Try and connect to the database
$this->mysqli = new mysqli($this->dbhost, $this->dbuser, $this->dbpass, $this->dbname);
//If the connection threw an error, report it
if (mysqli_connect_errno())
{
return false;
}
else
{
return true;
}
}
//Get method for retrieving the database conection
public function getConnection()
{
return $this->mysqli;
}
//Close the connection to the database
public function closeConnection()
{
//If there is a connection to the database then close it
if ($this->mysqli != null)
$this->mysqli->close();
}
//-----------------------------------QUERY METHODS-------------------------------------
public function getResults()
{
$sql = "SELECT room.room_description FROM room WHERE room.room_id = 1";
$result = $this->mysqli->query($sql);
//if (mysql_num_rows($result) == 1) {
// $obj = mysql_fetch_object($result, 'obResults');
// echo($obj);
// return $obj;
//}
echo json_encode($result);
//echo($result);
//return false;
}
}
?>
My AJAX code in my js file:
$.ajax ({
type: "GET",
datatype: "application/json",
url: "BaseClass.php",
data: { action : 'getResults' },
//error: function(err){console.log(err)},
success: function(output) {
console.log(output);
//alert(output);
}
//error, function(err){console.log(err)}
});
Any help is appreciated thanks!

Variable getting via Ajax is empty ( Phonegap-Ajax-Json-PHP-MySQL )

I created an android application using Phonegap. I made an account in 000webhost and I've added my PHP files on the server. In the phpMyAdmin, I've created my database.
Right, now I tried to connect my project with the online database and insert or check some data in it.
PROBLEM:
When I run the application in my mobile phone i get this alert from the success: ... part of code in ajax :
There is no such username.
(my PHP had in comments all the echo, except the: echo json_encode)
When I added this line (var_dump($_POST);) right after i am getting the $usernamefrom ajax in the PHP and run my app, I saw this alert: array(1){ [\"username\"]=> string(2) \"hi"\" }
When I added these lines: if (empty($username)) { echo '...' } , after I run my app, I saw that in the alert inside the error: ... part of the ajax, it is printed the echo that is inside this if. So, the $username is empty for sure.
This is my JavaScript file: (I get correctly for sure all the values from html so Focus on the two Ajax parts of code)
document.addEventListener("deviceready", onDeviceReady, false);
// PhoneGap is ready
function onDeviceReady() {
var el = document.getElementById("register");
el.addEventListener("click", Register, false);
}
function Register() {
var username = document.getElementsByName('username')[0];
var password = document.getElementsByName('password')[0];
var email = document.getElementsByName('email')[0];
var strong_flag_user = 0;
var user = username.value;
if (username.value == "") {
$("#username").focus();
document.getElementById('username').style.boxShadow = "0 0 7px #f00";
navigator.notification.vibrate(500);
}
else{
$.ajax({
url: "http://www.guidemeforall.freeiz.com/phps/check_for_dublicates/check_username.php",
type: "POST",
crossDomain: true,
data: { username: user },
dataType:'json',
success: function(response){
if (response.status == 'success') {
alert(response.message);
document.getElementById('username').style.boxShadow = "none";
strong_flag_user = 1;
}
else if (response.status == 'error') {
alert(response.message);
navigator.notification.alert("This username is already taken! Please use another one!", null, 'Username', 'Okay');
document.getElementById('username').style.boxShadow = "0 0 7px #f00";
navigator.notification.vibrate(500);
strong_flag_user = 0;
//window.location("main.html");
}
else {
alert("error");
strong_flag_user = 0;
}
},
error: function(error){ //function(error){
alert(JSON.stringify(error));
strong_flag_user = 0;
//window.location = "main.html";
}
});
}
//>5 characters, 1 upper case, at least 1 lower case, at least 1 numerical character, at least 1 special character
var passExp = /(?=^.{6,15}$)((?=.*\d)(?=.*[A-Z])(?=.*[a-z])|(?=.*\d)(?=.*[^A-Za-z0-9])(?=.*[a-z])|(?=.*[^A-Za-z0-9])(?=.*[A-Z])(?=.*[a-z])|(?=.*\d)(?=.*[A-Z])(?=.*[^A-Za-z0-9]))^.*/;
var strong_flag_pass = 0;
if (!(password.value.match(passExp))) {
$("#password").focus();
document.getElementById('password').style.boxShadow = "0 0 7px #f00";
navigator.notification.alert("Please enter a strong Password! It has to have at least: 6 characters, 1 upper case, 1 lower case, 1 numerical character and 1 special character!", null, 'Password', 'Okay');
navigator.notification.vibrate(500);
strong_flag_pass = 0;
}
else{
document.getElementById('password').style.boxShadow = "none";
strong_flag_pass = 1;
}
var emailExp = /^.+#[^\.].*\.[a-z]{2,}$/;
var strong_flag_email = 0;
if (!(email.value.match(emailExp))) {
$("#email").focus();
document.getElementById('email').style.boxShadow = "0 0 7px #f00";
navigator.notification.alert("Please enter a correct Email!", null, 'Email', 'Okay');
navigator.notification.vibrate(500);
strong_flag_email = 0;
}
else {
document.getElementById('email').style.boxShadow = "none";
strong_flag_email = 1;
}
var gender;
if (document.getElementById("gender").value == "female")
gender = 'F';
else
gender = 'M';
var about_you = document.getElementById("about_you").value;
var age = document.getElementById("radio-choice").value;
if (document.getElementById('radio-choice-1').checked) {
age = document.getElementById('radio-choice-1').value;
}
else if (document.getElementById('radio-choice-2').checked) {
age = document.getElementById('radio-choice-2').value;
}
else if (document.getElementById('radio-choice-3').checked) {
age = document.getElementById('radio-choice-3').value;
}
else if (document.getElementById('radio-choice-4').checked) {
age = document.getElementById('radio-choice-4').value;
}
else if (document.getElementById('radio-choice-5').checked) {
age = document.getElementById('radio-choice-5').value;
}
else if (document.getElementById('radio-choice-6').checked) {
age = document.getElementById('radio-choice-6').value;
}
if (strong_flag_user == 1 && strong_flag_pass == 1 && strong_flag_email == 1){
//add to db
register_db(email.value, password.value, username.value, gender, about_you, age);
}
}
function register_db(em, pass, user, gend, about, ag) {
$.ajax({
url: "http://www.guidemeforall.freeiz.com/phps/sign-up.php",
type: "POST",
crossDomain: true,
data: { username:user, password:pass, email:em, gender:gend, about_you:about, age:ag },
dataType:'json',
success: function(data)
{
if (data.status == 'success')
{
alert("Success!");
}
else if (data.status == 'error')
{
alert("Failure!");
}
}
});
}
This is my PHP file in which I check if the username already exists (Username = Primary Key):
<?php
header('Content-type: application/json');
header('Access-Control-Allow-Origin: *');
//require_once('../database_config.php');
$server = "my***.000webhost.com";
$database = "a1****37_guideme";
$username = "a1****37_guideme";
$password = "*****";
$con = mysql_connect($server, $username, $password);
// if($con) { //echo "Connected to database!"; }
// else { //echo "Could not connect!"; }
mysql_select_db($database, $con);
$topost = file_get_contents('php://input');
$thedata = json_decode($topost, true);
$username = $thedata['username'];
//var_dump($_POST);
//if (empty($username)) {
// echo 'The username is either 0, empty, or not set at all';
//}
$sql = "SELECT COUNT(*) as Count FROM `user` WHERE `username`='$username'";
$result= mysql_query($sql, $con);
$rows = mysql_fetch_array($result);
$count = $rows['Count'];
if (!$result) {
die('Error: ' . mysql_error());
//$response_array['status'] = 'error';
//echo json_encode($response_array);
}
else {
if ($count == 0) {
echo json_encode(array('status' => 'success','message'=> 'There is no such username'));
//$response_array['status'] = 'success';
//echo json_encode($response_array);
}
else
{
echo json_encode(array('status' => 'error','message'=> 'The username already exists'));
//$response_array['status'] = 'error';
//echo json_encode($response_array);
}
}
mysql_close($con);
?>
And this is the PHP file in which I tried to insert the new entry in my database ( my credentials are for sure correct):
<?php
header('Content-type: application/json');
header('Access-Control-Allow-Origin: *');
//require_once('database_config.php');
$server = "mys****.000webhost.com";
$database = "a***37_guideme";
$username = "a***37_guideme";
$password = "******";
$con = mysql_connect($server, $username, $password);
// if($con) { //echo "Connected to database!"; }
// else { //echo "Could not connect!"; }
mysql_select_db($database, $con);
$topost = file_get_contents('php://input');
$thedata = json_decode($topost, true);
$username = $thedata['username'];
$password = $thedata['password'];
$email = $thedata['email'];
$gender = $thedata['gender'];
$age = $thedata['age'];
$about_you = $thedata['about_you'];
$sql = "INSERT INTO user (username, password, email, gender, age, about_you) ";
$sql .= "VALUES ('$username', '$password', '$email', '$gender', '$age', '$about_you')";
if (!mysql_query($sql, $con)) {
die('Error: ' . mysql_error());
// $response_array['status'] = 'error';
// echo json_encode($response_array);
}
else {
echo json_encode(array('status' => 'success','message'=> 'No problem'));
// $response_array['status'] = 'success';
// echo json_encode($response_array);
}
mysql_close($con);
?>
My problem solved by changing the way I get the data in my PHP to -> $user = $_POST['username']; instead of the way with Json (json_decode e.t.c.).

Undefined index errors - How do I set the last amount after discount?

I made a coupon code system for the admin to create new coupons. On the form, I need to calculate the last amount to be paid after the discount. I wrote the
if(!empty($discountCode)) {
$amount = ($unitCost - $unitCost * $couponDiscount / 100);
}
before adding the shipping costs and processing the payment. I'm not sure if it's correct...
I'm getting undefined index errors for $email - $qty - $cardName - $cardAddress1 - $cardAddress2 - $cardCity - $cardState - $cardZipcode - $shippingMethod - $product - $token - $couponDiscount, weird but not for $unitCost, $intRate or $domRate.
How can I fix this?
This is my form preorder.php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
// Stores errors:
$errors = array();
// Need a payment token:
if (isset($_POST['stripeToken'])) {
$token = $_POST['stripeToken'];
// Check for a duplicate submission, just in case:
// Uses sessions
if (isset($_SESSION['token']) && ($_SESSION['token'] == $token)) {
$errors['token'] = 'You have apparently resubmitted the form. Please do not do that.';
} else { // New submission.
$_SESSION['token'] = $token;
}
} else {
$errors['token'] = 'The order cannot be processed. Please make sure you have JavaScript enabled and try again.';
}
$unitCost = 6995;
$intRate = 1500;
$domRate = 500;
//print_r($_POST);
$email = $_POST['email'];
$qty = $_POST['qty'];
$cardName = $_POST['card-name'];
$cardAddress1 = $_POST['address'];
$cardAddress2 = $_POST['address2'];
$cardCity = $_POST['city'];
$cardState = $_POST['state'];
$cardZipcode = $_POST['zipcode'];
$shippingMethod = $_POST['shipping-method'];
$product = $_POST['productColor'];
$token = $_POST['stripeToken'];
$couponDiscount = $_POST['couponDiscount'];
if(!empty($discountCode)) {
$amount = ($unitCost - $unitCost * $couponDiscount / 100);
}
if($shippingMethod == 'International') :
$amount = $qty * ($intRate + $unitCost);
$description = ''.$qty.' - products(s) in '.$product.'(+International Shipping)';
else:
$amount = $qty * ($domRate + $unitCost);
$description = ''.$qty.' - products(s) in '.$product.'(+Domestic Shipping)';
endif;
// Charge the order:
$charge = Stripe_Charge::create(array(
"amount" => $amount, // amount in cents, again
"currency" => "usd",
"description" => $description,
"customer" => $customer->id
));
// Check that it was paid:
if ($charge->paid == true) {
$amountReadable = $amount / 100; // to add in decimal points
echo '<div class="alert alert-success">Your card was successfully billed for $'.$amountReadable.'</div>';
$status = "paid";
$tracking_num = "";
The form submission is done along with the coupon validation inside preorder.js, which is working well and checking the code correctly :
// Watch for the document to be ready:
$(document).ready(function() {
// Watch for a form submission:
$("#preorder").submit(function(event) {
// Flag variable:
var error = false;
// disable the submit button to prevent repeated clicks:
$('#submitBtn').attr("disabled", "disabled");
// Check for errors:
if (!error) {
Stripe.card.createToken({
number: $('.card-number').val(),
cvc: $('.card-cvc').val(),
exp_month: $('.card-expiry-month').val(),
exp_year: $('.card-expiry-year').val()
}, stripeResponseHandler);
}
// Prevent the form from submitting:
return false;
}); // Form submission
//Coupon code validation
$("#coupon_code").keyup(function(){
var value = $(this).val();
var data = {
code:value,
validateCouponCode:true
}
$.post("core.php",data,function(response){
//Since the response will be json_encode'd JSON string we parse it here
var callback = JSON.parse(response);
if(callback.status){
$("#couponStatus").html(" <span style='color:green'>Coupon is valid =) "+callback.discount_rate+"% discount</span> ");
}else{
$("#couponStatus").html(" <span style='color:red'>Coupon is not valid</span> ");
}
})
})
//Coupon Code validation END
}); // Document ready.
// Function handles the Stripe response:
function stripeResponseHandler(status, response) {
// Check for an error:
if (response.error) {
reportError(response.error.message);
} else { // No errors, submit the form:
var f = $("#preorder");
// Token contains id, last4, and card type:
var token = response['id'];
// Insert the token into the form so it gets submitted to the server
f.append("<input type='hidden' name='stripeToken' value='" + token + "' />");
// Submit the form:
f.get(0).submit();
}
} // End of stripeResponseHandler() function.
Here is the core.php:
//For ajax requests create an empty respond object
$respond = new stdClass();
$respond->status = false;
//END
$conn = mysql_connect("localhost",DB_USER,DB_PASSWORD);
mysql_select_db(DB_NAME);
//Execute the query
$foo = mysql_query("SELECT * FROM coupons WHERE expire > NOW() OR expire IS NULL OR expire = '0000-00-00 00:00:00'");
//Create an empty array
$rows = array();
while ($a=mysql_fetch_assoc($foo)) {
//Assign the rows fetched from query to the array
$rows[] = $a;
}
//Turn the array into an array of objects
$coupons = json_decode(json_encode($rows));
if(#$_POST["validateCouponCode"]){
foreach ($coupons as $coupon) {
if($coupon->coupon_code == $_POST["code"]){
//Coupon found
$respond->status = true;
//Additional instances to the respond object
$respond->discount_rate = $coupon->coupon_discount;
}
}
echo json_encode($respond);
}
After hours of practice on this, I ended up finding the solution and it's working.
Thanks for everyone for their suggestions.
Still open to any kind of advice to improve the code.
// Check for a form submission:
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
// Stores errors:
$errors = array();
// Need a payment token:
if (isset($_POST['stripeToken'])) {
$token = $_POST['stripeToken'];
// Check for a duplicate submission, just in case:
// Uses sessions, you could use a cookie instead.
if (isset($_SESSION['token']) && ($_SESSION['token'] == $token)) {
$errors['token'] = 'You have apparently resubmitted the form. Please do not do that.';
} else { // New submission.
$_SESSION['token'] = $token;
}
} else {
$errors['token'] = 'The order cannot be processed. Please make sure you have JavaScript enabled and try again.';
}
$unitCost = 4995;
$intRate = 1500;
$domRate = 500;
//print_r($_POST);
$email = $_POST['email'];
$qty = $_POST['qty'];
$cardName = $_POST['card-name'];
$cardAddress1 = $_POST['address'];
$cardAddress2 = $_POST['address2'];
$cardCity = $_POST['city'];
$cardState = $_POST['state'];
$cardZipcode = $_POST['zipcode'];
$shippingMethod = $_POST['shipping-method'];
$product = $_POST['kloqeColor'];
$token = $_POST['stripeToken'];
$couponDiscount = '';
$sql = "SELECT * FROM `------`.`coupons` WHERE `coupon_code` = '" .addslashes($_POST['coupon-code']) . "'";
//echo $sql;
$query = $connectAdmin->Query($sql);
if($query->num_rows > 0) {
$results = $query->fetch_array(MYSQLI_ASSOC);
$couponDiscount = $results['coupon_discount'];
}
//echo '<pre>' . print_r($_POST, true) . '</pre>';
$amount = $unitCost;
if(!empty($couponDiscount)) {
//$amount = ($unitCost - $unitCost * $couponDiscount / 100);
//echo 'Discount not empty<br>';
$amount = $unitCost * ((100-$couponDiscount) / 100);
}
//echo $amount . '<br>';
Can you please add your html of the form? You didn't list stripeToken as undefined index and this your if condition. So the variables $unitCost, $intRate or $domRate can be defined since you are assigning numbers. The question is, why stripeToken is defined but not the other indexes. Probably there is a problem with the form and its fields?

Categories

Resources