RUN API inside SQL database upload - php

I have an API to do an action for a site.
/api/api.php?api=server&ver=1.0&key=**&cmd=ADD_OBJECT,862011228001930
The API works and does what it needs to be done. The API information is populated from a form I have. the form also needs to upload information to MYSQL database using SQL
I have the following SQL
$sql = "INSERT INTO tracking_units SET
status = 'Tech',
unit_nr = '".$unit_nr."',
imei = '".$imei."',
sysdate = '".$date."',
systime = '".$time."',
controller = '".$slname."',
branch = 'JHB',
client = 'eTrack'";
if ($conn->query($sql) === TRUE)
{$last_id = mysqli_insert_id($conn); //Retrieve the last ID of the record
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
header("Location: http://***/api/api.php?api=server&ver=1.0&key=***&cmd=ADD_OBJECT,$imei");
The above works as the header runs the API, but once the API is completed I would like to redirect the page to another html page. Is this possible with me running the header command.
I am very new to API's and not sure how else I can run the API after the SQL command and then use the header to divert to another page

I have found this to work
$ch = curl_init("http://***/api/api.php?api=server&ver=1.0&key=***&cmd=ADD_OBJECT,$imei,$unit_nr,false,2021-01-01");
curl_exec($ch);
if (curl_error($ch)) {
fwrite($ch, curl_error($ch));
}
curl_close($ch);
fclose($ch);

Related

How to store order data from shopify webhooks in mysql database using php?

I want to use shopify order webhook to store order data into mysql database. I am beginner in webhooks. Googled many times to find the guidance about how to achieve it.I found this solutions is very close for me.I wrote the php code but I am getting error like this error img.I don't know why I am getting this error and how to resolve it.Please suggest us.
I followed these steps
I created the webhook from shopify admin dashboard
Point the webhook to my own domain
And write the following code in the pointed link
here is my code
my code is
<?php
$webhook_content = NULL;
// Get webhook content from the POST
$webhook = fopen('php://input' , 'rb');
while (!feof($webhook)) {
$webhook_content .= fread($webhook, 4096);
}
fclose($webhook);
// Decode Shopify POST
$webhook_content = json_decode($webhook_content, TRUE);
$servername = "localhost";
$database = "xxxxxxxx_xxxhalis";
$username = "xxxxxxxx_xxxhalis";
$password = "***********";
$sql = "mysql:host=$servername;dbname=$database;";
// Create a new connection to the MySQL database using PDO, $my_Db_Connection is an object
try {
$db = new PDO($sql, $username, $password);
//echo "<p> DB Connect = Success.</p>";
} catch (PDOException $error) {
echo 'Connection error: ' . $error->getMessage();
}
$order_num= $webhook_content['name'];
$order_date = $webhook_content['created_at'];
$order_mode = "Online";
$location= $webhook_content['default_address']['province'];
$cust_name = $webhook_content['billing_address']['name'];
$address = $webhook_content['default_address']['address1']['address2']['city']['province']['zip'];
$phone_num = $webhook_content['default_address']['phone'];
$special_note= $webhook_content['note'];
$total_mrp = $webhook_content['current_subtotal_price'];
$total_discount= $webhook_content['current_total_discounts'];
$sub_total = $webhook_content['current_subtotal_price'];
$delivery_charges = $webhook_content['presentment_money']['amount'];
$totalOrderValues= $webhook_content['total_price'];
$discount_approval = "NA";
$invoice_status= "NA";
$punching_status = "NA";
$order_source = "Shopify";
$payment_mode= $webhook_content['payment_gateway_names'];
$payement_status = "Done";
$payement_recieve_date= $webhook_content['processed_at'];
$reference_number = $webhook_content['reference'];
$cash_handover_status = "NA";
$my_Insert_Statement = $my_Db_Connection->prepare("INSERT INTO `customer_order_sab`( `order_num`, `order_datetime`, `modeOfOrder`, `location`, `customer_name`, `address`, `phone_number`, `special_note`, `total_mrp`, `total_discount`, `sub_total`, `delivery_charges`, `totalOrderValues`, `discount_approval`, `invoice_status`, `punching_status`, `order_source`, `payment_mode`, `payement_status`, `payement_recieve_date`, `reference_number`, `cash_handover_status`) VALUES (:order_num, :order_date, :order_mode, :location, :cust_name, :address, :phone_num, :special_note, :total_mrp, :total_discount, :sub_total, :delivery_charges, :totalOrderValues, :discount_approval, :invoice_status, :punching_status, :order_source, :payment_mode, :payement_status, :payement_recieve_date, :reference_number, :cash_handover_status)");
$my_Insert_Statement->bindParam(':order_num', $order_num);
$my_Insert_Statement->bindParam(':order_date', $order_date);
$my_Insert_Statement->bindParam(':order_mode', $order_mode);
$my_Insert_Statement->bindParam(':location', $location);
$my_Insert_Statement->bindParam(':cust_name', $cust_name);
$my_Insert_Statement->bindParam(':address', $address);
$my_Insert_Statement->bindParam(':phone_num', $phone_num);
$my_Insert_Statement->bindParam(':special_note', $special_note);
$my_Insert_Statement->bindParam(':total_mrp', $total_mrp);
$my_Insert_Statement->bindParam(':total_discount', $total_discount);
$my_Insert_Statement->bindParam(':sub_total', $sub_total);
$my_Insert_Statement->bindParam(':delivery_charges', $delivery_charges);
$my_Insert_Statement->bindParam(':totalOrderValues', $totalOrderValues);
$my_Insert_Statement->bindParam(':discount_approval', $discount_approval);
$my_Insert_Statement->bindParam(':invoice_status', $invoice_status);
$my_Insert_Statement->bindParam(':punching_status', $punching_status);
$my_Insert_Statement->bindParam(':order_source', $order_source);
$my_Insert_Statement->bindParam(':payment_mode', $payment_mode);
$my_Insert_Statement->bindParam(':payement_status', $payement_status);
$my_Insert_Statement->bindParam(':payement_recieve_date', $payement_recieve_date);
$my_Insert_Statement->bindParam(':reference_number', $reference_number);
$my_Insert_Statement->bindParam(':cash_handover_status', $cash_handover_status);
if ($my_Insert_Statement->execute()) {
echo "New record created successfully";
} else {
echo "Unable to create record";
}
?>
You are doing it wrong in one giant respect, but I respect you for trying!
If you expect webhooks to be sent to your App from some store where you installed your App, and you expect to save data from the webhooks in your database you cannot create the webhooks from the Shopify Admin and then process them in your App due to security. Instead, you install a webhook from your App, instructing Shopify to send your App webhooks. This way, Shopify can use your App API token to secure the webhooks. Your App then receives webhooks and decides if they are legit or not. You cannot do that if you use the Admin.
Read up on creating webhooks for use with your App! You can choose RestAPI or GraphQL and go from there.

why google recaptcha did not call back in my process?

EDITED: I have registered my domain in admin panel
blabla.org
but it still not worked
so i have some process with google recaptcha verification.
but when i click the button process.
$response cant detected and it given null content.
here is my code
$site_key = 'secret';
$secret_key = secret';
if(isset($_POST['req_token'])){
if(isset($_POST['g-recaptcha-response']))
{
$api_url = 'https://www.google.com/recaptcha/api/siteverify?secret=' . $secret_key . '&response='.$_POST['g-recaptcha-response'];
$response = file_get_contents($api_url);
$data = json_decode($response);
if($data['success'])
{
$nama =$_POST['nama'];
$email =$_POST['email'];
$telp_1 =$_POST['telp_1'];
$status_id = 1;
$sql="INSERT INTO data_recruitment
( status_id,
nama,
email,
telp_1
)
VALUES
( '$status_id',
'$nama',
'$email',
'$telp_1'
)";
if(mysqli_query($conn, $sql)){ // jika query insert berhasil dieksekusi
header("location:../index.php?status=1");
}
else{
header("location:../index.php?status=2");
}
} else
{
header("location:../index.php?status=4");
}
}
else{
header("location:../index.php?status=3");
}
}
$response not detected in my server. but when i tested in localhost. the process working fine.
any suggestion?
Did you take a look at this? file_get_contents returns empty string
You might want to do a phpinfo() and see what version your server is running.

PHP calling another PHP page for MySQL Query (returning JSON data)

I would like to find out how a PHP page calls another PHP page, which will return JSON data.
I am working with PHP (UsersView.php) files to display my contents of a website. However, I have separated the MySQL Queries in another PHP (Get_Users.php) file.
In the Get_Users.php, I will have a MySQL statement to query the database for data. It will then encode in JSON and be echo-ed out.
In the UsersView.php, I will call the Get_Users.php in order to retrieve the Users JSON data. The data will then be used to populate a "Users Table".
The thing is, I do not know how to call the "Get_Users.php" from the "UsersView.php" in order to get the data.
Part of UserView.php
$url = "get_user.php?id=" . $id;
$json = file_get_contents($url);
$result = json_decode($json, true);
I am trying to call the file which is in the same directory, but this does not seem to work.
Whole of Get_Users.php
<?php
$connection = mysqli_connect("localhost", "root", "", "bluesky");
// Test if connection succeeded
if(mysqli_connect_errno()) {
die("Database connection failed: " . mysqli_connect_error() . " (" . mysqli_connect_errno() . ") " .
"<br>Please retry your last action. Please retry your last action. " .
"<br>If problem persist, please follow strictly to the instruction manual and restart the system.");
}
$valid = true;
if (!isset($_GET['id'])) {
$valid = false;
$arr=array('success'=>0,'message'=>"No User ID!");
echo json_encode($arr);
}
$id = $_GET['id'];
if($valid == true){
$query = "SELECT * FROM user WHERE id = '$id'";
$result = mysqli_query($connection, $query);
if(mysqli_num_rows($result) == 1){
$row = mysqli_fetch_assoc($result);
$arr=array('success'=>1,'type'=>$row['type'],'user_id'=>$row['id'],'email'=>$row['email'],'name'=>$row['name'],'phone'=>$row['phone'],'notification'=>$row['notification']);
echo json_encode($arr);
}else{
$arr=array('success'=>0,'message'=>"Invalid User ID!");
echo json_encode($arr);
}
}
mysqli_close($connection);
?>
You have a couple of different ways to accomplish this:
You should be able to first set the actual id and then include the Get_Users.php file like this. Notice that you should not echo out the output from Get_Users.php, instead only return the encoded json data using return json_encode($arr);:
// set the id in $_GET super global
$_GET['id'] = 1;
// include the file and catch the response
$result = include_once('Get_Users.php');
You can also create a function that can be called from UserView.php:
// Get_Users.php
<?php
function get_user($id) {
// connect to and query database here
// then return the result as json
return json_encode($arr);
}
?>
// In UserView.php you first include the above file and call the function
include_once('Get_Users.php');
$result = get_user(1);
You could also use file_get_contents(). Notice that you need to make sure so that allow_url_fopen is enabled in your php.ini file for this to work:
$result = file_get_contents('http://example.com/Get_Users.php?id=1');
To enable allow_url_fopen you need to open up your loaded configuration file and set allow_url_fopen=1 and finally restart your webserver.
You could also use curl to achieve the same result:
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, 'http://example.com/Get_Users.php?id=1');
$result = curl_exec($ch);
curl_close($ch);
An ajax request could also be made to get the result. This example uses jQuery:
$(document).ready(function() {
$.get({
url: 'Get_Users.php',
data: 'id=1',
success: function(response) {
// response contains your json encoded data
// in this case you **must** use echo to transfer the data from `Get_Users.php`
}
});
});
Change UsersView.php to like this
$actual_link = 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['CONTEXT_PREFIX'];
$url = "get_users.php?id=" . $id;
$url = $actual_link.$url;
$json = file_get_contents($url);
$result = json_decode($json, true);
This will work fine.

