2

I'm using Stripe Payments and would like to give customers the possibility to change their credit card. Referring to https://stripe.com/docs/api#create_subscription -> source, I tried the following PHP-code:

        $customer = \Stripe\Customer::retrieve($client_id);

        $customer = \Stripe\Customer::create(array(
        "source" => $token) //the token contains credit card details
        );

This works, but unfortunately it unintentionally also creates a new customer ID:

Stripe Dashboard

The original customer ID was cus_6elZAJHMELXkKI and I would like to keep it.

Does anybody know the PHP-code that would update the card without creating a new customer?

Thank you very much in advance!

PS: Just in case you need it – this was the code that originally created the customer and the subscription:

$customer = \Stripe\Customer::create(array(
    "source" => $token,
    "description" => "{$fn} {$ln}",
    "email" => $e,
    "plan" => "basic_plan_id")
 );

\Stripe\Charge::create(array(
  "amount" => 10000, # amount in cents, again
  "currency" => "eur",
  "customer" => $customer->id)
);

2 Answers 2

10

I've just found the answer, maybe it helps someone of you, too:

You can replace the old card with the new one like so:

$customer = \Stripe\Customer::retrieve($client_id);
$new_card = $customer->sources->create(array("source" => $token));
$customer->default_source = $new_card->id;
$customer->save();
1
  • 2
    hi, thanks for this code. i tried this code but it doesn't replace the old card. what this do is it stores the new card and set the new card as the default card. the old card is still in the stripe customer's account.
    – ikikika
    Commented Jan 23, 2018 at 11:15
2

The answer helped a bunch but commenter was correct that old card wasn't deleted.

Assuming you would only ever have one card for a customer you would do this instead:

//get customer
$customer = \Stripe\Customer::retrieve($client_id);

//get the only card's ID
$card_id=$customer->sources->data[0]->id;
//delete the card if it exists
if ($card_id) $customer->sources->retrieve($card_id)->delete();

//add new card
$new_card = $customer->sources->create(array("source" => $token));
$customer->default_source = $new_card->id;
$customer->save();

Not the answer you're looking for? Browse other questions tagged or ask your own question.