Convert Stripe API response to JSON using stripe-php library

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!

Answers


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

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")
));

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)

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).


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


Need Your Help

Find unique values in a Pandas dataframe, irrespective of row or column location

python pandas dataframe

I have a Pandas dataframe and I want to find all the unique values in that dataframe...irrespective of row/columns. If I have a 10 x 10 dataframe, and suppose they have 84 unique values, I need to ...

Disable landscape orientation for iOS 7 application?

ios landscape-portrait

First time developer and have just setup the certificates to be able to run my application on an iOS device.