Stripe set the amount as $variable - javascript

I am working with stripe payment and I am trying to set the amount to a variable. I see there's a lot of questions in regards to this out there, but I haven't been able to find he answer.
On the top of the page I query my database for the a number and do some basic math to set the amount. I echo the cost just to make sure it's working and it is. Here's the code for that
require_once('../stripe/lib/Stripe.php');
require_once("../auth/config.class.php");
require_once("../auth/auth.class.php");
$config = new Config;
$dbh = new PDO("mysql:host={$config->dbhost};dbname={$config->dbname}", $config->dbuser, $config->dbpass);
$auth = new Auth($dbh, $config);
$id= $_GET['rid'];
$query = $dbh->prepare("SELECT hours FROM svcrequest WHERE id=? ");
$query->execute(array($id));
$rslt = $query->fetch(PDO::FETCH_ASSOC);
$cost = ($rslt[hours] * 27)*100;
echo $cost;
I then try to assign the cost to another variable amount inside some if statement and exception and I try to echo the amount but I get nothing.
// Set the order amount somehow:
$amount = $cost; // in cents
echo $amount;
$email = "info#intelycare.com";
$description = "Jane Doe"; //customer
When I echo $amount nothing shows. Here the full code for the page. I could use some help with this.
<?php
// Created by Larry Ullman, www.larryullman.com, #LarryUllman
// Posted as part of the series "Processing Payments with Stripe"
// http://www.larryullman.com / series / processing - payments - with - stripe /
// Last updated February 20, 2013
// The class names are based upon Twitter Bootstrap (http://twitter.github.com / bootstrap / )
// This page is used to make a purchase.
// Every page needs the configuration file:
// Uses sessions to test for duplicate submissions:
session_start();
?><!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>
IntelyCare
</title>
<script type="text/javascript" src="https://js.stripe.com/v2/"> </script>
<script src="http://code.jquery.com/jquery-1.11.1.min.js"> </script>
<script src="http://code.jquery.com/mobile/1.4.3/jquery.mobile-1.4.3.min.js"> </script>
</head>
<body>
<?php
require_once('../stripe/lib/Stripe.php');
require_once("../auth/config.class.php");
require_once("../auth/auth.class.php");
$config = new Config;
$dbh = new PDO("mysql:host={$config->dbhost};dbname={$config->dbname}", $config->dbuser, $config->dbpass);
$auth = new Auth($dbh, $config);
$id= $_GET['rid'];
$query = $dbh->prepare("SELECT hours FROM svcrequest WHERE id=? ");
$query->execute(array($id));
$rslt = $query->fetch(PDO::FETCH_ASSOC);
$cost = ($rslt[hours] * 27)*100;
echo $cost;
// Set the Stripe key:
// Uses STRIPE_PUBLIC_KEY from the config file.
echo '<script type="text/javascript">Stripe.setPublishableKey("' . STRIPE_PUBLIC_KEY . '");</script>';
// 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.';
}
// Set the order amount somehow:
$amount = $cost; // in cents
echo $amount;
$email = "info#intelycare.com";
$description = "Jane Doe"; //customer
// Validate other form data!
// If no errors, process the order:
if(empty($errors))
{
// create the charge on Stripe's servers - this will charge the user's card
try
{
// Include the Stripe library:
// set your secret key: remember to change this to your live secret key in production
// see your keys here https://manage.stripe.com / account
Stripe::setApiKey(STRIPE_PRIVATE_KEY);
// Charge the order:
// Create a Customer
$customer = Stripe_Customer::create(array(
"card" => $token,
"description"=> $description
)
);
// Charge the Customer instead of the card
Stripe_Charge::create(array(
"amount" => $amount ,# amount in cents, again
"currency"=> "usd",
"customer"=> $customer->id
)
);
// Save the customer ID in your database so you can use it later
//saveStripeCustomerId($user, $customer->id);
// Later...
//$customerId = getStripeCustomerId($user);
$charge = Stripe_Charge::create(array(
"amount" => $amount,// amount in cents, again
"currency"=> "usd",
"customer"=> $customer
)
);
// Check that it was paid:
if($charge->paid == true)
{
// Store the order in the database.
// Send the email.
// Celebrate!
}
else
{
// Charge was not paid!
echo '<div class="alert alert-error"><h4>Payment System Error!</h4>Your payment could NOT be processed (i.e., you have not been charged) because the payment system rejected the transaction. You can try again or use another card.</div>';
}
} catch(Stripe_CardError $e)
{
// Card was declined.
$e_json = $e->getJsonBody();
$err = $e_json['error'];
$errors['stripe'] = $err['message'];
} catch(Stripe_ApiConnectionError $e)
{
// Network problem, perhaps try again.
} catch(Stripe_InvalidRequestError $e)
{
// You screwed up in your programming. Shouldn't happen!
} catch(Stripe_ApiError $e)
{
// Stripe's servers are down!
} catch(Stripe_CardError $e)
{
// Something else that's not the customer's fault.
}
} // A user form submission error occurred, handled below.
} // Form submission.
?>
<h1>
IntelyCare
</h1>
<form action="buy.php" method="POST" id="payment-form">
<?php // Show PHP errors, if they exist:
if(isset($errors) && !empty($errors) && is_array($errors))
{
echo '<div class="alert alert-error"><h4>Error!</h4>The following error(s) occurred:<ul>';
foreach($errors as $e)
{
echo "<li>$e</li>";
}
echo '</ul></div>';
}?>
<div id="payment-errors">
</div>
<span class="help-block">
Form of Payment accepted: Mastercard, Visa, American Express, JCB, Discover, and Diners Club.
</span>
<br />
<input type="text" name="clientid" value="<?php if(isset($_GET['rid'])) {echo $_GET['rid']; } ?>" >
<br />
<label> Card Number </label>
<input type="text" size="20" autocomplete="off" class="card-number input-medium">
<span class="help-block"> Enter the number without spaces or hyphens. </span>
<label> CVC </label>
<input type="text" size="4" autocomplete="off" class="card-cvc input-mini">
<label> Expiration (MM/YYYY) </label>
<input type="text" size="2" class="card-expiry-month input-mini">
<span> / </span>
<input type="text" size="4" class="card-expiry-year input-mini">
<button type="submit" class="btn" id="submitBtn">
Submit Payment
</button>
</form>
<script src="../stripe/buy.js">
</script>
</body>
</html>

