@hasnainali9 So what’s the issue? Or do we have to guess?
Jan 29, 2024
4
Level 1
Stripe Detach Payment Methods From Client.
Hey i just want to know the correct way to detach a Card or Payment Method from Client Tried different way from Stripe api docs but couldn't help me. Here is my Function.
/**
* Remove customer card
*
* @response {
* "success": true,
* "message": "card_removed_successfully"
* }
*/
public function removeCustomerCards(Request $request)
{
$Stripe_ENV=get_settings(Settings::STRIPE_ENVIRONMENT);
$Stripe_TEST_SECRET_KEY=get_settings(Settings::STRIPE_TEST_SECRET_KEY);
$Stripe_LIVE_SECRET_KEY=get_settings(Settings::STRIPE_LIVE_SECRET_KEY);
$Stripe_TEST_PUBLISHER_KEY=get_settings(Settings::STRIPE_TEST_PUBLISHABLE_KEY);
$Stripe_LIVE_PUBLISHER_KEY=get_settings(Settings::STRIPE_LIVE_PUBLISHABLE_KEY);
if($Stripe_ENV=='test'){
$test_environment = true;
\Stripe\Stripe::setApiKey($Stripe_TEST_SECRET_KEY);
}else{
\Stripe\Stripe::setApiKey($Stripe_LIVE_SECRET_KEY);
$test_environment = false;
}
try {
$user = auth()->user();
$customer_id = $user->stripe_customer_id;
$customer = \Stripe\Customer::retrieve($customer_id);
// Retrieve the customer's cards from Stripe
$cards = \Stripe\PaymentMethod::all([
'customer' => $customer_id,
'type' => 'card',
]);
// Check if the card to be removed belongs to the current user
$cardBelongsToUser = false;
foreach ($cards->data as $card) {
if ($card->id === $request->card_id) {
$cardBelongsToUser = true;
break;
}
}
if (!$cardBelongsToUser) {
return $this->respondError([], 'card_not_linked_to_user');
}
// If the card belongs to the user, remove it
$customer->paymentMethods->detach($request->card_id,[]);
return $this->respondSuccess([], 'card_removed_successfully');
} catch (\Exception $e) {
\Log::error('Stripe Error: ' . $e->getMessage());
return $this->respondError([], 'error_removing_card');
}
}
Please or to participate in this conversation.