Paypal IPN not executing license creation code - php

Let’s get detailed…cause I’m stumped.
Server File structure:
/home/name/public_html/CryptlexApi.php
/home/name/public_html/generate-license.php see below
/home/name/public_html/generate-license-IPN_combined.php
/home/name/public_html/paypalIPN.php
source
generate-license.php:
<?php
require('CryptlexApi.php');
// pass this secret as query param in the url e.g. https://yourserver.com/generate-license.php?cryptlex_secret=SOME_RANDOM_STRING
$CRYPTLEX_SECRET = "SOME_RANDOM_STRING";
// access token must have following permissions (scope): license:write, user:read, user:write
$PERSONAL_ACCESS_TOKEN = "Yes, I have my PAT here";
// utility functions
function IsNullOrEmptyString($str){
return (!isset($str) || trim($str) === '');
}
function ForbiddenRequest() {
http_response_code(403);
$message['error'] = 'You are not authorized to perform this action!';
echo json_encode($message);
}
function BadRequest($error) {
http_response_code(400);
$message['error'] = $error;
echo json_encode($message);
}
function VerifySecret($secret) {
if($secret == $GLOBALS['CRYPTLEX_SECRET']) {
return true;
}
return false;
}
function parsePayPalPostData() {
$postBody['company'] = $_POST['payer_email'];
if(IsNullOrEmptyString($postBody['email'])) {
$postBody['company'] = "";
}
$postBody['quantity'] = $_POST['quantity'];
if(IsNullOrEmptyString($postBody['quantity'])) {
$postBody['quantity'] = NULL;
}
$postBody['email'] = $_POST['payer_email'];
if(IsNullOrEmptyString($postBody['email'])) {
BadRequest('email is missing!');
return NULL;
}
$postBody['last_name'] = $_POST['last_name'];
if(IsNullOrEmptyString($_POST['last_name'])) {
BadRequest('last name is missing!');
return NULL;
}
$postBody['first_name'] = $_POST['first_name'];
if(IsNullOrEmptyString($_POST['first_name'])) {
BadRequest('first name is missing!');
return NULL;
}
$postBody['order_id'] = $_POST['txn_id'];
if(IsNullOrEmptyString($postBody['order_id'])) {
BadRequest('reference is missing!');
return NULL;
}
return $postBody;
}
try {
if(VerifySecret($_GET['cryptlex_secret']) == false) {
return ForbiddenRequest();
}
CryptlexApi::SetAccessToken($GLOBALS['PERSONAL_ACCESS_TOKEN']);
$product_id = "this is my product id";
$postBody = parsePayPalPostData();
if($postBody == NULL) {
echo "no data \n";
return;
}
$email = $postBody['email'];
$first_name = $postBody['first_name'];
$last_name = $postBody['last_name'];
$quantity = $postBody['quantity'];
// required for renewing the license subscription
$order_id = $postBody['order_id'];
// creating user is optional
$user_exists = false;
$user = CryptlexApi::GetUser($email);
if($user == NULL) {
$user_body["email"] = $email;
$user_body["firstName"] = $first_name;
$user_body["lastName"] = $last_name;
$user_body["company"] = $last_name;
// generate a random 8 character password
$user_body["password"] = substr(md5(uniqid()), 0, 8);
$user_body["role"] = "user";
$user = CryptlexApi::CreateUser($user_body);
} else {
$user_exists = true;
}
echo "Quantity = $quantity \n";
// creating license
if($quantity != NULL) {
$license_body["allowedActivations"] = (int)$quantity;
}
$license_body["productId"] = $product_id;
$license_body["userId"] = $user->id;
$metadata["key"] = "order_id";
$metadata["value"] = $order_id;
$metadata["visible"] = false;
$license_body["metadata"] = array($metadata);
$license = CryptlexApi::CreateLicense($license_body);
http_response_code(200);
echo $license->key;
} catch(Exception $e) {
http_response_code(500);
echo 'message: ' .$e->getMessage();
}
Ok, So if I do the following in the terminal, I will successfully create a user/license
curl -d "payer_email=emailaddress%40gmail.com&quantity=1&last_name=smith&first_name=bob&txn_id=ordernumber" -X POST https://mywebsite.com/generate-license.php?cryptlex_secret=SOME_RANDOM_STRING
So, I take that code and put it in paypalIPN.php and renamed to generate-license-IPN_combined.php
In the paypalIPN.php file, I inserted the above code here:
// Check if PayPal verifies the IPN data, and if so, return true.
if ($res == self::VALID) {
######## I put all of my code above right here #########
return true;
} else {
return false;
}
The IPN code seems to work since the Paypal IPN simulator says it does. Nothing happens on the database side though. I’ve removed checks and even went as far as putting this code before the IPN but it’s not working. Please help.

