【问题标题】:Convert Stripe API response to JSON using stripe-php library使用 stripe-php 库将 Stripe API 响应转换为 JSON
【发布时间】:2013-10-24 06:58:56
【问题描述】:

我正在从Stripe API 访问客户数据,我想将其转换为 JSON。通常我会将对象转换为数组并使用json_encode(),但在这种情况下我似乎无法做到,即使尝试访问嵌套数组也是如此。

这是我试图转换为 json 的响应:

Stripe_Customer Object
(
    [_apiKey:protected] => MY_KEY_IS_HERE
    [_values:protected] => Array
        (
            [id] => cus_2dVcTSc6ZtHQcv
            [object] => customer
            [created] => 1380101320
            [livemode] => 
            [description] => Bristol : John Doe
            [email] => someone6@gmail.com
            [delinquent] => 
            [metadata] => Array
                (
                )

            [subscription] => 
            [discount] => 
            [account_balance] => 0
            [cards] => Stripe_List Object
                (
                    [_apiKey:protected] => MY_KEY_IS_HERE
                    [_values:protected] => Array
                        (
                            [object] => list
                            [count] => 1
                            [url] => /v1/customers/cus_2dVcTSc6ZtHQcv/cards
                            [data] => Array
                                (
                                    [0] => Stripe_Object Object
                                        (
                                            [_apiKey:protected] => MY_KEY_IS_HERE
                                            [_values:protected] => Array
                                                (
                                                    [id] => card_2dVcLabLlKkOys
                                                    [object] => card
                                                    [last4] => 4242
                                                    [type] => Visa
                                                    [exp_month] => 5
                                                    [exp_year] => 2014
                                                    [fingerprint] => NzDd6OkHnfElGUif
                                                    [customer] => cus_2dVcTSc6ZtHQcv
                                                    [country] => US
                                                    [name] => John Doe
                                                    [address_line1] => 
                                                    [address_line2] => 
                                                    [address_city] => 
                                                    [address_state] => 
                                                    [address_zip] => 
                                                    [address_country] => 
                                                    [cvc_check] => pass
                                                    [address_line1_check] => 
                                                    [address_zip_check] => 
                                                )

                                            [_unsavedValues:protected] => Stripe_Util_Set Object
                                                (
                                                    [_elts:Stripe_Util_Set:private] => Array
                                                        (
                                                        )

                                                )

                                            [_transientValues:protected] => Stripe_Util_Set Object
                                                (
                                                    [_elts:Stripe_Util_Set:private] => Array
                                                        (
                                                        )

                                                )

                                            [_retrieveOptions:protected] => Array
                                                (
                                                )

                                        )

                                )

                        )

                    [_unsavedValues:protected] => Stripe_Util_Set Object
                        (
                            [_elts:Stripe_Util_Set:private] => Array
                                (
                                )

                        )

                    [_transientValues:protected] => Stripe_Util_Set Object
                        (
                            [_elts:Stripe_Util_Set:private] => Array
                                (
                                )

                        )

                    [_retrieveOptions:protected] => Array
                        (
                        )

                )

            [default_card] => card_2dVcLabLlKkOys
        )

    [_unsavedValues:protected] => Stripe_Util_Set Object
        (
            [_elts:Stripe_Util_Set:private] => Array
                (
                )

        )

    [_transientValues:protected] => Stripe_Util_Set Object
        (
            [_elts:Stripe_Util_Set:private] => Array
                (
                )

        )

    [_retrieveOptions:protected] => Array
        (
        )

)

非常感谢任何帮助!

【问题讨论】:

  • 他们的响应已经是 JSON - “JSON 将在 API 的所有响应中返回,包括错误。”来自 API 文档

标签: php json stripe-payments


【解决方案1】:

PHP 保留了所有带有双下划线前缀的方法名称以供将来使用。见https://www.php.net/manual/en/language.oop5.magic.php

目前,在最新的 php-stripe 库中,您可以通过简单的调用 **->toJSON() 将 Stripe 对象转换为 JSON。

[以前]

Stripe PHP API 库创建的所有对象都可以使用它们的 __toJSON() 方法转换为 JSON。

Stripe::setApiKey("sk_xxxxxxxxxxxxxxxxxxxxxxxxx");

$customer = Stripe_Customer::create(array(
    "card" => $token, 
    "plan" => $plan,  
));

$customer_json = $customer->__toJSON();

还有一个 __toArray($recursive=false) 方法。请记住将 true 设置为参数,否则您将得到一个填充有条带对象的数组。

Stripe::setApiKey("sk_xxxxxxxxxxxxxxxxxxxxxxxxx");

$customer = Stripe_Customer::create(array(
    "card" => $token, 
    "plan" => $plan,  
));

$customer_array = $customer->__toArray(true);

