使用客户对象获取卡的最后 4 位数字 - 条纹 API 和 PHP

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

我想使用 Stripe 获取客户卡的最后 4 位数字。 我已经使用以下方式存储了客户:

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

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

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

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

$last4 = $StripeCustomer->来源->数据[0]->last4;

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

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

对于通过搜索引擎登陆这里的任何其他人,这里有一个 link 到 Stripe 文档,介绍如何将卡的最后 4 位数字保存给客户 https://stripe.com/docs/api/customers/object#customer_object-sources-data-last4

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

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

您可以从该对象中获取所有信息。

这个 API 自第一次回答以来已经改变。对于 API 版本 2020-08-27,您需要使用 ListPaymentsMethod API on the Customer object.

通过 JSON 访问的路径如下所示

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