Subscription.php 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306
  1. <?php
  2. // File generated from our OpenAPI spec
  3. namespace Stripe;
  4. /**
  5. * Subscriptions allow you to charge a customer on a recurring basis.
  6. *
  7. * Related guide: <a href="https://stripe.com/docs/billing/subscriptions/creating">Creating subscriptions</a>
  8. *
  9. * @property string $id Unique identifier for the object.
  10. * @property string $object String representing the object's type. Objects of the same type share the same value.
  11. * @property null|string|\Stripe\Application $application ID of the Connect Application that created the subscription.
  12. * @property null|float $application_fee_percent A non-negative decimal between 0 and 100, with at most two decimal places. This represents the percentage of the subscription invoice total that will be transferred to the application owner's Stripe account.
  13. * @property \Stripe\StripeObject $automatic_tax
  14. * @property int $billing_cycle_anchor The reference point that aligns future <a href="https://stripe.com/docs/subscriptions/billing-cycle">billing cycle</a> dates. It sets the day of week for <code>week</code> intervals, the day of month for <code>month</code> and <code>year</code> intervals, and the month of year for <code>year</code> intervals. The timestamp is in UTC format.
  15. * @property null|\Stripe\StripeObject $billing_cycle_anchor_config The fixed values used to calculate the <code>billing_cycle_anchor</code>.
  16. * @property null|\Stripe\StripeObject $billing_thresholds Define thresholds at which an invoice will be sent, and the subscription advanced to a new billing period
  17. * @property null|int $cancel_at A date in the future at which the subscription will automatically get canceled
  18. * @property bool $cancel_at_period_end If the subscription has been canceled with the <code>at_period_end</code> flag set to <code>true</code>, <code>cancel_at_period_end</code> on the subscription will be true. You can use this attribute to determine whether a subscription that has a status of active is scheduled to be canceled at the end of the current period.
  19. * @property null|int $canceled_at If the subscription has been canceled, the date of that cancellation. If the subscription was canceled with <code>cancel_at_period_end</code>, <code>canceled_at</code> will reflect the time of the most recent update request, not the end of the subscription period when the subscription is automatically moved to a canceled state.
  20. * @property null|\Stripe\StripeObject $cancellation_details Details about why this subscription was cancelled
  21. * @property string $collection_method Either <code>charge_automatically</code>, or <code>send_invoice</code>. When charging automatically, Stripe will attempt to pay this subscription at the end of the cycle using the default source attached to the customer. When sending an invoice, Stripe will email your customer an invoice with payment instructions and mark the subscription as <code>active</code>.
  22. * @property int $created Time at which the object was created. Measured in seconds since the Unix epoch.
  23. * @property string $currency Three-letter <a href="https://www.iso.org/iso-4217-currency-codes.html">ISO currency code</a>, in lowercase. Must be a <a href="https://stripe.com/docs/currencies">supported currency</a>.
  24. * @property int $current_period_end End of the current period that the subscription has been invoiced for. At the end of this period, a new invoice will be created.
  25. * @property int $current_period_start Start of the current period that the subscription has been invoiced for.
  26. * @property string|\Stripe\Customer $customer ID of the customer who owns the subscription.
  27. * @property null|int $days_until_due Number of days a customer has to pay invoices generated by this subscription. This value will be <code>null</code> for subscriptions where <code>collection_method=charge_automatically</code>.
  28. * @property null|string|\Stripe\PaymentMethod $default_payment_method ID of the default payment method for the subscription. It must belong to the customer associated with the subscription. This takes precedence over <code>default_source</code>. If neither are set, invoices will use the customer's <a href="https://stripe.com/docs/api/customers/object#customer_object-invoice_settings-default_payment_method">invoice_settings.default_payment_method</a> or <a href="https://stripe.com/docs/api/customers/object#customer_object-default_source">default_source</a>.
  29. * @property null|string|\Stripe\Account|\Stripe\BankAccount|\Stripe\Card|\Stripe\Source $default_source ID of the default payment source for the subscription. It must belong to the customer associated with the subscription and be in a chargeable state. If <code>default_payment_method</code> is also set, <code>default_payment_method</code> will take precedence. If neither are set, invoices will use the customer's <a href="https://stripe.com/docs/api/customers/object#customer_object-invoice_settings-default_payment_method">invoice_settings.default_payment_method</a> or <a href="https://stripe.com/docs/api/customers/object#customer_object-default_source">default_source</a>.
  30. * @property null|\Stripe\TaxRate[] $default_tax_rates The tax rates that will apply to any subscription item that does not have <code>tax_rates</code> set. Invoices created will have their <code>default_tax_rates</code> populated from the subscription.
  31. * @property null|string $description The subscription's description, meant to be displayable to the customer. Use this field to optionally store an explanation of the subscription for rendering in Stripe surfaces and certain local payment methods UIs.
  32. * @property null|\Stripe\Discount $discount Describes the current discount applied to this subscription, if there is one. When billing, a discount applied to a subscription overrides a discount applied on a customer-wide basis. This field has been deprecated and will be removed in a future API version. Use <code>discounts</code> instead.
  33. * @property (string|\Stripe\Discount)[] $discounts The discounts applied to the subscription. Subscription item discounts are applied before subscription discounts. Use <code>expand[]=discounts</code> to expand each discount.
  34. * @property null|int $ended_at If the subscription has ended, the date the subscription ended.
  35. * @property \Stripe\StripeObject $invoice_settings
  36. * @property \Stripe\Collection<\Stripe\SubscriptionItem> $items List of subscription items, each with an attached price.
  37. * @property null|string|\Stripe\Invoice $latest_invoice The most recent invoice this subscription has generated.
  38. * @property bool $livemode Has the value <code>true</code> if the object exists in live mode or the value <code>false</code> if the object exists in test mode.
  39. * @property \Stripe\StripeObject $metadata Set of <a href="https://stripe.com/docs/api/metadata">key-value pairs</a> that you can attach to an object. This can be useful for storing additional information about the object in a structured format.
  40. * @property null|int $next_pending_invoice_item_invoice Specifies the approximate timestamp on which any pending invoice items will be billed according to the schedule provided at <code>pending_invoice_item_interval</code>.
  41. * @property null|string|\Stripe\Account $on_behalf_of The account (if any) the charge was made on behalf of for charges associated with this subscription. See the Connect documentation for details.
  42. * @property null|\Stripe\StripeObject $pause_collection If specified, payment collection for this subscription will be paused. Note that the subscription status will be unchanged and will not be updated to <code>paused</code>. Learn more about <a href="/billing/subscriptions/pause-payment">pausing collection</a>.
  43. * @property null|\Stripe\StripeObject $payment_settings Payment settings passed on to invoices created by the subscription.
  44. * @property null|\Stripe\StripeObject $pending_invoice_item_interval Specifies an interval for how often to bill for any pending invoice items. It is analogous to calling <a href="https://stripe.com/docs/api#create_invoice">Create an invoice</a> for the given subscription at the specified interval.
  45. * @property null|string|\Stripe\SetupIntent $pending_setup_intent You can use this <a href="https://stripe.com/docs/api/setup_intents">SetupIntent</a> to collect user authentication when creating a subscription without immediate payment or updating a subscription's payment method, allowing you to optimize for off-session payments. Learn more in the <a href="https://stripe.com/docs/billing/migration/strong-customer-authentication#scenario-2">SCA Migration Guide</a>.
  46. * @property null|\Stripe\StripeObject $pending_update If specified, <a href="https://stripe.com/docs/billing/subscriptions/pending-updates">pending updates</a> that will be applied to the subscription once the <code>latest_invoice</code> has been paid.
  47. * @property null|string|\Stripe\SubscriptionSchedule $schedule The schedule attached to the subscription
  48. * @property int $start_date Date when the subscription was first created. The date might differ from the <code>created</code> date due to backdating.
  49. * @property string $status <p>Possible values are <code>incomplete</code>, <code>incomplete_expired</code>, <code>trialing</code>, <code>active</code>, <code>past_due</code>, <code>canceled</code>, <code>unpaid</code>, or <code>paused</code>.</p><p>For <code>collection_method=charge_automatically</code> a subscription moves into <code>incomplete</code> if the initial payment attempt fails. A subscription in this status can only have metadata and default_source updated. Once the first invoice is paid, the subscription moves into an <code>active</code> status. If the first invoice is not paid within 23 hours, the subscription transitions to <code>incomplete_expired</code>. This is a terminal status, the open invoice will be voided and no further invoices will be generated.</p><p>A subscription that is currently in a trial period is <code>trialing</code> and moves to <code>active</code> when the trial period is over.</p><p>A subscription can only enter a <code>paused</code> status <a href="/billing/subscriptions/trials#create-free-trials-without-payment">when a trial ends without a payment method</a>. A <code>paused</code> subscription doesn't generate invoices and can be resumed after your customer adds their payment method. The <code>paused</code> status is different from <a href="/billing/subscriptions/pause-payment">pausing collection</a>, which still generates invoices and leaves the subscription's status unchanged.</p><p>If subscription <code>collection_method=charge_automatically</code>, it becomes <code>past_due</code> when payment is required but cannot be paid (due to failed payment or awaiting additional user actions). Once Stripe has exhausted all payment retry attempts, the subscription will become <code>canceled</code> or <code>unpaid</code> (depending on your subscriptions settings).</p><p>If subscription <code>collection_method=send_invoice</code> it becomes <code>past_due</code> when its invoice is not paid by the due date, and <code>canceled</code> or <code>unpaid</code> if it is still not paid by an additional deadline after that. Note that when a subscription has a status of <code>unpaid</code>, no subsequent invoices will be attempted (invoices will be created, but then immediately automatically closed). After receiving updated payment information from a customer, you may choose to reopen and pay their closed invoices.</p>
  50. * @property null|string|\Stripe\TestHelpers\TestClock $test_clock ID of the test clock this subscription belongs to.
  51. * @property null|\Stripe\StripeObject $transfer_data The account (if any) the subscription's payments will be attributed to for tax reporting, and where funds from each payment will be transferred to for each of the subscription's invoices.
  52. * @property null|int $trial_end If the subscription has a trial, the end of that trial.
  53. * @property null|\Stripe\StripeObject $trial_settings Settings related to subscription trials.
  54. * @property null|int $trial_start If the subscription has a trial, the beginning of that trial.
  55. */
  56. class Subscription extends ApiResource
  57. {
  58. const OBJECT_NAME = 'subscription';
  59. use ApiOperations\Update;
  60. const COLLECTION_METHOD_CHARGE_AUTOMATICALLY = 'charge_automatically';
  61. const COLLECTION_METHOD_SEND_INVOICE = 'send_invoice';
  62. const STATUS_ACTIVE = 'active';
  63. const STATUS_CANCELED = 'canceled';
  64. const STATUS_INCOMPLETE = 'incomplete';
  65. const STATUS_INCOMPLETE_EXPIRED = 'incomplete_expired';
  66. const STATUS_PAST_DUE = 'past_due';
  67. const STATUS_PAUSED = 'paused';
  68. const STATUS_TRIALING = 'trialing';
  69. const STATUS_UNPAID = 'unpaid';
  70. /**
  71. * Creates a new subscription on an existing customer. Each customer can have up to
  72. * 500 active or scheduled subscriptions.
  73. *
  74. * When you create a subscription with
  75. * <code>collection_method=charge_automatically</code>, the first invoice is
  76. * finalized as part of the request. The <code>payment_behavior</code> parameter
  77. * determines the exact behavior of the initial payment.
  78. *
  79. * To start subscriptions where the first invoice always begins in a
  80. * <code>draft</code> status, use <a
  81. * href="/docs/billing/subscriptions/subscription-schedules#managing">subscription
  82. * schedules</a> instead. Schedules provide the flexibility to model more complex
  83. * billing configurations that change over time.
  84. *
  85. * @param null|array $params
  86. * @param null|array|string $options
  87. *
  88. * @throws \Stripe\Exception\ApiErrorException if the request fails
  89. *
  90. * @return \Stripe\Subscription the created resource
  91. */
  92. public static function create($params = null, $options = null)
  93. {
  94. self::_validateParams($params);
  95. $url = static::classUrl();
  96. list($response, $opts) = static::_staticRequest('post', $url, $params, $options);
  97. $obj = \Stripe\Util\Util::convertToStripeObject($response->json, $opts);
  98. $obj->setLastResponse($response);
  99. return $obj;
  100. }
  101. /**
  102. * By default, returns a list of subscriptions that have not been canceled. In
  103. * order to list canceled subscriptions, specify <code>status=canceled</code>.
  104. *
  105. * @param null|array $params
  106. * @param null|array|string $opts
  107. *
  108. * @throws \Stripe\Exception\ApiErrorException if the request fails
  109. *
  110. * @return \Stripe\Collection<\Stripe\Subscription> of ApiResources
  111. */
  112. public static function all($params = null, $opts = null)
  113. {
  114. $url = static::classUrl();
  115. return static::_requestPage($url, \Stripe\Collection::class, $params, $opts);
  116. }
  117. /**
  118. * Retrieves the subscription with the given ID.
  119. *
  120. * @param array|string $id the ID of the API resource to retrieve, or an options array containing an `id` key
  121. * @param null|array|string $opts
  122. *
  123. * @throws \Stripe\Exception\ApiErrorException if the request fails
  124. *
  125. * @return \Stripe\Subscription
  126. */
  127. public static function retrieve($id, $opts = null)
  128. {
  129. $opts = \Stripe\Util\RequestOptions::parse($opts);
  130. $instance = new static($id, $opts);
  131. $instance->refresh();
  132. return $instance;
  133. }
  134. /**
  135. * Updates an existing subscription to match the specified parameters. When
  136. * changing prices or quantities, we optionally prorate the price we charge next
  137. * month to make up for any price changes. To preview how the proration is
  138. * calculated, use the <a href="/docs/api/invoices/upcoming">upcoming invoice</a>
  139. * endpoint.
  140. *
  141. * By default, we prorate subscription changes. For example, if a customer signs up
  142. * on May 1 for a <currency>100</currency> price, they’ll be billed
  143. * <currency>100</currency> immediately. If on May 15 they switch to a
  144. * <currency>200</currency> price, then on June 1 they’ll be billed
  145. * <currency>250</currency> (<currency>200</currency> for a renewal of her
  146. * subscription, plus a <currency>50</currency> prorating adjustment for half of
  147. * the previous month’s <currency>100</currency> difference). Similarly, a
  148. * downgrade generates a credit that is applied to the next invoice. We also
  149. * prorate when you make quantity changes.
  150. *
  151. * Switching prices does not normally change the billing date or generate an
  152. * immediate charge unless:
  153. *
  154. * <ul> <li>The billing interval is changed (for example, from monthly to
  155. * yearly).</li> <li>The subscription moves from free to paid, or paid to
  156. * free.</li> <li>A trial starts or ends.</li> </ul>
  157. *
  158. * In these cases, we apply a credit for the unused time on the previous price,
  159. * immediately charge the customer using the new price, and reset the billing date.
  160. *
  161. * If you want to charge for an upgrade immediately, pass
  162. * <code>proration_behavior</code> as <code>always_invoice</code> to create
  163. * prorations, automatically invoice the customer for those proration adjustments,
  164. * and attempt to collect payment. If you pass <code>create_prorations</code>, the
  165. * prorations are created but not automatically invoiced. If you want to bill the
  166. * customer for the prorations before the subscription’s renewal date, you need to
  167. * manually <a href="/docs/api/invoices/create">invoice the customer</a>.
  168. *
  169. * If you don’t want to prorate, set the <code>proration_behavior</code> option to
  170. * <code>none</code>. With this option, the customer is billed
  171. * <currency>100</currency> on May 1 and <currency>200</currency> on June 1.
  172. * Similarly, if you set <code>proration_behavior</code> to <code>none</code> when
  173. * switching between different billing intervals (for example, from monthly to
  174. * yearly), we don’t generate any credits for the old subscription’s unused time.
  175. * We still reset the billing date and bill immediately for the new subscription.
  176. *
  177. * Updating the quantity on a subscription many times in an hour may result in <a
  178. * href="/docs/rate-limits">rate limiting</a>. If you need to bill for a frequently
  179. * changing quantity, consider integrating <a
  180. * href="/docs/billing/subscriptions/usage-based">usage-based billing</a> instead.
  181. *
  182. * @param string $id the ID of the resource to update
  183. * @param null|array $params
  184. * @param null|array|string $opts
  185. *
  186. * @throws \Stripe\Exception\ApiErrorException if the request fails
  187. *
  188. * @return \Stripe\Subscription the updated resource
  189. */
  190. public static function update($id, $params = null, $opts = null)
  191. {
  192. self::_validateParams($params);
  193. $url = static::resourceUrl($id);
  194. list($response, $opts) = static::_staticRequest('post', $url, $params, $opts);
  195. $obj = \Stripe\Util\Util::convertToStripeObject($response->json, $opts);
  196. $obj->setLastResponse($response);
  197. return $obj;
  198. }
  199. use ApiOperations\Delete {
  200. delete as protected _delete;
  201. }
  202. public static function getSavedNestedResources()
  203. {
  204. static $savedNestedResources = null;
  205. if (null === $savedNestedResources) {
  206. $savedNestedResources = new Util\Set([
  207. 'source',
  208. ]);
  209. }
  210. return $savedNestedResources;
  211. }
  212. /**
  213. * @param null|array $params
  214. * @param null|array|string $opts
  215. *
  216. * @throws \Stripe\Exception\ApiErrorException if the request fails
  217. *
  218. * @return \Stripe\Subscription the updated subscription
  219. */
  220. public function deleteDiscount($params = null, $opts = null)
  221. {
  222. $url = $this->instanceUrl() . '/discount';
  223. list($response, $opts) = $this->_request('delete', $url, $params, $opts);
  224. $this->refreshFrom(['discount' => null], $opts, true);
  225. return $this;
  226. }
  227. const PAYMENT_BEHAVIOR_ALLOW_INCOMPLETE = 'allow_incomplete';
  228. const PAYMENT_BEHAVIOR_DEFAULT_INCOMPLETE = 'default_incomplete';
  229. const PAYMENT_BEHAVIOR_ERROR_IF_INCOMPLETE = 'error_if_incomplete';
  230. const PAYMENT_BEHAVIOR_PENDING_IF_INCOMPLETE = 'pending_if_incomplete';
  231. const PRORATION_BEHAVIOR_ALWAYS_INVOICE = 'always_invoice';
  232. const PRORATION_BEHAVIOR_CREATE_PRORATIONS = 'create_prorations';
  233. const PRORATION_BEHAVIOR_NONE = 'none';
  234. /**
  235. * @param null|array $params
  236. * @param null|array|string $opts
  237. *
  238. * @throws \Stripe\Exception\ApiErrorException if the request fails
  239. *
  240. * @return \Stripe\Subscription the canceled subscription
  241. */
  242. public function cancel($params = null, $opts = null)
  243. {
  244. $url = $this->instanceUrl();
  245. list($response, $opts) = $this->_request('delete', $url, $params, $opts);
  246. $this->refreshFrom($response, $opts);
  247. return $this;
  248. }
  249. /**
  250. * @param null|array $params
  251. * @param null|array|string $opts
  252. *
  253. * @throws \Stripe\Exception\ApiErrorException if the request fails
  254. *
  255. * @return \Stripe\Subscription the resumed subscription
  256. */
  257. public function resume($params = null, $opts = null)
  258. {
  259. $url = $this->instanceUrl() . '/resume';
  260. list($response, $opts) = $this->_request('post', $url, $params, $opts);
  261. $this->refreshFrom($response, $opts);
  262. return $this;
  263. }
  264. /**
  265. * @param null|array $params
  266. * @param null|array|string $opts
  267. *
  268. * @throws \Stripe\Exception\ApiErrorException if the request fails
  269. *
  270. * @return \Stripe\SearchResult<\Stripe\Subscription> the subscription search results
  271. */
  272. public static function search($params = null, $opts = null)
  273. {
  274. $url = '/v1/subscriptions/search';
  275. return static::_requestPage($url, \Stripe\SearchResult::class, $params, $opts);
  276. }
  277. }