PHP _POST['field'] is empty when using API url

I followed the below online tutorial to build a PHP API.
https://trinitytuts.com/restful-web-services-with-php-mysqli/
The HTTP request works perfectly when I use Chrome's "Advanced Rest Client". I get the following response:
{
"status": 1
"msg": "Your record inserted successfully"
}
I tried to put the following URL directly into my web browser:
http://localhost/API/insert.php/name=paul&email=paul#domain.com&status=active
I expected the same result as I received when I used the Advanced Rest Client however, I received the following error:
Notice: Undefined index: name
I am setting the variable 'name' using the following PHP code:
$name = $_POST['name'];
My understanding is that when I paste the URL into the browser, the $name variable is not set to $_POST['name'] because entering the URL is not actually a post action.
Is it possible for me add a parameter to the URL so as to tell the browser to post? For example:
http://localhost/API/insert.php/type=POST&name=paul&email=paul#domain.com&status=active
In a nutshell, I want to be able to past a URL directly into a web browser and and not have to post it via a HTML form.
This is my PHP code for insert.php
<?php
include 'conn.php';
$name = $_POST['name'];
$email = $_POST['email'];
$status = $_POST['status'];
$id = 1;
$sql = "INSERT INTO `service`.`user` (`id`, `name`, `email`, `status`) VALUES ($id, '$name', '$email', '$status');";
if ($connection->query($sql)) {
$msg = array("status" =>1 , "msg" => "Your record inserted successfully");
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($connection);
}
$json = $msg;
header('content-type: application/json');
echo json_encode($json);
#mysqli_close($conn);
?>
Issue has been resolved by changing $_POST to $_GET in insert.php

