### Install and Run stripe-mock Source: https://github.com/stripe/stripe-dotnet/blob/master/README.md Install `stripe-mock` using `go install` and run it in a background terminal to facilitate local testing. This is a dependency for the test suite. ```sh go install github.com/stripe/stripe-mock@latest stripe-mock ``` -------------------------------- ### Install Public Preview SDK Source: https://github.com/stripe/stripe-dotnet/blob/master/README.md Install a public preview version of the stripe-dotnet package using the dotnet add package command. Replace the version with your choice. ```bash dotnet add package Stripe.net --version ``` -------------------------------- ### ListOptions Pagination Example Source: https://github.com/stripe/stripe-dotnet/blob/master/_autodocs/types.md Example of using ListOptions to specify the number of items per page and a cursor for forward pagination. ```csharp var options = new CustomerListOptions { Limit = 50, StartingAfter = "cus_123" }; var page = client.V1.Customers.List(options); ``` -------------------------------- ### Create Customer - Minimal Source: https://github.com/stripe/stripe-dotnet/blob/master/_autodocs/api-reference/customer-service.md Use this minimal example for quick customer creation when only an email is required. ```csharp // Minimal customer creation var customer = client.V1.Customers.Create(new CustomerCreateOptions { Email = "customer@example.com" }); ``` -------------------------------- ### Customer Creation Example Source: https://github.com/stripe/stripe-dotnet/blob/master/_autodocs/INDEX.md Demonstrates how to create a new customer using the Stripe.net SDK. ```APIDOC ## POST /v1/customers ### Description Creates a new customer object. ### Method POST ### Endpoint /v1/customers ### Parameters #### Request Body - **email** (string) - Required - The customer's email address. ### Request Example ```json { "email": "customer@example.com" } ``` ### Response #### Success Response (200) - **id** (string) - The unique identifier for the customer. - **email** (string) - The customer's email address. #### Response Example ```json { "id": "cus_12345", "email": "customer@example.com" } ``` ``` -------------------------------- ### Create Subscription with Coupon Source: https://github.com/stripe/stripe-dotnet/blob/master/_autodocs/api-reference/subscription-service.md This example shows how to apply a coupon to a new subscription during creation. Provide the CouponId of the desired discount. ```csharp var withCoupon = await client.V1.Subscriptions.CreateAsync(new SubscriptionCreateOptions { CustomerId = "cus_123", Items = new List { new SubscriptionItemOptions { Price = "price_1234" } }, CouponId = "DISCOUNT20" }); ``` -------------------------------- ### Configuration Hierarchy Example Source: https://github.com/stripe/stripe-dotnet/blob/master/_autodocs/api-reference/stripe-configuration.md Demonstrates the configuration hierarchy in Stripe.net, showing how per-request, per-client, and global configurations are prioritized. This example illustrates how API keys are applied based on specificity. ```APIDOC ## Configuration Hierarchy The Stripe.net library follows this configuration hierarchy (highest to lowest priority): 1. **Per-request configuration** (`RequestOptions`) - most specific 2. **Per-client configuration** (`StripeClientOptions`) - client-level 3. **Global configuration** (`StripeConfiguration`) - fallback default ### Example ```csharp // 1. Global configuration StripeConfiguration.ApiKey = "sk_global_key"; // 2. Per-client configuration var clientOptions = new StripeClientOptions { ApiKey = "sk_client_key" }; var client = new StripeClient(clientOptions); // 3. Per-request configuration var requestOptions = new RequestOptions { ApiKey = "sk_request_key" }; // This request uses "sk_request_key" (most specific) var customer = client.V1.Customers.Get("cus_123", null, requestOptions); // This request uses "sk_client_key" (client level) var customer2 = client.V1.Customers.Get("cus_456"); // A new service (not using the client) uses "sk_global_key" var service = new CustomerService(); var customer3 = service.Get("cus_789"); ``` ``` -------------------------------- ### Create Customer - Full Options Source: https://github.com/stripe/stripe-dotnet/blob/master/_autodocs/api-reference/customer-service.md Use this example for comprehensive customer creation, including address, phone, and metadata. ```csharp // Full customer creation var options = new CustomerCreateOptions { Email = "customer@example.com", Name = "John Doe", Description = "Premium tier customer", Phone = "+1-555-123-4567", Address = new AddressOptions { Line1 = "123 Main St", City = "San Francisco", State = "CA", PostalCode = "94105", Country = "US" }, Metadata = new Dictionary { { "plan", "premium" }, { "signup_date", "2024-01-15" } } }; var createdCustomer = await client.V1.Customers.CreateAsync(options); ``` -------------------------------- ### StripeClientOptions Initialization Example Source: https://github.com/stripe/stripe-dotnet/blob/master/_autodocs/api-reference/stripe-client.md Demonstrates how to initialize StripeClientOptions with an API key, connected account ID, and a custom HTTP client. ```csharp var options = new StripeClientOptions { ApiKey = "sk_test_123456", StripeAccount = "acct_connected_123", HttpClient = new SystemNetHttpClient(customHttpClient) }; ``` -------------------------------- ### Create Subscription Schedule with Price Change Source: https://github.com/stripe/stripe-dotnet/blob/master/_autodocs/api-reference/subscription-service.md Use `SubscriptionScheduleService` to create a schedule that modifies a subscription's price on a future date. This example demonstrates setting up phases with different prices and start dates. ```csharp var schedule = await client.V1.SubscriptionSchedules.CreateAsync(new SubscriptionScheduleCreateOptions { CustomerId = "cus_123", StartDate = new DateTime(2024, 9, 1), Phases = new List { new SubscriptionSchedulePhaseOptions { Items = new List { new SubscriptionItemOptions { Price = "price_1234" } }, StartDate = new DateTime(2024, 9, 1), EndDate = new DateTime(2025, 9, 1) }, new SubscriptionSchedulePhaseOptions { Items = new List { new SubscriptionItemOptions { Price = "price_5678" } // New price }, StartDate = new DateTime(2025, 9, 1) } } }); ``` -------------------------------- ### Create Product and Price, then Subscription Source: https://github.com/stripe/stripe-dotnet/blob/master/_autodocs/api-reference/subscription-service.md This snippet demonstrates the one-time setup of a product and price, followed by creating a subscription for a customer. It uses 'default_incomplete' payment behavior to allow the customer to complete payment later. ```csharp // 1. Create product and price (one-time setup) var product = await client.V1.Products.CreateAsync(new ProductCreateOptions { Name = "Premium Membership" }); var price = await client.V1.Prices.CreateAsync(new PriceCreateOptions { ProductId = product.Id, Currency = "usd", UnitAmount = 2999, // $29.99 RecurringOptions = new PriceRecurringOptions { Interval = "month", IntervalCount = 1 } }); // 2. Create subscription for customer var subscription = await client.V1.Subscriptions.CreateAsync(new SubscriptionCreateOptions { CustomerId = "cus_123", Items = new List { new SubscriptionItemOptions { Price = price.Id } }, PaymentBehavior = "default_incomplete" // Let customer complete payment }); ``` -------------------------------- ### Listing Customers with Pagination Source: https://github.com/stripe/stripe-dotnet/blob/master/_autodocs/README.md Provides examples of manual pagination using a limit and auto-pagination for listing customers. ```csharp var page = client.V1.Customers.List(new CustomerListOptions { Limit = 10 }); foreach (var cust in client.V1.Customers.ListAutoPaging()) { } ``` -------------------------------- ### Example Usage of V1 API Services Source: https://github.com/stripe/stripe-dotnet/blob/master/_autodocs/api-reference/stripe-client.md Demonstrates how to use the V1 API services to retrieve a customer, create an invoice, and list charges. ```csharp var customer = client.V1.Customers.Get("cus_123"); var invoice = client.V1.Invoices.Create(options); var charges = client.V1.Charges.List(); ``` -------------------------------- ### Install Stripe.net using NuGet CLI Source: https://github.com/stripe/stripe-dotnet/blob/master/README.md Use this command to add the Stripe.net package to your project via the NuGet CLI. ```sh nuget install Stripe.net ``` -------------------------------- ### Stripe.net Configuration Hierarchy Example Source: https://github.com/stripe/stripe-dotnet/blob/master/_autodocs/api-reference/stripe-configuration.md Demonstrates the configuration hierarchy: per-request, per-client, and global configuration. Requests use the most specific API key available. ```csharp // 1. Global configuration StripeConfiguration.ApiKey = "sk_global_key"; // 2. Per-client configuration var clientOptions = new StripeClientOptions { ApiKey = "sk_client_key" }; var client = new StripeClient(clientOptions); // 3. Per-request configuration var requestOptions = new RequestOptions { ApiKey = "sk_request_key" }; // This request uses "sk_request_key" (most specific) var customer = client.V1.Customers.Get("cus_123", null, requestOptions); // This request uses "sk_client_key" (client level) var customer2 = client.V1.Customers.Get("cus_456"); // A new service (not using the client) uses "sk_global_key" var service = new CustomerService(); var customer3 = service.Get("cus_789"); ``` -------------------------------- ### SearchOptions Query Example Source: https://github.com/stripe/stripe-dotnet/blob/master/_autodocs/types.md Example of using SearchOptions to define a search query using Stripe Query Language and limit the number of results per page. ```csharp var options = new CustomerSearchOptions { Query = "email:\"test@example.com\" AND created:>1640995200", Limit = 10 }; var results = client.V1.Customers.Search(options); ``` -------------------------------- ### Create Subscription with Multiple Items Source: https://github.com/stripe/stripe-dotnet/blob/master/_autodocs/api-reference/subscription-service.md This example demonstrates creating a subscription that includes multiple items, allowing for complex billing arrangements. Provide a list of SubscriptionItemOptions. ```csharp var multiItem = await client.V1.Subscriptions.CreateAsync(new SubscriptionCreateOptions { CustomerId = "cus_123", Items = new List { new SubscriptionItemOptions { Price = "price_monthly" }, new SubscriptionItemOptions { Price = "price_addon" } } }); ``` -------------------------------- ### List All Charges Asynchronously Example Source: https://github.com/stripe/stripe-dotnet/blob/master/_autodocs/api-reference/charge-service.md Asynchronously iterates through all charges, printing their IDs and amounts. ```csharp // Async variant await foreach (var charge in client.V1.Charges.ListAutoPagingAsync()) { Console.WriteLine($"Charge: {charge.Id} - {charge.Amount}"); } ``` -------------------------------- ### Service Architecture Entry Point Source: https://github.com/stripe/stripe-dotnet/blob/master/_autodocs/README.md Illustrates the delegation flow starting from the StripeClient entry point to lower-level request handling. ```text StripeClient.V1.Customers.Get(id) ↓ (delegates to) CustomerService.Get(id) ↓ (delegates to) ApiRequestor.RequestAsync() ↓ (delegates to) SystemNetHttpClient.SendRequestAsync() ``` -------------------------------- ### Search Subscriptions Source: https://github.com/stripe/stripe-dotnet/blob/master/_autodocs/api-reference/subscription-service.md This example demonstrates how to search for subscriptions using specific criteria, such as status and date ranges, and how to find subscriptions nearing their renewal date. ```csharp // Find active subscriptions in July var july = client.V1.Subscriptions.Search(new SubscriptionSearchOptions { Query = "status:\"active\" AND current_period_start:[2024-07-01 TO 2024-07-31]" }); // Find subscriptions near renewal var ending = client.V1.Subscriptions.Search(new SubscriptionSearchOptions { Query = "status:\"active\" AND current_period_end:<" + DateTimeOffset.UtcNow.AddDays(3).ToUnixTimeSeconds() }); foreach (var sub in ending.Data) { Console.WriteLine($"Subscription {sub.Id} renews on {sub.CurrentPeriodEnd}"); } ``` -------------------------------- ### Install Stripe.net using .NET CLI Source: https://github.com/stripe/stripe-dotnet/blob/master/README.md Use this command to add the Stripe.net package to your project via the .NET Core CLI. ```sh dotnet add package Stripe.net ``` -------------------------------- ### List All Charges by Customer Example Source: https://github.com/stripe/stripe-dotnet/blob/master/_autodocs/api-reference/charge-service.md Iterates through all charges associated with a specific customer using the auto-paging feature. ```csharp var allCharges = new List(); foreach (var charge in client.V1.Charges.ListAutoPaging(new ChargeListOptions { CustomerId = "cus_123" })) { allCharges.Add(charge); } ``` -------------------------------- ### Search Charges by Customer and Status Example Source: https://github.com/stripe/stripe-dotnet/blob/master/_autodocs/api-reference/charge-service.md Searches for succeeded charges belonging to a specific customer. ```csharp // Search by customer and status var successfulCharges = client.V1.Charges.Search(new ChargeSearchOptions { Query = "customer:\"cus_123\" AND status:\"succeeded\"" }); ``` -------------------------------- ### Create a Payment Intent for a Customer Source: https://github.com/stripe/stripe-dotnet/blob/master/_autodocs/api-reference/payment-intent-service.md This example shows how to create a payment intent associated with a specific customer and enable automatic payment methods. ```csharp var piWithCustomer = await client.V1.PaymentIntents.CreateAsync(new PaymentIntentCreateOptions { Amount = 5000, Currency = "usd", CustomerId = "cus_123", AutomaticPaymentMethods = new PaymentIntentAutomaticPaymentMethodsOptions { Enabled = true } }); ``` -------------------------------- ### List Resources with Pagination (Sync/Async) Source: https://github.com/stripe/stripe-dotnet/blob/master/_autodocs/api-reference/service-classes.md Use to list resources with support for pagination. This method returns a single page of results. To get subsequent pages, use the `StartingAfter` parameter with the ID of the last item from the previous page. ```csharp public virtual StripeList List(TOptions options = null, RequestOptions requestOptions = null) public virtual Task> ListAsync(TOptions options = null, RequestOptions requestOptions = null, CancellationToken cancellationToken = default) ``` ```csharp // Get first page var page1 = client.V1.Customers.List(new CustomerListOptions { Limit = 10 }); foreach (var customer in page1) { Console.WriteLine(customer.Email); } // Get next page if (page1.HasMore) { var page2 = client.V1.Customers.List(new CustomerListOptions { Limit = 10, StartingAfter = page1.Data[page1.Data.Count - 1].Id }); } ``` -------------------------------- ### Install Stripe.net using Package Manager Console Source: https://github.com/stripe/stripe-dotnet/blob/master/README.md Use this command to add the Stripe.net package to your project via the Package Manager Console in Visual Studio. ```powershell Install-Package Stripe.net ``` -------------------------------- ### Create StripeClient with API Key Source: https://github.com/stripe/stripe-dotnet/blob/master/_autodocs/api-reference/stripe-client.md Instantiate a Stripe client using only a test API key. This is a common way to start making API calls. ```csharp // Create a client with custom API key var client = new StripeClient("sk_test_123456"); ``` -------------------------------- ### Set Up Recurring Billing with Stripe .NET Source: https://github.com/stripe/stripe-dotnet/blob/master/_autodocs/INDEX.md Guides through creating a product, a recurring price, and then a subscription for a customer. This is used for subscription-based services. ```csharp // Create product and price var product = await client.V1.Products.CreateAsync(new ProductCreateOptions { Name = "Premium Plan" }); var price = await client.V1.Prices.CreateAsync(new PriceCreateOptions { ProductId = product.Id, Currency = "usd", UnitAmount = 2999, RecurringOptions = new PriceRecurringOptions { Interval = "month", IntervalCount = 1 } }); // Create subscription var subscription = await client.V1.Subscriptions.CreateAsync(new SubscriptionCreateOptions { CustomerId = "cus_123", Items = new List { new SubscriptionItemOptions { Price = price.Id } } }); ``` -------------------------------- ### Create Subscription Schedule Source: https://github.com/stripe/stripe-dotnet/blob/master/_autodocs/api-reference/subscription-service.md Example of creating a subscription schedule to modify a subscription's price at a future date. This is useful for planned upgrades or downgrades. ```APIDOC ## Create Subscription Schedule ### Description Creates a subscription schedule to manage future changes to a customer's subscription, such as price adjustments. ### Method `SubscriptionSchedules.CreateAsync` ### Parameters - **SubscriptionScheduleCreateOptions** (object) - Required - Options for creating the subscription schedule. - **CustomerId** (string) - Required - The ID of the customer to associate with the schedule. - **StartDate** (DateTime) - Required - The date the schedule becomes effective. - **Phases** (List) - Required - A list of phases defining the subscription's lifecycle. - **Items** (List) - Required - The items included in this phase. - **Price** (string) - Required - The ID of the price to use for the item. - **StartDate** (DateTime) - Required - The start date of this phase. - **EndDate** (DateTime) - Optional - The end date of this phase. ### Request Example ```csharp var schedule = await client.V1.SubscriptionSchedules.CreateAsync(new SubscriptionScheduleCreateOptions { CustomerId = "cus_123", StartDate = new DateTime(2024, 9, 1), Phases = new List { new SubscriptionSchedulePhaseOptions { Items = new List { new SubscriptionItemOptions { Price = "price_1234" } }, StartDate = new DateTime(2024, 9, 1), EndDate = new DateTime(2025, 9, 1) }, new SubscriptionSchedulePhaseOptions { Items = new List { new SubscriptionItemOptions { Price = "price_5678" } // New price }, StartDate = new DateTime(2025, 9, 1) } } }); ``` ### Response #### Success Response (200) Returns the created `SubscriptionSchedule` object. #### Response Example (Response structure depends on the Stripe API, typically includes schedule details, phases, status, etc.) ``` -------------------------------- ### Retrieve a Customer Resource Source: https://github.com/stripe/stripe-dotnet/blob/master/README.md Demonstrates retrieving a customer resource by its ID using the `Get` method. The retrieved customer object is returned. ```C# var client = new StripeClient("sk_test_..."); Customer customer = client.V1.Customers.Get("cus_1234"); Console.WriteLine(customer.Email); ``` -------------------------------- ### Get Client ID Source: https://github.com/stripe/stripe-dotnet/blob/master/_autodocs/api-reference/stripe-client.md Gets the client ID for OAuth requests. ```csharp public string ClientId { get; } ``` -------------------------------- ### Creating a Customer with Options Source: https://github.com/stripe/stripe-dotnet/blob/master/_autodocs/README.md Shows how to use an options object to pass parameters for creating a new customer. ```csharp var options = new CustomerCreateOptions { Email = "..." }; var customer = client.V1.Customers.Create(options); ``` -------------------------------- ### Get API Key Source: https://github.com/stripe/stripe-dotnet/blob/master/_autodocs/api-reference/stripe-client.md Gets the API key used by this client. ```csharp public string ApiKey { get; } ``` -------------------------------- ### Get HTTP Client Source: https://github.com/stripe/stripe-dotnet/blob/master/_autodocs/api-reference/stripe-client.md Gets the HTTP client used for sending requests. ```csharp public IHttpClient HttpClient { get; } ``` -------------------------------- ### Get API Base URL Source: https://github.com/stripe/stripe-dotnet/blob/master/_autodocs/api-reference/stripe-client.md Gets the base URL for Stripe's API. The default is 'https://api.stripe.com'. ```csharp public string ApiBase { get; } ``` -------------------------------- ### Get Connect Base URL Source: https://github.com/stripe/stripe-dotnet/blob/master/_autodocs/api-reference/stripe-client.md Gets the base URL for Stripe's OAuth API. The default is 'https://connect.stripe.com'. ```csharp public string ConnectBase { get; } ``` -------------------------------- ### Create a Customer using StripeClient Source: https://github.com/stripe/stripe-dotnet/blob/master/_autodocs/api-reference/stripe-client.md Demonstrates how to use a configured StripeClient instance to create a new customer with specified options. ```csharp // Create a customer using the client var customer = client.V1.Customers.Create(new CustomerCreateOptions { Email = "customer@example.com" }); ``` -------------------------------- ### Get Files API Base URL Source: https://github.com/stripe/stripe-dotnet/blob/master/_autodocs/api-reference/stripe-client.md Gets the base URL for Stripe's Files API. The default is 'https://files.stripe.com'. ```csharp public string FilesBase { get; } ``` -------------------------------- ### Get Meter Events API Base URL Source: https://github.com/stripe/stripe-dotnet/blob/master/_autodocs/api-reference/stripe-client.md Gets the base URL for Stripe's Meter Events API. The default is 'https://meter-events.stripe.com'. ```csharp public string MeterEventsBase { get; } ``` -------------------------------- ### Basic Subscription Creation Source: https://github.com/stripe/stripe-dotnet/blob/master/_autodocs/api-reference/subscription-service.md Demonstrates how to create a product, a price, and then a subscription for a customer. ```APIDOC ## Basic Subscription Creation ### Description This example shows the process of creating a new subscription for a customer. It involves first setting up a product and its associated price, then creating the subscription itself, specifying payment behavior to allow the customer to complete the payment. ### Method POST ### Endpoint /v1/subscriptions ### Parameters #### Request Body - **CustomerId** (string) - Required - The ID of the customer to create the subscription for. - **Items** (list of SubscriptionItemOptions) - Required - A list of items to include in the subscription, each specifying a Price ID. - **PaymentBehavior** (string) - Optional - Specifies how to handle payment collection. 'default_incomplete' allows the customer to complete payment later. ### Request Example ```csharp var subscription = await client.V1.Subscriptions.CreateAsync(new SubscriptionCreateOptions { CustomerId = "cus_123", Items = new List { new SubscriptionItemOptions { Price = price.Id } }, PaymentBehavior = "default_incomplete" }); ``` ### Response #### Success Response (200) - **Subscription** (object) - The created subscription object. #### Response Example (Response structure depends on Stripe API, typically includes subscription details like ID, status, customer, items, etc.) ``` -------------------------------- ### StripeClient vs. Global Configuration Source: https://github.com/stripe/stripe-dotnet/blob/master/README.md Illustrates the recommended `StripeClient` pattern for managing configurations per client, contrasting it with the legacy global configuration pattern. ```C# // StripeClient pattern (Recommended) var client = new StripeClient("sk_test_..."); Customer customer = client.V1.Customers.Get("cus_1234"); // Global Configuration pattern (Legacy) StripeConfiguration.ApiKey = "sk_test_..."; var service = new CustomerService(); Customer customer = service.Get("cus_1234"); ``` -------------------------------- ### Service Instantiation with Custom Client Source: https://github.com/stripe/stripe-dotnet/blob/master/_autodocs/api-reference/service-classes.md Demonstrates how to create a service instance using a custom StripeClient, allowing for specific configurations. It also shows how to access services directly from the client instance. ```APIDOC ## Service Instantiation with Custom Client Instantiate a service with a custom client: ```csharp // Instantiate a service with a custom client var client = new StripeClient("sk_test_123456"); var customerService = new CustomerService(client); var customer = customerService.Get("cus_123"); // Or use the service from the client var customer2 = client.V1.Customers.Get("cus_456"); ``` ``` -------------------------------- ### StripeNetVersion Source: https://github.com/stripe/stripe-dotnet/blob/master/_autodocs/api-reference/stripe-configuration.md Gets the version of the Stripe.net SDK. ```APIDOC ## StripeNetVersion ### Description Gets the version of the Stripe.net SDK. **Type:** string (read-only) ### Example ```csharp Console.WriteLine($"Using Stripe.net v{StripeConfiguration.StripeNetVersion}"); ``` ``` -------------------------------- ### List Recent Charges Example Source: https://github.com/stripe/stripe-dotnet/blob/master/_autodocs/api-reference/charge-service.md Retrieves the 10 most recent charges. ```csharp // List recent charges var charges = await client.V1.Charges.ListAsync(new ChargeListOptions { Limit = 10 }); ``` -------------------------------- ### Instantiate Stripe Service with Custom Client Source: https://github.com/stripe/stripe-dotnet/blob/master/_autodocs/api-reference/service-classes.md Demonstrates how to create a Stripe service instance using a custom StripeClient, and how to access services directly from the client. Use this when you need to configure the client with specific settings like API keys or custom HTTP clients. ```csharp // Instantiate a service with a custom client var client = new StripeClient("sk_test_123456"); var customerService = new CustomerService(client); var customer = customerService.Get("cus_123"); // Or use the service from the client var customer2 = client.V1.Customers.Get("cus_456"); ``` -------------------------------- ### Filter Charges by Customer Example Source: https://github.com/stripe/stripe-dotnet/blob/master/_autodocs/api-reference/charge-service.md Retrieves up to 25 charges for a specific customer. ```csharp // Filter by customer var customerCharges = await client.V1.Charges.ListAsync(new ChargeListOptions { CustomerId = "cus_123", Limit = 25 }); ``` -------------------------------- ### SerializerOptions Source: https://github.com/stripe/stripe-dotnet/blob/master/_autodocs/api-reference/stripe-configuration.md Gets or sets System.Text.Json serialization options for serializing and deserializing API requests/responses. ```APIDOC ## SerializerOptions ### Description Gets or sets System.Text.Json serialization options for serializing and deserializing API requests/responses. **Type:** System.Text.Json.JsonSerializerOptions **Default:** Default options with Stripe custom converters ``` -------------------------------- ### Configure Stripe Client with Proxy Source: https://github.com/stripe/stripe-dotnet/blob/master/_autodocs/http-client-configuration.md Set up a System.Net.Http.HttpClientHandler with proxy details and UseProxy set to true. Then, create an HttpClient with this handler and use it to initialize the StripeClient. ```csharp var handler = new System.Net.Http.HttpClientHandler { Proxy = new System.Net.WebProxy("http://proxy.example.com:8080"), UseProxy = true }; var httpClient = new System.Net.Http.HttpClient(handler); var stripeHttpClient = new SystemNetHttpClient(httpClient); var client = new StripeClient("sk_test_123456", httpClient: stripeHttpClient); ``` -------------------------------- ### Search Charges by Amount Range Example Source: https://github.com/stripe/stripe-dotnet/blob/master/_autodocs/api-reference/charge-service.md Searches for charges with an amount greater than 10000. ```csharp // Search by amount range var largeCharges = client.V1.Charges.Search(new ChargeSearchOptions { Query = "amount:>10000" }); ``` -------------------------------- ### Get Subscription Source: https://github.com/stripe/stripe-dotnet/blob/master/_autodocs/api-reference/subscription-service.md Retrieves a subscription by its ID. Allows for expanding related objects for more detailed information. ```APIDOC ## GET /v1/subscriptions/{id} ### Description Retrieves a subscription by ID. ### Method GET ### Endpoint /v1/subscriptions/{id} ### Parameters #### Path Parameters - **id** (string) - Required - Subscription ID #### Query Parameters - **options** (SubscriptionGetOptions) - Optional - Expand options ### Request Example ``` GET /v1/subscriptions/sub_123 ``` ### Response #### Success Response (200) - **Subscription** (Stripe.Subscription) - The requested subscription object #### Response Example ```json { "id": "sub_123", "object": "subscription", "status": "active", "customer": "cus_123", "current_period_start": 1678800000, "current_period_end": 1681478400 } ``` ``` -------------------------------- ### List Customer Resources (Manual Pagination) Source: https://github.com/stripe/stripe-dotnet/blob/master/README.md Demonstrates listing customer resources page-by-page using the `List` method. Manual iteration using `StartingAfter` is required for subsequent pages. ```C# var client = new StripeClient("sk_test_..."); var customers = client.V1.Customers.List(); string lastId = null; // Enumerate the first page of the list foreach (Customer customer in customers) { lastId = customer.Id; Console.WriteLine(customer.Email); } customers = service.List(new CustomerListOptions() { StartingAfter = lastId, }); // Enumerate the subsequent page foreach (Customer customer in customers) { lastId = customer.Id; Console.WriteLine(customer.Email); } ``` -------------------------------- ### Handling Subscription Status Source: https://github.com/stripe/stripe-dotnet/blob/master/_autodocs/api-reference/subscription-service.md Provides an example of how to retrieve a subscription and handle its different status states. ```APIDOC ## Handling Subscription Status ### Description This example shows how to fetch a subscription by its ID and then use a switch statement to perform actions based on its current status, such as 'trialing', 'active', 'incomplete', 'past_due', or 'canceled'. ### Method GET ### Endpoint /v1/subscriptions/{subscription_id} ### Parameters #### Path Parameters - **subscription_id** (string) - Required - The ID of the subscription to retrieve. ### Request Example ```csharp var subscription = await client.V1.Subscriptions.GetAsync("sub_123"); switch (subscription.Status) { case "trialing": Console.WriteLine($"Trial ends: {subscription.TrialEnd}"); break; case "active": Console.WriteLine("Subscription is active"); break; case "incomplete": Console.WriteLine("Awaiting payment confirmation"); break; case "past_due": Console.WriteLine("Payment is overdue"); break; case "canceled": Console.WriteLine($"Cancelled at: {subscription.CanceledAt}"); break; } ``` ### Response #### Success Response (200) - **Subscription** (object) - The subscription object with its current status and related fields. #### Response Example (Response structure depends on Stripe API, includes status, trialEnd, canceledAt, etc.) ``` -------------------------------- ### Legacy vs. New Service Instantiation Patterns Source: https://github.com/stripe/stripe-dotnet/blob/master/_autodocs/api-reference/service-classes.md Compares the legacy pattern of directly instantiating service classes with the recommended new pattern using StripeClient for service instantiation. The new pattern is preferred for modern development. ```csharp // Old pattern - still supported but not recommended StripeConfiguration.ApiKey = "sk_test_123456"; var customerService = new CustomerService(); var customer = customerService.Get("cus_123"); // New pattern - recommended var client = new StripeClient("sk_test_123456"); var customer = client.V1.Customers.Get("cus_123"); ``` -------------------------------- ### Create Customer with Metadata Source: https://github.com/stripe/stripe-dotnet/blob/master/_autodocs/api-reference/customer-service.md Use this to create a new customer and attach custom metadata for tracking purposes. The signup date is automatically recorded. ```csharp var customer = await client.V1.Customers.CreateAsync(new CustomerCreateOptions { Email = "user@example.com", Name = "Alice Johnson", Metadata = new Dictionary { { "customer_id", "app_12345" }, { "subscription_level", "premium" }, { "signup_date", DateTime.UtcNow.ToString("O") } } }); ``` -------------------------------- ### Search Subscriptions Source: https://github.com/stripe/stripe-dotnet/blob/master/_autodocs/api-reference/subscription-service.md Provides examples of how to search for subscriptions based on various criteria using a query language. ```APIDOC ## Search Subscriptions ### Description This section demonstrates how to use the search functionality to find subscriptions that match specific criteria. You can query based on status, date ranges, and other subscription attributes. ### Method POST ### Endpoint /v1/subscriptions/search ### Parameters #### Request Body - **Query** (string) - Required - The search query string. Supports operators like `status:`, `current_period_start:`, `current_period_end:`, and date ranges `[start TO end]`. ### Request Examples ```csharp // Find active subscriptions in July var july = client.V1.Subscriptions.Search(new SubscriptionSearchOptions { Query = "status:\"active\" AND current_period_start:[2024-07-01 TO 2024-07-31]" }); // Find subscriptions near renewal var ending = client.V1.Subscriptions.Search(new SubscriptionSearchOptions { Query = "status:\"active\" AND current_period_end:<" + DateTimeOffset.UtcNow.AddDays(3).ToUnixTimeSeconds() }); foreach (var sub in ending.Data) { Console.WriteLine($"Subscription {sub.Id} renews on {sub.CurrentPeriodEnd}"); } ``` ### Response #### Success Response (200) - **SearchResult** (object) - Contains a list of matching subscriptions (`Data`) and pagination information. #### Response Example (Response structure depends on Stripe API, returning a list of subscription objects that match the query.) ``` -------------------------------- ### Basic Stripe.net Usage Source: https://github.com/stripe/stripe-dotnet/blob/master/_autodocs/INDEX.md Demonstrates creating a Stripe client, making an API call to create a customer, and listing customers with auto-pagination. ```csharp // Create a client var client = new StripeClient("sk_test_123456"); // Make API calls var customer = client.V1.Customers.Create(new CustomerCreateOptions { Email = "customer@example.com" }); // List resources with auto-pagination foreach (var cust in client.V1.Customers.ListAutoPaging()) { Console.WriteLine(cust.Email); } ``` -------------------------------- ### Filter Charges by Date Range Example Source: https://github.com/stripe/stripe-dotnet/blob/master/_autodocs/api-reference/charge-service.md Retrieves up to 50 charges created within the year 2024. ```csharp // Filter by date range var charges2024 = await client.V1.Charges.ListAsync(new ChargeListOptions { Limit = 50, Created = new RangeOptions { GreaterThanOrEqual = new DateTime(2024, 1, 1), LessThan = new DateTime(2024, 12, 31) } }); ``` -------------------------------- ### Subscription with Trial Source: https://github.com/stripe/stripe-dotnet/blob/master/_autodocs/api-reference/subscription-service.md Shows how to create a subscription with a specified trial period and end behavior. ```APIDOC ## Subscription with Trial ### Description This example demonstrates creating a subscription that includes a trial period. You can configure the number of trial days and specify actions to take if payment information is missing at the end of the trial. ### Method POST ### Endpoint /v1/subscriptions ### Parameters #### Request Body - **CustomerId** (string) - Required - The ID of the customer. - **Items** (list of SubscriptionItemOptions) - Required - A list of subscription items, each with a Price ID. - **TrialPeriodDays** (integer) - Optional - The number of days the trial period should last. - **TrialSettings** (SubscriptionTrialSettingsOptions) - Optional - Settings for the trial period. - **EndBehavior** (SubscriptionTrialSettingsEndBehaviorOptions) - Specifies behavior when the trial ends. - **MissingPaymentMethod** (string) - Optional - Action to take if payment method is missing ('cancel', 'pause'). ### Request Example ```csharp var subscription = await client.V1.Subscriptions.CreateAsync(new SubscriptionCreateOptions { CustomerId = "cus_123", Items = new List { new SubscriptionItemOptions { Price = "price_1234" } }, TrialPeriodDays = 14, TrialSettings = new SubscriptionTrialSettingsOptions { EndBehavior = new SubscriptionTrialSettingsEndBehaviorOptions { MissingPaymentMethod = "cancel" } } }); ``` ### Response #### Success Response (200) - **Subscription** (object) - The created subscription object with trial details. #### Response Example (Response structure depends on Stripe API, typically includes subscription details and trial information.) ``` -------------------------------- ### Get / Retrieve Source: https://github.com/stripe/stripe-dotnet/blob/master/_autodocs/api-reference/service-classes.md Retrieves a single resource by its unique identifier. Supports optional parameters for expansion and request configuration. ```APIDOC ## Get / Retrieve ### Description Retrieves a single resource by ID. ### Method ```csharp public virtual T Get(string id, TOptions options = null, RequestOptions requestOptions = null) public virtual Task GetAsync(string id, TOptions options = null, RequestOptions requestOptions = null, CancellationToken cancellationToken = default) ``` ### Parameters - `id` (string): The resource ID - `options` (TOptions): Optional retrieve options (e.g., expand parameters) - `requestOptions` (RequestOptions): Optional per-request configuration ### Returns Retrieved resource entity ### Example ```csharp var customer = client.V1.Customers.Get("cus_123"); // With expansion var options = new CustomerGetOptions(); options.AddExpand("default_source"); var customerExpanded = client.V1.Customers.Get("cus_123", options); ``` ``` -------------------------------- ### ClientId Source: https://github.com/stripe/stripe-dotnet/blob/master/_autodocs/api-reference/stripe-configuration.md Gets or sets the global client ID used for OAuth flows. This can be set directly or via AppSettings. ```APIDOC ## ClientId ### Description Gets or sets the global client ID used for OAuth flows. **Type:** string **Default:** null **Setting sources:** 1. Property assignment 2. AppSettings configuration key `StripeClientId` ``` -------------------------------- ### Initialize StripeClient with Options Object Source: https://github.com/stripe/stripe-dotnet/blob/master/_autodocs/api-reference/stripe-client.md Use this constructor to initialize a Stripe client by providing a `StripeClientOptions` object, which encapsulates various configuration settings. ```csharp public StripeClient(StripeClientOptions options) ``` -------------------------------- ### ApiVersion Source: https://github.com/stripe/stripe-dotnet/blob/master/_autodocs/api-reference/stripe-configuration.md Gets the Stripe API version used by this SDK. This version is pinned at SDK compile time and cannot be changed. ```APIDOC ## ApiVersion ### Description Gets the Stripe API version used by this SDK. **Type:** string (read-only) **Note:** This is the version pinned at SDK compile time and cannot be changed. ``` -------------------------------- ### Apply Coupon During Subscription Signup Source: https://github.com/stripe/stripe-dotnet/blob/master/_autodocs/api-reference/subscription-service.md This snippet illustrates how to apply a coupon to a new subscription during its creation. It also shows how to record the coupon's usage in metadata. ```csharp var subscription = await client.V1.Subscriptions.CreateAsync(new SubscriptionCreateOptions { CustomerId = "cus_123", Items = new List { new SubscriptionItemOptions { Price = "price_1234" } }, CouponId = "SUMMER2024", // 20% off Metadata = new Dictionary { { "promotion_code", "SUMMER2024" } } }); ``` -------------------------------- ### Get Invoice Source: https://github.com/stripe/stripe-dotnet/blob/master/_autodocs/api-reference/invoice-service.md Retrieves a specific invoice by its unique ID. Supports expanding related objects for more detailed information. ```APIDOC ## GET /v1/invoices/{id} ### Description Retrieves an invoice by ID. ### Method GET ### Endpoint /v1/invoices/{id} ### Parameters #### Path Parameters - **id** (string) - Required - Invoice ID #### Query Parameters - **options** (InvoiceGetOptions) - Optional - Expand options - **requestOptions** (RequestOptions) - Optional - Per-request configuration ### Response #### Success Response (200) - **Invoice** (Invoice) - The retrieved invoice object #### Response Example ```json { "id": "in_123", "object": "invoice", "status": "paid", "total": 1000, "invoice_pdf": "https://stripe.com/invoice/in_123/pdf" } ``` ``` -------------------------------- ### Process invoice payment Source: https://github.com/stripe/stripe-dotnet/blob/master/_autodocs/api-reference/invoice-service.md This code example shows how to retrieve an invoice and attempt to process its payment if it is in an 'open' state. ```APIDOC ## Process invoice payment This code example shows how to retrieve an invoice and attempt to process its payment if it is in an 'open' state. ```csharp var invoice = client.V1.Invoices.Get("in_123"); if (invoice.Status == "open") { // Attempt payment var paid = await client.V1.Invoices.PayAsync(invoice.Id); if (paid.Paid) { Console.WriteLine("Invoice paid successfully"); // Fulfill order, send confirmation, etc. } else { Console.WriteLine("Payment failed"); // Retry or contact customer } } ``` ``` -------------------------------- ### Create StripeClient with StripeClientOptions Source: https://github.com/stripe/stripe-dotnet/blob/master/_autodocs/api-reference/stripe-client.md Instantiate a Stripe client using a `StripeClientOptions` object, specifying the API key and Stripe Account ID for the client. ```csharp var options = new StripeClientOptions { ApiKey = "sk_test_123456", StripeAccount = "acct_connect_id" }; var client = new StripeClient(options); ``` -------------------------------- ### Create Customer with Metadata Source: https://github.com/stripe/stripe-dotnet/blob/master/_autodocs/api-reference/customer-service.md Demonstrates how to create a new customer and include custom metadata in the request. ```APIDOC ## Create Customer with Metadata ### Description Creates a new customer with specified email, name, and custom metadata. ### Method POST ### Endpoint /v1/customers ### Parameters #### Request Body - **Email** (string) - Required - The customer's email address. - **Name** (string) - Optional - The customer's full name. - **Metadata** (Dictionary) - Optional - A set of key-value pairs to store additional information about the customer. ### Request Example ```csharp var customer = await client.V1.Customers.CreateAsync(new CustomerCreateOptions { Email = "user@example.com", Name = "Alice Johnson", Metadata = new Dictionary { { "customer_id", "app_12345" }, { "subscription_level", "premium" }, { "signup_date", DateTime.UtcNow.ToString("O") } } }); ``` ``` -------------------------------- ### Update a Payment Intent Source: https://github.com/stripe/stripe-dotnet/blob/master/_autodocs/api-reference/payment-intent-service.md Modifies an existing payment intent. This example updates the amount and metadata before the payment is confirmed. ```csharp var updated = await client.V1.PaymentIntents.UpdateAsync("pi_123", new PaymentIntentUpdateOptions { Amount = 3000, // Update amount before confirmation Metadata = new Dictionary { { "status", "updated" } } }); ``` -------------------------------- ### Create Subscription with Trial Period Source: https://github.com/stripe/stripe-dotnet/blob/master/_autodocs/api-reference/subscription-service.md Use this to create a subscription that includes an initial trial period. Specify the number of days for the trial using TrialPeriodDays. ```csharp var withTrial = await client.V1.Subscriptions.CreateAsync(new SubscriptionCreateOptions { CustomerId = "cus_123", Items = new List { new SubscriptionItemOptions { Price = "price_1234" } }, TrialPeriodDays = 14 }); ``` -------------------------------- ### Create Resource (Sync/Async) Source: https://github.com/stripe/stripe-dotnet/blob/master/_autodocs/api-reference/service-classes.md Use to create a new resource. Provide required fields in the options object. The async variant accepts a cancellation token. ```csharp public virtual T Create(TOptions options, RequestOptions requestOptions = null) public virtual Task CreateAsync(TOptions options, RequestOptions requestOptions = null, CancellationToken cancellationToken = default) ``` ```csharp var options = new CustomerCreateOptions { Email = "customer@example.com", Name = "John Doe" }; var customer = client.V1.Customers.Create(options); // Async variant var customerAsync = await client.V1.Customers.CreateAsync(options); ``` -------------------------------- ### Get Customer Source: https://github.com/stripe/stripe-dotnet/blob/master/_autodocs/api-reference/customer-service.md Retrieves a customer by their unique ID. Supports synchronous and asynchronous retrieval, with options for expanding related objects. ```APIDOC ## Get Customer ### Description Retrieves a customer by ID. ### Method GET ### Endpoint /v1/customers/{id} ### Parameters #### Path Parameters - **id** (string) - Required - Customer ID (e.g., "cus_123") #### Query Parameters - **options** (CustomerGetOptions) - Optional - Expand options - **requestOptions** (RequestOptions) - Optional - Per-request configuration ### Request Example ```json { "id": "cus_123", "options": { "expand": ["default_source", "invoice_settings.custom_fields"] } } ``` ### Response #### Success Response (200) - **customer** (Customer) - The requested customer object #### Response Example ```json { "id": "cus_123", "object": "customer", "email": "customer@example.com", "name": "John Doe", "default_source": { "id": "card_xyz789", "object": "card", "brand": "Visa", "last4": "4242" } } ``` ``` -------------------------------- ### Initialize StripeClient with Custom Configuration Source: https://github.com/stripe/stripe-dotnet/blob/master/_autodocs/api-reference/stripe-client.md Use this constructor to create a Stripe client with a specific API key, client ID, HTTP client, or custom base URLs for Stripe services. If apiKey is null, it defaults to the global StripeConfiguration.ApiKey. ```csharp public StripeClient( string apiKey = null, string clientId = null, IHttpClient httpClient = null, string apiBase = null, string connectBase = null, string filesBase = null, string meterEventsBase = null) ``` -------------------------------- ### Get Customer - Basic Retrieval Source: https://github.com/stripe/stripe-dotnet/blob/master/_autodocs/api-reference/customer-service.md Retrieves a customer using their unique ID. This is the most straightforward way to fetch customer data. ```csharp // Basic retrieval var customer = client.V1.Customers.Get("cus_123"); ``` -------------------------------- ### Create a Customer Resource Source: https://github.com/stripe/stripe-dotnet/blob/master/README.md Shows how to create a new customer resource using the `Create` method on the `Customers` service. The newly created customer object is returned. ```C# var options = new CustomerCreateOptions { Email = "customer@example.com" }; var client = new StripeClient("sk_test_..."); Customer customer = client.V1.Customers.Create(options); // Newly created customer is returned Console.WriteLine(customer.Email); ``` -------------------------------- ### Apply Coupon During Signup Source: https://github.com/stripe/stripe-dotnet/blob/master/_autodocs/api-reference/subscription-service.md Shows how to apply a coupon to a subscription when it is initially created. ```APIDOC ## Apply Coupon During Signup ### Description This example demonstrates how to apply a coupon code to a new subscription during the creation process. This allows for discounts to be applied automatically upon signup. ### Method POST ### Endpoint /v1/subscriptions ### Parameters #### Request Body - **CustomerId** (string) - Required - The ID of the customer. - **Items** (list of SubscriptionItemOptions) - Required - A list of subscription items, each with a Price ID. - **CouponId** (string) - Optional - The ID of the coupon to apply. - **Metadata** (dictionary) - Optional - Key-value pairs to store additional information, such as the promotion code used. ### Request Example ```csharp var subscription = await client.V1.Subscriptions.CreateAsync(new SubscriptionCreateOptions { CustomerId = "cus_123", Items = new List { new SubscriptionItemOptions { Price = "price_1234" } }, CouponId = "SUMMER2024", // 20% off Metadata = new Dictionary { { "promotion_code", "SUMMER2024" } } }); ``` ### Response #### Success Response (200) - **Subscription** (object) - The created subscription object, including details of the applied coupon if successful. #### Response Example (Response structure depends on Stripe API, showing subscription details and potentially discount information.) ``` -------------------------------- ### Resource-Specific Methods Source: https://github.com/stripe/stripe-dotnet/blob/master/_autodocs/api-reference/service-classes.md Provides examples of resource-specific operations available on various service classes beyond standard CRUD operations. ```APIDOC ## Resource-Specific Methods Beyond standard CRUD, services often expose resource-specific operations: **Customer examples:** - `DeleteDiscount()` - Remove discount from customer - `FundingInstructions.*` - Manage funding instructions - `PaymentMethods.*` - Manage payment methods - `TaxIds.*` - Manage tax IDs **Charge examples:** - `Capture()` - Capture an authorized charge - `Refund()` - Refund a charge - `MarkFraudulent()` - Mark as fraudulent - `MarkSafe()` - Mark as safe **Invoice examples:** - `Finalize()` - Finalize a draft invoice - `Pay()` - Attempt payment - `Send()` - Email to customer - `Void()` - Void an invoice - `MarkUncollectible()` - Mark as uncollectible See individual service documentation for complete method listings. ```