Haroldo
Haroldo

Reputation: 37377

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

Upvotes: 15

Views: 22150

Answers (7)

ilidiocn
ilidiocn

Reputation: 390

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

Upvotes: 1

manas paul
manas paul

Reputation: 87

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

Upvotes: 3

gevert
gevert

Reputation: 682

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

Upvotes: 59

Luke Madhanga
Luke Madhanga

Reputation: 7457

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)

Upvotes: 0

shaggy
shaggy

Reputation: 205

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

Upvotes: -1

ErnestV
ErnestV

Reputation: 137

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

Upvotes: -1

brian
brian

Reputation: 3394

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

Upvotes: 4

Related Questions