In testing mode when I create a new customer and tries for payment, i got this error.
Customer cus_7Zz2BCnybIZLGw does not have a linked card with ID
This is my solution process, and works for me to prevent double payment and finish the proccess, feel free to improve if necesary
in stripe form add
genRandAlphaNumber is function to create a string to avoid double payment in stripe
function genRandAlphaNumber($length) {
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$randomString = '';
for ($i = 0; $i < $length; $i++) {
$randomString .= $characters[rand(0, strlen($characters) - 1)];
}
return $randomString;
}
In Stripe Post Proccess
$user = auth()->user();
try {
$cart = new Cart();
$cart->user_id = $user->id;
$cart->save();
$description = 'description';
Stripe\Stripe::setApiKey(env('STRIPE_SECRET'));
$idempotency = preg_replace('/[^a-z\d]/im', '', $request->idempotency);
$stripe_token = $request->stripeToken;
//if user's stripe_token is null, create the user
if (!$user->stripe_token) {
$result = \Stripe\Customer::create(array(
'name' => $user->name .' '. $user->name,
"email" => $user->email,
"source" => $stripe_token
));
if($result && $result->id) {
$user->stripe_id = $result->id;
$user->stripe_token = $stripe_token;
$user->save();
}
}
//if user has token
if($user->stripe_token) {
// charge customer with your amount
$result = \Stripe\Charge::create(array(
"currency" => 'usd',
"customer" => $user->stripe_id,
"amount" => $cart->price * 100,
"description" => $description
),
["idempotency_key" => $idempotency,]
);
Session::flash('success', 'Payment successful!');
$cart->status = 4;
$cart->save();
return redirect()->route('cart.finish', $cart->id);
}
} catch (\Exception $ex) {
if ($ex->getStripeCode() == "idempotency_key_in_use") {
sleep(2);
//search last cart
$cart = Cart::whereUser_id($user->id)->whereStatus(4)->orderBy('id', 'DESC')->first();
if (!is_null($cart)) {
Session::flash('success', 'Payment successful!, double payment prevented');
return redirect()->route('cart.finish', $cart->id);
}
return back();
}
if ($ex->getJsonBody()['error']['type'] == "idempotency_error") {
$cart = Cart::whereUser_id($user->id)->whereStatus(4)->orderBy('id', 'DESC')->first();
if (!is_null($cart)) {
Session::flash('success', 'Payment successful!...');
return redirect()->route('cart.membership.update', $cart->id);
}
return back();
}
return $ex->getMessage();
}