Abraham Williams Twitter oAuth PHP Callback Issue - php

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:

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.

RUN API inside SQL database upload

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

php - Login redirecting to same page, static but different roles

After doing my SQL Schema (Different types of users redirected to same page (index.php) with different content), I'm starting to make my login system.
I now have this:
function login($email,$password){
$mysqli = $this ->dbConnect();
if($mysqli){
$strQuery = "SELECT USERS.ID, USERS.EMAIL, TYPES.NAME FROM `USERS` LEFT JOIN `TYPES` ON USERS.TYPEID = TYPES.ID WHERE `EMAIL` = '$email' AND `PASSWORD` = '$password'";
$recordSet = $mysqli->query($strQuery);
$row = $recordset->fetch_assoc();
if($recordset->num_rows>0){
$_SESSION['auth'] = $row['ID'];
$_SESSION['username'] = $row['EMAIL'];
$_SESSION['type'] = $row['NAME'];
header ("location:"index.php");
return true;
}
//....
}
}
Does this look good? Is the query right? Any suggestions for improvement?
UPDATE
I have my login working now. And it's redirecting to index.php. But in index php I don't have acess to the $_SESSIONS variables i have stored on my function login. Is there any problem with the attribuitions? Placing the header inside the function not good?
Thanks :)
I summarized the previous comments.
1. Issue: you didn't used the same variables
function login($email,$password){ and $strQuery = " ... WHERE EMAIL = '$email' AND PASSWORD = '$password'";
2. Recomendation: use the same namming convention
On your SQL request you used two way to use fields: USERS.EMAIL and EMAIL = (with ` arround).
Use the same. This will be easier for later & debugging.
i.e.: of course, you should not use table.field each time. Not mandatory for example if you have only one table OR if the fields are not shared between them. For my perosnnal usage, I always use this table.field. This will prevent any future issue :)
3. Protect your data from any injection
Example:
$post_email = isset($_POST['email']) ? htmlspecialchars($_POST['email']) : null;
Alter call
$this->login($post_email, ...)
And finally use something like this to protect your data:
$email = $mysqli->real_escape_string($email);
and you are ready for your request:
" SELECT [..] FROM users as u [...] WHERE u.email = '$email' "
4. Or use specific functions
Example (real_escape_string not needed anymore):
$stmt = $dbConnection->prepare('SELECT * FROM users WHERE email = ? AND password = ?');
$stmt->bind_param('s', $email);
$stmt->bind_param('s', $password);
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
// do something with $row
}
http://php.net/manual/fr/class.mysqli.php
5. Sessions
If you want to activate sessions on a spacific page, the first code (at the first line) should be session_start().
Calling this method will activate the sessions and load the $_SESSION variable with content.
<?php // index.php
session_start(); // first line
// ... code
var_dump($_SESSION);
?>
&
<?php // page.php
session_start(); // first line
// ... code
$_SESSION['test'] = time();
Header('Location: index.php');
?>
Visit index.php -> nothing on the debug
Visit page.php -> you will be redirected on index.php
On index.php -> you will have data
Enjoy session :p
6. Handle specific data
To begin with, you should coose a way to store the credential access (ACL) for each user. For example, store on the database some values as 100001, and each number is a yes/no access for a specific action (binary access mode) ; another system is to store the level '1,2,3,4,5' ... or 'member,customer,admin, ...'. So many ways :)
I will choose the USER.ACCESS = member|customer|admin solution
On the login page
// is user successfully logged
$_SESSION['access'] = $row['access']; // member|customer|admin
// Header('Location: index.php');
On any page of your site:
if( in_array($_SESSION['access'], ['member', 'admin']) ) {
echo 'You are a member, you can see this part';
}
if( in_array($_SESSION['access'], ['customer', 'admin']) ) {
echo 'You are a customer, you can see this part';
}
Or
if( checkAccess() ) {
echo 'Welcome user !';
if( checkAccess(['member', 'customer']) ) {
echo 'This is a section for member, customer or admin :)';
}
if( checkAccess('member') ) {
echo 'You are a member, you can see this part';
}
if( checkAccess('customer') ) {
echo 'You are a customer, you can see this part';
}
}
function checkAccess($types = null) {
if( !isset($_SESSION['access']) )
return false; // not logged
if( is_null($types) )
retun true; // if empty, provide info about loggin.
// admin has always access to all sections of the website
$hasAccess = in_array($_SESSION['access'], ((array) $types) + ['admin']);
return $hasAccess; // user is logged + has accessor not ?
}
Of course, you can also use includes
if( checkAccess('member') ) {
include 'secret_page_for_member.php';
}
Or, at the begening of the included page:
<?php
if( !checkAccess('admin') ) {
return '403 - Not authorized';
// die('403');
// throw new Exception('403');
}
// your code
?>

how create rest / soap throw create forgot password webservices in magento?

I am using following code in soap api for forgot password for magento and how can send mail for change password link perticular user throw api using magento functionality mail using if any simple mathed for related rest api guide me
error_reporting(0);
$client = new SoapClient('http://127.0.0.1/mycart/api/soap/?wsdl');
$session = $client->login('admin', '123456789');
$return_array = array ();
$result = $client->call($session, 'customer.list');
$email=addslashes($_POST['email']);
//$email=addslashes("test#mail.com");
if(!empty($email)){
foreach ($result as $key=>$value){
//echo $value[email];
if ($value[email]==$email)
{
$return_array['message']="You will receive an email with a link to reset your password ";
$return_array['status']= "1";
echo json_encode($return_array);
exit;
}elseif ($value[email]!=$email) {
$return_array['message']="You are not registered with us. Please sign up to create an account";
$return_array['status']= "2";
echo json_encode($return_array);
exit;
}
}
}
else {
$return_array['message']="You are not registered with us. Please sign up to create an account ";
$return_array['status']= "0";
echo json_encode($return_array);
exit;
}
exit;
I guess you are using admin credentials for client login also you are using magento api V1 whether Magento v1 or v2 api needs api user. Please follow the guidance
https://www.yireo.com/tutorials/magebridge/administration/596-step-by-step-create-a-magento-api-user

INVALID_SESSION_ID: Invalid Session ID found in SessionHeader: Illegal Session

Similar issues -
INVALID_SESSION_ID using partner/enterprise wsdl for two different SF users - Tried solution but didn't work.
I was trying to use Salesforce PHP toolkit with ZF 2. I have added namespace to php files in salesforce soap client and used it in zend controller.
Added follwing line to all php files in Salesforce SOAP client library.
namespace Salesforce\Soapclient;
Then included it in ZF controller.
use Salesforce\Soapclient;
Here is the connetion code -
$empid = 'e1234567';
$sf_WSDL = 'C:\wamp\www\myapp\app\vendor\salesforce\wsdl\enterprise.wsdl.xml';
$sf_username = $config['salesforce']['username'];
$sf_password = $config['salesforce']['password'];
$sf_token = $config['salesforce']['token'];
/***********/
try {
// Create SOAP client instance
$sfSoapClient = new Soapclient\SforceEnterpriseClient();
// Create connection
$sfSoapClient->createConnection($sf_WSDL);
var_dump($_SESSION['enterpriseSessionId']);
if (isset($_SESSION['enterpriseSessionId'])) {
$location = $_SESSION['enterpriseLocation'];
$sessionId = $_SESSION['enterpriseSessionId'];
$sfSoapClient->setEndpoint($location);
$sfSoapClient->setSessionHeader($sessionId);
} else {
// Login to SF
$sfSoapClient->login($sf_username,$sf_password . $sf_token);
$_SESSION['enterpriseLocation'] = $sfSoapClient->getLocation();
$_SESSION['enterpriseSessionId'] = $sfSoapClient->getSessionId();
}
var_dump($_SESSION['enterpriseSessionId']);
// Get candidate profile by employee id
$candidate_profile = $this->getCandidateTable()->getCandidateByEmpId($empid);
$ids = array();
array_push($ids, $empid);
// If no profile for logged internal employee
if (!$candidate_profile){
$query = "SELECT Id, First_Name__c from Employee__c";
$response = $sfSoapClient->query($query);
echo "Results of query '$query'<br/><br/>\n";
foreach ($response->records as $record) {
echo $record->Id . ": " . $record->First_Name__c . "<br/>\n";
}
}
} catch (Exception $exc) {
//TODO Handle error login exception
die('Connection could not established.');
}
But I'm getting following error -
INVALID_SESSION_ID: Invalid Session ID found in SessionHeader: Illegal
Session
Note that "Lock sessions to the IP address from which they originated" setting is turned off.

Categories