Stripe check for existing card

本小妞迷上赌 提交于 2019-12-12 19:06:27

问题


I'm looking to do the following sequence (using the Stripe API) when a customer submits a credit card:

  1. Check if the user has a stripe customer id in their meta
  2. If they don't, create a new customer, save the entered card to that user
  3. If the user already has a customer id, check if the entered card is already one of their saved cards.
  4. If it is, charge that card
  5. If it's not, add the new card to the customer object, and then charge that card.

In my current code, Stripe is returning an invalid_request error upon trying to create the charge. Here's the section of code that relates:

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

Any help is appreciated.


回答1:


The issue turned out to be this section:

if ($card['fingerprint'] == $thisCard['fingerprint']) {
    $source = $thisCard['id'];
}

If a fingerprint match is successful, I need to grab the id of the card already in the users's meta, not the matching card that was inputted. So, this works:

if ($card['fingerprint'] == $thisCard['fingerprint']) {
    $source = $card['id'];
}


来源:https://stackoverflow.com/questions/42686415/stripe-check-for-existing-card

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!