Struct stripe::Subscription
source · [−]pub struct Subscription {Show 38 fields
pub id: SubscriptionId,
pub application: Option<Expandable<Application>>,
pub application_fee_percent: Option<f64>,
pub automatic_tax: SubscriptionAutomaticTax,
pub billing_cycle_anchor: Timestamp,
pub billing_thresholds: Option<SubscriptionBillingThresholds>,
pub cancel_at: Option<Timestamp>,
pub cancel_at_period_end: bool,
pub canceled_at: Option<Timestamp>,
pub collection_method: Option<CollectionMethod>,
pub created: Timestamp,
pub current_period_end: Timestamp,
pub current_period_start: Timestamp,
pub customer: Expandable<Customer>,
pub days_until_due: Option<u32>,
pub default_payment_method: Option<Expandable<PaymentMethod>>,
pub default_source: Option<Expandable<PaymentSource>>,
pub default_tax_rates: Option<Vec<TaxRate>>,
pub description: Option<String>,
pub discount: Option<Discount>,
pub ended_at: Option<Timestamp>,
pub items: List<SubscriptionItem>,
pub latest_invoice: Option<Expandable<Invoice>>,
pub livemode: bool,
pub metadata: Metadata,
pub next_pending_invoice_item_invoice: Option<Timestamp>,
pub pause_collection: Option<SubscriptionsResourcePauseCollection>,
pub payment_settings: Option<SubscriptionsResourcePaymentSettings>,
pub pending_invoice_item_interval: Option<SubscriptionPendingInvoiceItemInterval>,
pub pending_setup_intent: Option<Expandable<SetupIntent>>,
pub pending_update: Option<SubscriptionsResourcePendingUpdate>,
pub schedule: Option<Expandable<SubscriptionSchedule>>,
pub start_date: Timestamp,
pub status: SubscriptionStatus,
pub test_clock: Option<Expandable<TestHelpersTestClock>>,
pub transfer_data: Option<SubscriptionTransferData>,
pub trial_end: Option<Timestamp>,
pub trial_start: Option<Timestamp>,
}
Expand description
The resource representing a Stripe “Subscription”.
For more details see https://stripe.com/docs/api/subscriptions/object
Fields
id: SubscriptionId
Unique identifier for the object.
application: Option<Expandable<Application>>
ID of the Connect Application that created the subscription.
application_fee_percent: Option<f64>
A non-negative decimal between 0 and 100, with at most two decimal places.
This represents the percentage of the subscription invoice subtotal that will be transferred to the application owner’s Stripe account.
automatic_tax: SubscriptionAutomaticTax
billing_cycle_anchor: Timestamp
Determines the date of the first full invoice, and, for plans with month
or year
intervals, the day of the month for subsequent invoices.
billing_thresholds: Option<SubscriptionBillingThresholds>
Define thresholds at which an invoice will be sent, and the subscription advanced to a new billing period.
cancel_at: Option<Timestamp>
A date in the future at which the subscription will automatically get canceled.
cancel_at_period_end: bool
If the subscription has been canceled with the at_period_end
flag set to true
, cancel_at_period_end
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.
canceled_at: Option<Timestamp>
If the subscription has been canceled, the date of that cancellation.
If the subscription was canceled with cancel_at_period_end
, canceled_at
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.
collection_method: Option<CollectionMethod>
Either charge_automatically
, or send_invoice
.
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.
created: Timestamp
Time at which the object was created.
Measured in seconds since the Unix epoch.
current_period_end: Timestamp
End of the current period that the subscription has been invoiced for.
At the end of this period, a new invoice will be created.
current_period_start: Timestamp
Start of the current period that the subscription has been invoiced for.
customer: Expandable<Customer>
ID of the customer who owns the subscription.
days_until_due: Option<u32>
Number of days a customer has to pay invoices generated by this subscription.
This value will be null
for subscriptions where collection_method=charge_automatically
.
default_payment_method: Option<Expandable<PaymentMethod>>
ID of the default payment method for the subscription.
It must belong to the customer associated with the subscription.
This takes precedence over default_source
.
If neither are set, invoices will use the customer’s invoice_settings.default_payment_method or default_source.
default_source: Option<Expandable<PaymentSource>>
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 default_payment_method
is also set, default_payment_method
will take precedence.
If neither are set, invoices will use the customer’s invoice_settings.default_payment_method or default_source.
default_tax_rates: Option<Vec<TaxRate>>
The tax rates that will apply to any subscription item that does not have tax_rates
set.
Invoices created will have their default_tax_rates
populated from the subscription.
description: Option<String>
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.
discount: Option<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.
ended_at: Option<Timestamp>
If the subscription has ended, the date the subscription ended.
items: List<SubscriptionItem>
List of subscription items, each with an attached price.
latest_invoice: Option<Expandable<Invoice>>
The most recent invoice this subscription has generated.
livemode: bool
Has the value true
if the object exists in live mode or the value false
if the object exists in test mode.
metadata: Metadata
Set of key-value pairs that you can attach to an object.
This can be useful for storing additional information about the object in a structured format.
next_pending_invoice_item_invoice: Option<Timestamp>
Specifies the approximate timestamp on which any pending invoice items will be billed according to the schedule provided at pending_invoice_item_interval
.
pause_collection: Option<SubscriptionsResourcePauseCollection>
If specified, payment collection for this subscription will be paused.
payment_settings: Option<SubscriptionsResourcePaymentSettings>
Payment settings passed on to invoices created by the subscription.
pending_invoice_item_interval: Option<SubscriptionPendingInvoiceItemInterval>
Specifies an interval for how often to bill for any pending invoice items.
It is analogous to calling Create an invoice for the given subscription at the specified interval.
pending_setup_intent: Option<Expandable<SetupIntent>>
You can use this SetupIntent 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 SCA Migration Guide.
pending_update: Option<SubscriptionsResourcePendingUpdate>
If specified, pending updates that will be applied to the subscription once the latest_invoice
has been paid.
schedule: Option<Expandable<SubscriptionSchedule>>
The schedule attached to the subscription.
start_date: Timestamp
Date when the subscription was first created.
The date might differ from the created
date due to backdating.
status: SubscriptionStatus
Possible values are incomplete
, incomplete_expired
, trialing
, active
, past_due
, canceled
, or unpaid
.
For collection_method=charge_automatically
a subscription moves into incomplete
if the initial payment attempt fails.
A subscription in this state can only have metadata and default_source updated.
Once the first invoice is paid, the subscription moves into an active
state.
If the first invoice is not paid within 23 hours, the subscription transitions to incomplete_expired
.
This is a terminal state, the open invoice will be voided and no further invoices will be generated.
A subscription that is currently in a trial period is trialing
and moves to active
when the trial period is over.
If subscription collection_method=charge_automatically
it becomes past_due
when payment to renew it fails and canceled
or unpaid
(depending on your subscriptions settings) when Stripe has exhausted all payment retry attempts.
If subscription collection_method=send_invoice
it becomes past_due
when its invoice is not paid by the due date, and canceled
or unpaid
if it is still not paid by an additional deadline after that.
Note that when a subscription has a status of unpaid
, 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.
test_clock: Option<Expandable<TestHelpersTestClock>>
ID of the test clock this subscription belongs to.
transfer_data: Option<SubscriptionTransferData>
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.
trial_end: Option<Timestamp>
If the subscription has a trial, the end of that trial.
trial_start: Option<Timestamp>
If the subscription has a trial, the beginning of that trial.
Implementations
sourceimpl Subscription
impl Subscription
sourcepub fn list(
client: &Client,
params: &ListSubscriptions<'_>
) -> Response<List<Subscription>>
pub fn list(
client: &Client,
params: &ListSubscriptions<'_>
) -> Response<List<Subscription>>
By default, returns a list of subscriptions that have not been canceled.
In order to list canceled subscriptions, specify status=canceled
.
sourcepub fn create(
client: &Client,
params: CreateSubscription<'_>
) -> Response<Subscription>
pub fn create(
client: &Client,
params: CreateSubscription<'_>
) -> Response<Subscription>
Creates a new subscription on an existing customer.
Each customer can have up to 500 active or scheduled subscriptions. When you create a subscription with collection_method=charge_automatically
, the first invoice is finalized as part of the request. The payment_behavior
parameter determines the exact behavior of the initial payment. To start subscriptions where the first invoice always begins in a draft
status, use subscription schedules instead. Schedules provide the flexibility to model more complex billing configurations that change over time.
Examples found in repository?
17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130
async fn main() {
let secret_key = std::env::var("STRIPE_SECRET_KEY").expect("Missing STRIPE_SECRET_KEY in env");
let client = Client::new(secret_key);
let customer = Customer::create(
&client,
CreateCustomer {
name: Some("Alexander Lyon"),
email: Some("test@async-stripe.com"),
description: Some(
"A fake customer that is used to illustrate the examples in async-stripe.",
),
metadata: Some(
[("async-stripe".to_string(), "true".to_string())].iter().cloned().collect(),
),
..Default::default()
},
)
.await
.unwrap();
println!("created a customer at https://dashboard.stripe.com/test/customers/{}", customer.id);
let payment_method = {
let pm = PaymentMethod::create(
&client,
CreatePaymentMethod {
type_: Some(PaymentMethodTypeFilter::Card),
card: Some(CreatePaymentMethodCardUnion::CardDetailsParams(CardDetailsParams {
number: "4000008260000000".to_string(), // UK visa
exp_year: 2025,
exp_month: 1,
cvc: Some("123".to_string()),
..Default::default()
})),
..Default::default()
},
)
.await
.unwrap();
PaymentMethod::attach(
&client,
&pm.id,
AttachPaymentMethod { customer: customer.id.clone() },
)
.await
.unwrap();
pm
};
println!(
"created a payment method with id {} and attached it to {}",
payment_method.id,
customer.name.unwrap()
);
// create a new exmaple project
let product = {
let mut create_product = CreateProduct::new("Monthly T-Shirt Subscription");
create_product.metadata =
Some([("async-stripe".to_string(), "true".to_string())].iter().cloned().collect());
Product::create(&client, create_product).await.unwrap()
};
// and add a price for it in USD
let price = {
let mut create_price = CreatePrice::new(Currency::USD);
create_price.product = Some(IdOrCreate::Id(&product.id));
create_price.metadata =
Some([("async-stripe".to_string(), "true".to_string())].iter().cloned().collect());
create_price.unit_amount = Some(1000);
create_price.recurring = Some(CreatePriceRecurring {
interval: CreatePriceRecurringInterval::Month,
..Default::default()
});
create_price.expand = &["product"];
Price::create(&client, create_price).await.unwrap()
};
println!(
"created a product {:?} at price {} {}",
product.name.unwrap(),
price.unit_amount.unwrap() / 100,
price.currency.unwrap()
);
let subscription = {
let mut params = CreateSubscription::new(customer.id);
params.items = Some(vec![CreateSubscriptionItems {
price: Some(price.id.to_string()),
..Default::default()
}]);
params.default_payment_method = Some(&payment_method.id);
params.expand = &["items", "items.data.price.product", "schedule"];
Subscription::create(&client, params).await.unwrap()
};
println!(
"created a {} subscription for {:?} for {} {} per {} at https://dashboard.stripe.com/test/subscriptions/{}",
subscription.status,
match subscription.items.data[0].price.as_ref().unwrap().product.as_ref().unwrap() {
Expandable::Object(p) => p.name.as_ref().unwrap(),
_ => panic!("product not found"),
},
subscription.items.data[0].price.as_ref().unwrap().unit_amount.unwrap() / 100,
subscription.items.data[0].price.as_ref().unwrap().currency.unwrap(),
subscription.items.data[0].price.as_ref().unwrap().recurring.as_ref().unwrap().interval,
subscription.id
);
}
sourcepub fn retrieve(
client: &Client,
id: &SubscriptionId,
expand: &[&str]
) -> Response<Subscription>
pub fn retrieve(
client: &Client,
id: &SubscriptionId,
expand: &[&str]
) -> Response<Subscription>
Retrieves the subscription with the given ID.
sourcepub fn update(
client: &Client,
id: &SubscriptionId,
params: UpdateSubscription<'_>
) -> Response<Subscription>
pub fn update(
client: &Client,
id: &SubscriptionId,
params: UpdateSubscription<'_>
) -> Response<Subscription>
Updates an existing subscription on a customer to match the specified parameters.
When changing plans or quantities, we will optionally prorate the price we charge next month to make up for any price changes. To preview how the proration will be calculated, use the upcoming invoice endpoint.
sourcepub fn delete(
client: &Client,
id: &SubscriptionId
) -> Response<Deleted<SubscriptionId>>
pub fn delete(
client: &Client,
id: &SubscriptionId
) -> Response<Deleted<SubscriptionId>>
Cancels a customer’s subscription immediately.
The customer will not be charged again for the subscription. Note, however, that any pending invoice items that you’ve created will still be charged for at the end of the period, unless manually deleted. If you’ve set the subscription to cancel at the end of the period, any pending prorations will also be left in place and collected at the end of the period. But if the subscription is set to cancel immediately, pending prorations will be removed. By default, upon subscription cancellation, Stripe will stop automatic collection of all finalized invoices for the customer. This is intended to prevent unexpected payment attempts after the customer has canceled a subscription. However, you can resume automatic collection of the invoices manually after subscription cancellation to have us proceed. Or, you could check for unpaid invoices before allowing the customer to cancel the subscription at all.
sourceimpl Subscription
impl Subscription
sourcepub fn cancel(
client: &Client,
subscription_id: &SubscriptionId,
params: CancelSubscription
) -> Response<Subscription>
pub fn cancel(
client: &Client,
subscription_id: &SubscriptionId,
params: CancelSubscription
) -> Response<Subscription>
Cancels a subscription.
For more details see https://stripe.com/docs/api#cancel_subscription.
Trait Implementations
sourceimpl Clone for Subscription
impl Clone for Subscription
sourcefn clone(&self) -> Subscription
fn clone(&self) -> Subscription
Returns a copy of the value. Read more
1.0.0 · sourcefn clone_from(&mut self, source: &Self)
fn clone_from(&mut self, source: &Self)
Performs copy-assignment from source
. Read more
sourceimpl Debug for Subscription
impl Debug for Subscription
sourceimpl Default for Subscription
impl Default for Subscription
sourcefn default() -> Subscription
fn default() -> Subscription
Returns the “default value” for a type. Read more
sourceimpl<'de> Deserialize<'de> for Subscription
impl<'de> Deserialize<'de> for Subscription
sourcefn deserialize<__D>(__deserializer: __D) -> Result<Self, __D::Error> where
__D: Deserializer<'de>,
fn deserialize<__D>(__deserializer: __D) -> Result<Self, __D::Error> where
__D: Deserializer<'de>,
Deserialize this value from the given Serde deserializer. Read more
sourceimpl Object for Subscription
impl Object for Subscription
sourceimpl Serialize for Subscription
impl Serialize for Subscription
Auto Trait Implementations
impl RefUnwindSafe for Subscription
impl Send for Subscription
impl Sync for Subscription
impl Unpin for Subscription
impl UnwindSafe for Subscription
Blanket Implementations
sourceimpl<T> BorrowMut<T> for T where
T: ?Sized,
impl<T> BorrowMut<T> for T where
T: ?Sized,
const: unstable · sourcefn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Mutably borrows from an owned value. Read more
sourceimpl<T> Instrument for T
impl<T> Instrument for T
sourcefn instrument(self, span: Span) -> Instrumented<Self>
fn instrument(self, span: Span) -> Instrumented<Self>
sourcefn in_current_span(self) -> Instrumented<Self>
fn in_current_span(self) -> Instrumented<Self>
impl<V, T> VZip<V> for T where
V: MultiLane<T>,
impl<V, T> VZip<V> for T where
V: MultiLane<T>,
fn vzip(self) -> V
sourceimpl<T> WithSubscriber for T
impl<T> WithSubscriber for T
sourcefn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> where
S: Into<Dispatch>,
fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> where
S: Into<Dispatch>,
Attaches the provided Subscriber
to this type, returning a
WithDispatch
wrapper. Read more
sourcefn with_current_subscriber(self) -> WithDispatch<Self>
fn with_current_subscriber(self) -> WithDispatch<Self>
Attaches the current default Subscriber
to this type, returning a
WithDispatch
wrapper. Read more