A quick way to generate test IPNs in sandbox is to pay with a link of the form:
https://www.sandbox.paypal.com/webscr?cmd=_xclick&item_name=test&amount=100&currency_code=USD&business=sandboxbusinessemail#domain.com&notify_url={URL_ENCODE_YOUR_IPN_LISTENER_URL}
(Reference: HTML Variables for PayPal Payments Standard )
Get a sandbox business account to sub into the above, and a sandbox personal account to pay with, via: https://www.paypal.com/signin?intent=developer&returnUri=https%3A%2F%2Fdeveloper.paypal.com%2Fdeveloper%2Faccounts%2F
Review the business account's IPN history via: https://www.sandbox.paypal.com/webscr?cmd=_display-ipns-history

Related

Weird behaviour of PHP Login

This is more like a debugging problem than an actual question. I have a login script in PHP which should check for user information from a local database and if present, then display them. Or else, redirect them to the Google OAuth2 Login process. The following php files concern the login flow :
google_login.php
<?php
error_reporting(E_ALL); ini_set('display_errors', 1);
require('http.php');
require('oauth_client.php');
require('../config.php');
require('StructuredQuery.php');
define("SCOPE", 'https://www.googleapis.com/auth/userinfo.email '.
'https://www.googleapis.com/auth/userinfo.profile' );
$client = new oauth_client_class;
$sq= new StructuredQuery();
// set the offline access only if you need to call an API
// when the user is not present and the token may expire
$client->offline = FALSE;
$client->debug = false;
$client->debug_http = true;
$client->redirect_uri = GOOGLE_REDIRECT_URL;
$client->client_id = GOOGLE_CLIENT_ID;
$application_line = __LINE__;
$client->client_secret = GOOGLE_CLIENT_SECRET;
if (strlen($client->client_id) == 0 || strlen($client->client_secret) == 0)
die('Please go to Google APIs console page ' .
'http://code.google.com/apis/console in the API access tab, ' .
'create a new client ID, and in the line ' . $application_line .
' set the client_id to Client ID and client_secret with Client Secret. ' .
'The callback URL must be ' . $client->redirect_uri . ' but make sure ' .
'the domain is valid and can be resolved by a public DNS.');
/* API permissions
*/
$client->scope = SCOPE;
if (($success = $client->Initialize())) {
if (($success = $client->Process())) {
if (strlen($client->authorization_error)) {
$client->error = $client->authorization_error;
$success = false;
} elseif (strlen($client->access_token)) {
$success = $client->CallAPI(
'https://www.googleapis.com/oauth2/v1/userinfo', 'GET', array(), array('FailOnAccessError' => true), $user);
}
}
$success = $client->Finalize($success);
}
if ($client->exit)
exit;
if ($success) {
// Now check if user exist with same email ID
try {
$result = $sq->getUserInfo($user->id);
if ($result["count"] > 0) {
// User Exist
$_SESSION["name"] = $result["name"];
$_SESSION["email"] = $result["email"];
$_SESSION["clevel"]=$result["clevel"];
$_SESSION["new_user"] = "no";
} else {
// New user, Insert in database
$result = $sq->putNewUserInfo($user->id,$user->name,$user->email);
if ($result===true) {
$_SESSION["name"] = $user->name;
$_SESSION["email"] = $user->email;
$_SESSION["new_user"] = "yes";
$_SESSION["e_msg"] = "";
}
}
$_SESSION["login_type"]="Google";
} catch (Exception $ex) {
$_SESSION["e_msg"] = $ex->getMessage();
}>
$_SESSION["user_id"] = $user->id;
} else {
$_SESSION["e_msg"] = $client->error;
}
header("Location: ".ROOT_DIR."homepage.php");
exit;
?>
StructuredQuery.php
<?php
error_reporting(E_ALL); ini_set('display_errors', 1);
require_once 'config.php';
class StructuredQuery{
var $opt;
var $pdo;
function __construct(){
$opt = [
PDO::ATTR_PERSISTENT => FALSE,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
];
$this->pdo = new PDO(DB_DRIVER.":host=".DB_SERVER.";dbname=".DB_NAME, DB_SERVER_USERNAME, DB_SERVER_PASSWORD, $opt);
}
// Cross Site Script & Code Injection Sanitization
function xss_cleaner($input_str) {
$return_str = str_replace( array('<',';','|','&','>',"'",'"',')','('), array('<',':','|','&','>','&apos;','"',')','('), $input_str );
$return_str = str_ireplace( '%3Cscript', '', $return_str );
return $return_str;
}
//SQLInjection detect
function sql_injection_detect($input_query){
try{
$blacklist=array('SELECT','WHERE','UPDATE','DELETE','INSERT','FROM','DROP','MERGE','SET','INSERT','REMOVE','REPLACE','QUERY');
$err_level=0;
foreach($blacklist as $blacklist_item){
if(stripos($input_query,$blacklist_item)!==false){
$err_level++; //Counter for number of blacklist words used. 2 means dangerous. Terminate immediately.
if($err_level==2){
die('Was that an IT joke? Cause I am a 12th grader, not an IT Pro.');
}
}
}
return true;
}catch(Exception $e){
echo 'Exception Occured:',$e->getMessage(),"\n";
die('You\'ve been Terminated');
}
}
function getUserInfo($user_id){
$user_id=xss_cleaner($user_id);
if(sql_injection_detect($user_id)){
$query=$pdo->prepare("select statement");
$query->bindParam(":user_id",$user_id,PDO::PARAM_STR);
$query->execute();
$result=$query->fetch();
$result["count"]=$query->rowCount();
return $result;
}
}
function putNewUserInfo($user_id,$name,$email){
$user_id=$this->xss_cleaner($user_id);
$name=xss_cleaner($name);
$email=xss_cleaner($email);
if(sql_injection_detect($user_id) && sql_injection_detect($name) && sql_injection_detect($email)){
$query=$pdo->prepare("insert statement");
$query->bindParam(":user_id",$user_id,PDO::PARAM_STR);
$query->bindParam(":name",$name,PDO::PARAM_STR);
$query->bindParam(":email",$email,PDO::PARAM_STR);
$query->execute();
return true;
}else{
return false;
}
}
function modifyUserInfo($user_id,$name,$email,$clevel){
$user_id=xss_cleaner($user_id);
$name=xss_cleaner($name);
$email=xss_cleaner($email);
$clevel=xss_cleaner($clevel);
if(sql_injection_detect($user_id) && sql_injection_detect($name) && sql_injection_detect($email) && sql_injection_detect($clevel)){
$query=$pdo->prepare("update statement");
$query->bindParam(":user_id",$user_id,PDO::PARAM_STR);
$query->bindParam(":name",$name,PDO::PARAM_STR);
$query->bindParam(":email",$email,PDO::PARAM_STR);
$query->bindParam(":clevel",$clevel,PDO::PARAM_INT);
$query->execute();
return true;
}else{
return false;
}
}
}
Now the issue that bothers me is this- whenever i press Login With Google, it redirects to google_login.php, well and fine. And then, directly to the homepage as if I am already logged in even though I am not. Even weirder is that it displays my e-mail and my username as blank, even though it says that I am an existing user.
P.S. No, the database does not contain any blank entries and it works fine, I double-checked.

