2
votes

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

2 Answers

10
votes

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();
2
votes

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();