> ## 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.

# Go

# Overview

This Go module 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 [gqlgenc](https://github.com/Yamashou/gqlgenc) library to generate the types under the hood and by default utilizes the `http.Client` module to execute the API requests.

# Installing the SDK

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

<CodeGroup>
  ```shell shell theme={null}
  go get github.com/stiggio/api-client-go/v5
  ```
</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>
  ```go main.go theme={null}
  import (
    "context"
    "github.com/stiggio/api-client-go/v5"
    "os"
  )

  // Ptr is a helper function that returns a pointer to whatever 
  // value we pass to it, will be widely used in the examples below
  func Ptr[T any](v T) *T {
    return &v
  }

  func main() {
    apiKey := os.Getenv("STIGG_FULL_ACCESS_KEY")

    client := stigg.NewStiggClient(apiKey, nil, nil)

    // client is initialized
  }
  ```
</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>
  ```go ProvisionCustomer.go theme={null}

  result, err := client.ProvisionCustomer(context.Background(), stigg.ProvisionCustomerInput{
    CustomerID: Ptr("customer-id"),
    Name:  Ptr("Acme"), 						// optional
    Email: Ptr("john@example.com"), 	// optional - billing email address
    CouponRefID: Ptr("coupon-id"),	// optional
    SubscriptionParams: &stigg.ProvisionCustomerSubscriptionInput{ // optional
      PlanID: "plan-revvenu-basic",
      BillingCountryCode: Ptr("DK"), // optional, required for price localization, must be in the ISO-3166-1 format   
    },
    BillingInformation: &stigg.CustomerBillingInfo{ // optional
      Language: Ptr("en"),
      Timezone: Ptr("America/New_York"),
      BillingAddress: &stigg.Address{
        Country:      Ptr("US"),
        City:         Ptr("New York"),
        State:        Ptr("NY"),
        AddressLine1: Ptr("123 Main Street"),
        AddressLine2: Ptr("Apt. 1"),
        PhoneNumber:  Ptr("+1 212-499-5321"),
        PostalCode:   Ptr("10164"),
      },
      ShippingAddress: &stigg.Address{
        Country:      Ptr("US"),
        City:         Ptr("New York"),
        State:        Ptr("NY"),
        AddressLine1: Ptr("123 Main Street"),
        AddressLine2: Ptr("Apt. 1"),
        PhoneNumber:  Ptr("+1 212-499-5321"),
        PostalCode:   Ptr("10164"),
      },
    },
    AdditionalMetaData: map[string]interface{}{ // optional
      "Key": "Value",
    },
  })
  ```
</CodeGroup>

<Expandable title="Result">
  ```json theme={null}
  {
      "provisionCustomer": {
        "customer": {
          "refId": "customer-id",
          "name": "Acme",
          "email": "john@example.com",
          "createdAt": "2022-09-22T08:00:28.965Z",
          "billingId": null,
          "crmId": null,
          "hasPaymentMethod": false,
          "additionalMetaData": {
            "key": "value"
          }
        },
        "subscriptionDecisionStrategy": "REQUESTED_PLAN",
        "subscription": {
          "refId": "subscription-plan-revvenu-basic-7b5a40",
          "status": "ACTIVE",
          "plan": {
            "refId": "plan-revvenu-basic"
          }
        }
      }
  }
  ```
</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>
  ```go UpdateCustomer.go theme={null}
  result, err := client.UpdateCustomer(context.Background(), stigg.UpdateCustomerInput{
    CustomerID:  Ptr("customer-id"),
    Name:  Ptr("Acme"),
    Email: Ptr("john@example.com"),
    BillingInformation: &stigg.CustomerBillingInfo{
      Language: Ptr("en"),
      Timezone: Ptr("America/New_York"),
      BillingAddress: &stigg.Address{
        Country:      Ptr("US"),
        City:         Ptr("New York"),
        State:        Ptr("NY"),
        AddressLine1: Ptr("123 Main Street"),
        AddressLine2: Ptr("Apt. 1"),
        PhoneNumber:  Ptr("+1 212-499-5321"),
        PostalCode:   Ptr("10164"),
      },
    },
    AdditionalMetaData: map[string]interface{}{
      "Key": "Value",
    },
  })
  ```
</CodeGroup>

<Expandable title="Result">
  ```json theme={null}
  {
  "updateCustomer": {
    "id": "customer-f9942a",
    "name": "Acme",
    "email": "john@example.com",
    "createdAt": "2022-12-13T17:27:05.143Z",
    "updatedAt": "2022-12-13T17:44:45.712Z",
    "promotionalEntitlements": [],
    "hasPaymentMethod": false,
    "coupon": null,
    "billingId": "cus_MyZOEhlqn2bBGp",
    "metadata": {
    "Key": "Value"
    }
  }
  }
  ```
</Expandable>

# Getting customer data

<CodeGroup>
  ```go GetCustomerByID.go theme={null}
  result, err := client.GetCustomerByID(context.Background(), stigg.GetCustomerByRefIDInput{
    CustomerID: "customer-f9942a",
  })
  ```
</CodeGroup>

<Expandable title="Result">
  ```json theme={null}
  {
  "getCustomerByRefId": {
    "id": "customer-f9942a",
    "name": "Acme",
    "email": "john@example.com",
    "createdAt": "2022-12-13T17:27:05.143Z",
    "updatedAt": "2022-12-13T17:44:51.707Z",
    "promotionalEntitlements": [],
    "hasPaymentMethod": false,
    "coupon": null,
    "billingId": "cus_MyZOEhlqn2bBGp",
    "metadata": {
    "Key": "Value"
    }
  }
  }
  ```
</Expandable>

# Getting customer active subscriptions

There are two SDK methods for retrieving a customer's active subscriptions. See [Fetching subscriptions — methods compared](/api-and-sdks/api-reference/queries/fetching-subscriptions) for a full comparison including the GraphQL equivalents.

## GetActiveSubscriptionList

Returns a slim, Edge-cached list of active subscriptions. This is the **fastest** option and is preferred for runtime checks. Without `ResourceID`, only global (non-resource-attached) subscriptions are returned.

<CodeGroup>
  ```go GetActiveSubscriptionList.go theme={null}
  result, err := client.GetActiveSubscriptionList(context.Background(), stigg.GetActiveSubscriptionListInput{
    CustomerID: "customer-f9942a",

    // Optional — omit for global subscriptions, provide for resource-backed products
    ResourceID: Ptr("resource-01"),
  })
  ```
</CodeGroup>

## GetActiveSubscriptions

Returns full subscription objects via a direct GraphQL call. Without `ResourceID`, only global (non-resource-attached) subscriptions are returned.

<CodeGroup>
  ```go GetActiveSubscriptions.go theme={null}
  result, err := client.GetActiveSubscriptions(context.Background(), stigg.GetActiveSubscriptionsInput{
    CustomerID: "customer-f9942a",

    // Optional — omit for global subscriptions, provide for resource-backed products
    ResourceID: Ptr("resource-01"),
  })
  ```
</CodeGroup>

<Expandable title="Result">
  ```json theme={null}
  {
  "getActiveSubscriptions": [
    {
      "id": "subscription-plan-revvenu-basic-4a9432",
      "status": "ACTIVE",
      "startDate": "2022-12-13T17:27:05.873Z",
      "endDate": null,
      "trialEndDate": null,
      "cancellationDate": null,
      "effectiveEndDate": null,
      "currentBillingPeriodEnd": "2023-01-13T17:27:15.000Z",
      "metadata": null,
      "billingId": "sub_1MEcG8AnAO1PFouUcqM98PA5",
      "billingLinkUrl": "https://dashboard.stripe.com/test/subscriptions/sub_1MEcG8AnAO1PFouUcqM98PA5",
      "prices": [],
      "totalPrice": null,
      "pricingType": "FREE",
      "plan": {
      "id": "plan-revvenu-basic",
      "displayName": "Basic",
      "description": null,
      "metadata": null,
      "product": {
        "id": "product-revvenu",
        "displayName": "Revvenu",
        "description": null
      },
      "basePlan": null,
      "entitlements": [
        {
        "usageLimit": 3,
        "hasUnlimitedUsage": null,
        "featureId": "cbcae3e8-a0ab-4b67-a093-426a2f98a72f",
        "resetPeriod": null,
        "feature": {
          "id": "feature-01-templates",
          "featureType": "NUMBER",
          "meterType": "Fluctuating",
          "featureUnits": "template",
          "featureUnitsPlural": "templates",
          "displayName": "Templates",
          "description": null
        }
        },
        {
        "usageLimit": 6,
        "hasUnlimitedUsage": null,
        "featureId": "d50cf34b-8f04-450b-a2d5-07088f2ef162",
        "resetPeriod": "MONTH",
        "feature": {
          "id": "feature-02-campaigns",
          "featureType": "NUMBER",
          "meterType": "Incremental",
          "featureUnits": "campaign",
          "featureUnitsPlural": "campaigns",
          "displayName": "Campaigns",
          "description": null
        }
        }
      ],
      "inheritedEntitlements": [],
      "compatibleAddons": [],
      "prices": [],
      "pricingType": "FREE",
      "defaultTrialConfig": null
      },
      "addons": [],
      "paymentCollection": "NOT_REQUIRED", // status of the payment collection of the subscription - can be either 'NOT_REQUIRED', 'FAILED', 'ACTION_REQUIRED' or 'PROCESSING'
      "latestInvoice": {
        "billingId": "invoice-01", // ID of the invoice of the billing provider
        "status": "PAID", // can be either 'OPEN', 'CANCELED' or 'PAID'
        "createdAt": "2023-08-22T11:27:41.000Z",
        "updatedAt": "2023-08-22T11:27:44.608Z",
        "requiresAction": false, // indicate of the payment requires action to complete the payment
        "paymentUrl": "https://...", // payment url that can be sent to the customer to complete the payment
        "paymentSecret": "secret-01", // secret to be used to initiate next action with billing provider
        "errorMessage": "", // optinal error message, if the status is FAILED
      },
    }
  ]
  }
  ```
</Expandable>

## GetSubscriptions

Retrieves a paginated, filterable list of subscriptions — equivalent to the GraphQL `subscriptions` admin query. Use this for reporting or admin use cases, not for runtime per-customer checks.

<CodeGroup>
  ```go GetSubscriptions.go theme={null}
  result, err := client.GetSubscriptions(context.Background(), stigg.GetSubscriptionsInput{
    Filter: &stigg.SubscriptionQueryFilter{
      Status: &stigg.SubscriptionStatusFilterComparison{
        In: []stigg.SubscriptionStatus{stigg.SubscriptionStatusActive},
      },
    },
    Paging:  &stigg.CursorPaging{First: Ptr(20)},
    Sorting: []*stigg.SubscriptionSort{{Field: "createdAt", Direction: "DESC"}},
  })
  ```
</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>
  ```go ProvisionSubscription.go theme={null}
  result, err := client.ProvisionSubscription(context.Background(), stigg.ProvisionSubscriptionInput{
    // Mandatory, subscription customer ID
    CustomerID: "customer-demo-01",

    // Mandatory, subscription plan ID
    PlanID: "plan-revvenu-essentials",

    // Optional, required only for paid subscriptions  
    BillingPeriod: Ptr(stigg.BillingPeriodMonthly),

    // Optional, required for multiple subscription for same product
    ResourceID: Ptr("resource-01"),                

    // Optional, required for subscriptions with per unit pricing
    BillableFeatures: []*stigg.BillableFeatureInput{
      {
        FeatureID: "feature-01-templates",
        Quantity:  20,
      },
    },

    // Optional, list of subscription addons and quantities
    Addons: []*stigg.SubscriptionAddonInput{
      {
        AddonID:  "addon-revvenu-extra-campaigns",
        Quantity: Ptr(int64(3)),
      },
    },

    // Optional, entitlements for custom plans (feature + credit)
    Entitlements: []*stigg.SubscriptionEntitlementInputV2{
      {
        Feature: &stigg.SubscriptionFeatureEntitlementInput{
          FeatureID:  "feature-seats",
          UsageLimit: Ptr(float64(50)),
        },
      },
      {
        Credit: &stigg.SubscriptionCreditEntitlementInput{
          CustomCurrencyID: "currency-api-credits",
          Amount:           50000,
          Cadence:          stigg.CreditCadenceMonth,
        },
      },
    },

    // Optional, required for price localization, must be in the ISO-3166-1 format
    BillingCountryCode: Ptr("DK"),

    // Optional, parameters used for the hosted checkout
    CheckoutOptions: &stigg.CheckoutOptions{ 
      SuccessURL: "https://your-success-url.com",
      CancelURL:  "https://your-cancel-url.com",
    }
  })
  ```
</CodeGroup>

<Expandable title="Success result">
  ```json theme={null}
  {
  "provisionSubscriptionV2": {
    "checkoutUrl": "https://your-success-url.com",
    "status": "SUCCESS",
    "subscription": {
    "id": "subscription-plan-revvenu-essentials-dc847c",
    "status": "PAYMENT_PENDING",
    "metadata": null,
    "billingId": null,
    "billingLinkUrl": null,
    "effectiveEndDate": null,
    "currentBillingPeriodEnd": "2023-01-13T17:51:51.979Z",
    "pricingType": "PAID",
    "prices": [
      {
      "usageLimit": null,
      "price": {
        "billingModel": "FLAT_FEE",
        "billingPeriod": "MONTHLY",
        "price": {
        "amount": 20,
        "currency": "USD"
        },
        "feature": null
      }
      }
    ],
    "totalPrice": {
      "subTotal": {
      "amount": 20,
      "currency": "USD"
      },
      "total": {
      "amount": 20,
      "currency": "USD"
      }
    },
    "plan": {
      "id": "plan-revvenu-essentials"
    },
    "addons": [],
    "customer": {
      "id": "customer-demo-01"
    },
    "paymentCollection": "NOT_REQUIRED",
    "latestInvoice": {
      "billingId": "invoice-01",
      "status": "PAID",
    },
    }
  }
  }
  ```
</Expandable>

<Expandable title="Payment requires action">
  ```json theme={null}
  {
  "provisionSubscriptionV2": {
    "status": "SUCCESS",
    "subscription": {
      "paymentCollection": "ACTION_REQUIRED",
      "latestInvoice": {
        "paymentUrl": "https...",
        "paymentSecret": "secret"
      }
    }
    }
  }
  ```
</Expandable>

<Expandable title="Payment failed">
  ```json theme={null}
  {
  "provisionSubscriptionV2": {
    "status": "SUCCESS",
    "subscription": {
      "paymentCollection": "FAILED",
      "latestInvoice": {
        "paymentUrl": "https...",
        "errorMessage": "no sufficient funds"
      }
    }
    }
  }
  ```
</Expandable>

<Expandable title="Payment requires checkout">
  ```json theme={null}
  {
    "provisionSubscriptionV2": {
      "checkoutUrl": "https://checkout.stripe.com/c/pay/cs_test_a1v4yjs2PqWvWPy1PiYKhDT05fxY7g1KPO4LQArZdgawINQufLmcfmcm3Z#fidkdWxOYHwnPyd1blpxYHZxWjA0TnZpVjZCX11oMk9QUzxWcEpPRzN8cTZQXDZSSDRwcGRpQ3BiZ0w8NDY9PFZiX2REa0tHZzJDdXBHTD1caEN%2FQ3doS21Abn00REhDUH12cW50fW9rcHJ0NTVwVTxpdEFsMicpJ2N3amhWYHdzYHcnP3F3cGApJ2lkfGpwcVF8dWAnPyd2bGtiaWBabHFgaCcpJ2BrZGdpYFVpZGZgbWppYWB3dic%2FcXdwYCkndnF3bHVgRGZmanBrcSc%2FJ2RmZnFaNE59QUhxRGtESjRVQ2pwUCd4JSUl",
      "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>
  ```go UpdateSubscription.go theme={null}
  result, err := client.UpdateSubscription(context.Background(), stigg.UpdateSubscriptionInput{
    SubscriptionID: Ptr("subscription-plan-revvenu-essentials-dc847c"),
    BillingPeriod: Ptr(stigg.BillingPeriodMonthly),
    BillableFeatures: []*stigg.BillableFeatureInput{
      {
        FeatureID: "feature-01-templates",
        Quantity:  6,
      },
    },
    Addons: []*stigg.SubscriptionAddonInput{
      {
        AddonID:  "addon-revvenu-extra-campaigns",
        Quantity: Ptr(int64(2)),
      },
    }
  })
  ```
</CodeGroup>

<Expandable title="Result">
  ```json theme={null}
  {
  "updateSubscription": {
    "id": "subscription-plan-revvenu-essentials-dc847c",
    "status": "ACTIVE",
    "metadata": null,
    "billingId": "sub_1MEcdyAnAO1PFouUtuDIYy2f",
    "billingLinkUrl": "https://dashboard.stripe.com/test/subscriptions/sub_1MEcdyAnAO1PFouUtuDIYy2f",
    "effectiveEndDate": null,
    "currentBillingPeriodEnd": "2023-01-13T17:51:53.000Z",
    "pricingType": "PAID",
    "prices": [
    {
      "usageLimit": null,
      "price": {
      "billingModel": "FLAT_FEE",
      "billingPeriod": "MONTHLY",
      "price": {
        "amount": 20,
        "currency": "USD"
      },
      "feature": null
      }
    }
    ],
    "totalPrice": {
    "subTotal": {
      "amount": 20,
      "currency": "USD"
    },
    "total": {
      "amount": 20,
      "currency": "USD"
    }
    },
    "plan": {
    "id": "plan-revvenu-essentials"
    },
    "addons": [],
    "customer": {
    "id": "customer-demo-01"
    },
    "paymentCollection": "NOT_REQUIRED", // status of the payment collection of the subscription - can be either 'NOT_REQUIRED', 'FAILED', 'ACTION_REQUIRED' or 'PROCESSING'
    "latestInvoice": {
      "billingId": "invoice-01", // ID of the invoice of the billing provider
      "status": "PAID", // can be either 'OPEN', 'CANCELED' or 'PAID'
      "createdAt": "2023-08-22T11:27:41.000Z",
      "updatedAt": "2023-08-22T11:27:44.608Z",
      "requiresAction": false, // indicate of the payment requires action to complete the payment
      "paymentUrl": "https://...", // payment url that can be sent to the customer to complete the payment
      "paymentSecret": "secret-01", // secret to be used to initiate next action with billing provider
      "errorMessage": "", // optinal error message, if the status is FAILED
    },
  }
  }
  ```
</Expandable>

# Cancel subscription

<CodeGroup>
  ```go CancelSubscription.go theme={null}
  result, err := client.CancelSubscription(context.Background(), stigg.SubscriptionCancellationInput{
    SubscriptionRefID: "subscription-plan-revvenu-essentials-dc847c",
    SubscriptionCancellationTime: Ptr(stigg.SubscriptionCancellationTimeImmediate),
  })
  ```
</CodeGroup>

<Expandable title="Result">
  ```json theme={null}
  {
  "cancelSubscription": {
    "id": "subscription-plan-revvenu-essentials-dc847c",
    "status": "CANCELED",
    "metadata": null,
    "billingId": "sub_1MEcdyAnAO1PFouUtuDIYy2f",
    "billingLinkUrl": "https://dashboard.stripe.com/test/subscriptions/sub_1MEcdyAnAO1PFouUtuDIYy2f",
    "effectiveEndDate": "2022-12-13T18:02:20.564Z",
    "currentBillingPeriodEnd": "2023-01-13T17:51:53.000Z",
    "pricingType": "PAID",
    "prices": [
    {
      "usageLimit": null,
      "price": {
      "billingModel": "FLAT_FEE",
      "billingPeriod": "MONTHLY",
      "price": {
        "amount": 20,
        "currency": "USD"
      },
      "feature": null
      }
    }
    ],
    "totalPrice": {
    "subTotal": {
      "amount": 20,
      "currency": "USD"
    },
    "total": {
      "amount": 20,
      "currency": "USD"
    }
    },
    "plan": {
    "id": "plan-revvenu-essentials"
    },
    "addons": [],
    "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>
  ```go GetEntitlement.go theme={null}

  result, err := client.GetEntitlement(context.Background(), stigg.FetchEntitlementQuery{
    CustomerID: "customer-demo-01",
    FeatureID:  "feature-01-templates",
    Options: &stigg.EntitlementOptions{
      RequestedUsage: Ptr(float64(0)),
    },
    ResourceID: Ptr("resource-01"),  // optional, pass it to get entitlement of specific resource
  })

  if result.Entitlement.IsGranted {
    // customer has access to the feature 
  } else {
    // access denied
  }
  ```
</CodeGroup>

<Expandable title="Result">
  ```json theme={null}
  {
  "entitlement": {
    "isGranted": true,
    "accessDeniedReason": null,
    "customerId": "0e5e888a-5598-4626-bc97-cda67bc387b9",
    "usageLimit": 3,
    "hasUnlimitedUsage": false,
    "currentUsage": 3,
    "requestedUsage": 0,
    "usagePeriodAnchor": null,
    "usagePeriodStart": null,
    "usagePeriodEnd": null,
    "resetPeriod": null,
    "feature": {
    "id": "feature-01-templates",
    "featureType": "NUMBER",
    "meterType": "Fluctuating",
    "featureUnits": "template",
    "featureUnitsPlural": "templates",
    "displayName": "Templates",
    "description": null
    },
    "resetPeriodConfiguration": 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>
  ```go GetEntitlements.go theme={null}
  result, err := client.GetEntitlementsState(context.Background(), stigg.FetchEntitlementsQuery{
    CustomerID: "customer-demo-01",
    
    // Optional, pass it to get entitlements of specific resource
    ResourceID: Ptr("resource-01")
  })
  ```
</CodeGroup>

<Expandable title="Result">
  ```json theme={null}
  {
    "entitlementsState": {
      "entitlements": [
        {
        "isGranted": true,
        "accessDeniedReason": null,
        "customerId": "0e5e888a-5598-4626-bc97-cda67bc387b9",
        "usageLimit": null,
        "hasUnlimitedUsage": false,
        "currentUsage": 0,
        "requestedUsage": null,
        "usagePeriodAnchor": null,
        "usagePeriodStart": null,
        "usagePeriodEnd": null,
        "resetPeriod": null,
        "feature": {
          "id": "feature-03-custom-domain",
          "featureType": "BOOLEAN",
          "meterType": "None",
          "featureUnits": null,
          "featureUnitsPlural": null,
          "displayName": "Custom domain",
          "description": null
        },
        "resetPeriodConfiguration": null
        },
        {
        "isGranted": true,
        "accessDeniedReason": null,
        "customerId": "0e5e888a-5598-4626-bc97-cda67bc387b9",
        "usageLimit": 6,
        "hasUnlimitedUsage": false,
        "currentUsage": 0,
        "requestedUsage": null,
        "usagePeriodEnd": "2023-01-13T00:00:00.000Z",
        "usagePeriodEnd": "2023-09-13T00:00:00.000Z",
        "usagePeriodEnd": "2023-10-13T00:00:00.000Z",
        "resetPeriod": "MONTH",
        "feature": {
          "id": "feature-02-campaigns",
          "featureType": "NUMBER",
          "meterType": "Incremental",
          "featureUnits": "campaign",
          "featureUnitsPlural": "campaigns",
          "displayName": "Campaigns",
          "description": null
        },
        "resetPeriodConfiguration": {
          "MonthlyResetPeriodConfig": {
          "monthlyAccordingTo": "SubscriptionStart"
          },
          "WeeklyResetPeriodConfig": {
          "weeklyAccordingTo": null
          }
        }
        },
        {
        "isGranted": true,
        "accessDeniedReason": null,
        "customerId": "0e5e888a-5598-4626-bc97-cda67bc387b9",
        "usageLimit": 3,
        "hasUnlimitedUsage": false,
        "currentUsage": 3,
        "requestedUsage": null,
        "usagePeriodAnchor": null,
        "usagePeriodStart": null,
        "usagePeriodEnd": null,
        "resetPeriod": null,
        "feature": {
          "id": "feature-01-templates",
          "featureType": "NUMBER",
          "meterType": "Fluctuating",
          "featureUnits": "template",
          "featureUnitsPlural": "templates",
          "displayName": "Templates",
          "description": null
        },
        "resetPeriodConfiguration": null
        }
      ]
    },
    "accessDeniedReason": 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" horizontal href="/documentation/getting-usage-data-into-stigg/overview" />

<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>
  ```go ReportUsage.go theme={null}
  result, err := client.ReportUsage(context.Background(), stigg.ReportUsageInput{
    Value:      5,
    CustomerID: "customer-demo-01",
    FeatureID:  "feature-02-campaigns",
    ResourceID: Ptr("resource-01"),  // optional, pass it to report usage for specific resource
  })
  ```
</CodeGroup>

<Expandable title="Result">
  ```json theme={null}
  {
  "reportUsage": {
    "id": "9401dd9a-e350-43fc-8499-b1dbd3ac411c"
  }
  }
  ```
</Expandable>

### Raw events

<CodeGroup>
  ```go ReportEvent.go theme={null}
  result, err := client.ReportEvent(context.Background(), stigg.UsageEventsReportInput{
    UsageEvents: []*stigg.UsageEventReportInput{
      {
        CustomerID:     "customer-test-id",
        ResourceID:     Ptr("resource-01"), // optional, pass it to report event for specific resource
        EventName:      "user_login",
        IdempotencyKey: "227c1b73-883a-457b-b715-6ba5a2c69ce4",
        Dimensions: map[string]interface{}{
          "user_id":    "user-01",
          "user_email": "john@example.com",
        },
        Timestamp: Ptr("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>
  ```go GetCoupons.go theme={null}
  result, err := client.GetCoupons(context.Background())
  ```
</CodeGroup>

<Expandable title="Result">
  ```json theme={null}
  {
  "coupons": {
    "edges": [
    {
      "node": {
      "id": "coupon-vip",
      "name": "VIP",
      "description": null,
      "type": "PERCENTAGE",
      "discountValue": 20,
      "metadata": null,
      "createdAt": "2022-11-30T16:21:02.061Z",
      "updatedAt": "2022-11-30T16:21:05.896Z",
      "billingId": "FI5A6y4Q",
      "billingLinkUrl": "https://dashboard.stripe.com/test/coupons/FI5A6y4Q",
      "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>
  ```go EstimateSubscription.go theme={null}
  result, err := client.EstimateSubscription(context.Background(), stigg.EstimateSubscriptionInput{
  		CustomerID:      "customer-demo-01",
  		PlanID:          "plan-revvenu-essentials",
  		BillingPeriod:   Ptr(stigg.BillingPeriodMonthly),
  		PriceUnitAmount: Ptr(float64(4)), // optional, required for plans with per-unit pricing
  		Addons: []*stigg.SubscriptionAddonInput{{ // optional
  			AddonID:  "addon-10-campaigns",
  			Quantity: Ptr(int64(5)),
  		}},
  		BillingCountryCode: Ptr("DK"),          // optional, required for price localization, must be in the ISO-3166-1 format
  		ResourceID:         Ptr("resource-01"), // optional, required for multiple subscription for same product
  		BillingInformation: Ptr(stigg.SubscriptionBillingInfo{
  			TaxRateIds: []string{"tax-rate-1"},
  		}),
  	})
  ```
</CodeGroup>

<Expandable title="Result">
  ```json theme={null}
  {
  "estimateSubscription": {
    "subTotal": {
    "amount": 45,
    "currency": "USD"
    },
    "total": {
    "amount": 45,
    "currency": "USD"
    },
    "billingPeriodRange": {
    "start": "2022-12-13T18:14:07.364Z",
    "end": "2023-01-13T18:14:07.364Z"
    },
    "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>
  ```go EstimateSubscriptionUpdate.go theme={null}
  result, err := client.EstimateSubscriptionUpdate(context.Background(), stigg.EstimateSubscriptionUpdateInput{
    SubscriptionID: "subscription-plan-revvenu-basic-558071",
    UnitQuantity:   Ptr(float64(4)),
    Addons: []*stigg.SubscriptionAddonInput{{
      AddonID:  "addon-10-campaigns",
      Quantity: Ptr(int64(5)),
    }},
  })
  ```
</CodeGroup>

<Expandable title="Result">
  ```json theme={null}
  {
  "estimateSubscriptionUpdate": {
    "subTotal": {
    "amount": 0,
    "currency": "USD"
    },
    "total": {
    "amount": 0,
    "currency": "USD"
    },
    "billingPeriodRange": {
    "start": "2022-12-13T18:02:21.123Z",
    "end": "2023-01-13T18:02:21.123Z"
    },
    "proration": null
  }
  }
  ```
</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 Go's standard library.

## Check

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

<CodeGroup>
  ```go check.go theme={null}
  import (
    "bytes"
    "encoding/json"
    "net/http"
    "os"
  )

  baseURL   := os.Getenv("GOVERNANCE_API_URL")
  authToken := os.Getenv("GOVERNANCE_ACCESS_TOKEN")
  accountID := os.Getenv("STIGG_ACCOUNT_ID")
  envID     := os.Getenv("STIGG_ENVIRONMENT_ID")

  body, _ := json.Marshal(map[string]any{
    "entityIds":       []string{"team-eng"},
    "capabilityId":    "ai-tokens",
    "requestedAmount": 1000,
  })

  req, _ := http.NewRequest(http.MethodPost, baseURL+"/owners/cus-acme/check", bytes.NewReader(body))
  req.Header.Set("Authorization", "Bearer "+authToken)
  req.Header.Set("x-stigg-account-id", accountID)
  req.Header.Set("x-stigg-environment-id", envID)
  req.Header.Set("Content-Type", "application/json")

  resp, _ := http.DefaultClient.Do(req)

  var report struct {
    HasAccess bool `json:"hasAccess"`
  }
  json.NewDecoder(resp.Body).Decode(&report)

  if !report.HasAccess {
    panic("usage limit reached")
  }
  ```
</CodeGroup>

## Ingest

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

<CodeGroup>
  ```go ingest.go theme={null}
  body, _ = json.Marshal(map[string]any{
    "events": []map[string]any{
      {"entityIds": []string{"team-eng"}, "capabilityId": "ai-tokens", "amount": 1250},
    },
  })

  req, _ = http.NewRequest(http.MethodPost, baseURL+"/owners/cus-acme/ingest", bytes.NewReader(body))
  req.Header.Set("Authorization", "Bearer "+authToken)
  req.Header.Set("x-stigg-account-id", accountID)
  req.Header.Set("x-stigg-environment-id", envID)
  req.Header.Set("Content-Type", "application/json")

  http.DefaultClient.Do(req)
  ```
</CodeGroup>

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

# Full SDK reference

<Card title="Go SDK reference" icon="code" horizontal href="https://pkg.go.dev/github.com/stiggio/api-client-go/v5" />

# SDK changelog

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