How to do a task depending on Stripe API error response - php

Currently using Stripe to process payments however I would like to perform an SQL statement which will ban a user lets say when the Stripe risk evaluation is highest.
My current charge code using stripe's PHP library contains a basic error exception message:
<?php
require 'lib/Stripe.php';
if ($_POST) {
Stripe::setApiKey($stripeSecretKey);
$error = '';
$success = '';
try {
if (empty($_POST['street']) || empty($_POST['city']) || empty($_POST['zip']))
throw new Exception("Fill out all required fields.");
if (!isset($_POST['stripeToken']))
throw new Exception("The Stripe Token was not generated correctly");
Stripe_Charge::create(array("amount" => $price * 100,
"currency" => "gbp",
"card" => $_POST['stripeToken'],
"description" => "User: " . $userUsername . " - " . $userEmail,
"receipt_email" => $userEmail));
$success = '<div class="alert alert-success">
<strong>Success!</strong> Your payment was successful, Redirecting...
</div>';
header('Refresh: 3; URL=https://urlhere');
}
catch (Exception $e) {
$error = '<div class="alert alert-danger">
<strong>Error!</strong> '.$e->getMessage().'
</div>';
}
}
if(!(empty($success)))
$txid = generateTxid();
{
$SQL = $odb -> prepare("INSERT INTO `payments` VALUES(NULL, :price, :planid, :userid, :payer, :transactionid, UNIX_TIMESTAMP())");
$SQL -> execute(array(':price' => $price, ':planid' => $planID, ':userid' => $userID, ':payer' => $userEmail, ':transactionid' => $txid));
$unit = $plan['unit'];
$length = $plan['length'];
$newExpire = strtotime("+{$length} {$unit}");
$updateSQL = $odb -> prepare("UPDATE `users` SET `expire` = :expire, `membership` = :plan WHERE `ID` = :id");
$updateSQL -> execute(array(':expire' => $newExpire, ':plan' => (int)$planID, ':id' => (int)$userID));
}
?>
With reference to https://stripe.com/docs/api#charge_object I can see that under the PHP tab it has the outcome object which could be used in my cas ehowever not sure how to implement it.

