15

I'm accessing customer data from the Stripe API, which I'd like to convert to JSON. Usually I'd convert an object to an array and use json_encode() but I don't seem able to in this case, even when trying to access the nested arrays.

This is the response I'm trying to convert to 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
        (
        )

)

Any help greatly appreciated!

Mark Amery
  • 143,130
  • 81
  • 406
  • 459
Haroldo
  • 36,607
  • 46
  • 127
  • 169
  • 1
    Their response is already JSON - "JSON will be returned in all responses from the API, including errors." from the API docs – tommyd456 Oct 17 '13 at 08:14

7 Answers7

59

PHP has reserved all method names with a double underscore prefix for future use. See https://www.php.net/manual/en/language.oop5.magic.php

Currently, in the latest php-stripe library, you can convert the Stripe Object to JSON by simpl calling **->toJSON().

[PREVIOUSLY]

All objects created by the Stripe PHP API library can be converted to JSON with their __toJSON() methods.

Stripe::setApiKey("sk_xxxxxxxxxxxxxxxxxxxxxxxxx");

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

$customer_json = $customer->__toJSON();

There is also a __toArray($recursive=false) method. Remember to set true as argument otherwise you will get an array filled with stripe objects.

Stripe::setApiKey("sk_xxxxxxxxxxxxxxxxxxxxxxxxx");

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

$customer_array = $customer->__toArray(true);
fjrial
  • 23
  • 8
gevert
  • 682
  • 6
  • 8
4

The attributes of Stripe_Objects can be accessed like this:

$customer->attribute;

So to get the customer's card's last4, you can do this:

$customer->default_card->last4;

However, you'll need to make sure you have the default_card attribute populated. You can retrieve the default_card object at the same time as the rest of the customer by passing the expand argument:

$customer = Stripe_Customer::retrieve(array(
    "id" => "cus_2dVcTSc6ZtHQcv", 
    "expand" => array("default_card")
));
brian
  • 3,344
  • 2
  • 26
  • 35
3

On the latest version, You can use echo $customer->toJSON(); to get the output as JSON.

manas paul
  • 87
  • 7
1

I have done this way

`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'];`
ilidiocn
  • 323
  • 2
  • 5
0

If, like me, you arrived here looking for the python 2.7 solution, simply cast the stripe_object to str(). This triggers the object's inner __str__() function which converts the object into a JSON string.

E.g.

charge = stripe.Charge....
print str(charge)
Luke Madhanga
  • 6,871
  • 2
  • 43
  • 47
-1

Your top level object contains other object instances - the cast to (array) affects only the top level element. You might need to recursively walk down - but I'd do it differently here given that the classes are serializable:

$transfer = serialize($myobject);

What are you going to do with the otherwise JSONified data?

If you're going to transfer an object without the class information you might try to use Reflection:

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

}

This is the base class of most of my transferrable classes. It creates a stdClass object from a class, or initializes a class from a stdClass object. You might easily adopt this to your own needs (e.g. create an array).

ErnestV
  • 117
  • 1
  • 6
  • I'm returning some of the data to a javascript webapp, ie let the customer choose from their saved cards etc.. – Haroldo Oct 16 '13 at 08:50
  • Hmm, i'd like to be able to work with the array/obj in php a bit before serializing (parts of it) to json. Do you know of anyways i can access/manipulate/convert the stripe object without stringifying it? – Haroldo Oct 16 '13 at 08:53
  • If you'd like to work with it before transfer you'd just just keep it as is, no? and finally the JS webapp wouldn't understand the Stripe classes, and you are going to transfer only some of the data. So I believe you must do that instance by instance. But see also the edit to my answer I'm going to post here. – ErnestV Oct 16 '13 at 15:25
-1

This is already in a JSON format so you do need to convert it again into json_encode() just pass it into your script

shaggy
  • 205
  • 3
  • 5