I reached out to Stripe and they gave me couple recommendations, here's a solution to the problem hopefully it benefits someone else. I am able to pass a variable amount for stripe payment. Below is my charge.php file, I am not handling errors yet but I will include it later.
<?php
require_once(dirname(__FILE__) . '/config.php');
require_once("../auth/config.class.php");
require_once("../auth/auth.class.php");
$config = new Config;
$dbh = new PDO("mysql:host={$config->dbhost};dbname={$config->dbname}", $config->dbuser, $config->dbpass);
$auth = new Auth($dbh, $config);
$id= $_GET['rid'];
$query = $dbh->prepare("SELECT hours, cid FROM svcrequest WHERE id=? ");
$query->execute(array($id));
$rslt = $query->fetch(PDO::FETCH_ASSOC);
$cost = ($rslt['hours'] * 23)*100;
echo $cost;
$cid = $rslt['cid'];
$query = $dbh->prepare("SELECT email, fname, lname FROM client JOIN users ON client.uid = users.id WHERE uid =(SELECT uid FROM client WHERE id=?)");
$query->execute(array($cid));
$user =$query->fetch(PDO::FETCH_ASSOC);
$email = ($user['email']);
echo $email;
$token = $_POST['stripeToken'];
$customer = Stripe_Customer::create(array(
'email' => $email,
'card' => $token
));
$charge = Stripe_Charge::create(array(
'customer' => $customer->id,
'amount' => $cost,
'currency' => 'usd'
));
echo '<h3>Charge today:</h3>' . $cost;
?>

