### Start stripe-mock with Docker Source: https://github.com/beam-community/stripity-stripe/blob/main/README.md Use this command to start a local stripe-mock server for testing. Ensure Docker is installed. ```sh docker run --rm -it -p 12111-12112:12111-12112 stripe/stripe-mock:latest ``` -------------------------------- ### List Setup Attempts Source: https://github.com/beam-community/stripity-stripe/blob/main/_autodocs/13-common-entities.md Use to list all setup attempts for a given SetupIntent. This helps in tracking the history of payment method setup. ```elixir {:ok, attempts} = Stripe.SetupAttempt.list(%{ setup_intent: "seti_123" }) ``` -------------------------------- ### Confirm Card Setup on Frontend Source: https://github.com/beam-community/stripity-stripe/blob/main/README.md Use the created SetupIntent ID on the frontend with Stripe elements' `confirmCardSetup` method to collect payment details. This example uses JavaScript. ```javascript stripe.confirmCardSetup(setupIntentId, { payment_method: { ... } }) .then(result => { const setupIntentId = result.setupIntent.id const paymentMethodId = result.setupIntent.payment_method // send the paymentMethodId and optionally (if needed) the setupIntentId }) ``` -------------------------------- ### Example: Get and Store OAuth Tokens Source: https://github.com/beam-community/stripity-stripe/blob/main/_autodocs/12-connect-oauth.md Demonstrates how to call `Stripe.Connect.OAuth.get_token/1` to obtain credentials and then store them in a database. This is a typical workflow after a user authorizes your application. ```elixir {:ok, token_response} = Stripe.Connect.OAuth.get_token(code) # Store these credentials db_insert(%{ platform_id: current_user.id, stripe_account_id: token_response["stripe_user_id"], stripe_access_token: token_response["access_token"], stripe_refresh_token: token_response["refresh_token"], stripe_publishable_key: token_response["stripe_publishable_key"] }) ``` -------------------------------- ### Complete Stripity Stripe Configuration Example Source: https://github.com/beam-community/stripity-stripe/blob/main/_autodocs/06-configuration-reference.md A comprehensive example of configuring all available options for the Stripity Stripe library, including API key, version, JSON library, connection pool, HTTP client options, retries, and webhook secret. ```elixir # config/config.exs import Config config :stripity_stripe, # API Key (loaded at runtime in prod) api_key: "sk_test_abc123", # API Configuration api_version: "2025-11-17.clover", json_library: Jason, # HTTP Connection Pool use_connection_pool: true, pool_options: [ timeout: 5_000, max_connections: 10 ], # HTTP Client Options hackney_opts: [ {:connect_timeout, 8_000}, {:recv_timeout, 30_000} ], # Retry Configuration retries: [ max_attempts: 3, base_backoff: 500, max_backoff: 2_000 ], # Webhook webhook_secret: System.get_env("STRIPE_WEBHOOK_SECRET") ``` -------------------------------- ### Example API Endpoints for Customers Source: https://github.com/beam-community/stripity-stripe/blob/main/_autodocs/13-common-entities.md Illustrates specific examples of the common API endpoint patterns applied to the 'customers' resource. These examples show how to perform various operations on customer data. ```text GET /v1/customers # List customers POST /v1/customers # Create customer GET /v1/customers/cus_123 # Retrieve customer POST /v1/customers/cus_123 # Update customer DELETE /v1/customers/cus_123 # Delete customer GET /v1/customers/cus_123/payment_methods # List payment methods ``` -------------------------------- ### Stripe.SetupAttempt Source: https://github.com/beam-community/stripity-stripe/blob/main/_autodocs/13-common-entities.md Represents a record of a setup attempt for a payment method. Supports list and retrieve operations. ```APIDOC ## Stripe.SetupAttempt ### Description Record of a setup attempt. ### Operations - list - retrieve ### Usage Examples ```elixir {:ok, attempts} = Stripe.SetupAttempt.list(%{ setup_intent: "seti_123" }) ``` ``` -------------------------------- ### Example Stripe.Event Structure Source: https://github.com/beam-community/stripity-stripe/blob/main/_autodocs/05-webhook-integration.md Illustrates a concrete example of a Stripe.Event struct, showing typical values for its fields. ```elixir %Stripe.Event{ id: "evt_1234567890", type: "charge.succeeded", created: 1234567890, livemode: false, api_version: "2025-11-17.clover", account: nil, request: %{id: nil, idempotency_key: nil}, data: %{ object: %Stripe.Charge{ id: "ch_1234567890", amount: 2000, currency: "usd", status: "succeeded", ... }, previous_attributes: nil } } ``` -------------------------------- ### Search Customer by Name Source: https://github.com/beam-community/stripity-stripe/blob/main/_autodocs/07-core-types.md Example of using the `search_query()` type to find customers by their name. ```elixir Stripe.Customer.search(%{query: "name:\"John Doe\""}) ``` -------------------------------- ### Paginate through Stripe Events Source: https://github.com/beam-community/stripity-stripe/blob/main/README.md Example demonstrating how to paginate through Stripe events, retrieving a marker for subsequent requests. ```elixir # Example of paging through events {:ok, events} = Stripe.Events.list key, "", 100 # second arg is a marker for paging case events[:has_more] do true -> # retrieve marker last = List.last( events[:data] ) case Stripe.Events.list key, last["id"], 100 do {:ok, events} -> events[:data] # ... end false -> events[:data] end ``` -------------------------------- ### Get Current and Past Timestamps Source: https://github.com/beam-community/stripity-stripe/blob/main/_autodocs/07-core-types.md Example demonstrating how to get the current Unix timestamp and calculate a timestamp from one hour ago. ```elixir now = System.system_time(:second) one_hour_ago = now - 3600 ``` -------------------------------- ### Stripe List Pagination Example Source: https://github.com/beam-community/stripity-stripe/blob/main/_autodocs/04-entity-structs.md Demonstrates how to request a specific number of items and then retrieve the next page of results using the `starting_after` parameter. ```elixir # Request first 10 items {:ok, list} = Stripe.Charge.list(%{limit: 10}) # Request next page using starting_after if list.has_more do last_id = List.last(list.data).id {:ok, next_page} = Stripe.Charge.list(%{ limit: 10, starting_after: last_id }) end ``` -------------------------------- ### Search Customer by Email Source: https://github.com/beam-community/stripity-stripe/blob/main/_autodocs/07-core-types.md Example of using the `search_query()` type to find customers by their email address. ```elixir Stripe.Customer.search(%{query: "email:\"test@example.com\""}) ``` -------------------------------- ### Run tests with stripe-mock configured Source: https://github.com/beam-community/stripity-stripe/blob/main/_autodocs/00-index.md After starting stripe-mock and configuring your application, run your tests using the standard Mix test command. ```bash mix test ``` -------------------------------- ### Create Customer with Address Source: https://github.com/beam-community/stripity-stripe/blob/main/_autodocs/07-core-types.md Example of creating a Stripe customer with a defined address. Ensure the address map contains the necessary fields. ```elixir address = %{ line1: "123 Main St", line2: "Apt 4B", city: "New York", state: "NY", postal_code: "10001", country: "US" } Stripe.Customer.create(%{ email: "customer@example.com", address: address }) ``` -------------------------------- ### Elixir Example Transfer Schedule Source: https://github.com/beam-community/stripity-stripe/blob/main/_autodocs/07-core-types.md An example of how to define a weekly transfer schedule with a 2-day delay in Elixir. ```elixir # Transfer every Monday with 2-day delay transfer_schedule = %{ interval: "weekly", weekly_anchor: "monday", delay_days: 2 } ``` -------------------------------- ### Minimal Stripity Stripe Configuration Source: https://github.com/beam-community/stripity-stripe/blob/main/_autodocs/06-configuration-reference.md Sets the Stripe API key using an environment variable. This is the most basic setup required. ```elixir import Config config :stripity_stripe, api_key: System.get_env("STRIPE_SECRET_KEY") ``` -------------------------------- ### Example of Conditional Retry Logic Source: https://github.com/beam-community/stripity-stripe/blob/main/_autodocs/03-api-module.md Illustrates how to use the `should_retry?` function to conditionally retry an API request. This example shows checking for a 429 Too Many Requests error and calculating backoff time. ```elixir response = {:error, 429, [], ""} config = [max_attempts: 5, base_backoff: 1000] if Stripe.API.should_retry?(response, 1, config) do # Wait and retry :timer.sleep(Stripe.API.backoff(1, config)) # Make request again end ``` -------------------------------- ### List Charges Over a Certain Amount Source: https://github.com/beam-community/stripity-stripe/blob/main/_autodocs/07-core-types.md Example of using `integer_query()` to find charges exceeding a specific amount (e.g., over $100.00). ```elixir # Get charges over $100 Stripe.Charge.list(%{ amount: %{gte: 10000} # $100.00 }) ``` -------------------------------- ### List Charges within an Amount Range Source: https://github.com/beam-community/stripity-stripe/blob/main/_autodocs/07-core-types.md Example of using `integer_query()` to retrieve charges within a specified minimum and maximum amount range. ```elixir # Get charges in a specific amount range Stripe.Charge.list(%{ amount: %{ gte: 1000, # $10.00 lte: 100000 # $1000.00 } }) ``` -------------------------------- ### Install Stripity Stripe by Version Source: https://github.com/beam-community/stripity-stripe/blob/main/README.md Add the Stripity Stripe dependency to your project's mix.exs file using a version constraint. ```elixir {:stripity_stripe, "~> 2.0"} ``` -------------------------------- ### Example of Backoff Calculation Source: https://github.com/beam-community/stripity-stripe/blob/main/_autodocs/03-api-module.md Shows how to use the `backoff` function with different attempt numbers and configurations to determine appropriate wait times between retries. The results demonstrate exponential growth capped by `max_backoff`. ```elixir config = [base_backoff: 500, max_backoff: 5000] backoff_ms = Stripe.API.backoff(0, config) # ~250-500ms backoff_ms = Stripe.API.backoff(1, config) # ~500-1000ms backoff_ms = Stripe.API.backoff(2, config) # ~1000-2000ms backoff_ms = Stripe.API.backoff(3, config) # ~2000-4000ms backoff_ms = Stripe.API.backoff(4, config) # ~2000-5000ms (capped) ``` -------------------------------- ### Stripe Search Pagination Example Source: https://github.com/beam-community/stripity-stripe/blob/main/_autodocs/04-entity-structs.md Shows how to search for entities by a query and retrieve subsequent pages of results using the `page` parameter with the `next_page` token. ```elixir # Search customers by email {:ok, results} = Stripe.Customer.search(%{query: "email:\"test@example.com\""}) # Get next page if results.has_more do {:ok, next} = Stripe.Customer.search(%{ query: "email:\"test@example.com\"", page: results.next_page }) end ``` -------------------------------- ### Install Stripity Stripe by Git Reference Source: https://github.com/beam-community/stripity-stripe/blob/main/README.md Add the Stripity Stripe dependency by specifying a Git repository URL and a commit reference. ```elixir {:stripity_stripe, git: "https://github.com/beam-community/stripity_stripe", ref: "017d7ecdb5aeadccc03986c02396791079178ba2"} ``` -------------------------------- ### Create Account with DOB Source: https://github.com/beam-community/stripity-stripe/blob/main/_autodocs/07-core-types.md Example of creating a Stripe account for an individual, including their date of birth. The DOB fields should be within their valid ranges. ```elixir dob = %{day: 15, month: 6, year: 1990} Stripe.Account.create(%{ type: "individual", individual: %{ dob: dob } }) ``` -------------------------------- ### Development Setup with ngrok Source: https://github.com/beam-community/stripity-stripe/blob/main/_autodocs/05-webhook-integration.md Use ngrok to expose your local development server to the internet, allowing Stripe to send webhook events to your local machine. This involves running ngrok and configuring your Stripe webhook endpoint URL. ```bash # Terminal 1: Start ngrok ngrok http 4000 # Terminal 2: Configure callback in Stripe Dashboard # https://your-ngrok-url.ngrok.io/webhooks/stripe # Terminal 3: Run your app mix phx.server ``` -------------------------------- ### Troubleshooting: No Valid API Key Provided Source: https://github.com/beam-community/stripity-stripe/blob/main/_autodocs/06-configuration-reference.md Check the API key configuration in IEx. The resolved API key should be a non-empty string starting with 'sk_test_' or 'sk_live_'. ```elixir # Check in iex Stripe.Config.resolve(:api_key) # Should return a non-empty string starting with sk_test_ or sk_live_ ``` -------------------------------- ### List Charges Created in Last 7 Days Source: https://github.com/beam-community/stripity-stripe/blob/main/_autodocs/07-core-types.md Example of using `date_query()` to retrieve charges created within the last seven days. ```elixir # Get charges created in the last 7 days seven_days_ago = System.system_time(:second) - (7 * 24 * 3600) Stripe.Charge.list(%{ created: %{gte: seven_days_ago} }) ``` -------------------------------- ### Create Charge with Metadata Source: https://github.com/beam-community/stripity-stripe/blob/main/_autodocs/07-core-types.md Example of creating a Stripe charge and attaching metadata. Metadata keys and values must be strings, and there are limits on the number of keys and total size. ```elixir metadata = %{ "order_id" => "12345", "user_id" => "user_abc", "app_version" => "2.1.0" } Stripe.Charge.create(%{ amount: 2000, currency: "usd", metadata: metadata }) # Retrieve later {:ok, charge} = Stripe.Charge.retrieve("ch_123") charge.metadata["order_id"] # "12345" ``` -------------------------------- ### Paginate Through Charge Results Source: https://github.com/beam-community/stripity-stripe/blob/main/_autodocs/09-charge-entity.md Demonstrates how to paginate through charge results. Fetch the first page, get the ID of the last charge, and use it with `starting_after` to fetch the next page. ```elixir {:ok, first_page} = Stripe.Charge.list(%{limit: 10}) if first_page.has_more do last_id = List.last(first_page.data).id {:ok, second_page} = Stripe.Charge.list(%{ limit: 10, starting_after: last_id }) end ``` -------------------------------- ### Example of Generating and Using Idempotency Key Source: https://github.com/beam-community/stripity-stripe/blob/main/_autodocs/03-api-module.md Demonstrates how to generate an idempotency key and include it in an API request. This is useful for ensuring that duplicate POST requests are handled correctly by the Stripe API. ```elixir key = Stripe.API.generate_idempotency_key() # "5f8d4c6a3b2e1f9d7c5a4b3e2f1d9c8b7a6e5f4d3c2b1a0f9e8d7c6b5a4f3e" Stripe.API.request( %{amount: 2000}, :post, "/v1/charges", %{}, [idempotency_key: key] ) ``` -------------------------------- ### Create Charge with Shipping Source: https://github.com/beam-community/stripity-stripe/blob/main/_autodocs/07-core-types.md Example of creating a Stripe charge that includes shipping details. The shipping address must be a valid address map. ```elixir shipping = %{ name: "John Doe", address: %{ line1: "123 Main St", city: "New York", state: "NY", postal_code: "10001", country: "US" }, phone: "+1-555-123-4567", carrier: "FedEx", tracking_number: "794644701157" } Stripe.Charge.create(%{ amount: 2000, currency: "usd", source: "tok_visa", shipping: shipping }) ``` -------------------------------- ### Manual Testing Setup for Stripe Connect Source: https://github.com/beam-community/stripity-stripe/blob/main/README.md Instructions for manually testing Stripe Connect by obtaining an OAuth authorization code. This involves logging into the Stripe dashboard, creating a standalone account, and capturing the code from the redirect URL. ```text First, log in your account. Then go to the following url: https://dashboard.stripe.com/account/applications/settings Create a connect standalone account. Grab your development `client_id`. Put it in your config file. Enter a redirect url to your endpoint. Capture the "code" request parameter. Pass it to `Stripe.Connect.oauth_token_callback` or `Stripe.Connect.get_token`. ``` -------------------------------- ### Update a Stripe Subscription with optional parameters Source: https://github.com/beam-community/stripity-stripe/blob/main/README.md Example of updating a subscription by providing customer ID, subscription ID, and a keyword list of changes. ```elixir # Change customer to the Premium subscription {:ok, result} = Stripe.Customers.change_subscription "customer_id", "sub_id", [plan: "premium"] ``` -------------------------------- ### Define a Stripe Event Handler Source: https://github.com/beam-community/stripity-stripe/blob/main/_autodocs/05-webhook-integration.md Implement the `Stripe.WebhookHandler` behavior to define how to process different Stripe event types. This example shows handling 'charge.succeeded', 'charge.failed', and 'customer.subscription.created', with a catch-all for other events. ```elixir defmodule MyApp.StripeHandler do use Stripe.WebhookHandler @impl true def handle_event(%Stripe.Event{type: "charge.succeeded"} = event) do charge = event.data.object # Handle successful charge {:ok, "Charge processed"} end def handle_event(%Stripe.Event{type: "charge.failed"} = event) do charge = event.data.object # Handle failed charge {:ok, "Charge failure handled"} end def handle_event(%Stripe.Event{type: "customer.subscription.created"} = event) do subscription = event.data.object # Handle new subscription {:ok, "Subscription created"} end @impl true def handle_event(_event) do # Catch all other events {:ok, "Event acknowledged"} end end ``` -------------------------------- ### List Charges within a Specific Date Range Source: https://github.com/beam-community/stripity-stripe/blob/main/_autodocs/07-core-types.md Example of using `date_query()` to retrieve charges within a defined date range using Unix timestamps. ```elixir # Get charges from a specific date range Stripe.Charge.list(%{ created: %{ gte: 1577836800, # Jan 1, 2020 lt: 1609459200 # Jan 1, 2021 } }) ``` -------------------------------- ### Create and Retrieve SetupIntent Source: https://github.com/beam-community/stripity-stripe/blob/main/_autodocs/13-common-entities.md Use to create a SetupIntent for saving a payment method without immediate charging. The client_secret is then passed to the frontend for confirmation. Retrieve a SetupIntent to check its status. ```elixir {:ok, intent} = Stripe.SetupIntent.create(%{ customer: "cus_123" }) # Pass intent.client_secret to frontend # Frontend confirms payment method {:ok, confirmed} = Stripe.SetupIntent.retrieve("seti_123") # confirmed.payment_method contains saved method ID ``` -------------------------------- ### Create Stripe SetupIntent Source: https://github.com/beam-community/stripity-stripe/blob/main/README.md Create a new SetupIntent object in Stripe. The intent ID is then passed to the frontend for the user to enter payment details. ```elixir {:ok, setup_intent} = Stripe.SetupIntent.create(%{}) # Return the ID to your frontend, and pass it to the confirmCardSetup method from Stripe elements {:ok, setup_intent.id} ``` -------------------------------- ### Create Customer and Subscribe to a Plan Source: https://github.com/beam-community/stripity-stripe/blob/main/_autodocs/10-customer-entity.md Creates a new customer and immediately subscribes them to a specified plan. This pattern uses `with` for sequential operations. ```elixir def create_customer_with_subscription(email, plan_id) do with {:ok, customer} <- Stripe.Customer.create(%{email: email}), {:ok, subscription} <- Stripe.Subscription.create(%{ customer: customer.id, items: [%{price: plan_id}] }) do {:ok, {customer, subscription}} else {:error, error} -> {:error, error} end end ``` -------------------------------- ### Delete a Stripe Customer Source: https://github.com/beam-community/stripity-stripe/blob/main/README.md Example of how to delete a customer by providing their ID. ```elixir {:ok, result} = Stripe.Customers.delete "some_id" ``` -------------------------------- ### Stripe.SetupIntent Source: https://github.com/beam-community/stripity-stripe/blob/main/_autodocs/13-common-entities.md Represents an intent for saving a payment method without charging. Supports create, retrieve, confirm, cancel, and list operations. ```APIDOC ## Stripe.SetupIntent ### Description Intent for saving a payment method without charging. ### Operations - create - retrieve - confirm - cancel - list ### Usage Examples ```elixir {:ok, intent} = Stripe.SetupIntent.create(%{ customer: "cus_123" }) # Pass intent.client_secret to frontend # Frontend confirms payment method {:ok, confirmed} = Stripe.SetupIntent.retrieve("seti_123") # confirmed.payment_method contains saved method ID ``` ``` -------------------------------- ### Create a Subscription Source: https://github.com/beam-community/stripity-stripe/blob/main/_autodocs/00-index.md Creates a new customer and then a subscription for that customer with a specified price ID. ```elixir # Create customer {:ok, customer} = Stripe.Customer.create(%{ email: "user@example.com" }) # Create subscription {:ok, subscription} = Stripe.Subscription.create(%{ customer: customer.id, items: [%{price: "price_monthly"}] }) ``` -------------------------------- ### Runtime Configuration for Production Source: https://github.com/beam-community/stripity-stripe/blob/main/_autodocs/06-configuration-reference.md Configure API keys using environment variables for production releases. This file is compiled and executed at startup. ```elixir # config/runtime.exs import Config if config_env() == :prod do config :stripity_stripe, api_key: System.get_env("STRIPE_SECRET_KEY") || raise("STRIPE_SECRET_KEY environment variable not set") end ``` -------------------------------- ### Charge Creation with Options Source: https://github.com/beam-community/stripity-stripe/blob/main/_autodocs/07-core-types.md Demonstrates creating a Stripe Charge using common options like `api_key`, `expand`, and `idempotency_key`. Ensure you have a valid test API key. ```elixir Stripe.Charge.create( %{amount: 2000, currency: "usd"}, api_key: "sk_test_...", expand: ["customer"], idempotency_key: "unique-key-123" ) ``` -------------------------------- ### Expanded Charge Object Source: https://github.com/beam-community/stripity-stripe/blob/main/README.md Example of a Charge object where the 'balance_transaction' field has been expanded to show its full details. ```elixir %Charge{ id: "ch_123", balance_transaction: %BalanceTransaction{ id: "txn_123", fee: 125, ... }, ... } ``` -------------------------------- ### retrieve/2 — Get a Charge Source: https://github.com/beam-community/stripity-stripe/blob/main/_autodocs/09-charge-entity.md Retrieves a specific charge by its unique ID, with an option to expand related objects. ```APIDOC ## retrieve/2 — Get a Charge ### Description Retrieves a charge by its ID. This operation allows for expanding certain fields to include more detailed information directly in the response. ### Method GET (implied by retrieve operation) ### Endpoint /v1/charges/{charge_id} (implied by Stripe API conventions) ### Parameters #### Path Parameters - **charge** (binary) - Required: Yes - Charge ID. #### Query Parameters - **params** (map) - Required: No - Query parameters. See 'Params Keys' for details. - **opts** (Keyword.t()) - Required: No - Shared options. **Params Keys:** - **:expand** ([binary]) - Required: No - Fields to expand (e.g., `["customer"]`). ### Request Example ```elixir {:ok, charge} = Stripe.Charge.retrieve("ch_123") ``` ### Response #### Success Response (200) - **charge** (Stripe.Charge.t()) - The retrieved charge object. #### Response Example ```elixir # Example response structure (actual fields may vary) %{ "id": "ch_123", "amount": 2000, "currency": "usd", ... } ``` ``` -------------------------------- ### put_method/2 Source: https://github.com/beam-community/stripity-stripe/blob/main/_autodocs/01-request-api.md Specifies the HTTP method for the request. Supported methods include GET, POST, PUT, PATCH, and DELETE. ```APIDOC ## put_method/2 ### Description Specifies the HTTP method for the request. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Method Signature ```elixir @spec put_method(t, Stripe.API.method()) :: t def put_method(%Request{} = request, method) when method in [:get, :post, :put, :patch, :delete] ``` ### Parameters - **request** (Stripe.Request.t()) - Required - The request being configured - **method** (Stripe.API.method()) - Required - One of `:get`, `:post`, `:put`, `:patch`, `:delete` ### Returns The updated request struct. ### Example ```elixir request = Stripe.Request.new_request() |> Stripe.Request.put_method(:post) ``` ``` -------------------------------- ### Update Stripe Customer Metadata Source: https://github.com/beam-community/stripity-stripe/blob/main/_autodocs/13-common-entities.md Update an existing customer's metadata, for example, to record the last login time. ```elixir # Update metadata {:ok, _} = Stripe.Customer.update("cus_123", %{ metadata: %{"last_login" => "2024-01-15"} }) ``` -------------------------------- ### Skip stripe-mock during tests Source: https://github.com/beam-community/stripity-stripe/blob/main/README.md Set the SKIP_STRIPE_MOCK_RUN environment variable to 1 to prevent the test runner from starting stripe-mock automatically. ```sh SKIP_STRIPE_MOCK_RUN=1 mix test ``` -------------------------------- ### List All Customers with Pagination Source: https://github.com/beam-community/stripity-stripe/blob/main/_autodocs/10-customer-entity.md Recursively lists all customers, fetching them in pages of 100 until all customers are retrieved. Handles pagination using `starting_after`. ```elixir def list_all_customers do list_customers_page([], nil) end defp list_customers_page(acc, starting_after) do params = %{limit: 100} params = if starting_after, do: Map.put(params, :starting_after, starting_after), else: params case Stripe.Customer.list(params) do {:ok, %{data: data, has_more: false}} -> acc ++ data {:ok, %{data: data, has_more: true}} -> last_id = List.last(data).id list_customers_page(acc ++ data, last_id) error -> error end end ``` -------------------------------- ### new_request/2 Source: https://github.com/beam-community/stripity-stripe/blob/main/_autodocs/01-request-api.md Creates a new request with optional shared options and headers. This is the starting point for building a Stripe API request. ```APIDOC ## new_request/2 ### Description Creates a new request with optional shared options and headers. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Method Signature ```elixir @spec new_request(Stripe.options(), map) :: t def new_request(opts \ [], headers \ %{}) ``` ### Parameters - **opts** (Stripe.options()) - Optional - Shared options (`:api_key`, `:connect_account`, etc.) - **headers** (map) - Optional - Custom HTTP headers ### Returns A new `Stripe.Request.t()` struct ready to be configured. ### Example ```elixir request = Stripe.Request.new_request(api_key: "sk_test_...") ``` ``` -------------------------------- ### retrieve/2 — Get a Customer Source: https://github.com/beam-community/stripity-stripe/blob/main/_autodocs/10-customer-entity.md Retrieves a specific customer by their unique ID. Supports expanding related objects in the response. ```APIDOC ## retrieve/2 — Get a Customer ### Description Retrieves a customer by ID. ### Method GET (inferred from retrieve operation) ### Endpoint /v1/customers/{customer_id} ### Parameters #### Path Parameters - **customer** (binary) - Required - Customer ID #### Query Parameters - **expand** (array of strings) - Optional - Related objects to expand (e.g., `["default_source", "sources", "subscriptions"]`) ### Response #### Success Response (200) - **Stripe.Customer.t()** - The requested customer struct. ``` -------------------------------- ### Create and Attach a PaymentMethod Source: https://github.com/beam-community/stripity-stripe/blob/main/_autodocs/13-common-entities.md This snippet demonstrates creating a payment method and then attaching it to a customer. Ensure you have the customer ID. ```elixir # Create payment method {:ok, pm} = Stripe.PaymentMethod.create(%{ type: "card", card: %{ number: "4242424242424242", exp_month: 12, exp_year: 2026, cvc: "314" } }) # Attach to customer {:ok, _} = Stripe.PaymentMethod.attach(%{ payment_method: pm.id, customer: "cus_123" }) ``` -------------------------------- ### Retrieve a Charge by ID Source: https://github.com/beam-community/stripity-stripe/blob/main/_autodocs/09-charge-entity.md Fetch a specific charge using its unique ID. This is the most straightforward way to get charge details. ```elixir {:ok, charge} = Stripe.Charge.retrieve("ch_123") ``` -------------------------------- ### retrieve/2 — Get a PaymentIntent Source: https://github.com/beam-community/stripity-stripe/blob/main/_autodocs/11-payment-intent-entity.md Retrieves a specific PaymentIntent using its unique ID, with the option to expand related objects in the response. ```APIDOC ## retrieve/2 — Get a PaymentIntent ### Description Retrieves a payment intent by its unique ID. You can also expand related objects in the response to get more details in a single request. ### Method GET ### Endpoint /v1/payment_intents/{intent} ### Parameters #### Path Parameters - **intent** (binary) - Required - Payment intent ID #### Query Parameters - **expand** (array) - Optional - List of related objects to expand (e.g., `["customer", "payment_method"]`) ### Response #### Success Response (200) - **id** (string) - Unique identifier for the PaymentIntent - **object** (string) - The type of object, "payment_intent" - **amount** (integer) - The amount processed - **currency** (string) - The currency of the amount - **status** (string) - The current status of the PaymentIntent - **customer** (object or string) - Customer details if expanded - **payment_method** (object or string) - Payment method details if expanded #### Response Example ```json { "id": "pi_123", "object": "payment_intent", "amount": 2000, "currency": "usd", "status": "succeeded", "customer": { "id": "cus_123", "object": "customer" }, "payment_method": { "id": "pm_456", "object": "payment_method" } } ``` ``` -------------------------------- ### create/2 — Create a Customer Source: https://github.com/beam-community/stripity-stripe/blob/main/_autodocs/10-customer-entity.md Creates a new customer with the provided parameters. Supports various fields like email, name, address, and metadata. ```APIDOC ## create/2 — Create a Customer ### Description Creates a new customer. ### Method POST (inferred from create operation) ### Endpoint /v1/customers ### Parameters #### Request Body - **email** (binary) - Optional - Customer email - **name** (binary) - Optional - Customer name - **phone** (binary) - Optional - Customer phone - **description** (binary) - Optional - Customer notes - **metadata** (map) - Optional - Custom metadata - **address** (map) - Optional - Customer address - **shipping** (map) - Optional - Shipping address - **default_source** (binary) - Optional - Default payment source ID - **tax_exempt** (binary) - Optional - "none", "exempt", or "reverse" ### Request Example ```json { "email": "john@example.com", "name": "John Doe", "phone": "+1-555-123-4567", "description": "VIP customer", "address": { "line1": "123 Main St", "city": "New York", "state": "NY", "postal_code": "10001", "country": "US" }, "shipping": { "name": "John Doe", "address": { "line1": "456 Oak Ave", "city": "Boston", "state": "MA", "postal_code": "02101", "country": "US" } }, "metadata": { "user_id": "12345", "app_version": "2.1.0" } } ``` ### Response #### Success Response (200) - **Stripe.Customer.t()** - The created customer struct. ``` -------------------------------- ### Create a PaymentIntent Source: https://github.com/beam-community/stripity-stripe/blob/main/_autodocs/13-common-entities.md Use this snippet to create a PaymentIntent, the recommended method for modern payment handling. ```elixir {:ok, intent} = Stripe.PaymentIntent.create(%{ amount: 2000, currency: "usd" }) ``` -------------------------------- ### Specify HTTP Method Source: https://github.com/beam-community/stripity-stripe/blob/main/_autodocs/01-request-api.md Configures the HTTP method for the request. Valid methods include :get, :post, :put, :patch, and :delete. ```elixir request = Stripe.Request.new_request() |> Stripe.Request.put_method(:post) ``` -------------------------------- ### Development Environment Configuration Source: https://github.com/beam-community/stripity-stripe/blob/main/_autodocs/06-configuration-reference.md Configure API key and API version for the development environment. Use a test key for development. ```elixir # config/dev.exs import Config config :stripity_stripe, api_key: "sk_test_...", # test key api_version: "2025-11-17.clover" ``` -------------------------------- ### Create Subscription Source: https://github.com/beam-community/stripity-stripe/blob/main/_autodocs/10-customer-entity.md Creates a new subscription for a customer with specified price items. ```APIDOC ## Create Subscription ### Description Creates a new subscription for a customer with specified price items. ### Method Elixir Function ### Parameters #### Request Body - **customer** (binary) - Required - The ID of the customer. - **items** (list) - Required - A list of subscription items, each containing a price ID. ### Request Example ```elixir {:ok, subscription} = Stripe.Subscription.create(%{ customer: "cus_123", items: [%{price: "price_monthly_plan"}] }) ``` ### Response #### Success Response - **{:ok, subscription}** - The created subscription object. ``` -------------------------------- ### Configure JSON Library Source: https://github.com/beam-community/stripity-stripe/blob/main/_autodocs/06-configuration-reference.md Choose the JSON encoding/decoding library to use. The default is `Jason` if available. Both `Jason` and `Poison` require being added as dependencies. ```elixir config :stripity_stripe, json_library: Jason ``` ```elixir config :stripity_stripe, json_library: Poison ``` ```elixir defp deps do [ {:stripity_stripe, "~> 2.0"}, {:jason, "~> 1.0"} # or {:poison, "~> 5.0"} ] end ``` -------------------------------- ### Schedule Subscription Changes Source: https://github.com/beam-community/stripity-stripe/blob/main/_autodocs/13-common-entities.md Schedules future changes to subscription details, such as price adjustments. Requires specifying a start date and phases for changes. ```elixir # Schedule price change for next month {:ok, schedule} = Stripe.SubscriptionSchedule.create(%{ customer: "cus_123", start_date: future_timestamp, phases: [ %{ start_date: future_timestamp, items: [%{price: "price_new"}] } ] }) ``` -------------------------------- ### Get OAuth Token Source: https://github.com/beam-community/stripity-stripe/blob/main/_autodocs/12-connect-oauth.md Exchanges the authorization code received after user authorization for an access token and other credentials. This is the second step in the OAuth flow. ```APIDOC ## `Stripe.Connect.OAuth.get_token/1` ### Description Exchanges the authorization code received after user authorization for an access token and other credentials. ### Parameters #### Path Parameters - **code** (String.t()) - Required - The authorization code received from Stripe. ### Returns `{:ok, token_response}` on success, where `token_response` contains the access token and other details. `{:error, reason}` on failure. ### Example ```elixir defp process_authorization(code) do case Stripe.Connect.OAuth.get_token(code) do {:ok, token_response} -> save_stripe_credentials(token_response) {:ok, "Connected"} {:error, reason} -> {:error, "Failed to connect: #{inspect(reason)}"} end end ``` ``` -------------------------------- ### Create a Full Customer with Details Source: https://github.com/beam-community/stripity-stripe/blob/main/_autodocs/10-customer-entity.md Use this snippet to create a new Stripe customer, providing comprehensive details including name, phone, address, shipping, and metadata. ```elixir {:ok, customer} = Stripe.Customer.create(%{ email: "john@example.com", name: "John Doe", phone: "+1-555-123-4567", description: "VIP customer", address: %{ line1: "123 Main St", city: "New York", state: "NY", postal_code: "10001", country: "US" }, shipping: %{ name: "John Doe", address: %{ line1: "456 Oak Ave", city: "Boston", state: "MA", postal_code: "02101", country: "US" } }, metadata: %{ "user_id" => "12345", "app_version" => "2.1.0" } }) ``` -------------------------------- ### Expand Related Objects in Stripe Charges Source: https://github.com/beam-community/stripity-stripe/blob/main/_autodocs/13-common-entities.md Retrieve a charge and expand its customer and balance transaction objects to get full details instead of just IDs. ```elixir # Without expansion {:ok, charge} = Stripe.Charge.retrieve("ch_123") charge.customer # "cus_456" (just ID) # With expansion {:ok, charge} = Stripe.Charge.retrieve("ch_123", %{ expand: ["customer", "balance_transaction"] }) charge.customer # %Stripe.Customer{...} (full object) charge.balance_transaction # %Stripe.BalanceTransaction{...} ``` -------------------------------- ### Handle customer.subscription.created Event in Elixir Source: https://github.com/beam-community/stripity-stripe/blob/main/_autodocs/05-webhook-integration.md Record a new customer subscription in the database. Logs success or returns an error. ```elixir def handle_event(%Stripe.Event{type: "customer.subscription.created"} = event) do %Stripe.Subscription{ id: subscription_id, customer: customer_id, items: items, current_period_end: period_end } = event.data.object case create_subscription_in_db(customer_id, subscription_id, period_end) do {:ok, _} -> Logger.info("Subscription created: #{subscription_id}") {:ok, "Subscription recorded"} {:error, reason} -> {:error, reason} end end ``` -------------------------------- ### Create a Simple Charge Source: https://github.com/beam-community/stripity-stripe/blob/main/_autodocs/09-charge-entity.md Use this snippet to create a basic charge with amount, currency, and a payment source token. ```elixir {:ok, charge} = Stripe.Charge.create(%{ amount: 2000, currency: "usd", source: "tok_visa" }) ``` -------------------------------- ### Handle Stripe OAuth Callback and Get Token Source: https://github.com/beam-community/stripity-stripe/blob/main/_autodocs/12-connect-oauth.md Processes the redirect from Stripe after user authorization. Verifies the CSRF token and exchanges the authorization code for an access token. ```elixir def stripe_connect_callback(conn, %{"code" => code, "state" => state}) do # Verify CSRF token stored_csrf = get_session(conn, :stripe_csrf) if state != stored_csrf do send_resp(conn, 400, "Invalid CSRF token") else process_authorization(code) end end defp process_authorization(code) do case Stripe.Connect.OAuth.get_token(code) do {:ok, token_response} -> save_stripe_credentials(token_response) {:ok, "Connected"} {:error, reason} -> {:error, "Failed to connect: #{inspect(reason)}"} end end ``` -------------------------------- ### Create Stripe Customer with Metadata Source: https://github.com/beam-community/stripity-stripe/blob/main/_autodocs/13-common-entities.md Create a new customer and attach custom metadata, such as user ID and tier. ```elixir {:ok, customer} = Stripe.Customer.create(%{ email: "test@example.com", metadata: %{ "user_id" => "12345", "tier" => "gold" } }) ``` -------------------------------- ### Get Configured JSON Library Module Source: https://github.com/beam-community/stripity-stripe/blob/main/_autodocs/03-api-module.md Retrieves the JSON library module (Jason or Poison) configured for the application. This is useful for encoding data structures into JSON format. ```elixir @type method :: :get | :post | :put | :delete | :patch @type headers :: %{String.t() => String.t()} | %{} @type body :: iodata() | {:multipart, list()} ``` ```elixir @spec json_library() :: module def json_library() Returns the JSON library module configured in the application. **Returns:** Either `Jason` (default) or `Poison` (if configured). **Configuration:** Set via `config :stripity_stripe, json_library: Poison` ``` ```elixir json_module = Stripe.API.json_library() json_module.encode!(%{amount: 2000}) ``` -------------------------------- ### Production Environment Configuration Source: https://github.com/beam-community/stripity-stripe/blob/main/_autodocs/06-configuration-reference.md Configure API key, connection pool options, and retry settings for the production environment. This includes setting a production API key from environment variables and tuning pool and retry parameters for performance and resilience. ```elixir # config/prod.exs import Config config :stripity_stripe, api_key: System.get_env("STRIPE_SECRET_KEY") || raise "STRIPE_SECRET_KEY not set", pool_options: [ timeout: 10_000, max_connections: 20 # higher for prod ], retries: [ max_attempts: 5, # more aggressive retries base_backoff: 500, max_backoff: 5_000 ] ``` -------------------------------- ### Handle Stripe API Errors Source: https://github.com/beam-community/stripity-stripe/blob/main/_autodocs/README.md This example demonstrates how to handle potential errors when making Stripe API calls. It specifically checks for card errors and logs other general errors. ```elixir case Stripe.Charge.create(params) do {:ok, charge} -> process(charge) {:error, %Stripe.Error{code: :card_error} = error} -> show_to_user(error.user_message) {:error, error} -> log_error(error) end ``` -------------------------------- ### Create a Charge Source: https://github.com/beam-community/stripity-stripe/blob/main/_autodocs/13-common-entities.md Use this snippet to create a legacy charge. Note that PaymentIntent is recommended for new code. ```elixir {:ok, charge} = Stripe.Charge.create(%{ amount: 2000, currency: "usd", source: "tok_visa" }) ``` -------------------------------- ### Stripe Connect OAuth Token Response Structure Source: https://github.com/beam-community/stripity-stripe/blob/main/README.md This is an example of the response structure received after a successful OAuth token callback. It contains essential keys like access_token, refresh_token, and stripe_user_id. ```elixir %{ token_type: "bearer", stripe_publishable_key: PUBLISHABLE_KEY, scope: "read_write", livemode: false, stripe_user_id: USER_ID, refresh_token: REFRESH_TOKEN, access_token: ACCESS_TOKEN } ``` -------------------------------- ### Configure Stripity Stripe for stripe-mock Source: https://github.com/beam-community/stripity-stripe/blob/main/_autodocs/00-index.md Configure your application to use the local stripe-mock instance by setting the API key and base URL in your configuration. ```elixir config :stripity_stripe, api_key: "sk_test_...", api_base_url: "http://localhost:12111" ``` -------------------------------- ### Create Customer Subscription Source: https://github.com/beam-community/stripity-stripe/blob/main/_autodocs/10-customer-entity.md Creates a new subscription for a customer, linking them to a specific pricing plan. Requires customer ID and item details including price ID. ```elixir {:ok, subscription} = Stripe.Subscription.create(%{ customer: "cus_123", items: [%{ price: "price_monthly_plan" }] }) ``` -------------------------------- ### Create Object Source: https://github.com/beam-community/stripity-stripe/blob/main/_autodocs/04-entity-structs.md Creates a new object with the provided parameters. ```APIDOC ## create/2 or create/3 Creates a new object. ### Method Signature ```elixir @spec create(params :: map, opts :: Keyword.t()) :: {:ok, struct} | {:error, Stripe.Error.t()} def create(params \\ %{}, opts \\ []) ``` ### Parameters #### Request Body - **params** (`map`) - Optional - Object data to create - **opts** (`Keyword.t()`) - Optional - Shared options (`:api_key`, `:idempotency_key`, etc.) ### Returns - The created object struct on success. - `{:error, Stripe.Error.t()}` on failure. ### Example ```elixir {:ok, charge} = Stripe.Charge.create(%{ amount: 2000, currency: "usd", source: "tok_visa" }) # %Stripe.Charge{id: "ch_...", amount: 2000, ...} ``` ``` -------------------------------- ### Create a Stripe Coupon Source: https://github.com/beam-community/stripity-stripe/blob/main/_autodocs/13-common-entities.md Creates a discount coupon with a specified percentage off and duration. Useful for promotional offers. ```elixir {:ok, coupon} = Stripe.Coupon.create(%{ percent_off: 10, duration: "forever", id: "10OFF" # Coupon code }) ``` -------------------------------- ### Configure API Module Settings Source: https://github.com/beam-community/stripity-stripe/blob/main/_autodocs/03-api-module.md Configure the API module with essential settings like API keys, versioning, base URLs, and retry options. This is typically done in `config/config.exs`. ```elixir config :stripity_stripe, api_key: System.get_env("STRIPE_SECRET_KEY"), api_version: "2025-11-17.clover", json_library: Jason, api_base_url: "https://api.stripe.com", api_upload_url: "https://files.stripe.com", use_connection_pool: true, pool_options: [ timeout: 5_000, max_connections: 10 ], hackney_opts: [ {:connect_timeout, 8_000}, {:recv_timeout, 30_000} ], retries: [ max_attempts: 3, base_backoff: 500, max_backoff: 2_000 ] ``` -------------------------------- ### Create a Minimal Payment Intent Source: https://github.com/beam-community/stripity-stripe/blob/main/_autodocs/11-payment-intent-entity.md Use this to create a new payment intent for frontend confirmation. The `client_secret` should be passed to the frontend. ```elixir {:ok, intent} = Stripe.PaymentIntent.create(%{ amount: 2000, currency: "usd" }) # Pass intent.client_secret to frontend ``` -------------------------------- ### Create a Stripe Product Source: https://github.com/beam-community/stripity-stripe/blob/main/_autodocs/13-common-entities.md Defines a product or service that can be sold. This is a prerequisite for creating prices associated with the product. ```elixir {:ok, product} = Stripe.Product.create(%{ name: "Premium Plan", type: "service" }) ``` -------------------------------- ### Create a Charge with Shared Options Source: https://github.com/beam-community/stripity-stripe/blob/main/_autodocs/00-index.md Demonstrates creating a Stripe charge using shared options that can override global configurations. This includes specifying an API key, API version, Stripe Connect account, expanding objects, idempotency keys, and response format. ```elixir Stripe.Charge.create( %{amount: 2000, currency: "usd"}, api_key: "sk_test_...", # Override API key api_version: "2025-11-17.clover", # Override API version connect_account: "acct_123", # Stripe Connect account expand: ["customer"], # Expand objects idempotency_key: "unique-key", # Idempotency response_as: :struct # Response format ) ``` -------------------------------- ### Test Environment Configuration Source: https://github.com/beam-community/stripity-stripe/blob/main/_autodocs/06-configuration-reference.md Configure API key, API base URL, and optionally disable the connection pool for the test environment. Disabling the pool can simplify testing. ```elixir # config/test.exs import Config config :stripity_stripe, api_key: "sk_test_", api_base_url: "http://localhost:12111", use_connection_pool: false # optional, simpler for tests ```