Abraham Williams Twitter oAuth PHP Callback Issue

I am building an app using Abraham William's TwitterOAuth Package. The app is working fine, except I am running into one problem.
About the 25% of the users who try to install the app cannot do so. They verify the application on the Twitter Page and click "Sign In" (on Twitter's website). When they are referred back to the Callback.php page, it gives them a blank page. I cannot figure out what is wrong, because it works for most users. Any ideas?
Here is the callback.php code:
<?php
require_once("config_db.php");
session_start();
// Include class & create
require_once("consumer-keys.php");
require_once("twitteroauth/twitteroauth/twitteroauth.php");
// User has selected to DENY access
if(!empty($_GET["denied"])) {
// could re-direct or display cancelled view/template
// we're just echoing out a message
echo "No deal! <a href='login.php'>Try again?</a>";
die();
}
// User has selected to ALLOW access for given token
if($_GET["oauth_token"] == $_SESSION["oauth_token"]) {
// Use generated request tokens (from session) to construct object
$tOAuth = new TwitterOAuth($consumerKey, $consumerSecret, $_SESSION["oauth_token"], $_SESSION["oauth_token_secret"]);
// Retrieve access token from Twitter
$accessToken = $tOAuth->getAccessToken();
//echo "RECEIVED TOKENS<br>";
// Check we have valid response
if(is_numeric($accessToken["user_id"])) {
// Save the access tokens to a DB (we're using a session)
$_SESSION["access_token"] = $accessToken;
//GET CREDENTIALS VIA API
$credentials = $tOAuth->get('account/verify_credentials');
//echo "HAS NUMERIC ID<br>";
//ISAAC ADD DB INFO
$query = "SELECT * FROM `t4i_app`.`users_twitter` WHERE user_id = '".$_SESSION["access_token"]["user_id"]."'";
$rs = mysql_query($query);
if(mysql_num_rows($rs)) {
//update query
//echo "user already exists..need to update";
$query = "UPDATE `t4i_app`.`users_twitter` SET `token` = '".$_SESSION["access_token"]["oauth_token"]."', `secret` = '".$_SESSION["access_token"]["oauth_token_secret"]."', `screen_name` = '".$credentials->screen_name."', `followers` = '".$credentials->followers_count."' WHERE `users_twitter`.`user_id` = '".$_SESSION["access_token"]["user_id"]."';";
mysql_query($query);
} else {
$query = "INSERT INTO `t4i_app`.`users_twitter` (`id` ,`screen_name` ,`token` ,`secret`, `user_id`, `followers`, `referer` ,`last_update` ,`date_registered`) VALUES (NULL, '".$credentials->screen_name."', '".$_SESSION["access_token"]["oauth_token"]."', '".$_SESSION["access_token"]["oauth_token_secret"]."', '".$_SESSION["access_token"]["user_id"]."', '".$credentials->followers_count."', '0', CURRENT_TIMESTAMP , CURRENT_TIMESTAMP);";
mysql_query($query);
}
//echo $query;
//echo mysql_error();
//print_r($_SESSION["access_token"]);
$message = array('status' => 'Test OAuth update. #testoauth');
$test = $tOAuth->post('statuses/update', array('status' => 'I just added the new APPNAME Twitter Application http://bit.ly/sampleurl'));
//echo "POSTED STATUS<br>";
//END ISAAC
// Remove request token session variables
unset($_SESSION["oauth_token"]);
unset($_SESSION["oauth_token_secret"]);
// Redirect to main page
header("location: http://www.mydomain.com/welcome.php");
} else {
//echo "TRYING TO REDIRECT <br>";
header("location: http://www.mydomain.com");
}
}
?>
if ($_GET["oauth_token"] == $_SESSION["oauth_token"])
You'll want to put an error_log in the else for this, you're failing without any messages if the oauth_tokens in the get and session don't match. It could be that Twitter isn't responding properly.
Also, I would capitalize the Location in the header call. I'm not 100% that every browser will honor it when it's not Location:

Categories