Cannot get response from PUT request using Slim Framework

Am trying to update an existing entity in my database using PUT request but i have 2 issues, when am calling the request from phpStorm rest client debugger am getting an error
{"error":true,"message":"Required field(s) restaurant_id, service_rating, food_rating, music_rating is missing or empty"}
when i call the same request from Advance rest client addon on google chrome am getting
{"error":true,"message":"Task failed to update. Please try again!"}
so i can't understand if the real bug is on the verifyRequiredParams or in my function implementation . Am providing the code if someone can help me.
This is my index.php file
$app->put('/userRatings/:rating_id', 'authenticate', function($rating_id) use($app) {
// check for required params
verifyRequiredParams(array('restaurant_id', 'service_rating', 'food_rating', 'music_rating'));
global $user_id;
$restaurant_id = $app->request->put('restaurant_id');
$service_rating = $app->request->put('service_rating');
$food_rating = $app->request->put('food_rating');
$music_rating = $app->request->put('music_rating');
$db = new DbHandler();
$response = array();
// updating rating
$result = $db->updateRating($user_id, $rating_id, $restaurant_id, $service_rating, $food_rating, $music_rating);
if ($result) {
// rating updated successfully
$response["error"] = false;
$response["message"] = "Task updated successfully";
} else {
// task failed to update
$response["error"] = true;
$response["message"] = "Task failed to update. Please try again!";
}
echoRespnse(200, $response);
});
This is the function code for the verifyRequiredParams which is located in the index.php file
function verifyRequiredParams($required_fields) {
$error = false;
$error_fields = "";
$request_params = array();
$request_params = $_REQUEST;
// Handling PUT request params
if ($_SERVER['REQUEST_METHOD'] == 'PUT') {
$app = \Slim\Slim::getInstance();
parse_str($app->request()->getBody(), $request_params);
}
foreach ($required_fields as $field) {
if (!isset($request_params[$field]) || strlen(trim($request_params[$field])) <= 0) {
$error = true;
$error_fields .= $field . ', ';
}
}
if ($error) {
// Required field(s) are missing or empty
// echo error json and stop the app
$response = array();
$app = \Slim\Slim::getInstance();
$response["error"] = true;
$response["message"] = 'Required field(s) ' . substr($error_fields, 0, -2) . ' is missing or empty';
echoRespnse(400, $response);
$app->stop();
}
}
And this is my DbHandler.php file where the function is located.
public function updateRating( $user_id, $rating_id, $restaurant_id, $service_rating, $food_rating, $music_rating) {
$stmt = $this->conn->prepare("UPDATE user_ratings set service_rating = ?, food_rating = ?, music_rating = ? WHERE user_id = ? AND rating_id = ? AND restaurant_id = ?");
$stmt->bind_param("iiiiii", $user_id , $rating_id, $restaurant_id, $service_rating, $food_rating, $music_rating);
$stmt->execute();
$num_affected_rows = $stmt->affected_rows;
$stmt->close();
return $num_affected_rows > 0;
}
All my connections are ok i have checked them and also my other services are working fine
The two errors was because advance rest client use "PUT" with capital letters and php storm with lower characters even if its written with capital in php storm i notice that by changing "PUT" with "put" in the if statement of verifyRequiredParams function and now its working and updating perfectly
Add bellow code in your index.php file
$app->addBodyParsingMiddleware();