Related

Why my password_verify does not work on login?

I am learning to create a simple signup and login page which using password_hash and password_verify function.
The sign up page is working fine, and the password_hash are able to encrypt my password in the mysql database. As photo below.
Only thing that is not working is that I cannot make the login to work, its always return to error message saying that the password is invalid. I am not using the hashed password, i am using the password that I entered during sign-up (which is just 123).
Below is my code:
Login Form:
<div class="InnerDiv">
<form method="post" action="">
<div class="form-group">
<label for="exampleInputEmail1">Email</label>
<input name="email" type="email" value="<?php echo #$_POST['email']; ?>" class="form-control input-fields" id="exampleInputEmail1" aria-describedby="emailHelp" placeholder="Enter email" required="true">
</div>
<div class="form-group">
<label for="exampleInputPassword1">Password</label>
<input name="password" type="password" class="form-control input-fields" id="exampleInputPassword1" placeholder="Password" required="true">
</div>
<center>
<button name="submit2" type="submit" class="btn btn-primary btn-login-form">Login</button>
<p data-toggle="modal" data-target="#forgotpassdialog" class="forgot-para">Forgot Password?
</p>
</center>
</form>
</div>
Verify login credentials
<?php
if (isset($_GET['msg'])) {
$var=$_GET['msg'];
echo "<script>alert('$var')</script>";
}
if(isset($_POST['submit2'])){
$email = $_POST["email"];
$password = $_POST["password"];
$data = mysqli_query($sql_con,"select *from students where stdemail = '$email' AND password='$password'");
$datarow = mysqli_num_rows($data);
if ($datarow > 0) {
if (password_verify($email, $password)) {
$row = mysqli_fetch_array($data);
$value3 = $row['id'];
$_SESSION['sid'] = $value3;
echo "<script>window.location='/students/dashboard.php'</script>";
}
}
else{
echo "<script>alert('Invalid password')</script>";
}
}
?>
Any help would be appreciated, let me know if more details is needed.
EDITED: I have tried to substitute the $email with the hashpassword value in the password_verify, but still return invalid message.
<?php
if (isset($_GET['msg'])) {
$var=$_GET['msg'];
echo "<script>alert('$var')</script>";
}
if(isset($_POST['submit2'])){
$email = $_POST["email"];
$password = $_POST["password"];
$data = mysqli_query($sql_con,"select *from students where stdemail = '$email' AND password='$passwordDB'");
$datarow = mysqli_num_rows($data);
if ($datarow > 0) {
if (password_verify($password, $passwordDB)) {
$row = mysqli_fetch_array($data);
$value3 = $row['id'];
$_SESSION['sid'] = $value3;
echo "<script>window.location='/students/dashboard.php'</script>";
}
}
else{
echo "<script>alert('Invalid password')</script>";
}
}
?>
You can't just make up some extra variables and slap them in the code. Your new version is no better than the previous one because you're selecting on a password variable that isn't initialised, and you're not retrieving the hashed password for PHP to check.
There's also the issue of possible SQL injection to address.
So, here's a rewritten version of your code, with some key changes:
Mysqli is set to throw an exception if there's an error.
I've used the OOP structure of MySQLi because it's less verbose and easier to follow
I've restructured your query to used a prepared statement, thus avoiding SQL injection problems
I've reworked your query to retrieve the student ID and hashed password. No other data is required in this code.
the code correctly verifies the user-supplied password against the hashed version retrieved from the database
session_start();
// Set MySQLi to throw an exception if it detects an error
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
try {
$sql_con = new mysqli('server', 'usernane', 'userpass', 'database');
if (isset($_POST['submit2'])) {
$email = $_POST["email"];
$password = $_POST["password"];
// set up query to retrieve id and hashed password
$query = "select id, password from students where stdemail = ?";
// Prepare query & bind parameters, execute
$stmt = $sql_con->prepare($query);
$stmt->bind_param('s', $email);
$stmt->execute();
// Bind variable to accept the result
$stmt->bind_result($id, $hashedPassword);
// fetch result. There should only be one, so no loop required.
$data = $stmt->fetch();
// Check we retrieved some data, and if so, check the password.
if ($data && password_verify($password, $hashedPassword)) {
$_SESSION['sid'] = $id;
echo "<script>window.location='/students/dashboard.php'</script>";
} else {
echo "<script>alert('Invalid credentials')</script>";
}
}
} catch(Exception $e) {
echo $e->getMessage();
}
I have run this code on my server - it works. If you have problems check your server connection, and ensure that the passwords in your database have been correctly hashed with password_hash().
Note: for this example the exception handler just displays the exception message. Your live code should not do that, but should handle the exception appropriately.

