London Smith
London Smith

Reputation: 1659

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?

Upvotes: 2

Views: 391

Answers (1)

PierreLoi
PierreLoi

Reputation: 26

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']

Upvotes: 1

Related Questions