Reputation: 155
I'm looking for a way to create a new source for a customer and then set that source as the default source for the customer. The problem I'm currently facing is that the response from creating the source does not give me a easy way to identify the id for the new created source so that I can set that source as default.
Below is my code, without any API key and customer ID:
\Stripe\Stripe::setApiKey($stripe_api_key);
$customer = \Stripe\Customer::retrieve($_SESSION['parent']['stripe_customer_id']);
$customer->sources->create(array('source' => array("object" => "card", 'exp_month' => $expire_month, 'exp_year' => $expire_year, 'number' => $card_number, 'address_line1' => $billing_address1, 'address_line2' => $billing_address2, 'address_city' => $billing_city, 'address_zip' => $billing_postal_code, 'address_country' => $billing_country, 'currency' => 'GBP', 'cvc' => $security_code, 'name' => $_SESSION['parent']['firstname'] . ' ' . $_SESSION['parent']['lastname'])))->__toArray(true);
//set as default
if (isset($_POST['check_default_source'])) {
$customer->default_source=$customer['id'];
$customer->save();
}
Upvotes: 2
Views: 1690
Reputation: 1676
I also had this problem, slightly different.
I added a new source from a token_id.
The getLastResponse
method was not available in my API or library version.
But using the token object (Stripe::Token::retreive( token_id )) you can actually retrieve the card_id, and use that to update the default_source.
Took me a long time to figure this out, so I post it here. Maybe it helps someone in the future...
Upvotes: 1
Reputation: 155
I was able to to find the solution to my question. Stripe API does send back the id of the source that was just created and to get the ID I use the below code:
$source_id = json_decode($customer->sources->getLastResponse()->body)->id;
Upvotes: 1