【讨论】:

  • 正是我想要的
  • 这个答案完全符合 OP 的要求。我发现它也很有帮助。谢谢。
  • __toArray() 与 __toJSON() 相比会返回大量垃圾。
  • 简直太棒了!
  • 在__toArray和__toJSON之外,除了“返回大量垃圾”之外,还有哪些优缺点?
【解决方案2】:

Stripe_Objects 的属性可以这样访问:

$customer->attribute;

所以要获取客户卡的last4,可以这样做:

$customer->default_card->last4;

但是,您需要确保已填充 default_card 属性。通过传递expand 参数,您可以与其他客户同时检索default_card 对象:

$customer = Stripe_Customer::retrieve(array(
    "id" => "cus_2dVcTSc6ZtHQcv", 
    "expand" => array("default_card")
));

【讨论】:

    【解决方案3】:

    在最新版本中,您可以使用echo $customer->toJSON(); 获取 JSON 格式的输出。

    【讨论】:

      【解决方案4】:

      我是这样做的

      `Stripe::setApiKey("sk_xxxxxxxxxxxxxxxxxxxxxxxxx");
      
      $stripe_response= Stripe_Customer::create(array(
          "card" => $token, 
          "plan" => $plan,  
      ));
      
      //Encoding stripe response to json
      $resposnse_json_ecoded= json_encode($stripe_response);
      //decoding ecoded respose
      $response_decoded = json_decode($resposnse_json_ecoded, true);
      //get data in first level
      $account_id=$response_decoded['id'];
      $individual = $response_decoded['individual'];
      //get  data in second level
      $person_id=$individual['id'];`
      

      【讨论】:

        【解决方案5】:

        如果您像我一样来到这里寻找python 2.7 解决方案,只需将stripe_object 转换为str()。这会触发对象的内部 __str__() 函数,该函数将对象转换为 JSON 字符串。

        例如

        charge = stripe.Charge....
        print str(charge)
        

        【讨论】:

          【解决方案6】:

          您的顶级对象包含其他对象实例 - 转换为 (array) 仅影响顶级元素。您可能需要递归地走下去 - 但鉴于这些类是可序列化的,我会在这里采取不同的做法:

          $transfer = serialize($myobject);
          

          您打算如何处理其他 JSON 化的数据?

          如果您要传输没有类信息的对象,您可以尝试使用反射:

          abstract class Object {
          
              /**
               * initialize an object from matching properties of another object
               */
              protected function cloneInstance($obj) {
                  if (is_object($obj)) {
                      $srfl = new ReflectionObject($obj);
                      $drfl = new ReflectionObject($this);
                      $sprops = $srfl->getProperties();
                      foreach ($sprops as $sprop) {
                          $sprop->setAccessible(true);
                          $name = $sprop->getName();
                          if ($drfl->hasProperty($name)) {
                              $value = $sprop->getValue($obj);
                              $propDest = $drfl->getProperty($name);
                              $propDest->setAccessible(true);
                              $propDest->setValue($this,$value);
                          }
                      }
                  }
                  else
                      Log::error('Request to clone instance %s failed - parameter is not an object', array(get_class($this)));
                  return $this;
              }
          
              public function stdClass() {
                  $trg = (object)array();
                  $srfl = new ReflectionObject($this);
                  $sprops = $srfl->getProperties();
                  foreach ($sprops as $sprop) {
                      if (!$sprop->isStatic()) {
                          $sprop->setAccessible(true);
                          $name = $sprop->getName();
                          $value = $sprop->getValue($this);
                          $trg->$name = $value;
                      }
                  }
                  return $trg;
              }
          
          }
          

          这是我的大多数可转移类的基类。它从一个类创建一个 stdClass 对象,或者从一个 stdClass 对象初始化一个类。您可以很容易地根据自己的需要采用它(例如创建一个数组)。

          【讨论】:

          • 我正在将一些数据返回到 javascript webapp,即让客户从他们保存的卡片等中进行选择。
          • 嗯,在将(部分)序列化为 json 之前,我希望能够在 php 中使用数组/obj。你知道无论如何我可以访问/操作/转换条带对象而不对其进行字符串化吗?
          • 如果您想在转移前使用它,您只需保持原样,不是吗?最后,JS webapp 无法理解 Stripe 类,您将只传输部分数据。所以我相信你必须逐个实例进行。但另请参阅我将在此处发布的答案的编辑。
          【解决方案7】:

          这已经是 JSON 格式,所以您需要再次将其转换为 json_encode() 只需将其传递到您的脚本中

          【讨论】:

            猜你喜欢
            • 2021-03-22
            • 2017-07-10
            • 1970-01-01
            • 1970-01-01
            • 2020-11-10
            • 2016-10-27
            • 1970-01-01
            • 1970-01-01
            • 2020-10-30
            相关资源
            最近更新 更多