条纹检查现有卡片

4

我想在客户提交信用卡时使用Stripe API执行以下操作序列:

  1. 检查用户的元数据中是否有Stripe客户ID
  2. 如果没有,创建一个新客户,将输入的卡保存到该用户
  3. 如果用户已经有客户ID,请检查输入的卡是否已经是其保存的卡之一。
  4. 如果是,对该卡进行扣款
  5. 如果不是,则将新卡添加到客户对象中,然后对该卡进行扣款。

在我的当前代码中,尝试创建收费时,Stripe会返回一个invalid_request错误。以下是相关的代码部分:

//See if our user already has a customer ID, if not create one
$stripeCustID = get_user_meta($current_user->ID, 'stripeCustID', true);
if (!empty($stripeCustID)) {
    $customer = \Stripe\Customer::retrieve($stripeCustID);
} else {
    // Create a Customer:
    $customer = \Stripe\Customer::create(array(
        'email' => $current_user->user_email,
        'source' => $token,
    ));
    $stripeCustID = $customer->id;

    //Add to user's meta
    update_user_meta($current_user->ID, 'stripeCustID', $stripeCustID);
}

//Figure out if the user is using a stored card or a new card by comparing card fingerprints
$tokenData = \Stripe\Token::retrieve($token);
$thisCard = $tokenData['card'];

$custCards = $customer['sources']['data'];
foreach ($custCards as $card) {
    if ($card['fingerprint'] == $thisCard['fingerprint']) {
        $source = $thisCard['id'];
    }
}
//If this card is not an existing one, we'll add it
if ($source == false) {
    $newSource = $customer->sources->create(array('source' => $token));
    $source=$newSource['id'];
}

// Try to authorize the card
$chargeArgs = array(
    'amount' => $cartTotal,
    'currency' => 'usd',
    'description' => 'TPS Space Rental',
    'customer' => $stripeCustID, 
    'source' => $source,
    'capture' => false, //this pre-authorizes the card for 7 days instead of charging it immedietely
    );

try {
    $charge = \Stripe\Charge::create($chargeArgs);

感谢您的帮助。


我会仔细检查 $chargeArgs 中的 $source。如果我没记错的话,它期望一个代表令牌的字符串(例如:'tok_189fx52eZvKYlo2CrxQsq5zF')。请验证 $source = $customer->sources->create(array('source' => $token));$source = $thisCard['id']; 都返回这个值。 - avip
好的想法。如果提供了客户信息,源还可以接受卡片ID(https://stripe.com/docs/api#create_charge)。看起来我在一个地方获取了卡片对象(而不是ID),所以我进行了更新,但仍然没有成功。 - Eckstein
1
啊,我懂了。还有一个想法:如果您登录Stripe仪表板,在API下面有一个日志选项卡,它应该包含问题的确切来源——至少从Stripe后端看来是这样的。 - avip
这确实很有帮助!我没有意识到那些日志存在。 - Eckstein
太棒了,很高兴能帮到你! :) - avip
1个回答

2
问题最终出在这个部分:
if ($card['fingerprint'] == $thisCard['fingerprint']) {
    $source = $thisCard['id'];
}

如果指纹匹配成功,我需要获取用户元数据中的已有卡片的ID,而不是输入的匹配卡片的ID。所以,这段代码可以实现:
if ($card['fingerprint'] == $thisCard['fingerprint']) {
    $source = $card['id'];
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接