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] => [email protected]
            [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!

1
  • 1
    Their response is already JSON - "JSON will be returned in all responses from the API, including errors." from the API docs Commented Oct 17, 2013 at 8:14

7 Answers 7

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);
Sign up to request clarification or add additional context in comments.

4 Comments

This answer does exactly what the OP asked for. I found it helpful as well. Thanks.
__toArray() returns a great deal of junk as compared with __toJSON().
Simply awesome!
Out of __toArray and __toJSON, what are the pros and cons other than "returns a great deal of junk"?
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")
));

Comments

3

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

Comments

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'];`

Comments

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)

Comments

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

3 Comments

I'm returning some of the data to a javascript webapp, ie let the customer choose from their saved cards etc..
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?
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.
-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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.