我创建了一个包含客户ID的表app__stripe_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);
}
}
它工作正常,但如果客户存在,则不使用令牌,如果用户重新加载页面,他将再次收费。
对我来说,这段代码看起来不错,但我怎么能阻止用户多次充电呢?
答案 0 :(得分:1)
在$_SESSION
之前使用if($_POST)
的方法:
if( (isset($_SESSION['stripe_token']) && ($_SESSION['stripe_token'] == $_POST['stripeToken']) ) {
show__errorTokenTwice($token);
exit;
}
收费完成后:
$_SESSION['stripe_token'] = $_POST['stripeToken']