Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stripe, verify card and only charge it after an action

I'm working on enabling payments for a website. I'm using Stripe as the provider. I wanted to know how I could charge the card if 2 conditions are true. When the user pays, I want to change a value in the database, and charge the card. But I don't want to charge the card if the database query fails. Similarly, I don't want to query if the card is invalid. I need both, the card to be valid and for the query to be successful. How do I do that?

Here's the code for charging the card

try {
$charge = \Stripe\Charge::create(array(
  "amount" => $amount, // amount in cents, again
  "currency" => "cad",
  "source" => $token,
  "description" => $description)
);
} catch(\Stripe\Error\Card $e) {
  // The card has been declined
}
like image 910
user4559334 Avatar asked Jul 09 '15 02:07

user4559334


2 Answers

Instead of charging the card, you should think about charging a customer. By this I mean:

1. Create a customer

$customer = \Stripe\Customer::create(array(
  "description" => "Customer for [email protected]",
  "source" => "tok_15gDQhLIVeeEqCzasrmEKuv8" // obtained with Stripe.js
));

2. Create a card

$card = $customer->sources->create(array("source" => "tok_15gDQhLIVeeEqCzasrmEKuv8"));

From Stripe API Reference:

source | external_account REQUIRED When adding a card to a customer, the parameter name is source. The value can either be a token, like the ones returned by our Stripe.js, or a dictionary containing a user’s credit card details. Stripe will automatically validate the card.

By creating a card, Stripe will automatically validate it. So having a valid credit card object you can then perform whatever query you want on your db and if success, charge the customer.

3. Charge

\Stripe\Charge::create(array(
    "amount" => 400,
    "currency" => "usd",
    "source" => "tok_15gDQhLIVeeEqCzasrmEKuv8", // obtained with Stripe.js,
    // "customer" => $cusomer->id // the customer created above
    "metadata" => array("order_id" => "6735")
));

When charging, you can either pass the source (the token obtained with Stripe.js) or the customer id we just created.

Also don't forget to try...catch everything.

like image 155
viarnes Avatar answered Oct 12 '22 23:10

viarnes


Ok, so after reading through the API, I found that this is acheivable by setting the capture parameter to false

Like this:

$charge = \Stripe\Charge::create(array(
  "amount" => $amount, // amount in cents, again
  "currency" => "cad",
  "source" => $token,
  "description" => $description,
  "capture" => false)
);

And this will authorize the payment and the card but not create a charge. After you do the querying and make sure it's successful, you can charge the customer (capture the charge) using this

$ch = \Stripe\Charge::retrieve({$charge->id});
$ch->capture();
like image 24
user4559334 Avatar answered Oct 12 '22 23:10

user4559334