How to delete a card of a customer on Stripe in Laravel via API
Stripe is a most common and trusted payment gateway used by lots of businesses and companies and it provides lots of functionalities to make payment more smoother, faster and secure in no time. Stripe provides every service to fulfill your requirement for implementing payment gateway to your business.
We have already discussed about why to use stripe , how to create a customer , how to save a card and how to create a token and continuing this series , in this article we will see how to delete / detach a card of customer in Stripe.
As we know card details are very sensitive and we should not store the user's detail on our databases. To delete a card we will Stripe's API to delete card from Stripe. So that user cannot use the card further on your platform.
Currently i have 3 cards for a customer , i will delete one of these cards via API.
PaymentController.php :-
On your controller , you need customer ID to fetch his/her card details as shown below.
public function deleteCard(Request $request){
try{
// Get the card id and customer id from your database or from request body
$card_id = $request->card_id;
$customer_id = $request->customer_id;
// Connect to your stripe account
$stripe_account = Config('constants.Stripe_account');
$stripe_secret = $stripe_account['secret_key'];
$stripe = new \Stripe\StripeClient(
$stripe_secret
);
$delete_response = $stripe->customers->deleteSource(
$customer_id,
$card_id,
[]
);
return $delete_response;
}
catch(\Exception $e){
Log::error(
'Failed to delete card',
['message' => $e->getMessage(), 'trace' => $e->getTraceAsString()]
);
return false;
}
}
Output:-
{ "id": "card_1KKnxLSGh31t2ygOsDFJtt3G", "object": "card", "deleted": true }
Thank you for reading this article 😊
For any query do not hesitate to comment 💬