I have been following this tutorial Tutorial and i managed to create the rest api with slim.
here is my .htaccess
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ %{ENV:BASE}index.php [QSA,L]
just as in the example and then when i go to my index.php
http://localhost/thefaith/v1/user/register
i get a an error
404 Page Not Found
The page you are looking for could not be found. Check the address bar to ensure your URL is spelled correctly. If all else fails, you can visit our home page at the link below.
but all my files are well arranged
plus below is my index.php which is in the v1 folder
<?php
include_once '../Includes/account_db_handler.php';
require '.././libs/Slim/Slim.php';
\Slim\Slim::registerAutoloader();
$app = new \Slim\Slim();
// User register
$app->post('/user/register', function() use ($app) {
// check for required params
//verifyRequiredParams(array('name', 'email'));
$response = array();
// reading post params
//$name = $app->request->post('name');
//$email = $app->request->post('email');
// validating email address
//validateEmail($email);
//$db = new AcoountDbHandler();
//$response = $db->createUser($name, $email);
$response["message"] = "You are successfully registered";
// echo json response
echoRespnse(201, $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\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();
}
}
function echoRespnse($status_code, $response) {
$app = \Slim\Slim::getInstance();
// Http response code
$app->status($status_code);
// setting response content type to json
$app->contentType('application/json');
echo json_encode($response);
}
/**
* Validating email address
*/
function validateEmail($email) {
$app = \Slim\Slim::getInstance();
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$response["error"] = true;
$response["message"] = 'Email address is not valid';
echoRespnse(400, $response);
$app->stop();
}
}
$app->run();
?>
am still new using slim, need some help on how to solve this
Related
I want to use Authorize.Net for payment but got stuck in middle.
There is not any Error message,
I am using SANDBOX for authCaptureTransaction,
First I have created token with amount , return url.
$response = $controller->executeWithApiResponse(\net\authorize\api\constants\ANetEnvironment::SANDBOX);
after generating token, I add it into form and post to
http://test.authorize.net/payment/payment
it redirects to payment, but after success/cancel it returns to url with empty response.
Please refer my below code.
//function for generating coupon
function getAnAcceptPaymentPage($amount)
{
/* Create a merchantAuthenticationType object with authentication details
retrieved from the constants file */
$merchantAuthentication = new \net\authorize\api\contract\v1\MerchantAuthenticationType();
$merchantAuthentication->setName(Yii::$app->params['authLoginName']);
$merchantAuthentication->setTransactionKey(Yii::$app->params['authTransId']);
// Set the transaction's refId
$refId = 'ref' . time();
//create a transaction
$transactionRequestType = new \net\authorize\api\contract\v1\TransactionRequestType();//AnetAPI\TransactionRequestType();
$transactionRequestType->setTransactionType("authCaptureTransaction");
$transactionRequestType->setAmount($amount);
// Set Hosted Form options
$setting1 = new \net\authorize\api\contract\v1\SettingType();//AnetAPI\SettingType();
$setting1->setSettingName("hostedPaymentButtonOptions");
$setting1->setSettingValue("{\"text\": \"Pay\"}");
$setting2 = new \net\authorize\api\contract\v1\SettingType();//AnetAPI\SettingType();
$setting2->setSettingName("hostedPaymentOrderOptions");
$setting2->setSettingValue("{\"show\": true}");
$setting3 = new \net\authorize\api\contract\v1\SettingType();//AnetAPI\SettingType();
$setting3->setSettingName("hostedPaymentReturnOptions");
$returnUrlSuccess = helpers\Url::to('site/receipt', TRUE);
$returnUrlCancel = helpers\Url::to('site/cancel', TRUE);
$setting3->setSettingValue("{\"url\": \"".$returnUrlSuccess."\", \"cancelUrl\": \"".$returnUrlCancel."\", \"showReceipt\": true}");
// Build transaction request
$request = new \net\authorize\api\contract\v1\GetHostedPaymentPageRequest();//AnetAPI\Get HostedPaymentPageRequest();
$request->setMerchantAuthentication($merchantAuthentication);
$request->setRefId($refId);
$request->setTransactionRequest($transactionRequestType);
$request->addToHostedPaymentSettings($setting1);
$request->addToHostedPaymentSettings($setting2);
$request->addToHostedPaymentSettings($setting3);
//execute request
$controller = new \net\authorize\api\controller\GetHostedPaymentPageController($request);//AnetController\GetHostedPaymentPageController($request);
$response = $controller->executeWithApiResponse(\net\authorize\api\constants\ANetEnvironment::SANDBOX);
if (($response != null) && ($response->getMessages()->getResultCode() == "Ok")) {
echo $response->getToken();
} else {
echo "ERROR : Failed to get hosted payment page token\n";
$errorMessages = $response->getMessages()->getMessage();
echo "RESPONSE : " . $errorMessages[0]->getCode() . " " .$errorMessages[0]->getText() . "\n";die;
}
return $response;
}
//main function
public function actionPayment()
{
$token = $this->getAnAcceptPaymentPage($pack->package_cost);
$token = $token->getToken(); //Generating token successfully
return $this->render('/package/payform', [
'pack' => $pack, 'token' =>$token, 'userDetails' => $user, 'url'=>$url,
]);
}
//form where i put token
//payform.php
{
<form target="payframe" id="send_hptoken" action="http://test.authorize.net/payment/payment" method="post">
<input type="hidden" name="token" value="<?php echo $token;?>">
<input type="submit" value="Get Accept Hosted page"/>
</form>
}
//return success function
public function actionReceipt()
{
//receiving email of payment received but no response here
//empty response;
//tried $_POST, $_GET, $_REQUEST
print_r($_POST);
die;
}
//return cancel function
public function actionCancel()
{
//empty response;
//tried $_POST, $_GET, $_REQUEST
print_r($_POST);
die;
}
Please let me know what am I missing here.
I'm trying to build a simple project in which the google plus profile data will be saved or will get updated into the database. I'm unable to figure the way out of invalid character URI problem. I'm getting invalid character URI as response from google.
How can I solve this problem of invalid URI?
I have attached the image of the error at the end of this post.
Login Controller class code is:
public function index() {
// Include the google api php libraries
include_once APPPATH."libraries/google-api-php-client/Google_Client.php";
include_once APPPATH."libraries/google-api-php-client/contrib/Google_Oauth2Service.php";
// Google Project API Credentials
$clientId = 'My Client ID';
$clientSecret = 'My Secret here';
$redirectUrl = 'https://example.com/index.php?login/index/';
// Google Client Configuration
$gClient = new Google_Client();
$gClient->setApplicationName('Login to Application');
$gClient->setClientId($clientId);
$gClient->setClientSecret($clientSecret);
$gClient->setRedirectUri($redirectUrl);
$google_oauthV2 = new Google_Oauth2Service($gClient);
if (isset($_REQUEST['code'])) {
$gClient->authenticate();
$this->session->set_userdata('token', $gClient->getAccessToken());
redirect($redirectUrl);
}
$token = $this->session->userdata('token');
if (!empty($token)) {
$gClient->setAccessToken($token);
}
if ($gClient->getAccessToken()) {
$userProfile = $google_oauthV2->userinfo->get();
// Preparing data for database insertion
$userData['oauth_provider'] = 'google';
$userData['oauth_uid'] = $userProfile['id'];
$userData['first_name'] = $userProfile['given_name'];
$userData['last_name'] = $userProfile['family_name'];
$userData['email'] = $userProfile['email'];
$userData['gender'] = $userProfile['gender'];
$userData['locale'] = $userProfile['locale'];
$userData['profile_url'] = $userProfile['link'];
$userData['picture_url'] = $userProfile['picture'];
// Insert or update user data
$userID = $this->user->checkUser($userData);
if(!empty($userID)){
$data['userData'] = $userData;
$this->session->set_userdata('userData',$userData);
} else {
$data['userData'] = array();
}
} else {
$data['authUrl'] = $gClient->createAuthUrl();
}
$this->load->view('backend/login',$data);
}
The image of the error :
I am unable to tackle the problem. Please suggest me how can I avoid this.
I have been using Slim v2 for my APIs and am thinking about upgrading to v3.
Unfortunately I have limited experience and could use your help on a code example below.
This is the login code:
$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);
});
Here is the validateEmail function:
function validateEmail($email) {
$app = \Slim\Slim::getInstance();
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$response["error"] = true;
$response["message"] = 'Email address is not valid';
echoRespnse(400, $response);
$app->stop();
}
}
How do I get an Instance of app in Slim v3 to actually stop the app when input criteria are not met?
I would appreciate it if you could give me an example with the help of my code.
Thanks for the help!
EDIT
The above issue was solved. Unfortunately, a new issue arose after checking my code.
I have a middle layer to authenticate the user:
function authenticate(\Slim\Route $route) {
// Getting request headers
$headers = apache_request_headers();
$response = array();
$app = \Slim\Slim::getInstance();
// Verifying Authorization Header
if (isset($headers['Authorization'])) {
//omitted code
} else {
// api key is missing in header
$response["error"] = true;
$response["message"] = "Api key is misssing";
echoRespnse(400, $response);
$app->stop();
}
In my main code i implement function authenticate as follows:
$app->get('/tasks', 'authenticate', function() {
global $user_id;
$response = array();
$db = new DbHandler();
//ommit some code
echoRespnse(200, $response);
});
Would you know how to do this in Slim v3?
I would really appreciate your help.
In Slim3, return $response (return Response object) is a better way to stop app.
So how is the below?
$app->post('/register', function($request, $response, $args) {
// omit some codes
if(!validateEmail($request->getParsedBodyParam('email'))){
return $response->withJson(['message' => 'Email address is not valid', 'error' => true], 400);
}
// omit some codes
}
validateEmail function is changed to like below.
function validateEmail($email) {
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
return false
}
return true;
}
Hope it will help you.
This question already has answers here:
Call to undefined function apache_request_headers()
(6 answers)
Closed 5 years ago.
I'm only posting this because none of the other posts have helped solve my problem. I'm using slim and advanced rest api app on chrome for testing. I've tried many suggestions on the web but nothing is working. I'm running php 5.5 on hostgator. I am getting the error when passing authorization header:
call to undefined function apache_request_headers()
<?php
require_once '../include/DbHandler.php';
require_once '../include/PassHash.php';
require '.././libs/Slim/Slim.php';
\Slim\Slim::registerAutoloader();
$app = new \Slim\Slim();
// User id from db - Global Variable
$user_id = NULL;
function authenticate(\Slim\Route $route) {
// Getting request headers
$headers = apache_request_headers();
$response = array();
$app = \Slim\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);
//echoRespnse(400, $headers);
$app->stop();
}
}
.htaccess
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ %{ENV:BASE}index.php [QSA,L]
SetEnvIf Authorization "(.*)" HTTP_AUTHORIZATION=$1
Updating, this seems to take care of the the header problem
if (!function_exists('apache_request_headers')) {
function apache_request_headers() {
foreach($_SERVER as $key=>$value) {
if (substr($key,0,5)=="HTTP_") {
$key=str_replace(" ","-",ucwords(strtolower(str_replace("_"," ",substr($key,5)))));
$out[$key]=$value;
}else{
$out[$key]=$value;
}
}
return $out;
}
}
PHP 5.4.0 and later supports apache_request_headers(). But there are other solutions like the code below which comes from: http://php.net/manual/en/function.apache-request-headers.php
function apache_request_headers() {
$arh = array();
$rx_http = '/\AHTTP_/';
foreach($_SERVER as $key => $val) {
if( preg_match($rx_http, $key) ) {
$arh_key = preg_replace($rx_http, '', $key);
$rx_matches = array();
// do some nasty string manipulations to restore the original letter case
// this should work in most cases
$rx_matches = explode('_', $arh_key);
if( count($rx_matches) > 0 and strlen($arh_key) > 2 ) {
foreach($rx_matches as $ak_key => $ak_val) $rx_matches[$ak_key] = ucfirst($ak_val);
$arh_key = implode('-', $rx_matches);
}
$arh[$arh_key] = $val;
}
}
return( $arh );
}
I got some problem with php-sample.
I want to add users, but there were something went wrong.
Please help me!!
Here is code that I used:
<!DOCTYPE html>
<?php
require_once "vendor/autoload.php";
require_once "autoload.dist.php";
require_once "client/JasperClient.php";
require_once "client/User.php";
require_once "client/Role.php";
$client = new Jasper\JasperClient(
"localhost", // Hostname
8080, // Port
"jasperadmin", // Username
"jasperadmin", // Password
"/jasperserver-pro", // Base URL
"organization_1"
); // Organization (pro only)
$newUser = new Jasper\User("BI_User", // username
"superSTRENGTHpassw0rd", // password
"clever#email.com", // email
"Business Intelligence User", // description
"organization_1", // parent organization
"true" // enabled
);
$role = new Jasper\Role("ROLE_USER", NULL, "false");
$newUser->addRole($role);
try {
$client->putUsers($newUser);
}
catch (Exception $e) {
printf("Could not add new user: %s", $e->getMessage());
}?>
And Here is the error message that I got:
Could not add new user: Unexpected HTTP code returned: 400 Body of response:
Apache Tomcat/6.0.26 - Error report HTTP Status 400 - type Status
reportmessage description The request sent by the client was syntactically
incorrect ().Apache Tomcat/6.0.26
Ask I spent time google so much on that problem, I have found the solution.
Here is my solution whether someone are interested.
<?php
require_once "vendor/autoload.php";
require_once "autoload.dist.php";
use Jaspersoft\Client\Client;
use Jaspersoft\Dto\User\User;
use Jaspersoft\Dto\Role\Role;
function registerUsers(){
$client = new Client(
"localhost",
"8080",
"superuser",
"superuser",
"/jasperserver-pro",
"null"
);
$file_path = 'data/userlist.csv';
$handle = fopen($file_path,'r');
$array_users = array();
$i=0;
while (!feof($handle) !==false){
$line = fgetcsv($handle,1024,',');
$i++;
if($i==1) continue;
if(!empty($line)){
for($c = 0; $c < count($line); $c++){
$username = $line[0];
$password = $line[1];
$email = $line[2];
$fullname = $line[3];
$tenantId = $line[4];
$enabled = $line[5];
$user = new User($username, $password, $email,
$fullname, $tenantId, $enabled);
$role = new Role('ROLE_USER', null, 'false');
$array_users[$c] = $user;
$array_users[$c]->addRole($role);
try {
$client->userService()->addUsers($array_users[$c]);
} catch (Exception $e) {
printf('Could not add new user: %s', $e->getMessage());
}
}
}
}
}?>
And here is my csv data file:
User Name,Password,Email Address,Full Name,Tenant ID,Enable
User1,superSTRENGTHpassw0rd,clever#email.com,User One,a,true
User2,superSTRENGTHpassw0rd,clever#email.com,User One,a,true
User3,superSTRENGTHpassw0rd,clever#email.com,User One,a,true
User6,superSTRENGTHpassw0rd,clever#email.com,User One,organization_1,true
User7,superSTRENGTHpassw0rd,clever#email.com,User One,organization_1,true
User8,superSTRENGTHpassw0rd,clever#email.com,User One,b,true
User9,superSTRENGTHpassw0rd,clever#email.com,User One,b,true
User10,superSTRENGTHpassw0rd,clever#email.com,User One,c,true
User11,superSTRENGTHpassw0rd,clever#email.com,User One,c,true