Stripe PHP - 如何检索新添加的卡的ID?

时间:2017-09-21 05:46:23

标签: stripe-payments

我想允许我们的客户在他们的帐户中添加多张卡片。因此,在结账时,他们可以选择使用哪张卡或添加新卡。

我可以通过调用以下方式选择已添加的卡ID:

$cardid = $customer->sources->data[0]->id;
$cardid = $customer->sources->data[1]->id;
$cardid = $customer->sources->data[2]->id;
etc...

但我需要检索卡片ID或新添加的卡片。

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

1 个答案:

答案 0 :(得分:3)

card creation request将返回新创建的card object,因此您只需从中获取ID:

$new_card = $customer->sources->create(array(
    "source" => $token['id']
));

$new_card_id = $new_card->id;

请注意,在向客户添加新卡时,Stripe将向发卡银行验证卡,如果验证失败,则可能会返回card_error。您应该将卡创建请求包含在try/catch块中handle possible errors