Error on the login process (Invalid Request) (POST variables were not sent to this page)

I´m always getting "Invalid request" because of the "POST variables were not sent to this page". I already chech the javascript on the console and it was fine. And i read eveithing about this problem, maybe the problem is not the code. Can somebody please help me?
This is my index.php (login page)
<?php
include_once 'db_connect.php';
include_once 'functions.php';
sec_session_start();
if (login_check($mysqli) == true) {
$logged = 'in';
} else {
$logged = 'out';
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Secure Login: Log In</title>
<link rel="stylesheet" href="styles/main.css" />
<script type="text/JavaScript" src="js/sha512.js"></script>
<script type="text/JavaScript" src="js/forms.js"></script>
</head>
<body>
<?php
if (isset($_GET['error'])) {
echo '<p class="error">Error Logging In!</p>';
}
?>
<form action="process_login.php" method="POST" name="login_form">
Email: <input type="text" name="email" />
Password: <input type="password"
name="password"
id="password"/>
<input type="button"
value="Login"
onclick="formhash(this.form,this.form.password);"
/>
</form>
<?php
if (login_check($mysqli) == true) {
echo '<p>Currently logged ' . $logged . ' as ' .
htmlentities($_SESSION['username']) . '.</p>';
echo '<p>Do you want to change user? Log out.</p>';
} else {
echo '<p>Currently logged ' . $logged . '.</p>';
echo "<p>If you don't have a login, please <a
href='register.php'>register</a></p>";
}
?>
</body>
</html>
And this is my login_process:
<?php
include_once 'db_connect.php';
include_once 'functions.php';
sec_session_start(); // Our custom secure way of starting a PHP session.
if (isset($_POST['email'], $_POST['p'])) {
$email = $_POST['email'];
$password = $_POST['p']; // The hashed password.
if (login($email, $password, $mysqli) == true) {
// Login success
header('Location: protected_page.php');
} else {
// Login failed
header('Location: ../index.php?error=1');
}
} else {
// The correct POST variables were not sent to this page.
echo 'invalid Request';
}
And the form that seems to be working:
function formhash(form, password) {
// Create a new element input, this will be our hashed password field.
var p = document.createElement("input");
// Add the new element to our form.
document.body.appendChild(p);
p.name = "p";
p.type = "hidden";
p.value = hex_sha512(password.value);
// Make sure the plaintext password doesn't get sent.
password.value = "";
// Finally submit the form.
form.submit();
}
And the functions:
function login($email, $password, $mysqli) {
// Using prepared statements means that SQL injection is not possible.
if ($stmt = $mysqli->prepare("SELECT id, username, password
FROM users
WHERE email = ?
LIMIT 1")) {
$stmt->bind_param('s', $email); // Bind "$email" to parameter.
$stmt->execute(); // Execute the prepared query.
$stmt->store_result();
// get variables from result.
$stmt->bind_result($user_id, $username, $db_password);
$stmt->fetch();
if ($stmt->num_rows == 1) {
// If the user exists we check if the account is locked
// from too many login attempts
if (checkbrute($user_id, $mysqli) == true) {
// Account is locked
// Send an email to user saying their account is locked
return false;
} else {
// Check if the password in the database matches
// the password the user submitted. We are using
// the password_verify function to avoid timing attacks.
if (password_verify($password, $db_password)) {
// Password is correct!
// Get the user-agent string of the user.
$user_browser = $_SERVER['HTTP_USER_AGENT'];
// XSS protection as we might print this value
$user_id = preg_replace("/[^0-9]+/", "", $user_id);
$_SESSION['user_id'] = $user_id;
// XSS protection as we might print this value
$username = preg_replace("/[^a-zA-Z0-9_\-]+/",
"",
$username);
$_SESSION['username'] = $username;
$_SESSION['login_string'] = hash('sha512',
$db_password . $user_browser);
// Login successful.
return true;
} else {
// Password is not correct
// We record this attempt in the database
$now = time();
$mysqli->query("INSERT INTO login_attempts(user_id, time)
VALUES ('$user_id', '$now')");
return false;
}
}
} else {
// No user exists.
return false;
}
}
}
Thank you for your time.

PHP login script doesn't work in IE8 or IE9

I have a site using a PHP script to login the user. It works fine in most browsers, but IE8 and IE9 seem to be having trouble with the cookies. I've read a bunch of similar posts, but so far nothing seems to help. Any ideas as to where the problem is here? Details are code are below.
We are using this code for our login script: http://www.wikihow.com/Create-a-Secure-Login-Script-in-PHP-and-MySQL
Login Form
<?php
if($error == 1) echo "<p class=\"error\">Your Log in information is incorrect</p>";
?>
<form class="form-horizontal" role="form" action="includes/process_login.php" method="post" name="login_form">
<div class="form-group">
<!-- <label for="inputEmail1" class="col-md-2 control-label">Email</label> -->
<div class="col-md-12">
<input type="email" class="form-control" id="inputEmail1" name="inputEmail1">
</div>
</div>
<div class="form-group">
<!-- <label for="inputPass1" class="col-md-2 control-label">Password</label> -->
<div class="col-md-12">
<input type="password" class="form-control" id="inputPass1" name="inputPass1">
</div>
</div>
</div>
</div>
</div>
</div>
<div id="login-content">
<div class="form-group">
<button type="submit" class="btn btn-default signin-btn" onclick="formhash(this.form, this.form.inputPass1);">Sign In</button>
</div>
</form>
Process Login Page
<?php
header('P3P: CP="NOI ADM DEV COM NAV OUR STP"');
include_once 'db_connect.php';
include_once 'functions.php';
sec_session_start(); // Our custom secure way of starting a PHP session.
if (isset($_POST['inputEmail1'], $_POST['p'])) {
$email = $_POST['inputEmail1'];
$password = $_POST['p']; // The hashed password.
exit($email);
if (login($email, $password, $mysqli) == true) {
// Login success
header('Location: ../index.php');
} else {
// Login failed
header('Location: ../index.php?error=1');
}
} else {
// The correct POST variables were not sent to this page.
echo 'Invalid Request';
}
Login Function
//checks login info against db
function login($email, $password, $mysqli) {
// Using prepared statements means that SQL injection is not possible.
if ($stmt = $mysqli->prepare("SELECT id, fname, lname, pass, salt, type_id
FROM users
WHERE email = ?
LIMIT 1")) {
$stmt->bind_param('s', $email); // Bind "$email" to parameter.
$stmt->execute(); // Execute the prepared query.
$stmt->store_result();
// get variables from result.
$stmt->bind_result($user_id, $fname, $lname, $db_password, $salt, $user_type);
$stmt->fetch();
// hash the password with the unique salt.
$password = hash('sha512', $password . $salt);
if ($stmt->num_rows == 1) {
// If the user exists we check if the account is locked
// from too many login attempts
if (checkbrute($user_id, $mysqli) == true) {
// Account is locked
// Send an email to user saying their account is locked
return false;
} else {
// Check if the password in the database matches
// the password the user submitted.
if ($db_password == $password) {
// Password is correct!
// Get the user-agent string of the user.
$user_browser = $_SERVER['HTTP_USER_AGENT'];
// XSS protection as we might print this value
$user_id = preg_replace("/[^0-9]+/", "", $user_id);
$user_type = preg_replace("/[^0-9]+/", "", $user_type);
$_SESSION['user_id'] = $user_id;
$_SESSION['user_type'] = $user_type;
// XSS protection as we might print this value
$username = preg_replace("/[^a-zA-Z0-9_\-]+/",
"",
$fname . $lname);
$_SESSION['username'] = $username;
$_SESSION['login_string'] = hash('sha512',
$password . $user_browser);
// Login successful.
return true;
} else {
// Password is not correct
// We record this attempt in the database
$now = time();
$mysqli->query("INSERT INTO login_attempts(user_id, time)
VALUES ('$user_id', '$now')");
return false;
}
}
} else {
// No user exists.
return false;
}
}
}
The answer was in the javascript. Basically IE8 does not allow changing the 'type' of a field and there was a javascript function that hashed the password and then put the value in a new field where it set the type to hidden. I just made the field already set to hidden and then it worked.

Dynamic Payments with Stripe

I"m struggling with Stripe. I'm using PHP and I'm trying to set up a simple store, with no CMS. Wondering how I can pass the amount into charge.php so I can charge different amounts for different products. Here's my code:
$charge = Stripe_Charge::create(array(
'customer' => $customer->id,
'amount' => 1900;,
'currency' => 'gbp'
));
Here's the code from index.php - I would like to charge the customer whatever is in "data-amount" on the form below. Not quite sure how to do so.
<form action="inc/charge.php" method="POST">
<script
src="https://checkout.stripe.com/checkout.js" class="stripe-button"
data-key="<?php echo $stripe['publishable_key']; ?>"
data-amount="1900"
data-currency="GBP"
data-name="Pure - Tumblr Theme"
data-allow-remember-me="false"
data-description="Premium Tumblr Theme"
data-image="/128x128.png">
</script>
</form>
More comprehensive, go from index.php to charge.php rather than the reverse.
<?php
#set your variables
$amount = 500;
$name = 'My Company';
$currency = 'gbp';
$description = 'Value Plan';
$uid = get->your->uid;
$email = get->your->email;
?>
<center><form action="../charge.php" method="post">
<!-- make these hidden input types for the post action to charge.php -->
<input type="hidden" name="amount" value="<?php echo $amount?>">
<input type="hidden" name="name" value="<?php echo $name;?>">
<input type="hidden" name="currency" value="<?php echo $currency;?>">
<input type="hidden" name="description" value="<?php echo $description;?>">
<input type="hidden" name="uid" value="<?php echo $uid;?>">
<input type="hidden" name="email" value="<?php echo $email;?>">
<script src="https://checkout.stripe.com/checkout.js" class="stripe-button"
data-key = "<?php echo $stripe['publishable_key']; ?>"
data-amount = "<?php echo $amount;?>"
data-name = "<?php echo $name;?>"
data-currency = "<?php echo $currency;?>"
data-description = "<?php echo $description;?>"
data-email = "<?php echo $user->data()->email; ?>"
data-billing-address = "true"
data-allow-remember-me = "false"
>
</script>
</form></center>
Then in charge.php you can call the input values you hid in index.php
<?php
$token = $_POST['stripeToken'];
$email = $_POST['email'];
$uid = $_POST['uid'];
$currency = $_POST['currency'];
$amount = $_POST['amount'];
$description = $_POST['description'];
#This is the standard try catch block stripe suggests
try{
$charge = Stripe_Charge::create(array(
"amount" => $amount,
"currency" => $currency,
"customer" => $charge_to,
"description" => $description
));
} catch(Stripe_CardError $e) {
$error = $e->getMessage();
// Since it's a decline, Stripe_CardError will be caught
$body = $e->getJsonBody();
$err = $body['error'];
print('Status is:' . $e->getHttpStatus() . "\n");
print('Type is:' . $err['type'] . "\n");
print('Code is:' . $err['code'] . "\n");
// param is '' in this case
print('Param is:' . $err['param'] . "\n");
print('Message is:' . $err['message'] . "\n");
} catch (Stripe_InvalidRequestError $e) {
// Invalid parameters were supplied to Stripe's API
} catch (Stripe_AuthenticationError $e) {
// Authentication with Stripe's API failed
// (maybe you changed API keys recently)
} catch (Stripe_ApiConnectionError $e) {
// Network communication with Stripe failed
} catch (Stripe_Error $e) {
// Display a very generic error to the user, and maybe send
// yourself an email
} catch (Exception $e) {
// Something else happened, completely unrelated to Stripe
}
?>
Why do you want to charge whatever is in data-amount? Where do you get that value from? data-amount tells Stripe what the user allows you to charge. amount in Stripe_Charge::create is what you actually charge.
You could populate a hidden input field with the same value as data-amount. But i don't know what you would gain by that.
Your PHP skript should calculate the amount to pay. Don't trust the client. He could change the value of data-amount to pay less, i.e. 50.
Using the following the charge would work, but client pays 50 pence instead of 1900.
$charge = Stripe_Charge::create(array(
'customer' => $customer->id,
'amount' => $_POST['hidden_amount']
Ask Stripe for the total calculated payment. If the client has messed with data-amount the charge will fail.
'amount' => $shoppingcart->getTotal();,

Cant get session to store, what am I missing?

So I've got this form where users signs his ass up. When the user filled in all the details, he clicks on the submit button. An Ajax request submits the form and puts all the details in the database. If that has happen without any errors, a hidden div with two (payments) buttons opens up. After clicking on the iDeal or PayPal button, colorbox opens up and show the 'overview-page'. Now I'd like to show the users information from the database via $_SESSION['user_id']. But somehow, I'm not storing the session orso as the 'overview-page' is empty.
I'm not sure what I'm missing, any heads up would be awesome!
This is the form:
<div class="content main container" id="goShowOrderForm">
<div class="content main box">
<div id="udidOrderForm" class="order form">
<form action="post" id="orderForm" name="form">
<label for="email">Email</label>
<input type="email" class="input-fullwidth" name="email">
<div class="two-column">
<label for="password">Password</label>
<input type="password" name="password">
</div>
<div class="two-column right">
<label for="repassword">Confirm Password</label>
<input type="password" name="re_password">
</div>
<input type="hidden" name="token" value="<?php echo $_SESSION['guest_token'] ?>">
</form>
<div class="orderFormActions">
<input type="submit" class="button darkblue order" name="submitNewStep" id="submitNewStep" value="Nu afrekenen">
<div class="button red cancel" id="cancelUdidOrder">Afbreken</div>
</div>
</div>
</div>
Ajax post page (to store data in db after submit)
<?php
include '../includes/database/db_connect.php';
include '../includes/database/functions.php';
if($_POST) {
//Form data
$email = safe($mysqli,$_POST['email']);
$guestToken = safe($mysqli,$_POST['token']);
$password = veilig($mysqli,$_POST['password']);
$rePassword = veilig($mysqli,$_POST['re_password']);
//Check if everything has been filled in correctly
if ($email == '' || $password == '' || $rePassword == '') {
echo "orderFormRequiredFields";
exit();
}
//Check emailFormat
if (!CheckEmailFormat($email)) {
echo "orderFormerrorEmailFormat";
exit();
}
//Check if email already exist
$checkIfEmailExist = mysqli_query($mysqli,"SELECT * FROM members WHERE email = '$email'");
if (mysqli_num_rows($checkIfEmailExist) > 0){
echo "orderFormEmailAlreadyExist";
exit();
}
//Check if the two passwords do match
if ( $password == $rePassword ) {
//Als wachtwoorden overeen komen, maak er een hashed pw + salt van
$salt = bin2hex(mcrypt_create_iv(32, MCRYPT_DEV_URANDOM));
$saltedPW = $password . $salt;
$hashedPW = hash('sha256', $saltedPW);
} else {
echo "orderFormErrorPasswordConfirm";
exit();
}
$tstamp = time();
$token = md5(uniqid(mt_rand()));
//Add user to the database
$createUser = mysqli_query($mysqli,"INSERT INTO members (account_active, email, guest_token, password, salt)
VALUES ('0', '$email', '$guestToken', '$hashedPW', '$salt'); ");
//begin storing user_id
//Check for the users salt
$getSalt = mysqli_query($mysqli,"SELECT salt FROM members WHERE email = '$email';");
if (!$getSalt) {
echo "Error Salt";
exit();
}
$row = mysqli_fetch_assoc($getSalt);
$salt = $row['salt'];
//Find the user details
$saltedPW = $password . $salt;
$hashedPW = hash('sha256', $saltedPW);
$findUser = mysqli_query($mysqli,"SELECT * FROM members WHERE email = '$email' AND password = '$hashedPW'");
$roww = mysqli_fetch_assoc($findUser);
$user_id = $roww['user_id'];
//If users exist, count should be 1
$count = mysqli_num_rows($findUser);
if($count == 1) {
$_SESSION['user_id'] = $user_id;
$_SESSION['email'] = $email;
} else {
echo "Error";
exit();
}
//end
echo "succesMsgOrderForm";
}
?>
This is the basic of the overview page
<?php
include 'includes/database/db_connect.php';
include 'includes/database/functions.php';
sec_session_start();
$user_id = $_SESSION['user_id'];
$getAllDetails = mysqli_query($mysqli,"SELECT * FROM members WHERE user_id = '$user_id' ") OR die (mysqli_error($mysqli));
$row = mysqli_fetch_array($getAllDetails);
$email = $row['email'];
?>
<body>
user_id is: <?php echo $user_id ?> <br>
email is: <?php echo $email ?>
</body>
Thank you,
Edit #1 sec_session_start() part which is in functions.php:
function sec_session_start() {
$session_name = 'sec_session_id'; // Set a custom session name
$secure = SECURE;
// This stops JavaScript being able to access the session id.
$httponly = true;
// Forces sessions to only use cookies.
ini_set('session.use_only_cookies', 1);
// Gets current cookies params.
$cookieParams = session_get_cookie_params();
session_set_cookie_params($cookieParams["lifetime"],
$cookieParams["path"],
$cookieParams["domain"],
$secure,
$httponly);
// Sets the session name to the one set above.
session_name($session_name);
session_start(); // Start the PHP session
session_regenerate_id(); // regenerated the session, delete the old one.
}
Edit #2 - Part where I open up the colorbox (javascript)
$(document).on('click', '#pay_ideal', function(){
$.colorbox({
width: 500,
height: 350,
speed: 350,
closeButton: false,
href:"order-overview.php"
});
});
You need to check session status before refreshing your session lik;
function sec_session_start() {
$session_name = 'sec_session_id'; // Set a custom session name
$secure = SECURE;
// This stops JavaScript being able to access the session id.
$httponly = true;
// Forces sessions to only use cookies.
ini_set('session.use_only_cookies', 1);
// Gets current cookies params.
$cookieParams = session_get_cookie_params();
session_set_cookie_params($cookieParams["lifetime"],
$cookieParams["path"],
$cookieParams["domain"],
$secure,
$httponly);
// Sets the session name to the one set above.
if (session_id() == '') {
session_name($session_name);
session_start(); // Start the PHP session
session_regenerate_id();
}
}

Categories