简体   繁体   中英

Stripe API: Accessing Coupon Data

I'm trying to get the coupon id from a customer record using the Stripe API. I think I'm referencing it the wrong way. I've tried this:

 $cust = \Stripe\Customer::all(array("limit" => 3));

    if(!empty($cust)){

        foreach ($cust->data as $customer){

           foreach ($customer->subscriptions as $sub)
           {
                echo $sub->discount->coupon->id;

            } 

        }     
    }else{
        //No Customers
    }

As recommended above, you're outputting a variable with single quotes around it, which will output that string literally vs inserting the contents of the $sub->discount->coupon->id variable in the string. Either remove the single quotes or, if you fancy string interpolation, replace what you have with echo "{$sub->discount->coupon->id}";

You also need to loop over $customer->subscriptions->data as the subscriptions array has the same shape as the customers array:

$cust = \Stripe\Customer::all(array("limit" => 3, "expand" => "data.subscriptions"));

if(!empty($cust)){

    foreach ($cust->data as $customer){

       foreach ($customer->subscriptions->data as $sub)
       {
            if ($sub->discount && $sub->discount->coupon) {
               echo $sub->discount->coupon->id . "\n";
            }
       } 

    }

} else {
    // No Customers
}

I also added an if statement to avoid errors when $sub->discount or $sub->discount->coupon are null.

Have a look at the example output here: https://stripe.com/docs/api#retrieve_subscription

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM