获取最后4位数字的卡使用客户对象-带状API与PHP


Getting Last4 Digits of Card using Customer Object - Stripe API with PHP

我想使用Stripe获取客户卡的最后4位数字。我已经使用

存储了Customer
      // Get the credit card details submitted by the form
      $token = $_POST['stripeToken'];
      // Create a Customer
      $StripeCustomer = 'Stripe'Customer::create(array(
              "description" => "$username",
              "card" => $token
      ));

现在我想访问并存储卡的最后4位数字。(作为上下文,我想向用户展示他们使用Stripe存储了哪张卡以便将来付款——这不是订阅服务)。

我已经寻找了一个解决方案,但很多帖子都保存了收费后的最后4位数字,并从收费中提取信息,如:

$last4 = null;
try {
    $charge = Stripe_Charge::create(array(
    "amount" => $grandTotal, // amount in cents, again
    "currency" => "usd",
    "card" => $token,
    "description" => "Candy Kingdom Order")
);
$last4 = $charge->card->last4;

我想在收费之前做同样的事情,所以我想从Customer对象中提取最后4个。Stripe API文档显示了来自Customers的last4的属性路径,
customer->sources->data->last4

然而,这似乎没有给我正确的最后4位数字。
$last4 = $StripeCustomer->sources->data->last4;

我想我误解了如何在Stripe API中使用属性。有人能给我指个正确的方向吗?

$last4 = $ stripeccustomer ->sources->data[0]->last4;

sources->data是一个数组,所以你必须选择第一张卡片。

旁注:您使用令牌两次,一次创建客户,第二次创建收费,这将导致一个错误,因为令牌只能使用一次。您必须向客户收费,而不是向令牌收费。

对于任何从搜索引擎登陆这里的人,这里有一个链接到Stripe文档,关于如何获得保存给客户的卡的最后4位数字https://stripe.com/docs/api/customers/object#customer_object-sources-data-last4

这个API自从第一次回答这个问题以来已经改变了。对于API版本2020-08-27,您需要在Customer对象上使用ListPaymentsMethod API。

通过JSON访问的路径看起来像这样

$paymentMethods = $stripe->paymentMethods->all([
  'customer' => 'cus_123',
  'type' => 'card',
]);
$last4 = $paymentMethods->data[0]->card->last4

如果您使用Laravel收银员,此代码将对您有所帮助。

$data = User::find(auth()->user()->id);
$payment = $data->defaultPaymentMethod();
$last4 = $payment->last4;
$brand = $payment->brand;
dd($payment);

你可以从这个对象得到所有的信息