stripe payment error: uncaught exception - php

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.

Related

Call a user again if he/she did not answer using Twilio

EDIT: working now, editted this post to the working script.
I'm setting up an alarm which calls the user if a sensor reaches a certain value. I've got the calling part working but I need Twilio to call the user again if the user did not pick up the phone.
Currently, Twilio calls the user telling him that the alarm is going. If the user does not pick up in 15 seconds Twilio will end the call so it doesn't go to voicemail. Now the status of the call will be 'No Answer' in the Twilio console. I've tried the following code:
In my call.php:
<?php
require __DIR__ . '/vendor/autoload.php';
use Twilio\Rest\Client;
// /include 'insertcall.php';
// Your Account SID and Auth Token from twilio.com/console
$account_sid = 'xxx';
$auth_token = 'xxx';
// In production, these should be environment variables. E.g.:
// $auth_token = $_ENV["TWILIO_ACCOUNT_SID"]
// A Twilio number you own with Voice capabilities
$twilio_number = "+12242631292";
// Where to make a voice call (your cell phone?)
$time = time();
$call_id = $sensor_id . $time;
echo "callid: ";
echo $call_id;
echo "<br><br>";
$client = new Client($account_sid, $auth_token);
$client->account->calls->create(
$callto,
$twilio_number,
array(
"machineDetection" => "DetectMessageEnd",
"url" => "https://link.nl/includes/alarmbot/includes/cas_xml.inc.php?sensor=$sensor_id",
"statusCallbackMethod" => "POST",
"statusCallback" => "https://link.nl/includes/alarmbot/callback.php?sensor=$sensor_id&callid=$call_id",
"statusCallbackEvent" => array(
"completed"
),
"timeout" => 15 // Wanneer niemand op neemt na 15 sec -> No Answer zodat we niet naar voicemail gaan en alsnog als completed gaat.
)
);
$conn = mysqli_connect($servername, $username, $password, $dbname);
$sql5 = "INSERT INTO twilio_calls (id, sensor_id, completed) VALUES ($call_id, '$sensor_id', '0')";
if ($conn->query($sql5) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql5 . "<br>" . $conn->error;
}
In my callback.php:
<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);
setlocale(LC_ALL, 'nl_NL');
require 'includes/boot.php';
use Twilio\Rest\Client;
$servername = "localhost";
$username = "xxx";
$password = "xxx";
$dbname = 'xxx';
$account_sid = 'xxx';
$auth_token = 'xxx';
if (isset($_REQUEST['CallStatus'])) {
$call_status = $_REQUEST['CallStatus'];
$call_id = $_REQUEST['callid'];
$twilio_number = "+mynumber";
echo $call_status;
echo "<br>";
echo $call_id;
echo "<br>";
if ($call_status !== 'completed' && $call_status !== 'busy') {
$conn = mysqli_connect($servername, $username, $password, $dbname);
$sql = "SELECT * FROM twilio_calls WHERE id='$call_id'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
$sensor_id = $row['sensor_id'];
$sql_2 = "SELECT telefoonnummer FROM alarmnummers WHERE sensor_id='$sensor_id' AND backup = 1";
$result_2 = $conn->query($sql_2);
if ($result_2->num_rows > 0) {
while ($row_2 = $result_2->fetch_assoc()) {
$telefoonnummer = $row_2['telefoonnummer'];
echo $telefoonnummer;
$client = new Client($account_sid, $auth_token);
$client->account->calls->create(
$telefoonnummer,
$twilio_number,
array(
"url" => "https://link.nl/includes/alarmbot/includes/callback.php?sensor=$sensor_id",
"timeout" => 15
)
);
}
} else {
echo "query ni goed";
}
$sql_3 = "UPDATE twilio_calls SET completed=1 WHERE id='$call_id'";
$conn->query($sql_3);
}
} else {
echo "andere query ni goed";
}
} else {
$sql = "UPDATE twilio_calls SET completed=1 WHERE id='$call_id'";
$conn->query($sql);
echo "Updated, call busy or completed";
}
} else {
echo 'No valid callback';
}
So I need to call the user again when he/she did not pick up. I am not really sure how I am supposed to do this.

How to do a task depending on Stripe API error response

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.

I trying to create external bank (PHP)account but i am not getting any response.Neither i am getting error nor the account is created

function stripe_bank_payment()
{
$this->load->database();
$id = $_GET['user_id'];
$acc_id = $_GET['stripe_account_id'];
$amount = $_GET['amount'];
$get = $this->db->select('*')->where(array('user_id' => $id))->get('bank_detail');
$pay = $get->result_array();
foreach ($pay as $res) {
$token = $res['token'];
}
require_once 'stripe/init.php';
\Stripe\Stripe::setApiKey("sk_test_6zdfZQ6R0Jh7EiFONJTpYaFl");
$account = \Stripe\Account::retrieve($acc_id);
$account->external_accounts->create(array("external_account" => $token));
return $account;
}
The above is my code.
I am trying to create external bank account.
user_id, stripe_account_id, and amount is given by me.
the token which is to be used is there in bank_details table.
So i am getting token from there.
And then running the code.

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.

Categories