我有以下代码:
<?php
require_once('./config.php');
include("includes/db.php");
$token = $_POST["token"];
$userId = $_POST["userId"];
$email = $_POST["userEmail"];
$courseProvider = $_POST["courseProvider"];
$amount = $_POST["priceFinal"];
$courseTitle = $_POST["courseTitle"];
$amount = $amount * 100;
$customer = \Stripe\Customer::create(array(
'email' => $email,
'card' => $token
));
$charge = \Stripe\Charge::create(array(
'customer' => $customer->id,
'amount' => $amount,
'currency' => 'cad'
));
$amountDisplay = $amount / 100;
$course_paid = "Yes";
$course_paid_date = date("Y-m-d");
$insert_c = "insert into order_complete (course_title, course_price, course_buyer, course_provider, course_paid_date)
values ('$courseTitle','$amount','$email','$courseProvider','$course_paid_date')";
$run_c = mysqli_query($con, $insert_c);
$insert_c2 = "Update orders SET course_paid = '$course_paid' where course_id = '$userId'";
$run_c2 = mysqli_query($con, $insert_c2);
echo "<h4>Successfully charged $$amountDisplay to $email</h4>";
?>
如果以下成功运行(不返回任何错误),我只希望执行查询
$charge = \Stripe\Charge::create(array(
'customer' => $customer->id,
'amount' => $amount,
'currency' => 'cad'
));
原因是我不想在数据库中记录当条带无法在错误发生之前完成事务时付款成功。
答案 0 :(得分:2)
我们需要做的是了解该函数返回的内容:
\Stripe\Charge::create
成功后使用简单条件我们会将$charge
值与成功值进行比较。
虽然我并不真正熟悉此API,但根据API of create charge
创建新费用的响应:
如果充电成功,则返回充电对象。如果返回错误 出了点问题。常见的错误来源是无效或 过期的卡,或可用余额不足的有效卡。
因此,您可以使用use try - catch
块,如以下示例中所示:(https://stripe.com/docs/tutorials/charges)
$stripChargeValid = true;
try {
$charge = \Stripe\Charge::create(array(
"amount" => 1000, // amount in cents, again
"currency" => "usd",
"source" => $token,
"description" => "Example charge")
);
} catch(\Stripe\Error\Card $e) {
// The card has been declined
$stripChargeValid = false;
}
if($stripChargeValid){
//Run your queries.
}
或者以更全面的方式:
try {
// Use Stripe's bindings...
} catch(\Stripe\Error\Card $e) {
// Since it's a decline, \Stripe\Error\Card 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\Error\InvalidRequest $e) {
// Invalid parameters were supplied to Stripe's API
} catch (\Stripe\Error\Authentication $e) {
// Authentication with Stripe's API failed
// (maybe you changed API keys recently)
} catch (\Stripe\Error\ApiConnection $e) {
// Network communication with Stripe failed
} catch (\Stripe\Error\Base $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
}
答案 1 :(得分:1)
if($run_c === TRUE){
$insert_c2 = "Update orders SET course_paid = '$course_paid' where course_id = '$userId'";
$run_c2 = mysqli_query($con, $insert_c2);
}