code_legend
code_legend

Reputation: 3285

if code returns an error do not run query

I have the following code:

<?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>";




?>

where I would only want the queries to be executed if the following runs succesfully (no errors is returned)

  $charge = \Stripe\Charge::create(array(
          'customer' => $customer->id,
          'amount'   => $amount,
          'currency' => 'cad'
      ));

The reason for that is that I do not want to record in the database that the payment was successful when stripe was not able to finalize the transaction before of a error.

Upvotes: 0

Views: 72

Answers (2)

Ofir Baruch
Ofir Baruch

Reputation: 10346

What we would need to do is to understand what that function returns: \Stripe\Charge::create on success and then using a simple condition we'll compare the $charge value to the success values.

While I'm not truly familiar with this API, according to their API of create charge the response for creating a new charge:

Returns a charge object if the charge succeeded. Returns an error if something goes wrong. A common source of error is an invalid or expired card, or a valid card with insufficient available balance.

So you can use use try - catch block, as you can see in the following example: (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.
}

Or in a more comprehensive way:

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
}

Upvotes: 2

Kristiyan
Kristiyan

Reputation: 1663

if($run_c === TRUE){
    $insert_c2 = "Update orders SET course_paid = '$course_paid' where course_id = '$userId'";
    $run_c2 = mysqli_query($con, $insert_c2);
}

Upvotes: 1

Related Questions