Go SDK

How to install and use the Stigg Go SDK on the server-side

πŸ“˜

Stigg's Go SDK is a thin wrapper around the GraphQL API and does not support caching, polling or streaming of customer entitlements.

Overview

This Go module provides a wrapper to Stigg's GraphQL API based on the operations that are in use by the Stigg's Node.js SDK. It leverages the 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:

go get github.com/stiggio/api-client-go

Retrieving the server API Key

In the Stigg Cloud Console, go to Settings > Account > Environments.

Copy the Server API key of the relevant environment.

Initializing the SDK

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

import (
  "context"
  "github.com/stiggio/api-client-go"
  "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_SERVER_API_KEY")

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

  // client is initialized
}

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 Console using the product's Customer Journey configuration.

Query


result, err := client.ProvisionCustomer(context.Background(), stigg.ProvisionCustomerInput{
  CustomerID: Ptr("customer-id"),
  Name:  Ptr("Acme"), 						// optional
  Email: Ptr("[email protected]"), 	// 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",
  },
})

Response
{
    "provisionCustomer": {
      "customer": {
        "refId": "customer-id",
        "name": "Acme",
        "email": "[email protected]",
        "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"
        }
      }
    }
}

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.

Query

result, err := client.UpdateCustomer(context.Background(), stigg.UpdateCustomerInput{
  CustomerID:  Ptr("customer-id"),
  Name:  Ptr("Acme"),
  Email: Ptr("[email protected]"),
  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",
  },
})

Response
{
 "updateCustomer": {
  "id": "customer-f9942a",
  "name": "Acme",
  "email": "[email protected]",
  "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"
  }
 }
}

Getting customer data

Query

result, err := client.GetCustomerByID(context.Background(), stigg.GetCustomerByRefIDInput{
  CustomerID: "customer-f9942a",
})
Response
{
 "getCustomerByRefId": {
  "id": "customer-f9942a",
  "name": "Acme",
  "email": "[email protected]",
  "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"
  }
 }
}

Getting customer active subscriptions

Query

result, err := client.GetActiveSubscriptions(context.Background(), stigg.GetActiveSubscriptionsInput{
  CustomerID: "customer-f9942a",

  // Optional, pass it to get subscription of specific resource 
  ResourceID: Ptr("resource-01"),
})
Response
{
 "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
    },
   }
 ]
}

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.

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, 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",
  }
})

Success Result
{
 "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",
   },
  }
 }
}

Payment requires action
{
 "provisionSubscriptionV2": {
   "status": "SUCCESS",
   "subscription": {
     "paymentCollection": "ACTION_REQUIRED",
     "latestInvoice": {
       "paymentUrl": "https...",
       "paymentSecret": "secret"
     }
   }
 	}
}

Payment failed
{
 "provisionSubscriptionV2": {
   "status": "SUCCESS",
   "subscription": {
     "paymentCollection": "FAILED",
     "latestInvoice": {
       "paymentUrl": "https...",
       "errorMessage": "no sufficient funds"
     }
   }
 	}
}
Payment requires checkout
{
  "provisionSubscriptionV2": {
    "checkoutUrl": "https://checkout.stripe.com/c/pay/cs_test_a1v4yjs2PqWvWPy1PiYKhDT05fxY7g1KPO4LQArZdgawINQufLmcfmcm3Z#fidkdWxOYHwnPyd1blpxYHZxWjA0TnZpVjZCX11oMk9QUzxWcEpPRzN8cTZQXDZSSDRwcGRpQ3BiZ0w8NDY9PFZiX2REa0tHZzJDdXBHTD1caEN%2FQ3doS21Abn00REhDUH12cW50fW9rcHJ0NTVwVTxpdEFsMicpJ2N3amhWYHdzYHcnP3F3cGApJ2lkfGpwcVF8dWAnPyd2bGtiaWBabHFgaCcpJ2BrZGdpYFVpZGZgbWppYWB3dic%2FcXdwYCkndnF3bHVgRGZmanBrcSc%2FJ2RmZnFaNE59QUhxRGtESjRVQ2pwUCd4JSUl",
    "status": "PAYMENT_REQUIRED",
    "subscription": null
 	}
}


πŸ“š

SDK reference ↗️

🚧

  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.

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.

Query

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)),
    },
  }
})
Response
{
 "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
  },
 }
}

Cancel subscription

Query

result, err := client.CancelSubscription(context.Background(), stigg.SubscriptionCancellationInput{
  SubscriptionRefID: "subscription-plan-revvenu-essentials-dc847c",
  SubscriptionCancellationTime: Ptr(stigg.SubscriptionCancellationTimeImmediate),
})
Response
{
 "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"
  }
 }
}

🚧

Subscription cancellation will take place according to the defined product behavior.

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.

Query

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
}
Response
{
 "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
 }
}

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.

Query

result, err := client.GetEntitlements(context.Background(), stigg.FetchEntitlementsQuery{
  CustomerID: "customer-demo-01",
  
  // Optional, pass it to get entitlements of specific resource
  ResourceID: Ptr("resource-01")
})
Response
{
 "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
  }
 ]
}

Reporting usage measurements to Stigg

The Stigg SDK allows you to report usage measurements for metered features. 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 - usage that has been aggregated and calculated by your application. This type is useful for features, such as: seats.
  2. 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:

🚧

  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.

πŸ“˜

Validating that a measurement was successfully reported to Stigg is also possible in the customer details section of the relevant customer in the Stigg Cloud Console.

Calculated usage

Query

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
})
Response
{
 "reportUsage": {
  "id": "9401dd9a-e350-43fc-8499-b1dbd3ac411c"
 }
}

Raw events

Query

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": "[email protected]",
      },
      Timestamp: Ptr("2022-10-26T15:01:55.768Z"), // optional, pass it to report event with specific timestamp
    },
  },
})

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

Query

result, err := client.GetCoupons(context.Background())
Response
{
 "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"
    }
   }
  ]
 }
}

Estimating subscription cost

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

Query

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"},
		}),
	})
Result
{
 "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
 }
}


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

Query

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)),
  }},
})
Result
 {
 "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
 }
}