Я начинаю работать с JSON, поэтому, пожалуйста, несите меня. В принципе, я получаю этот массив JSON обратно из Stripe, что отлично (и я не верю, что в нем есть какая-то конфиденциальная информация, так как это тестовая учетная запись с фиктивным номером кредитной карты и не указанными ключами).
В принципе, на данный момент я был бы доволен любым методом получения следующих отдельных данных: current_period_end
Вот массив, когда я dd():
Customer {#270 ▼
#_opts: RequestOptions {#225 }
#_values: array:15 [▼
"id" => "cus_6slA9S24KBk8qK"
"object" => "customer"
"created" => 1440817503
"livemode" => false
"description" => null
"email" => null
"shipping" => null
"delinquent" => false
"metadata" => AttachedObject {#276 }
"subscriptions" => Collection {#257 ▼
#_opts: RequestOptions {#225 }
#_values: array:5 [▼
"object" => "list"
"total_count" => 1
"has_more" => false
"url" => "/v1/customers/cus_6slA9S24KBk8qK/subscriptions"
"data" => array:1 [▼
0 => Subscription {#249 ▼
#_opts: RequestOptions {#225 }
#_values: array:18 [▼
"id" => "sub_6slAE9UNlCLi24"
"plan" => Plan {#293 }
"object" => "subscription"
"start" => 1440817504
"status" => "trialing"
"customer" => "cus_6slA9S24KBk8qK"
"cancel_at_period_end" => false
"current_period_start" => 1440817504
"current_period_end" => 1441422304
"ended_at" => null
"trial_start" => 1440817504
"trial_end" => 1441422304
"canceled_at" => null
"quantity" => 1
"application_fee_percent" => null
"discount" => null
"tax_percent" => null
"metadata" => AttachedObject {#255 }
]
#_unsavedValues: Set {#294 }
#_transientValues: Set {#289 }
#_retrieveOptions: []
}
]
]
#_unsavedValues: Set {#280 }
#_transientValues: Set {#272 }
#_retrieveOptions: []
}
"discount" => null
"account_balance" => 0
"currency" => "usd"
"sources" => Collection {#260 ▼
#_opts: RequestOptions {#225 }
#_values: array:5 [▼
"object" => "list"
"total_count" => 1
"has_more" => false
"url" => "/v1/customers/cus_6slA9S24KBk8qK/sources"
"data" => array:1 [▼
0 => Card {#322 ▼
#_opts: RequestOptions {#225 }
#_values: array:23 [▼
"id" => "card_16ezeJKTaUqqkEkTmcBfksKh"
"object" => "card"
"last4" => "4242"
"brand" => "Visa"
"funding" => "credit"
"exp_month" => 10
"exp_year" => 2017
"fingerprint" => "Y1GhThZ3NCmHOdTv"
"country" => "US"
"name" => "[email protected]"
"address_line1" => null
"address_line2" => null
"address_city" => null
"address_state" => null
"address_zip" => null
"address_country" => null
"cvc_check" => null
"address_line1_check" => null
"address_zip_check" => null
"tokenization_method" => null
"dynamic_last4" => null
"metadata" => AttachedObject {#335 ▼
#_opts: RequestOptions {#225 }
#_values: []
#_unsavedValues: Set {#339 }
#_transientValues: Set {#340 }
#_retrieveOptions: []
}
"customer" => "cus_6slA9S24KBk8qK"
]
#_unsavedValues: Set {#336 }
#_transientValues: Set {#337 }
#_retrieveOptions: []
}
]
]
#_unsavedValues: Set {#321 }
#_transientValues: Set {#332 }
#_retrieveOptions: []
}
"default_source" => "card_16ezeJKTaUqqkEkTmcBfksKh"
]
#_unsavedValues: Set {#269 }
#_transientValues: Set {#288 }
#_retrieveOptions: []
}
Вот как это выглядит, просто повторяя это:
Stripe\Customer JSON: { "id": "cus_6smHAG99OncrSm", "object": "customer", "created": 1440821625, "livemode": false, "description": null, "email": null, "shipping": null, "delinquent": false, "metadata": [], "subscriptions": { "object": "list", "total_count": 1, "has_more": false, "url": "\/v1\/customers\/cus_6smHAG99OncrSm\/subscriptions", "data": [ { "id": "sub_6smHbsmTA6JhrP", "plan": { "id": "yearly", "interval": "year", "name": "yearly", "created": 1439229255, "amount": 5000, "currency": "usd", "object": "plan", "livemode": false, "interval_count": 1, "trial_period_days": 7, "metadata": [], "statement_descriptor": "Degree Tracker yearly" }, "object": "subscription", "start": 1440821627, "status": "trialing", "customer": "cus_6smHAG99OncrSm", "cancel_at_period_end": false, "current_period_start": 1440821627, "current_period_end": 1441426427, "ended_at": null, "trial_start": 1440821627, "trial_end": 1441426427, "canceled_at": null, "quantity": 1, "application_fee_percent": null, "discount": null, "tax_percent": null, "metadata": [] } ] }, "discount": null, "account_balance": 0, "currency": "usd", "sources": { "object": "list", "total_count": 1, "has_more": false, "url": "\/v1\/customers\/cus_6smHAG99OncrSm\/sources", "data": [ { "id": "card_16f0ioKTaUqqkEkT7osN0knY", "object": "card", "last4": "4242", "brand": "Visa", "funding": "credit", "exp_month": 10, "exp_year": 2017, "fingerprint": "Y1GhThZ3NCmHOdTv", "country": "US", "name": "[email protected]", "address_line1": null, "address_line2": null, "address_city": null, "address_state": null, "address_zip": null, "address_country": null, "cvc_check": null, "address_line1_check": null, "address_zip_check": null, "tokenization_method": null, "dynamic_last4": null, "metadata": [], "customer": "cus_6smHAG99OncrSm" } ] }, "default_source": "card_16f0ioKTaUqqkEkT7osN0knY" }
Выше, наверное, достаточно, чтобы найти мне простое решение моей проблемы. Однако, вот еще несколько дополнительных дополнительных материалов, которые могут помочь вам найти решение, если вы знакомы с Laravel и Cashier
Я могу вытащить пару значений из ответа JSON, который я получаю, например, значение "last4" (последние четыре цифры кредитной карты), делая следующее:
$this_customer = \Stripe\Customer::retrieve($user->stripe_id);
$last_four = $this_customer->sources->retrieve($this_customer->default_source)->last4;
и я также могу получить значение "exp_year", делая что-то очень похожее:
$this_customer = \Stripe\Customer::retrieve($user->stripe_id); //This is the first billing date
$expiration_year = $this_customer->sources->retrieve($this_customer->default_source)->exp_year;
Однако мне не удалось получить значение current_period_end. Вот что я пробовал:
$this_customer = \Stripe\Customer::retrieve($user->stripe_id); //This is the first billing date
$expiration_year = $this_customer->subscriptions->retrieve($this_customer->default_source)->current_period_end;
Одна из причин проблемы, с которой я столкнулся, вероятно, что JSON, который возвращается мне, подает подписок "массив находится в другом месте от массива" sources ". Однако я некоторое время стучал головой о стену пытаясь понять, как исправить мой код для доступа к нему, хотя я уверен, что существует более 1 простого решения вышеупомянутой проблемы.
<?php
$json = '{ "id": "cus_6smHAG99OncrSm", "object": "customer", "created": 1440821625, "livemode": false, "description": null, "email": null, "shipping": null, "delinquent": false, "metadata": [], "subscriptions": { "object": "list", "total_count": 1, "has_more": false, "url": "\/v1\/customers\/cus_6smHAG99OncrSm\/subscriptions", "data": [ { "id": "sub_6smHbsmTA6JhrP", "plan": { "id": "yearly", "interval": "year", "name": "yearly", "created": 1439229255, "amount": 5000, "currency": "usd", "object": "plan", "livemode": false, "interval_count": 1, "trial_period_days": 7, "metadata": [], "statement_descriptor": "Degree Tracker yearly" }, "object": "subscription", "start": 1440821627, "status": "trialing", "customer": "cus_6smHAG99OncrSm", "cancel_at_period_end": false, "current_period_start": 1440821627, "current_period_end": 1441426427, "ended_at": null, "trial_start": 1440821627, "trial_end": 1441426427, "canceled_at": null, "quantity": 1, "application_fee_percent": null, "discount": null, "tax_percent": null, "metadata": [] } ] }, "discount": null, "account_balance": 0, "currency": "usd", "sources": { "object": "list", "total_count": 1, "has_more": false, "url": "\/v1\/customers\/cus_6smHAG99OncrSm\/sources", "data": [ { "id": "card_16f0ioKTaUqqkEkT7osN0knY", "object": "card", "last4": "4242", "brand": "Visa", "funding": "credit", "exp_month": 10, "exp_year": 2017, "fingerprint": "Y1GhThZ3NCmHOdTv", "country": "US", "name": "[email protected]", "address_line1": null, "address_line2": null, "address_city": null, "address_state": null, "address_zip": null, "address_country": null, "cvc_check": null, "address_line1_check": null, "address_zip_check": null, "tokenization_method": null, "dynamic_last4": null, "metadata": [], "customer": "cus_6smHAG99OncrSm" } ] }, "default_source": "card_16f0ioKTaUqqkEkT7osN0knY" }';
$data = json_decode($json, true);
$current_period_end = $data['subscriptions']['data'][0]['current_period_end'];
print_r($current_period_end);
Вывод:
1441426427
И, наконец, дату, когда вы можете получить дату с этим кодом:
echo date('Y-m-d', $current_period_end);
Дата:
2015-09-05