web service for mobile application in yii

In my Yii web application I want to write a web service for mobile application. I create a url for access student details with GET method. That I want to change GET method to POST method or PUT method. My url is,
url/index.php/user/login/studentdetails/?username=demo
I am getting this username from client side and giving the response from server side to client side in json format.
My code is,
public function actionStudentdetails() {
if (isset($_GET['username'])) {
$user = Users::model()->findByAttributes(array('username' => $_GET['username']));
$usertypeid = $user->usertypeid;
if ($usertypeid === '1') {
$studentid = $user->userid;
} else if ($usertypeid === '3') {
$guardianid = $user->userid;
$studentid = $_GET['studentid'];
} else {
$employeemasterid = $user->userid;
}
$student = Student::model()->findByPk($studentid);
header('Content-type: application/json');
$response["student_admissionno"] = $student->student_admissionno;
$response["student_firstname"] = $student->student_firstname;
$response["student_middlename"] = $student->student_middlename;
$response["student_lastname"] = $student->student_lastname;
$response["student_admissiondate"] = $student->student_admissiondate;
$response["student_dob"] = $student->student_dob;
$response["student_gender"] = $student->student_gender;
$response["student_religion"] = $student->student_religion;
$response["student_caste"] = $student->student_caste;
$response["student_address1"] = $student->student_address1;
$response["student_address2"] = $student->student_address2;
$response["student_city"] = $student->student_city;
$response["student_state"] = $student->student_state;
$response["success"] = 1;
$response["message"] = "success";
echo json_encode($response);
}
}
}
Please help me.
you can try this code for webserivce. you can used any method GET or POST Method of data posting in server side.
StudentController.php
public function actionStudentdetails() {
$json_data = array();
$params = isset($_REQUEST) ? $_REQUEST: "";
if (!empty($params)) {
$username = $params['username'];
if($username == "") {
$json_data['success'] = false;
$json_data['message'] = 'Username are required.';
} else {
$user = Users::model()->findByAttributes(array('username' => $params['username']));
$usertypeid = $user->usertypeid;
if ($usertypeid === '1') {
$studentid = $user->userid;
} else if ($usertypeid === '3') {
$guardianid = $user->userid;
$studentid = $_GET['studentid'];
} else {
$employeemasterid = $user->userid;
}
$student = Student::model()->findByPk($studentid);
header('Content-type: application/json');
$json_data["student_admissionno"] = $student->student_admissionno;
$json_data["student_firstname"] = $student->student_firstname;
$json_data["student_middlename"] = $student->student_middlename;
$json_data["student_lastname"] = $student->student_lastname;
$json_data["student_admissiondate"] = $student->student_admissiondate;
$json_data["student_dob"] = $student->student_dob;
$json_data["student_gender"] = $student->student_gender;
$json_data["student_religion"] = $student->student_religion;
$json_data["student_caste"] = $student->student_caste;
$json_data["student_address1"] = $student->student_address1;
$json_data["student_address2"] = $student->student_address2;
$json_data["student_city"] = $student->student_city;
$json_data["student_state"] = $student->student_state;
$json_data['success'] = true;
$json_data['message'] = "Data found Successful.";
}
} else {
$json_data['success'] = false;
$json_data['message'] = "Please try again.";
}
echo json_encode($response);
}

Rest API and Slim Framework

I follow the tutorial here :
http://www.androidhive.info/2014/01/how-to-create-rest-api-for-android-app-using-php-slim-and-mysql-day-23/
So I have in my index.php :
<?php
error_reporting(-1);
ini_set('display_errors', 'On');
require_once '../include/DbHandler.php';
require_once '../include/PassHash.php';
require '.././libs/Slim/Slim.php';
$app = new Slim();
// User id from db - Global Variable
$user_id = NULL;
/**
* Adding Middle Layer to authenticate every request
* Checking if the request has valid api key in the 'Authorization' header
*/
function authenticate(\Slim\Route $route) {
// Getting request headers
$headers = apache_request_headers();
$response = array();
$app = Slim::getInstance();
// Verifying Authorization Header
if (isset($headers['Authorization'])) {
$db = new DbHandler();
// get the api key
$api_key = $headers['Authorization'];
// validating api key
if (!$db->isValidApiKey($api_key)) {
// api key is not present in users table
$response["error"] = true;
$response["message"] = "Access Denied. Invalid Api key";
echoRespnse(401, $response);
$app->stop();
} else {
global $user_id;
// get user primary key id
$user_id = $db->getUserId($api_key);
}
} else {
// api key is missing in header
$response["error"] = true;
$response["message"] = "Api key is misssing";
echoRespnse(400, $response);
$app->stop();
}
}
/**
* ----------- METHODS WITHOUT AUTHENTICATION ---------------------------------
*/
/**
* User Registration
* url - /register
* method - POST
* params - name, email, password
*/
$app->post('/register', function() use ($app) {
// check for required params
verifyRequiredParams(array('name', 'email', 'password'));
$response = array();
// reading post params
$name = $app->request->post('name');
$email = $app->request->post('email');
$password = $app->request->post('password');
// validating email address
validateEmail($email);
$db = new DbHandler();
$res = $db->createUser($name, $email, $password);
if ($res == USER_CREATED_SUCCESSFULLY) {
$response["error"] = false;
$response["message"] = "You are successfully registered";
} else if ($res == USER_CREATE_FAILED) {
$response["error"] = true;
$response["message"] = "Oops! An error occurred while registereing";
} else if ($res == USER_ALREADY_EXISTED) {
$response["error"] = true;
$response["message"] = "Sorry, this email already existed";
}
// echo json response
echoRespnse(201, $response);
});
/**
* User Login
* url - /login
* method - POST
* params - email, password
*/
$app->post('/login', function() use ($app) {
// check for required params
verifyRequiredParams(array('email', 'password'));
// reading post params
$email = $app->request()->post('email');
$password = $app->request()->post('password');
$response = array();
$db = new DbHandler();
// check for correct email and password
if ($db->checkLogin($email, $password)) {
// get the user by email
$user = $db->getUserByEmail($email);
if ($user != NULL) {
$response["error"] = false;
$response['name'] = $user['name'];
$response['email'] = $user['email'];
$response['apiKey'] = $user['api_key'];
$response['createdAt'] = $user['created_at'];
} else {
// unknown error occurred
$response['error'] = true;
$response['message'] = "An error occurred. Please try again";
}
} else {
// user credentials are wrong
$response['error'] = true;
$response['message'] = 'Login failed. Incorrect credentials';
}
echoRespnse(200, $response);
});
/*
* ------------------------ METHODS WITH AUTHENTICATION ------------------------
*/
/**
* Listing all tasks of particual user
* method GET
* url /tasks
*/
$app->get('/tasks', 'authenticate', function() {
global $user_id;
$response = array();
$db = new DbHandler();
// fetching all user tasks
$result = $db->getAllUserTasks($user_id);
$response["error"] = false;
$response["tasks"] = array();
// looping through result and preparing tasks array
while ($task = $result->fetch_assoc()) {
$tmp = array();
$tmp["id"] = $task["id"];
$tmp["task"] = $task["task"];
$tmp["status"] = $task["status"];
$tmp["createdAt"] = $task["created_at"];
array_push($response["tasks"], $tmp);
}
echoRespnse(200, $response);
});
/**
* Listing single task of particual user
* method GET
* url /tasks/:id
* Will return 404 if the task doesn't belongs to user
*/
$app->get('/tasks/:id', 'authenticate', function($task_id) {
global $user_id;
$response = array();
$db = new DbHandler();
// fetch task
$result = $db->getTask($task_id, $user_id);
if ($result != NULL) {
$response["error"] = false;
$response["id"] = $result["id"];
$response["task"] = $result["task"];
$response["status"] = $result["status"];
$response["createdAt"] = $result["created_at"];
echoRespnse(200, $response);
} else {
$response["error"] = true;
$response["message"] = "The requested resource doesn't exists";
echoRespnse(404, $response);
}
});
/**
* Creating new task in db
* method POST
* params - name
* url - /tasks/
*/
$app->post('/tasks', 'authenticate', function() use ($app) {
// check for required params
verifyRequiredParams(array('task'));
$response = array();
$task = $app->request->post('task');
global $user_id;
$db = new DbHandler();
// creating new task
$task_id = $db->createTask($user_id, $task);
if ($task_id != NULL) {
$response["error"] = false;
$response["message"] = "Task created successfully";
$response["task_id"] = $task_id;
echoRespnse(201, $response);
} else {
$response["error"] = true;
$response["message"] = "Failed to create task. Please try again";
echoRespnse(200, $response);
}
});
/**
* Updating existing task
* method PUT
* params task, status
* url - /tasks/:id
*/
$app->put('/tasks/:id', 'authenticate', function($task_id) use($app) {
// check for required params
verifyRequiredParams(array('task', 'status'));
global $user_id;
$task = $app->request->put('task');
$status = $app->request->put('status');
$db = new DbHandler();
$response = array();
// updating task
$result = $db->updateTask($user_id, $task_id, $task, $status);
if ($result) {
// task updated successfully
$response["error"] = false;
$response["message"] = "Task updated successfully";
} else {
// task failed to update
$response["error"] = true;
$response["message"] = "Task failed to update. Please try again!";
}
echoRespnse(200, $response);
});
/**
* Deleting task. Users can delete only their tasks
* method DELETE
* url /tasks
*/
$app->delete('/tasks/:id', 'authenticate', function($task_id) use($app) {
global $user_id;
$db = new DbHandler();
$response = array();
$result = $db->deleteTask($user_id, $task_id);
if ($result) {
// task deleted successfully
$response["error"] = false;
$response["message"] = "Task deleted succesfully";
} else {
// task failed to delete
$response["error"] = true;
$response["message"] = "Task failed to delete. Please try again!";
}
echoRespnse(200, $response);
});
/**
* Verifying required params posted or not
*/
function verifyRequiredParams($required_fields) {
$error = false;
$error_fields = "";
$request_params = array();
$request_params = $_REQUEST;
// Handling PUT request params
if ($_SERVER['REQUEST_METHOD'] == 'PUT') {
$app = Slim::getInstance();
parse_str($app->request()->getBody(), $request_params);
}
foreach ($required_fields as $field) {
if (!isset($request_params[$field]) || strlen(trim($request_params[$field])) <= 0) {
$error = true;
$error_fields .= $field . ', ';
}
}
if ($error) {
// Required field(s) are missing or empty
// echo error json and stop the app
$response = array();
$app = Slim::getInstance();
$response["error"] = true;
$response["message"] = 'Required field(s) ' . substr($error_fields, 0, -2) . ' is missing or empty';
echoRespnse(400, $response);
$app->stop();
}
}
/**
* Validating email address
*/
function validateEmail($email) {
$app = Slim::getInstance();
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$response["error"] = true;
$response["message"] = 'Email address is not valid';
echoRespnse(400, $response);
$app->stop();
}
}
/**
* Echoing json response to client
* #param String $status_code Http response code
* #param Int $response Json response
*/
function echoRespnse($status_code, $response) {
$app = Slim::getInstance();
// Http response code
$app->status($status_code);
// setting response content type to json
$app->contentType('application/json');
echo json_encode($response);
}
$app->run();
?>
But, like others people, I've got some error when I try to call the register method :
{
error: true
message: "Required field(s) name, email, password is missing or empty"
}
It seems that $_REQUEST is empty so the parameters are not sent...
I try with curl or with RestClient app extension in Google Chrome, it still doesn't work...
Any idea to make it work ?
Another way of accessing the post params, which worked for me is:
// reading post params
$name = $app->request->params('name');
$email = $app->request->params('email');
$password = $app->request->params('password');
And the response you got
{
error: true
message: "Required field(s) name, email, password is missing or empty"
}
means your post parameters are empty. Try using Postman - REST Client to test your REST API calls. I faced the same problem while using Firefox Add-On "Poster"
Note: while testing the api make sure you are properly making a POST request and not GET request.
You should remove '.' in DbConnect.php and DbHandler.php
DbConnect.php
include_once dirname(__FILE__) . './Config.php';
-> include_once dirname(__FILE__) . '/Config.php';
DbHandler.php
include_once dirname(__FILE__) . './Config.php';
-> include_once dirname(__FILE__) . '/Config.php';
That make 2 file include exact what they need. I change this and the API run very good.
Note: You should add header when you call api by Chrome add-on.
Content-Type: application/x-www-form-urlencoded
You need to parse the raw data from php input stream.
if (!empty($_GET)) {
$_INPUT = $_GET;
} else {
$_INPUT = json_decode(file_get_contents('php://input'), TRUE);
}
see this
and this
I used firefox and POSTER addon for test REST API. After I open poster window from tools->poster. In the url put my path to www/task_manager/v1/register and in parameters tab I pass three parameter for name, email, password and after that I click on body from parameters and click post button.
its worked for me. and i saw good result.
Note:
I cant use chrome advanced REST, because for unknown reason chrome didnt let me to install that addon!

