> ## Documentation Index
> Fetch the complete documentation index at: https://docs.stigg.io/llms.txt
> Use this file to discover all available pages before exploring further.

# Ruby

# Overview

This Ruby gem provides a wrapper to [Stigg's GraphQL API](./graphql) based on the operations that are in use by the [Stigg's Node.js SDK](/api-and-sdks/integration/backend/nodejs). It leverages the [graphlient](https://github.com/ashkan18/graphlient) library under the hood and utilizes the `Graphlient::Client` class to execute the API requests.

# Installing the SDK

The first step is to install the Stigg SDK as a dependency in your application using your application's dependency manager:

<CodeGroup>
  ```shell shell theme={null}
  bundle add stigg-api-client
  ```
</CodeGroup>

If bundler is not being used to manage dependencies, install the gem by executing:

<CodeGroup>
  ```shell shell theme={null}
  gem install stigg-api-client
  ```
</CodeGroup>

# Retrieving the full access key

In the Stigg app, go to **Integrations > API keys**.

Copy the **Full access key** of the relevant environment.

# Initializing the SDK

Import the Stigg client and initialize it with the API key:

<CodeGroup>
  ```ruby create_client.rb theme={null}
  require("stigg")

  api_key = ENV["STIGG_FULL_ACCESS_KEY"]

  client = Stigg.create_client(api_key)
  ```
</CodeGroup>

# Provisioning customers

When a new customer is provisioned within your application (for example: as part of your registration or onboarding process), you should also provision them in Stigg.

The customer's billing information can also be passed to Stigg when a customer is created or updated. When Stigg is integrated with additional service, this information will be propagated to the active integrations. The billing information is not persisted on Stigg's servers.

You can optionally pass `subscriptionParams` to create subscription for that customer using a single operation. Doing so, will allow Stigg admins to override the requested subscription with no-code from the Stigg app using the [product's Customer Journey configuration](/documentation/modeling-your-pricing-in-stigg/products/defining-customer-journey).

<CodeGroup>
  ```ruby provision_customer.rb theme={null}
  resp = client.request(Stigg::Mutation::ProvisionCustomer, {
      "input": {
          "customerId": "CUSTOMER-ID-1",
          "name": "Acme",							# optional
          "email": "john@example.com",	# optional - billing email address
          "couponRefId": "coupon-id", # optional
        	"subscriptionParams": {
              "planId": "plan-revvenu-basic"
            	"billingCountryCode":"DK"   # optional, required for price localization, must be in the ISO-3166-1 format
          }
          "billingInformation": {			# optional
              "language": "en",
              "timezone": "America/New_York",
              "billingAddress": {
                  "country": "US",
                  "city": "New York",
                  "state": "NY",
                  "addressLine1": "123 Main Street",
                  "addressLine2": "Apt. 1",
                  "phoneNumber": "+1 212-499-5321",
                  "postalCode": "10164"
              },
              "shippingAddress": {
                  "country": "US",
                  "city": "New York",
                  "state": "NY",
                  "addressLine1": "123 Main Street",
                  "addressLine2": "Apt. 1",
                  "phoneNumber": "+1 212-499-5321",
                  "postalCode": "10164"
              }
          },
          "additionalMetaData": {			# optional
              "key": "value"
          }
      },
  })
  ```
</CodeGroup>

<Expandable title="Result">
  ```json theme={null}
  {
      "data": {
          "provision_customer": {
              "customer": {
                  "id": "CUSTOMER-ID-1",
                  "name": "Acme",
                  "email": "john@example.com",
                  "created_at": "2022-11-13T22:50:13.185Z",
                  "updated_at": "2022-11-13T22:50:13.185Z",
                  "promotional_entitlements": [],
                  "has_payment_method": false,
                  "coupon": null,
                  "billing_id": null,
                  "metadata": {
                      "key": "value"
                  }
              },
              "subscription_strategy_decision": "REQUESTED_PLAN",
              "subscription": {
                  "id": "subscription-plan-revvenu-basic-9ee4ff",
                  "status": "ACTIVE",
                  "metadata": null,
                  "billing_id": null,
                  "billing_link_url": null,
                  "effective_end_date": null,
                  "current_billing_period_end": "2022-12-13T22:50:13.370Z",
                  "pricing_type": "FREE",
                  "prices": [],
                  "total_price": null,
                  "plan": {
                      "id": "plan-revvenu-basic"
                  },
                  "addons": [],
                  "customer": {
                      "id": "customer-id"
                  }
              }
          }
      }
  }
  ```
</Expandable>

# Updating customers

Customer information can also be updated whenever you like assuming it already exists, for example: In order to update the customer's email, you only need to send the new email value without the rest of the customer. Due to the fact that the customer's billing information is not persisted on Stigg's servers, in order to update it, the entire billing information object must be passed each time.

<CodeGroup>
  ```ruby update_customer.rb theme={null}
  resp = client.request(Stigg::Mutation::UpdateCustomer, {
      "input": {
          "customerId": "CUSTOMER-ID-1",
          "email": "john@example.com",
          "name": "Acme",
          "billingInformation": {
              "language": "en",
              "timezone": "America/New_York",
              "currency": "USD",
              "taxIds": [
                  {"type": "...", "value": "..."}
              ],
          },
          "additionalMetaData": {
              "key": "value"
          }
      }
  })
  ```
</CodeGroup>

<Expandable title="Result">
  ```json theme={null}
  {
    "data": {
      "update_customer": {
          "id": "CUSTOMER-ID-1",
          "name": "Acme",
          "email": "john@example.com",
          "created_at": "2022-10-30T23:25:44.099Z",
          "updated_at": "2022-10-30T23:46:50.675Z",
          "promotional_entitlements": [],
          "has_payment_method": false,
          "coupon": null,
          "billing_id": null,
          "metadata": {
              "key": "value"
          }
      }
    }
  }
  ```
</Expandable>

# Getting customer data

<CodeGroup>
  ```ruby get_customer_by_id.rb theme={null}
  resp = client.request(Stigg::Query::GetCustomerById,{
      "customerId": "customer-id"
  })
  ```
</CodeGroup>

<Expandable title="Result">
  ```json theme={null}
  {
    "data": {
      "customers": {
          "edges": [
              {
                  "node": {
                      "id": "customer-id2",
                      "name": "Acme",
                      "email": "john@example.com",
                      "created_at": "2022-10-30T23:25:44.099Z",
                      "updated_at": "2022-10-30T23:46:50.675Z",
                      "promotional_entitlements": [],
                      "has_payment_method": false,
                      "coupon": null,
                      "billing_id": null,
                      "metadata": {
                          "key": "value"
                      }
                  }
              }
          ]
      }
    }
  }
  ```
</Expandable>

# Listing customers active subscriptions

The `getActiveSubscriptionsList` method returns a list of slim subscription data, for extended data for a specific subscription use `getSubscription` method.

<CodeGroup>
  ```ruby get_active_subscriptions_list.rb theme={null}
  resp = client.request(Stigg::Query::GetActiveSubscriptionsList, {
  "input": {
    "customerId": "customer-id",
    "resourceId": "resource-id"  # required if multiple active subscriptions per product are enabled
    }
  })
  ```
</CodeGroup>

<Expandable title="Result">
  ```json theme={null}
  {
    "data": {
      "get_active_subscriptions": [
        {
          "subscription_id": "subscription-plan-stigg-pro-28a241",
          "status": "ACTIVE",
          "start_date": "2022-09-20T09:00:14.000Z",
          "end_date": null,
          "effective_end_date": "2023-09-20T09:00:14.000Z",
          "current_billing_period_start": "2023-08-20T09:00:14.000Z",
          "current_billing_period_end": "2023-09-20T09:00:14.000Z",
          "billing_period": "MONTHLY",
          "additional_meta_data": {
            "internal_tier_id": "tier-gold"
          },
          "customer": {
            "customer_id": "customer-demo-01",
            "email": "user@example.com"
          },
          "paying_customer": {
            "customer_id": "customer-demo-01",
            "email": "user@example.com"
          },
          "plan": {
            "plan_id": "plan-stigg-pro",
            "display_name": "Pro",
            "description": "Full access to all Pro features",
            "product": {
              "ref_id": "product-main",
              "display_name": "Main Product",
              "downgrade_plan": {
                "ref_id": "plan-free",
                "display_name": "Free Plan"
              }
            }
          },
          "addons": [
            {
              "quantity": 3,
              "addon": {
                "addon_id": "addon-stigg-1"
              }
            }
          ],
          "prices": [
            {
              "billing_model": "FLAT_FEE",
              "price": {
                "billing_period": "MONTHLY",
                "price": {
                  "amount": 99,
                  "currency": "USD"
                }
              }
            }
          ],
          "total_price": {
            "sub_total": {
              "amount": 99,
              "currency": "USD"
            },
            "total": {
              "amount": 99,
              "currency": "USD"
            }
          }
        }
      ]
    }
  }
  ```
</Expandable>

# Getting a subscription

To retrieve extended subscription data:

<CodeGroup>
  ```ruby get_subscription.rb theme={null}
  resp = client.request(Stigg::Query::GetSubscription,{
      "subscriptionId": "subscription-id",
  })
  ```
</CodeGroup>

<Expandable title="Result">
  ```json theme={null}
  {
    "data": {
      "get_subscription": {
        "id": "subscription-plan-revvenu-basic-169747",
        "status": "ACTIVE",
        "start_date": "2022-10-30T23:25:44.258Z",
        "end_date": null,
        "trial_end_date": null,
        "cancellation_date": null,
        "effective_end_date": null,
        "current_billing_period_end": "2022-11-30T23:25:44.258Z",
        "metadata": null,
        "billing_id": null,
        "billing_link_url": null,
        "prices": [],
        "total_price": null,
        "pricing_type": "FREE",
        "plan": {
          "id": "plan-revvenu-basic",
          "display_name": "Basic",
          "description": null,
          "metadata": null,
          "product": {
            "id": "product-revvenu",
            "display_name": "Revvenu",
            "description": null
          },
          "base_plan": null,
          "entitlements": [
            {
              "usage_limit": 3,
              "has_unlimited_usage": null,
              "feature_id": "6d15081c-a3dc-4091-ab8c-9f25dc366173",
              "reset_period": null,
              "feature": {
                "id": "feature-01-templates",
                "feature_type": "NUMBER",
                "meter_type": "Fluctuating",
                "feature_units": "template",
                "feature_units_plural": "templates",
                "display_name": "Templates",
                "description": null
              }
            },
            {
              "usage_limit": 4,
              "has_unlimited_usage": null,
              "feature_id": "08a4a367-4286-4dfd-bfae-6c77a723e80c",
              "reset_period": "MONTH",
              "feature": {
                "id": "feature-02-campaigns",
                "feature_type": "NUMBER",
                "meter_type": "Incremental",
                "feature_units": "campaign",
                "feature_units_plural": "campaigns",
                "display_name": "Campaigns",
                "description": null
              }
            }
          ],
          "inherited_entitlements": [],
          "compatible_addons": [],
          "prices": [],
          "pricing_type": "FREE",
          "default_trial_config": null
        },
        "addons": [],
        "payment_collection": "NOT_REQUIRED", // status of the payment collection of the subscription - can be either 'NOT_REQUIRED', 'FAILED', 'ACTION_REQUIRED' or 'PROCESSING'
        "latestInvoice": {
          "billing_id": "invoice-01", // ID of the invoice of the billing provider
          "status": "PAID", // can be either 'OPEN', 'CANCELED' or 'PAID'
          "created_at": "2023-08-22T11:27:41.000Z",
          "updated_at": "2023-08-22T11:27:44.608Z",
          "requires_action": false, // indicate of the payment requires action to complete the payment
          "payment_url": "https://...", // payment url that can be sent to the customer to complete the payment
          "payment_secret": "secret-01", // secret to be used to initiate next action with billing provider
          "error_message": "", // optinal error message, if the status is FAILED
        }
      }
    }
  }
  ```
</Expandable>

# Listing subscriptions

Use `GetSubscriptions` to retrieve subscriptions with rich filtering, sorting, and cursor-based pagination. This is useful for admin dashboards, audits, reporting, and support tooling.

<CodeGroup>
  ```ruby get_subscriptions_basic.rb  theme={null}
  resp = client.request(Stigg::Query::GetSubscriptions, { "filter": {}, # optional "paging": { "first": 25 }, "sorting": [ { "field": "createdAt", "direction": "DESC", "nulls": "LAST" } ] })

  resp.data.subscriptions.edges.each do |edge|
  s = edge.node
  puts "Subscription: #{s.id} (status: #{s.status})"
  end

  page = resp.data.subscriptions.page_info
  puts "next? #{page.has_next_page} — cursor: #{page.end_cursor}"
  ```
</CodeGroup>

## Filtering

`SubscriptionQueryFilter` supports logical composition (`and`, `or`) plus field comparisons.

Supported operators:

* Strings/enums: eq, neq, in, notIn
* Dates: `eq`, `neq`, `gt`, `gte`, `lt`, `lte`, `in`, `notIn`

<CodeGroup>
  ```ruby get_subscriptions_filtered.rb theme={null}
  filter = { and: [ { customerId: { eq: "customer-123" } }, { status: { in: ["ACTIVE", "IN_TRIAL"] } }, { createdAt: { gte: "2024-01-01T00:00:00Z" } } ] }

  sorting = [ { field: "createdAt", direction: "DESC", nulls: "LAST" } ]

  resp = client.request(Stigg::Query::GetSubscriptions, {
  "filter": filter,
  "sorting": sorting,
  "paging": { "first": 50 }
  })
  ```
</CodeGroup>

## Sorting

* Fields: `createdAt`, `customerId`, `environmentId`, `productId`, `resourceId`, `status`
* Direction: `ASC`, `DESC`
* Nulls: `FIRST`, `LAST`

<CodeGroup>
  ```ruby get_subscriptions_sorted.rb  theme={null}
  resp = client.request(Stigg::Query::GetSubscriptions, { "sorting": [ { field: "createdAt", direction: "DESC", nulls: "LAST" }, { field: "customerId", direction: "ASC", nulls: "FIRST" } ], "paging": { "first": 25 } }) 
  ```
</CodeGroup>

## Pagination

Cursor-based pagination via CursorPaging.

* Forward: `first`, `after`
* Backward: `last`, `before`

<CodeGroup>
  ```ruby get_subscriptions_all_pages.rb  theme={null}
  all = [] page_args = { "first": 100 }

  loop do
  resp = client.request(Stigg::Query::GetSubscriptions, {
  "filter": { status: { in: ["ACTIVE", "IN_TRIAL"] } },
  "sorting": [ { field: "createdAt", direction: "DESC", nulls: "LAST" } ],
  "paging": page_args
  })

  edges = resp.data.subscriptions.edges
  all.concat(edges.map(&:node))

  page = resp.data.subscriptions.page_info
  break unless page.has_next_page
  page_args = { "first": 100, "after": page.end_cursor }

  end

  puts "Fetched #{all.size} subscriptions"
  ```
</CodeGroup>

## Returned fields

Common fields on each subscription node:

* `id`
* `status` (e.g., ACTIVE, CANCELED, IN\_TRIAL)
* `pricing_type` (PAID, FREE, METERED)
* `start_date`
* `current_billing_period_end`
* `trial_end_date`

Nested:

* `customer.customer_id`
* `paying_customer.customer_id` (may differ)
* `resource.resource_id` (optional)
* `plan.plan_id` and `plan.display_name`
* `addons[]` with `quantity` and `addon.addon_id`
* `trial_configuration.trial_end_behavior`

Page info:

* `has_next_page`, `has_previous_page`, `start_cursor`, `end_cursor`

## Error handling and tips

* Use only supported operators (eq, neq, in, notIn for strings/enums).
* Use ISO-8601 UTC timestamps (e.g., 2024-01-01T00:00:00Z).
* Reasonable page sizes: 25-100.
* For performance, combine customerId, status, createdAt.
* Split very large OR lists into multiple calls if needed.

## End-to-end example

<CodeGroup>
  ```ruby get_subscriptions_end_to_end.rb theme={null}
  filter = {
    and: [
      { status: { in: ["ACTIVE", "IN_TRIAL"] } },
      { createdAt: { gte: "2024-01-01T00:00:00Z" } }
    ]
  }

  sorting = [ { field: "createdAt", direction: "DESC", nulls: "LAST" } ]
  paging  = { "first": 100 }

  resp = client.request(Stigg::Query::GetSubscriptions, {
    "filter": filter,
    "sorting": sorting,
    "paging": paging
  })

  resp.data.subscriptions.edges.each do |edge|
    s = edge.node
    puts [s.id, s.status, s.customer&.customer_id, s.plan&.display_name, s.current_billing_period_end].join(", ")
  end
  ```
</CodeGroup>

# Provisioning subscriptions

When a customer subscribes to a new plan (for example: during an upgrade from a free plan to a paid plan, or downgrade from a higher tier to a lower tier), a subscription needs to be created in Stigg.

When provisioning of a paid subscription is attempted, Stigg is integrated with a billing solution and payment details have not been previously provided by the customer, Stigg will auto-magically redirect customers to a the billing solution's checkout page. After the customer enters the required payment details in the presented checkout page, the relevant subscription will be created in both Stigg and the billing solution.

When no payment is required or when Stigg is not integrated with a billing solution, the subscription will be immediately created in Stigg.

When a customer subscribes to a new plan (free, paid, trial, etc.), provision a subscription in Stigg. The provision result can be a successfully created subscription, or a redirect link to stripe checkout in case payment is needed.

<CodeGroup>
  ```ruby provision_subscription.rb theme={null}
  resp = client.request(Stigg::Mutation::ProvisionSubscription, {
    "input": {
      "customerId": "customer-demo-02",
      "planId": "plan-revvenu-essentials",
      "resourceId": "resource-01", # optional, required for multiple subscription for same product
      "billingPeriod": "MONTHLY",  # optional, required for paid subscriptions
      "billingCountryCode":"DK"    # optional, required for price localization, must be in the ISO-3166-1 format
      "checkoutOptions": {				 # optional
        "successUrl": "https://your-success-url.com",
        "cancelUrl": "https://your-cancel-url.com",
        "collectPhoneNumber": true
      },
      "billableFeatures": [{
        "featureId": "feature-01-templates",
        "quantity": 2
      }],
      "entitlements": [  # optional, for custom plans (feature + credit)
        {
          "feature": {
            "featureId": "feature-seats",
            "usageLimit": 50
          }
        },
        {
          "credit": {
            "customCurrencyId": "currency-api-credits",
            "amount": 50000,
            "cadence": "MONTH"  # MONTH or YEAR
          }
        }
      ],
    }
  })
  ```
</CodeGroup>

<Expandable title="Success result">
  ```json theme={null}
  {
      "data": {
          "provision_subscription": {
              "checkout_url": "https:\/\/your-success-url.com",
              "status": "SUCCESS",
              "subscription": {
                  "id": "subscription-plan-revvenu-essentials-93981d",
                  "status": "PAYMENT_PENDING",
                  "metadata": null,
                  "billing_id": null,
                  "billing_link_url": null,
                  "effective_end_date": null,
                  "current_billing_period_end": "2022-12-17T15:26:01.291Z",
                  "pricing_type": "PAID",
                  "prices": [
                      {
                          "billing_model": "FLAT_FEE",
                          "price": {
                              "billing_period": "MONTHLY",
                              "price": {
                                  "amount": 99,
                                  "currency": "USD"
                              }
                          }
                      }
                  ],
                  "total_price": {
                      "sub_total": {
                          "amount": 20,
                          "currency": "USD"
                      },
                      "total": {
                          "amount": 20,
                          "currency": "USD"
                      }
                  },
                  "plan": {
                      "id": "plan-revvenu-essentials"
                  },
                  "addons": [],
                  "customer": {
                      "id": "customer-demo-02"
                  },
                "payment_collection": "NOT_REQUIRED",
                "latest_invoice": {
                    "billing_id": "invoice-01",
                    "status": "PAID",
                  }
              }
          }
      }
  }
  ```
</Expandable>

<Expandable title="Payment Requires action">
  ```json theme={null}
  {
      "data": {
          "provision_subscription": {
              "status": "SUCCESS",
              "subscription": {
                  "payment_collection": "ACTION_REQUIRED",
                  "latest_invoice": {
                      "payment_url": "https...",
                      "payment_secret": "secret",
                  }
              }
          }
      }
  }
  ```
</Expandable>

<Expandable title="Payment failed">
  ```json theme={null}
  {
      "data": {
          "provision_subscription": {
            "status": "SUCCESS",
            "subscription": {
                "payment_collection": "FAILED",
                "latest_invoice": {
                    "payment_url": "https...",
                    "error_message": "no sufficient funds"
                }
            }
          }
      }
  }
  ```
</Expandable>

<Expandable title="Payment Requires checkout">
  ```json theme={null}
  {
      "data": {
          "provision_subscription": {
              "checkout_url": "https:\/\/checkout.stripe.com\/c\/pay\/cs_test_a1ZW8HpF4G7hV6w9Q9hV7MGYpzBU2BPpt6RJRZXE2PC7WyxRHQKqQ2UvDj#fidkdWxOYHwnPyd1blpxYHZxWjA0Tzx1TlNJSHxCYEZGd1BHPU1kM0JAXVFHfXdrREhnQ3VJdldAS1MwZjRkNGxxcWBVf09SSE0zRzBcYTN3cXNkbFdMQnI0V3ZrN0toSGc3NnB9QEdBPVJMNTVzM3NpdnVDSycpJ2N3amhWYHdzYHcnP3F3cGApJ2lkfGpwcVF8dWAnPyd2bGtiaWBabHFgaCcpJ2BrZGdpYFVpZGZgbWppYWB3dic%2FcXdwYCkndnF3bHVgRGZmanBrcSc%2FJ2RmZnFaNE5MdGtyQDRiU1E3f3JfUyd4JSUl",
              "status": "PAYMENT_REQUIRED",
              "subscription": null
          }
      }
  }
  ```
</Expandable>

<Warning>
  1. A customer can have both a non-trial (free or paid) subscription and trial subscription to different plans of the same product in parallel - this logic allows customers to trial a higher tier plan, while still paying for an existing plan.
  2. When the customer has a trial subscription for plan X of product A and a new subscription is created for the same plan, the new subscription will be created as as non-trial (paid) subscription - this logic follows an upgrade flow of a trial subscription to a paid subscription of a specific plan.
  3. Except in the above mentioned cases, when a customer has an active subscription for product X, and another subscription for the same product is created with start date S, the existing subscription will automatically be cancelled and the new subscription will start on start date S.
  4. It's also possible to explicitly skip the trial period of the selected plan by providing the `skipTrial: true` parameter to the `provisionSubscription()` method.
</Warning>

# Updating subscriptions

Updating an existing subscription, this can be used to update the feature quantity that the customer is subscribed for or the add-ons.

<CodeGroup>
  ```ruby update_subscription.rb theme={null}
  resp = client.request(Stigg::Mutation::UpdateSubscription, {
    "input": {
      "subscriptionId": "subscription-plan-revvenu-growth-589879",
      "billableFeatures": [{
        "featureId": "feature-01-templates",
        "quantity": 2
      }],
    }
  })
  ```
</CodeGroup>

<Expandable title="Result">
  ```json theme={null}
  {
    "data": {
      "update_subscription": {
          "id": "subscription-plan-revvenu-growth-589879",
          "status": "ACTIVE",
          "metadata": null,
          "billing_id": "sub_1LxD4TE1gVT2zwZVSav7tZvC",
          "billing_link_url": "https:\/\/dashboard.stripe.com\/test\/subscriptions\/sub_1LxD4TE1gVT2zwZVSav7tZvC",
          "effective_end_date": null,
          "current_billing_period_end": "2022-11-26T17:07:17.000Z",
          "pricing_type": "PAID",
          "prices": [
              {
                  "usage_limit": 2,
                  "price": {
                      "billing_model": "PER_UNIT",
                      "billing_period": "MONTHLY",
                      "price": {
                          "amount": 1,
                          "currency": "USD"
                      },
                      "feature": {
                          "id": "feature-01-templates",
                          "feature_type": "NUMBER",
                          "meter_type": "Fluctuating",
                          "feature_units": "template",
                          "feature_units_plural": "templates",
                          "display_name": "Templates",
                          "description": null
                      }
                  }
              }
          ],
          "total_price": {
              "sub_total": {
                  "amount": 17,
                  "currency": "USD"
              },
              "total": {
                  "amount": 17,
                  "currency": "USD"
              }
          },
          "plan": {
              "id": "plan-revvenu-growth"
          },
          "addons": [
              {
                  "quantity": 3,
                  "addon": {
                      "id": "addon-10-campaigns"
                  }
              }
          ],
          "customer": {
              "id": "customer-demo-01"
          },
          "payment_collection": "NOT_REQUIRED", // status of the payment collection of the subscription - can be either 'NOT_REQUIRED', 'FAILED', 'ACTION_REQUIRED' or 'PROCESSING'
          "latest_invoice": {
              "billing_id": "invoice-01", // ID of the invoice of the billing provider
              "status": "PAID", // can be either 'OPEN', 'CANCELED' or 'PAID'
              "created_at": "2023-08-22T11:27:41.000Z",
              "updated_at": "2023-08-22T11:27:44.608Z",
              "requires_action": false, // indicate of the payment requires action to complete the payment
              "payment_url": "https://...", // payment url that can be sent to the customer to complete the payment
              "payment_secret": "secret-01", // secret to be used to initiate next action with billing provider
              "error_message": "", // optinal error message, if the status is FAILED
          }
      }
    }
  }
  ```
</Expandable>

# Cancel subscription

<CodeGroup>
  ```ruby cancel_subscription.rb theme={null}
  resp = client.request(Stigg::Mutation::CancelSubscription, {
    "input": {
      "subscriptionRefId": "subscription-plan-revvenu-growth-589879",
      "subscriptionCancellationTime":  "IMMEDIATE"
    }
  })
  ```
</CodeGroup>

<Expandable title="Result">
  ```json theme={null}
  {
    "data": {
      "cancel_subscription": {
          "id": "subscription-plan-revvenu-growth-589879",
          "status": "CANCELED",
          "metadata": null,
          "billing_id": "sub_1LxD4TE1gVT2zwZVSav7tZvC",
          "billing_link_url": "https:\/\/dashboard.stripe.com\/test\/subscriptions\/sub_1LxD4TE1gVT2zwZVSav7tZvC",
          "effective_end_date": "2022-10-30T23:54:38.582Z",
          "current_billing_period_end": "2022-11-26T17:07:17.000Z",
          "pricing_type": "PAID",
          "prices": [
              {
                  "usage_limit": 2,
                  "price": {
                      "billing_model": "PER_UNIT",
                      "billing_period": "MONTHLY",
                      "price": {
                          "amount": 1,
                          "currency": "USD"
                      },
                      "feature": {
                          "id": "feature-01-templates",
                          "feature_type": "NUMBER",
                          "meter_type": "Fluctuating",
                          "feature_units": "template",
                          "feature_units_plural": "templates",
                          "display_name": "Templates",
                          "description": null
                      }
                  }
              }
          ],
          "total_price": {
              "sub_total": {
                  "amount": 17,
                  "currency": "USD"
              },
              "total": {
                  "amount": 17,
                  "currency": "USD"
              }
          },
          "plan": {
              "id": "plan-revvenu-growth"
          },
          "addons": [
              {
                  "quantity": 3,
                  "addon": {
                      "id": "addon-10-campaigns"
                  }
              }
          ],
          "customer": {
              "id": "customer-demo-01"
          }
      }
    }
  }
  ```
</Expandable>

<Warning>
  Subscription cancellation will take place according to the defined product behavior.
</Warning>

# Getting the entitlement of a customer for a specific feature

Used to check if the customer has access to a feature, the usage limit, and the current usage.

<CodeGroup>
  ```ruby get_entitlement.rb theme={null}
  resp = client.request(Stigg::Query::GetEntitlement, {
    "query": {
      "customerId": "customer-id",
      "featureId": "feature-01-templates",
      "options": {  
        "requestedUsage": 10  
      },
      "resourceId": "resource-01",  # optional, pass it to get entitlement of specific resource
    }
  })

  if resp.data.entitlement.is_granted
      puts "Customer has access to the feature"
  else
      puts "Access denied"
  end
  ```
</CodeGroup>

<Expandable title="Result">
  ```json theme={null}
  {
      "data": {
          "entitlement": {
              "is_granted": true,
              "access_denied_reason": null,
              "customer_id": "eb741bdb-4ca7-416f-a6f1-49483ed2a2e2",
              "usage_limit": 3,
              "has_unlimited_usage": false,
              "current_usage": 0,
              "requested_usage": null,
              "usage_period_anchor": null,
              "usage_period_start": null,
              "usage_period_end": null,
              "reset_period": null,
              "feature": {
                  "id": "feature-01-templates",
                  "feature_type": "NUMBER",
                  "meter_type": "Fluctuating",
                  "feature_units": "template",
                  "feature_units_plural": "templates",
                  "display_name": "Templates",
                  "description": null
              },
              "reset_period_configuration": null
          }
      }
  }
  ```
</Expandable>

# Getting all of the entitlements of a customer

Used to check to what features the customer has access to, the usage limit , and the current usage of each entitlement.

<CodeGroup>
  ```ruby get_entitlements.rb theme={null}

  resp = client.request(Stigg::Query::GetEntitlementsState, {
    "query": {
      "customerId": "customer-id",
      "resourceId": "resource-01",  # optional, pass it to get entitlements of specific resource
    }
  })
  ```
</CodeGroup>

<Expandable title="Result">
  ```json theme={null}
  {
      "data": {
          "entitlementsState": {
            "entitlements": [
                {
                    "feature": {
                        "ref_id": "feature-03-custom-domain",
                        "display_name": "Custom domain",
                        "feature_units": null,
                        "feature_units_plural": null,
                        "feature_type": "BOOLEAN",
                        "meter_type": "None",
                        "description": null
                    },
                    "current_usage": 0,
                    "customer_id": "96ed6019-031a-4c52-bc41-b8fa3b5d86c5",
                    "usage_limit": null,
                    "has_unlimited_usage": false,
                    "usage_period_anchor": null,
                    "usage_period_start": null,
                    "usage_period_end": null,
                    "reset_period": null
                },
                {
                    "feature": {
                        "ref_id": "feature-04-analytics",
                        "display_name": "Analytics",
                        "feature_units": null,
                        "feature_units_plural": null,
                        "feature_type": "BOOLEAN",
                        "meter_type": "None",
                        "description": null
                    },
                    "current_usage": 0,
                    "customer_id": "96ed6019-031a-4c52-bc41-b8fa3b5d86c5",
                    "usage_limit": null,
                    "has_unlimited_usage": false,
                    "usage_period_anchor": null,
                    "usage_period_start": null,
                    "usage_period_end": null,
                    "reset_period": null
                },
                {
                    "feature": {
                        "ref_id": "feature-01-templates",
                        "display_name": "Templates",
                        "feature_units": "Template",
                        "feature_units_plural": "Templates",
                        "feature_type": "NUMBER",
                        "meter_type": "Fluctuating",
                        "description": null
                    },
                    "current_usage": 3,
                    "customer_id": "96ed6019-031a-4c52-bc41-b8fa3b5d86c5",
                    "usage_limit": 5,
                    "has_unlimited_usage": false,
                    "usage_period_anchor": null,
                    "usage_period_start": null,
                    "usage_period_end": null,
                    "reset_period": null
                },
                {
                    "feature": {
                        "ref_id": "feature-02-campaigns",
                        "display_name": "Campaigns",
                        "feature_units": "Campaign",
                        "feature_units_plural": "Campaigns",
                        "feature_type": "NUMBER",
                        "meter_type": "Incremental",
                        "description": null
                    },
                    "current_usage": 10,
                    "customer_id": "96ed6019-031a-4c52-bc41-b8fa3b5d86c5",
                    "usage_limit": 12,
                    "has_unlimited_usage": false,
                    "usage_period_anchor": "2022-02-21T00:00:00.000Z",
                    "usage_period_start": "2022-089-21T00:00:00.000Z",
                    "usage_period_end": "2022-09-21T00:00:00.000Z",
                    "reset_period": "MONTH"
                }
            ],
            "accessDeniedReason": null
          }
      }
  }
  ```
</Expandable>

# Getting paywall data

Useful for rendering the public pricing page or customer paywall.

<CodeGroup>
  ```ruby get_paywall.rb theme={null}
  resp = client.request(Stigg::Query::GetPaywall, {'input': {}})

  resp.data.paywall.plans.each { |plan|
    puts "Plan name: " + plan.display_name
    puts "Plan ID: " +plan.ref_id

    
  }
  ```
</CodeGroup>

<Expandable title="Result">
  ```json theme={null}
  {
    "plans": [
      {
        "id": "plan-stigg-starter",
        "order": 0,
        "display_name": "Starter",
        "description": "For getting started",
        "entitlements": [
          {
            "usage_limit": 100,
            "feature": {
              "id": "feature-demo-01",
              "feature_type": "Numeric",
              "description": "",
              "meter_type": "None",
              "units": "request",
              "units_plural": "requests",
              "display_name": "Feature #1",
              "is_metered": false,
              "metadata": {
                "key": "value"
              }
            },
            "has_unlimited_usage": false,
            "display_name_override": "Awesome feature #1",
            "hidden_from_widgets": []
          },
          {
            "usage_limit": 0,
            "feature": {
              "id": "feature-demo-02",
              "feature_type": "Boolean",
              "description": "",
              "meter_type": "None",
              "display_name": "Feature #2",
              "is_metered": false
            },
            "has_unlimited_usage": false,
            "display_name_override": null,
            "hidden_from_widgets": ["PAYWALL"]
          }
        ],
        "inherited_entitlements": [],
        "price_points": [],
        "pricing_type": "FREE",
        "default_trial_config": null,
        "compatible_addons": [],
        "product": {
          "id": "product-stigg",
          "display_name": "Stigg",
          "description": null,
          "metadata": null
        },
        "metadata": null
      }
    ]
  }
  ```
</Expandable>

# Reporting usage measurements to Stigg

The Stigg SDK allows you to report usage measurements for [metered features](/documentation/modeling-your-pricing-in-stigg/features/overview). The reported usage will be used to track, limit and bill the customer's usage of metered features.

Stigg supports metering of usage from the following data sources:

1. [Calculated usage](#calculated-usage) - usage that has been aggregated and calculated by **your application**. This type is useful for features, such as: seats.
2. [Raw events](#raw-events) - raw events from your application, which **Stigg** filters and aggregates aggregate to calculate customer usage. This type is useful for features, such as: monthly active users (MAUs).

More details about Stigg's metering and aggregation capabilities can be found here:

<Card title="Stigg's metering and aggregation capabilities" icon="gauge" href="/documentation/getting-usage-data-into-stigg/overview" horizontal />

<Warning>
  1. Reporting of measurements to Stigg should be done only after the relevant resources have been provisioned in your application.
  2. To ensure that the provisioned resources are aligned with the measurements that are reported to Stigg, ensure that customers are not allowed to allocate new resources until an acknowledgement about the processed measurement is received from the Stigg backend.
</Warning>

<Note>
  Validating that a measurement was successfully reported to Stigg is also possible in the [customer details section](/documentation/managing-customers-and-subscriptions/customers/viewing-customers-entitlement-usage) of the relevant customer in the Stigg app.
</Note>

### Calculated usage

<CodeGroup>
  ```ruby report_usage.rb theme={null}
  resp = client.request(Stigg::Mutation::ReportUsage, {
      "input": {
          "value": 5,
          "customerId": "customer-id",
          "featureId": "feature-02-campaigns",
          "resourceId": "resource-01",  # optional, pass it to report usage for specific resource
      }
  })
  ```
</CodeGroup>

<Expandable title="Result">
  ```json theme={null}
  {
    "data": {
      "report_usage": {
          "id": "d723d1c6-64fa-4a8b-aa2d-a6dc57e13804"
      }
    }
  }
  ```
</Expandable>

### Raw events

<CodeGroup>
  ```ruby report_event.rb theme={null}
  resp = client.request(Stigg::Mutation::ReportEvent, {
      "input": {
  					"usageEvents": [{
                    					"customerId": "customer-test-id",
  							    					"resourceId": "resource-01",      // optional, pass it to report event for specific resource
  							    					"eventName": "user_login",
  							    					"idempotencyKey": "227c1b73-883a-457b-b715-6ba5a2c69ce4",
  							    					"dimensions": {
  																						"user_id": "user-01",
  													    							"user_email": "john@example.com"
  												    							},
  														"timestamp": "2022-10-26T15:01:55.768Z" // optional, pass it to report event with specific timestamp
                 						}]
      }
  })
  ```
</CodeGroup>

It's also possible to send a batch of events in one invocation. To do so, simply pass an array of events to the `reportEvent` method.

# Getting available coupons

<CodeGroup>
  ```ruby get_coupons.rb theme={null}
  resp = client.request(Stigg::Query::GetCoupons, {
    "filter": {
      "status": {
        "eq": "ACTIVE",
      },
    },
  })
  ```
</CodeGroup>

<Expandable title="Result">
  ```json theme={null}
  {
    "data": {
      "coupons": {
          "edges": [
              {
                  "node": {
                      "id": "coupon-vip",
                      "name": "VIP",
                      "description": null,
                      "type": "PERCENTAGE",
                      "discount_value": 20,
                      "metadata": null,
                      "created_at": "2022-10-26T15:01:55.768Z",
                      "updated_at": "2022-10-26T15:01:56.432Z",
                      "billing_id": "YSkVNwUu",
                      "billing_link_url": "https:\/\/dashboard.stripe.com\/test\/coupons\/YSkVNwUu",
                      "status": "ACTIVE"
                  }
              }
          ]
      }
    }
  }
  ```
</Expandable>

# Estimating subscription cost

You can estimate the subscription cost using the `estimateSubscription` method. This can help the customer to understand the costs before paying.

<CodeGroup>
  ```ruby estimate_subscription.rb theme={null}
  resp = client.request(Stigg::Mutation::EstimateSubscription, {
      "input": {
          "customerId": "customer-demo-01",
          "billingPeriod": "MONTHLY",
          "planId": "plan-revvenu-essentials",
        	"billableFeatures": [{			 # optional, required for plans with per-unit pricing
            "featureId": "feature-01-templates",
            "quantity": 4
          }],
          "addons": [									 # optional
              {
                  "addonId": "addon-10-campaigns",
                  "quantity": 2
              }
          ],
        	"billingCountryCode": "DK" 	  # optional, required for price localization, must be in the ISO-3166-1 format
          "resourceId": "resource-01",  # optional, required for multiple subscription for same product
      }
  })
  ```
</CodeGroup>

<Expandable title="Result">
  ```json theme={null}
  {
    "data": {
      "estimate_subscription": {
          "sub_total": {
              "amount": 30,
              "currency": "USD"
          },
          "total": {
              "amount": 30,
              "currency": "USD"
          },
          "billing_period_range": {
              "start": "2022-10-31T00:26:06.028Z",
              "end": "2022-11-30T00:26:06.028Z"
          },
          "proration": null
      }
    }
  }
  ```
</Expandable>

You can also estimate the cost of updating an existing subscription using the `updateSubscription` method, which also returns a breakdown of the proration amounts:

<CodeGroup>
  ```ruby estimate_subscription_update.rb theme={null}
  resp = client.request(Stigg::Mutation::EstimateSubscriptionUpdate,{
    "input": {
      "subscriptionId": "subscription-plan-revvenu-growth-dfe598",
      "billableFeatures": [{
        "featureId": "feature-01-templates",
        "quantity": 7
      }],
      "addons": [
        {"addonId": "addon-10-campaigns", "quantity": 2 }
      ]
    }
  })
  ```
</CodeGroup>

<Expandable title="Result">
  ```json theme={null}
  {
      "data": {
          "estimate_subscription_update": {
              "sub_total": {
                  "amount": 7,
                  "currency": "USD"
              },
              "total": {
                  "amount": 7,
                  "currency": "USD"
              },
              "billing_period_range": {
                  "start": "2022-10-26T17:07:17.000Z",
                  "end": "2022-11-26T17:07:17.000Z"
              },
              "proration": {
                  "proration_date": "2022-10-26T17:08:23.000Z",
                  "credit": {
                      "amount": -10,
                      "currency": "USD"
                  },
                  "debit": {
                      "amount": 17,
                      "currency": "USD"
                  }
              }
          }
      }
  }
  ```
</Expandable>

# Governance

Stigg Governance lets your enterprise customers control AI usage and credit spend across their organizations. The governance API is a REST API — use `Net::HTTP` from Ruby's standard library.

## Check

Call `check` before allowing consumption. Returns `hasAccess: true` when every budget in the hierarchy allows the request.

<CodeGroup>
  ```ruby check.rb theme={null}
  require "net/http"
  require "json"
  require "uri"

  base_url = ENV["GOVERNANCE_API_URL"]
  headers  = {
    "Authorization"           => "Bearer #{ENV['GOVERNANCE_ACCESS_TOKEN']}",
    "x-stigg-account-id"     => ENV["STIGG_ACCOUNT_ID"],
    "x-stigg-environment-id" => ENV["STIGG_ENVIRONMENT_ID"],
    "Content-Type"            => "application/json",
  }

  uri  = URI("#{base_url}/owners/cus-acme/check")
  http = Net::HTTP.new(uri.host, uri.port)
  http.use_ssl = true

  req      = Net::HTTP::Post.new(uri.request_uri, headers)
  req.body = { entityIds: ["team-eng"], capabilityId: "ai-tokens", requestedAmount: 1000 }.to_json
  resp     = http.request(req)
  report   = JSON.parse(resp.body)

  raise "Usage limit reached" unless report["hasAccess"]
  ```
</CodeGroup>

## Ingest

Call `ingest` after consuming to increment the usage counter.

<CodeGroup>
  ```ruby ingest.rb theme={null}
  req      = Net::HTTP::Post.new("/owners/cus-acme/ingest", headers)
  req.body = { events: [{ entityIds: ["team-eng"], capabilityId: "ai-tokens", amount: 1250 }] }.to_json
  http.request(req)
  ```
</CodeGroup>

For the full check-then-ingest pattern, provisioning entities, setting budgets, and querying the governance tree, see [Governance](/documentation/governance/overview).

# SDK changelog

<Card title="Ruby SDK changelog" icon="list-timeline" href="/api-and-sdks/changelog/backend-graphql/ruby" horizontal />
