Reputation: 795
I would like to allow our customers to add multiple cards to their accounts. So at the checkout, they can select which card to use or add a new one.
I can select the already added card IDs by calling:
$cardid = $customer->sources->data[0]->id;
$cardid = $customer->sources->data[1]->id;
$cardid = $customer->sources->data[2]->id;
etc...
But I need to retrieve the card ID or the newly added card.
//Create Token
try {
$token = \Stripe\Token::create(
array(
"card" => array(
"name" => $_POST['ccname'],
"number" => $_POST['ccnum'],
"exp_month" => $_POST['ccxpm'],
"exp_year" => $_POST['ccxpy'],
"cvc" => $_POST['cccvc'] )
)); }
catch(\Stripe\Error\Card $e) {
$body = $e->getJsonBody();
$err = $body['error'];
$status = $err['message'];
}
// Add new Card to Custid
$customer = \Stripe\Customer::retrieve($_POST['custid']);
$customer->sources->create(
array(
"source" => $token['id']
));
$cardid = $customer->sources->data[]->id; ???
// Charge CustID
$mysum = $_POST['amount']*100;
$charge = \Stripe\Charge::create(array(
'customer' => $customer,
'amount' => $mysum,
'currency' => 'usd',
'card' => $cardid
));
Upvotes: 3
Views: 421
Reputation: 17505
The card creation request will return the newly created card object, so you can simply grab the ID from there:
$new_card = $customer->sources->create(array(
"source" => $token['id']
));
$new_card_id = $new_card->id;
Note that Stripe will validate the card with the issuing bank when adding the new card to the customer, and may return a card_error
if the validation fails. You should wrap the card creation request in a try/catch
block to handle possible errors.
Upvotes: 3