Check the response from your charge creation. Look at the risk_level attribute and write a condition that does something when the condition is met.
$response = Stripe_Charge::create(...
To get the risk_level attribute:
print $response->outcome->risk_level
P.S. you should be checking the charge response to verify it succeeded and not just assuming it succeeded if an Exception was not thrown. It could be Pending, which is not an Exception but it's also not a success, for example.

Related

How to check the user status in database first after making changes changes in crud

How do I make every user to check their user_status to get status code 200 every http request?
I have crud with disable account function but the problem is in the user end if i make changes in admin end, and disable user account they still logged in
here is my disable function in my crud:
if($_POST["action"] == 'change_status')
{
$status = '';
if($_POST['user_status'] == 'Active')
{
$status = 'Inactive';
}
else
{
$status = 'Active';
}
$query = '
UPDATE users SET user_status = :user_status WHERE id = :id
';
$statement = $connect->prepare($query);
$statement->execute(
array(
':user_status' => $status,
':id' => $_POST['id']
)
);
$result = $statement->fetchAll();
if(isset($result))
{
echo '<div class="alert alert-fill-warning" role="alert">User status set to <strong>'.$status.'</strong><div>';
}
}
and also in every page i have this is my code:
if($_SESSION['user_status'] == 'Inactive'){
header("HTTP/1.1 401");
readfile('../../error/401.html');
exit();
}
After disabling their account their status is still 'Active' it will make changes if they logout
if status column type is boolen you can do basicly
Tinyint type for mysql support true and false
$query = '
UPDATE users SET user_status = !user_status WHERE id = :id
';
$statement = $connect->prepare($query);
$statement->execute(
array(
':id' => $_POST['id']
)
);
Do not save the user_status in the $_SESSION. Instead check the current status of the user in the database. That way you know if the user is still allowed to use your service/API and not if the user was allowed to use your service/API at the time the session was started (or to be more precise, when the $_SESSION['user_status'] value was set).

stripe payment error: uncaught exception

I am trying to implement stripe payment gateway in my application.
Everything works well for the static payment i.e. $55 or $5 or any other amount. But I want to create application which charges dynamically based on hours and hourly rate. when I wrote my logic and tried it, shows me an error like.
Fatal error: Uncaught exception 'Stripe\Error\InvalidRequest' with message 'Invalid integer: $price' in C:\wamp64\www\PROJECT\stripe-php\lib\ApiRequestor.php:120 from API request 'req_jN42fBMzXZqjVB' in C:\wamp64\www\PROJECT\stripe-php\lib\ApiRequestor.php on line 120
( ! ) Stripe\Error\InvalidRequest: Invalid integer: $price in C:\wamp64\www\PROJECT\stripe-php\lib\ApiRequestor.php on line 120
below is my code for the file:
<?php
if(!isset($_SESSION))
{
session_start();
}
require_once ('dbconfigpdo.php');
print_r($_SESSION);
$parkingslot= $_SESSION["parkingslot"];
$booking_start = $_SESSION["booking_start"];
$booking_end = $_SESSION["booking_end"];
$booking_start_time = $_SESSION["booking_start_time"];
$booking_end_time = $_SESSION["booking_end_time"];
//$price = $_SESSION['price'];
$a = new DateTime($booking_start_time);
$b = new DateTime($booking_end_time);
$interval = $a->diff($b);
echo $duration=$interval->format("%H");
var_dump($duration);
$price = 3 * $duration;
echo $duration;
echo $price;
//echo "$booking_end";
//check whether stripe token is not empty
if(!empty($_POST['stripeToken'])){
//get token, card and user info from the form
$token = $_POST['stripeToken'];
$name = $_POST['name'];
$email = $_POST['email'];
$card_num = $_POST['card_num'];
$card_cvc = $_POST['cvc'];
$card_exp_month = $_POST['exp_month'];
$card_exp_year = $_POST['exp_year'];
//include Stripe PHP library
require_once('stripe-php\init.php');
//set api key
$stripe = array(
"secret_key" => "sk_test_yzsJAYlaZBO5SUcoga067K1s",
"publishable_key" => "pk_test_ApEdDkstpR0xRuASqSbz0fn9"
);
\Stripe\Stripe::setApiKey($stripe['secret_key']);
//add customer to stripe
$customer = \Stripe\Customer::create(array(
'email' => $email,
'source' => $token
));
//item information
$itemName = $parkingslot;
$itemNumber = $parkingslot;
$itemPrice = $price;
$currency = "CAD";
$orderID = rand();
//charge a credit or a debit card
$charge = \Stripe\Charge::create(array(
'customer' => $customer->id,
'amount' => $itemPrice,
'currency' => $currency,
'description' => $itemName,
'metadata' => array(
'order_id' => $orderID
)
));
//retrieve charge details
$chargeJson = $charge->jsonSerialize();
//check whether the charge is successful
if($chargeJson['amount_refunded'] == 0 && empty($chargeJson['failure_code']) && $chargeJson['paid'] == 1 && $chargeJson['captured'] == 1){
//order details
$amount = $chargeJson['amount'];
$balance_transaction = $chargeJson['balance_transaction'];
$currency = $chargeJson['currency'];
$status = $chargeJson['status'];
$date = date("Y-m-d H:i:s");
//include database config file
include_once 'dbConfig1.php';
//insert tansaction data into the database
$sql = "INSERT INTO orders(name,email,card_num,card_cvc,card_exp_month,card_exp_year,item_name,item_number,item_price,item_price_currency,paid_amount,paid_amount_currency,txn_id,payment_status,created,modified) VALUES('".$name."','".$email."','".$card_num."','".$card_cvc."','".$card_exp_month."','".$card_exp_year."','".$itemName."','".$itemNumber."','".$itemPrice."','".$currency."','".$amount."','".$currency."','".$balance_transaction."','".$status."','".$date."','".$date."')";
$insert = $db->query($sql);
$last_insert_id = $db->insert_id;
//if order inserted successfully
if($last_insert_id && $status == 'succeeded'){
$sql="UPDATE `fleming_dwing` SET `Status` = 'RESERVED' WHERE `ParkingSlotNo`=$parkingslot";
$st=$conn->prepare($sql);
$st->execute();
$statusMsg = "<h2>The transaction was successful.</h2><h4>Order ID: {$last_insert_id}</h4>";
}else{
$statusMsg = "Transaction has been failed";
}
}else{
$statusMsg = "Transaction has been failed";
}
}else{
$statusMsg = "Form submission error.......";
}
//show success or error message
echo $statusMsg;
?>
I think I made some mistake while assigning values to stripe payment variable.
please help me out.

Stripe, on reload page customer is charged again

I have created a table app__stripe_customer containing customers id in order to avoid creating multiple times a same customer.
if ($_POST) {
\Stripe\Stripe::setApiKey($StripeKeySecret);
$error = '';
$success = '';
/**
* Check if Customer Exists if not Create a Customer:
*/
try {
$sql = $dataBase->prepare('SELECT * FROM app__stripe_customer
WHERE user_id = :uid');
$sql->execute(array('uid' => $_SESSION['user_id']));
$stripeCustomer = $sql->fetch();
if(empty($stripeCustomer)) {
/**
* We create the new Stripe Customer
*/
$customer = \Stripe\Customer::create(array(
"email" => $user['email'],
"source" => $token));
/**
* Creating new Stripe Customer Id in database
*/
$sql = $dataBase->prepare('INSERT INTO app__stripe_customer(user_id, customer_id)
VALUES(:uid,
:cid)');
$sql->execute(array('uid' => $_SESSION['user_id'],
'cid' => $customer->id));
$stripeCustomerId = $customer->id;
} else {
$stripeCustomerId = $stripeCustomer['customer_id'];
}
if (!isset($_POST['stripeToken']))
throw new Exception("The Stripe Token was not generated correctly");
$charge = \Stripe\Charge::create(array("amount" => $AMT*100,
"currency" => "usd",
"customer" => $stripeCustomerId));
$chargeID = $charge->id;
$success = 'Your payment was successful: '.$chargeID;
//echo $success;
show__paymentDone();
} catch (Exception $e) {
$error = $e->getMessage();
show__errorPayment($error);
}
}
It's working fine, but if the customer exists the token is not used and if the user reload the page he will be charged again.
To me, this code looks fine but how could I prevent from charging multiple times a user?
A way using $_SESSION before if($_POST):
if( (isset($_SESSION['stripe_token']) && ($_SESSION['stripe_token'] == $_POST['stripeToken']) ) {
show__errorTokenTwice($token);
exit;
}
After the charge is done:
$_SESSION['stripe_token'] = $_POST['stripeToken']

My Stripe payment is working perfect. But now i want to catch from Database

I am using Stripe Payment. I have integrated the Stripe checkout system in my Php website.
With Static prices it works good. But not I want to get Prices from My Database. And it shows on screen that it is charged. But in my strip account it is not sending money..
$charge = Stripe_Charge::create(array(
"amount" => 999999, // I want here $price from my database.
"currency" => "usd",
"card" => $_POST['stripeToken'],
"description" => 'This is Different Thing'
));
When i Add $price instead of static price 99999 it not sends money to my stripe payments. But when i add 99999 again , it start working. My Database is Okay All veriables and database connections are okay. Issue is only here.. How i can get it fixed..
If you want my full code..
include 'header.php'; //Connection File is in header.php
error_reporting(0);
try {
require_once('Stripe/lib/Stripe.php');
Stripe::setApiKey("sk_test_GkvxX3TWD6juGRLhZwP2LQ1x");
$req_id = $_REQUEST['order_id'];
$get_req = "SELECT * FROM `requests` WHERE `req_id` = '$req_id'";
$result = mysqli_query($dbc, $get_req);
while($row = mysqli_fetch_array($result)){
$req_id = $row['req_id'];
$request_title = $row['request_title'];
$username = $row['username'];
$user_id = $row['user_id'];
$price = $row['price'];
$request_time = $row['request_time'];
$req_date = $row['req_date'];
$category = $row['category'];
$sub_category = $row['sub_category'];
$from_address = $row['from_address'];
$to_address = $row['to_address'];
$from_state = $row['from_state'];
$to_state = $row['to_state'];
$from_city = $row['from_city'];
$to_city = $row['to_city'];
$req_desc = $row['req_desc'];
$status = $row['req_status'];
$paid = $row['paid'];
}
$charge = Stripe_Charge::create(array(
"amount" => 999999,
"currency" => "usd",
"card" => $_POST['stripeToken'],
"description" => 'This is Different Thing'
));
$status = "";
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$errors = array();
if (isset($_POST['stripeToken'])) {
$token = $_POST['stripeToken'];
echo 'Payment Done ';
$status = 1;
//print_r($token);
} else {
$errors['token'] = 'The order cannot be processed. You have not been charged.
Please confirm that you have JavaScript enabled and try again.';
echo "payment not successfully done.Please try again";
$status = 0;
}
} // End of form submission conditional.
}
catch(Stripe_CardError $e) {
}
//catch the errors in any way you like
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
}
if($status2 = 1){
$query = "UPDATE `requests` SET `req_status`='1', `paid`='1' WHERE `req_id`='$req_id'";
$result = mysqli_query($dbc,$query);
}else{
}
I have not seen in your code, what the output of $price is. So, while I do
not assume that $price, drawn from your database, is incorrectly prepared,
it is as mentioned in the Stripe documentation, necessary to express the
price in cents. Such that if you place this code
$findme = ".";
$pos = strpos($price, $findme);
$PosPlus = $pos+1;
$Part1=substr($price, 0, $pos);
$Part2=substr($price, $PosPlus);
$price = ($Part1.$Part2);
above the line you have,
$charge = Stripe_Charge::create(array( //.....
your charge should succeed.

MySQL parameter error

I'm trying to get my query to work for this PHP but I'm getting a "Invalid Parameter Number: number of bound variables do not match number of tokens" This is a snippet of my PHP:
<?php
/*
Our "config.inc.php" file connects to database every time we include or require
it within a php script. Since we want this script to add a new user to our db,
we will be talking with our database, and therefore,
let's require the connection to happen:
*/
require("configmob.php");
//if posted data is not empty
if (!empty($_POST)) {
//If the username or password is empty when the user submits
//the form, the page will die.
//Using die isn't a very good practice, you may want to look into
//displaying an error message within the form instead.
//We could also do front-end form validation from within our Android App,
//but it is good to have a have the back-end code do a double check.
if (empty($_POST['FirstName']) || empty($_POST['LastName'])) {
// Create some data that will be the JSON response
$response["success"] = 0;
$response["message"] = "Please Enter Both a First Name and a Last Name.";
//die will kill the page and not execute any code below, it will also
//display the parameter... in this case the JSON data our Android
//app will parse
die(json_encode($response));
}
//if the page hasn't died, we will check with our database to see if there is
//already a user with the username specificed in the form. ":user" is just
//a blank variable that we will change,Spot FROM Reservation WHERE Date = ':Date' AND Time = ':Time' AND Spot = ':Spot' ";
//now lets update what :user should be
$query = "Select * FROM Reservation WHERE Date = ':Date' AND TimeIn = ':TimeIn' AND Spot = ':Spot'";
$query_params = array(':Date' => $_POST['Date'] , ':TimeIn' => $_POST['Time'] , ':Spot' => $_POST['Spot']
);
//Now let's make run the query:
try {
// These two statements run the query against your database table.
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch (PDOException $ex) {
// For testing, you could use a die and message.
//die("Failed to run query: " . $ex->getMessage());
//or just use this use this one to product JSON data:
$response["success"] = 0;
$response["message"] = $ex->getMessage();
die(json_encode($response));
}
//fetch is an array of returned data. If any data is returned,
//we know that the username is already in use, so we murder our
//page
$row = $stmt->fetch();
if ($row) {
// For testing, you could use a die and message.
//die("This username is already in use");
//You could comment out the above die and use this one:
$response["success"] = 0;
$response["message"] = "I'm sorry, this Reservation is already Taken";
die(json_encode($response));
}
//If we have made it here without dying, then we are in the clear to
//create a new user. Let's setup our new query to create a user.
//Again, to protect against sql injects, user tokens such as :user and :pass
$query = "INSERT INTO Reservation (Fname, Lname, Garno, Gname, EmpID, CustID, License, Floor, Spot, TimeIn, TimeOut, Date, Confirmation)
VALUES (:Fname, :Lname, :Garno, :Gname, :EmpID, :CustID, :License, :Floor, :Spot, :TimeIn, :TimeOut, :Date, :Confirmation) ";
//Again, we need to update our tokens with the actual data:
$query_params = array(
':Fname' => $_POST['FirstName'],
':Lname' => $_POST['LastName'],
':Gname' => $_POST['Garage'],
':Date' => $_POST['Date'],
':TimeIn' => $_POST['Time'],
':Spot' => $_POST['Spot'],
':Confirmation' => $_POST['Confirmation'],
);
//time to run our query, and create the user
try {
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch (PDOException $ex) {
// For testing, you could use a die and message.
//die("Failed to run query: " . $ex->getMessage());
//or just use this use this one:
$response["success"] = 0;
$response["message"] = $ex->getMessage();
die(json_encode($response));
}
//If we have made it this far without dying, we have successfully added
//a new user to our database. We could do a few things here, such as
//redirect to the login page. Instead we are going to echo out some
//json data that will be read by the Android application, which will login
//the user (or redirect to a different activity, I'm not sure yet..)
$response["success"] = 1;
$response["message"] = "Reservation Added!!";
echo json_encode($response);
//for a php webservice you could do a simple redirect and die.
//header("Location: loginmob.php");
//die("Redirecting to loginmob.php");
} else {
?>
<h1>Register</h1>
<form action="register.php" method="post">
Username:<br />
<input type="text" name="username" value="" />
<br /><br />
Password:<br />
<input type="password" name="password" value="" />
<br /><br />
<input type="submit" value="Register New User" />
</form>
<?php
}
?>
Thank you for the help!
This is what I found in your second statement:
$query = "Select * FROM Reservation WHERE Date = ':Date' AND TimeIn = ':Time' AND Spot = ':Spot'";
$query_params = array(':Date' => $_POST['Date'] , ':TimeIn' => $_POST['Time'] , ':Spot' => $_POST['Spot']
);
Your :TimeIn should be :Time like follows:
$query_params = array(':Date' => $_POST['Date'] , ':Time' => $_POST['Time'] , ':Spot' => $_POST['Spot']
Update:
Also in your second query you have :Garno missing, please try the following:
$query = "INSERT INTO Reservation (Fname, Lname, Garno, Gname, EmpID, CustID, License, Floor, Spot, TimeIn, TimeOut, Date, Confirmation)
VALUES (:Fname, :Lname, :Garno, :Gname, :EmpID, :CustID, :License, :Floor, :Spot, :TimeIn, :TimeOut, :Date, :Confirmation) ";
//Again, we need to update our tokens with the actual data:
$query_params = array(
':Fname' => $_POST['FirstName'],
':Lname' => $_POST['LastName'],
':Garno' => $_POST['Garno'], // Hopefully $_POST['Garno'] is what you want.
':EmpID' => $_POST['EmpID'], // Hopefully $_POST['EmpID'] is what you want.
':CustID' => $_POST['CustID'], // Hopefully $_POST['CustID'] is what you want.
':License' => $_POST['License'], // Hopefully $_POST['License'] is what you want.
':Floor' => $_POST['Floor'], // Hopefully $_POST['Floor'] is what you want.
':TimeOut' => $_POST['TimeOut'], // Hopefully $_POST['TimeOut'] is what you want.
':Gname' => $_POST['Garage'], // You don't need this, remove this.
':Date' => $_POST['Date'],
':TimeIn' => $_POST['Time'],
':Spot' => $_POST['Spot'],
':Confirmation' => $_POST['Confirmation'],
);

Categories