我想在客户提交信用卡时使用Stripe API执行以下操作序列:
- 检查用户的元数据中是否有Stripe客户ID
- 如果没有,创建一个新客户,将输入的卡保存到该用户
- 如果用户已经有客户ID,请检查输入的卡是否已经是其保存的卡之一。
- 如果是,对该卡进行扣款
- 如果不是,则将新卡添加到客户对象中,然后对该卡进行扣款。
在我的当前代码中,尝试创建收费时,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