ajax checking username onblur

here is the case guys, I'm trying to check username on onblur event with help of ajax , which is checking username availability in mysql database.
here is ajax script =>
document.getElementById("r_username").onblur = function(){
var http = false;
var error = document.getElementById("error_username");
var numLetter = /^[a-zA-Z-0-9]+$/;
if (this.value==""){
error.innerHTML = "Empty Field !!!";
error.style.display = "inline";
} else {
if (this.value.match(numLetter)){
if (window.XMLHttpRequest){
http = new XMLHttpRequest();
} else {
http = new ActiveXObject("Microsoft.XMLHTTP");
}
if (http){
http.open("POST","./config/AjaxUsernameEmail.php",true);
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.onreadystatechange = function(){
if (http.readyState==4 && http.status==200){
}
};
http.send("r_username=" + document.getElementById("r_username").value);
}
error.innerHTML = "";
error.style.display = "none";
} else {
error.innerHTML = "Invalid Number !!!";
error.style.display = "inline";
}
}
};
ajax working successfully and .php file too which script is below =>
class Checking{
private $con,$query,$flag;
public function __construct($con,$query){
$this->con = $con;
$this->query = $query;
}
public function func(){
if (mysqli_connect_errno()==0){
if ($result = mysqli_query($this->con,$this->query)){
if ($data = mysqli_fetch_assoc($result)){
return $this->flag = true;
} else {
return $this->flag = false;
}
}
}
}
}
if (isset($_POST['r_username'])){
$check = new Checking($connection,"SELECT username FROM users WHERE username='" . $_POST['r_username'] . "'");
} else {
header("Location: http://" . $mysql->host . "/index.php");
}
everything is working just fine , but here is the problem , i want to connect somehow this files , I mean that I want to know in .js file when username is matching in database and when not , because I want to do more action in .js file , but I can not set "flag" (variable which will help me for that).
Any ideas ? thanks :)))
In more details , .js file is in registration.php file , and how you can see guys .js file is invoking with ajax AjaxUsernameEmail.php file, so I want to do somehow to know when username is matching and when not , because I want in registration.php file to do more actions (notifications) during matching
The code could be a bit more like so:
$return = 'fail';
class Checking {
public function __construct($con, $query)
{
$this->con = $con;
$this->query = $query;
self::func()
}
public function func()
{
$result = 'ok';
if (mysqli_connect_errno()==0){
if ($result = mysqli_query($this->con,$this->query)){
$result = mysqli_num_rows($result) > 0? 'user_exists' : 'user_doesnt_exist';
}
}
return $result;
}
}
if( $_POST['r_username'] ){
$desired = mysqli_real_escape_string($_POST['r_username']);
$return = new Checking($connection,"SELECT username FROM users WHERE username='$desired'");
}
echo $return;
Also, you should be worried about escaping user input, and may want to look into jQuery for your ajax stuff.
The checking on the client side, should go something like this:
if (http.readyState==4 && http.status==200){
switch (http.responseText){
case 'fail':
//the username was not provided
break;
case 'user_exists':
//the username already exists
break;
case 'user_doesnt_exist':
//the username was not found on the database, continue
break;
}
}
For ajax request you must not return the value but print or echo it. Try
if ($data = mysqli_fetch_assoc($result)){
echo $this->flag = true; exit;
} else {
echo $this->flag = false; exit;
}
Evaluationg response:
if ( http.readyState == 4 && http.status == 200 ) {
switch ( http.responseText ) {
case 1: //user name taken, diplay error message
break;
case 0: //user name available, no action required
break;
}
}

Categories