Adding Monetization Capabilities to Your Firestore API

To continue with the Firebase REST API example we built previously, in today’s tutorial, we will expand on things further by showing you how to enhance your Firestore API by adding monetization capabilities through the Zuplo Developer Portal. We will use Zuplo’s Stripe plugin and Stripe to implement end-to-end monetization for our API in a few minutes.

Before we get started, you’ll need to make sure you have the following prerequisites in place:

  • Basic understanding of Firestore and REST APIs
  • Firestore API set up as per Firebase Day 1
  • API key authentication set up using Zuplo, covered in Firebase Day 2
  • Zuplo Developer Portal enabled, covered in Firebase Day 3

With these checked off, let’s begin by setting up our initial products in Stripe.

Step 1: Set Up Stripe Products#

To monetize our APIs, we need to create products in Stripe. In this example, we will create two products: a Free Tier and a Pro Tier.

Our Free tier will allow users to:

  • Perform 100 requests to retrieve, update, and delete to-do items
  • Create up to 3 to-do items

For users who require a higher quota, we will allow them to subscribe to the Pro tier, which will include the ability to:

  • Perform 1,000,000 requests to retrieve, update, and delete to-do items
  • Create up to 1000 to-do items

Create the Free Product#

To create the Free product, we will:

  1. Log into your Stripe dashboard, and, in the left-side menu, go to **More **and select Product Catalog.
  2. On the Product catalog screen, click Add product.
  3. On the Add a product modal, fill in the following values:
    1. In the Name field, enter “Free
    2. In the Description field, enter “Our awesome free Todo API. Includes 100 requests and up to 3 todo creates.
    3. Ensure the product is set as Recurring.
    4. Set the Amount field to “$0.00
    5. Ensure that Billing period is set to “Monthly
  4. Once the fields are filled in, click Add product at the bottom of the modal.

Here’s how the product should look before you submit the form:

Stripe product

With the Free product created, let’s create the Pro product next. For that, back on the Product catalog screen, we will:

  1. Click Add product, again.
  2. On the Add a product modal, fill in the following values:
    1. In the Name field, enter “Pro
    2. In the Description field, enter “Our awesome Todo API now with morrrrrrrrre. Includes 1000 Todo Creates and 1,000,000 requests.
    3. Ensure the product is set as Recurring.
    4. Set the Amount field to “$100.00
    5. Ensure that Billing period is set to “Monthly
  3. Once the fields are filled in, click Add product.

Create the Pro Product#

Here’s how your Pro product will look before you submit the form:

Stripe product configuration

We currently have two products that customers can subscribe to. On the Product catalog main screen, you should see both of your products on the list.

Stripe product catalog

Next, let’s create a Stripe Pricing Table, which we will use in the developer portal to facilitate checkout for our API users.

Step 2: Create a Pricing Table in Stripe#

Next, we want to give developers a way to subscribe to our APIs. Of course, we could create a custom checkout flow, but luckily, Stripe has a nicely wrapped-up way to facilitate the purchasing flow using a Pricing Table. The pricing table will allow users to select their plan and complete the entire checkout process, all handled by Stripe.

To set up the Pricing Table, we will need to do the following:

  1. On the Pricing catalog screen, in the header menu, choose the Pricing tables tab.
  2. Click Create pricing table.
  3. On the Create your pricing table modal, select the products you created in the previous step and add them to the table.

Stripe pricing table customization

  1. Optionally, you can also tweak the Button color field and others to customize the look and feel of the pricing table.
  2. Once the pricing table settings are dialed in, click Continue in the bottom-left of the modal.
  3. On the next page, Accept payment, you can keep the default settings and click Finish. To create the pricing table.

Note that subsequent screens appearing in the Create pricing table workflow can be accepted with the default settings.

Eventually, the pricing table will be created, and you’ll be presented with the code and values needed to embed it in the Zuplo Developer Portal.

Stripe pricing table code

We will extract a few values from this snippet shortly, so feel free to leave this screen up in your browser for easy access.

Step 3: Configure Zuplo for Stripe Integration#

With the products and pricing table set up in Stripe, we need to plug a few details from Stripe into our Zuplo instance. The first thing we will do is integrate with the Stripe API.

Retrieve the Stripe API Key#

To get our Stripe API key, log into Stripe (in a new browser tab if you want to keep the pricing table details open), and do the following:

  1. Go to the Stripe Developers page by clicking the link in the top-right of the dashboard.
  2. On the Developers page, select the API keys tab.
  3. Under the Standard keys section, go to Secret key and click Reveal test key.
  4. Copy the Secret key value.

Getting a stripe API key

Add the Stripe Secret Key to Zuplo#

With the Stripe API key on our clipboard, head back into Zuplo and do the following:

  1. Click on Settings in the header menu.
  2. On the Settings screen, click Environment Variables on the left-hand menu.
  3. On the Environment Variables screen, click Add Variable.
  4. On the Environment Variable form, Fill in the following details:
    1. For the Name, add “STRIPE_SECRET_KEY”.
    2. For Value, paste the Stripe secret key from your clipboard.
    3. Check off the Secret checkbox to encrypt the key and make it not visible once set.
  5. Click Save in the bottom-left to persist the value to Zuplo.

Adding an environment variable for your API key

Enable Monetization in Zuplo#

Next, we need to enable monetization in our Zuplo Developer Portal. For this, we will need to do the following steps in Zuplo:

  1. Go to the Code tab in the header menu, and in the left-side menu under config, open the dev-portal.json.
  2. In the file, scroll to the Monetization Settings section and check the Enable Monetization checkbox.
  3. In the Pricing Table ID and Publishable Key fields, add in the values from Stripe (in the code snippet on the Pricing Table** **screen).
  4. For the Secret Key field, click the Select Environment Variable button at the end and select the STRIPE_SECRET_KEY entry we created earlier.

Configuring Zuplo monetization

  1. Click the Save button at the bottom-left to persist with the updated configuration and push it to the gateway.

Confirm Monetization is Enabled in the Developer Portal#

Now, with monetization enabled, we can go back to our Developer Portal to check and ensure that monetization is available.

accessing the Zuplo developer portal

On the Developer Portal, a Pricing menu item should appear at the top right of the screen.

Navigating to the Zuplo pricing table

Clicking on Pricing, we should also see our pricing table appear.

Zuplo pricing table

At this point, users can subscribe to an API, but we aren’t quite ready to monetize yet. For this, we will need to configure our plans in Zuplo.

Step 4: Create Plans in Zuplo#

The Metering Service will create our plans in Zuplo. This service will allow us to attribute usage to a specific meter. That meter can then be used in a policy to ensure that users don’t exceed their plan quota.

Create the Free and Pro Meters in Zuplo#

We will need to create a meter for both the Free and Pro plans. We will start by creating the meters for the Free plan in Zuplo. To do this, we will do the following in Zuplo:

  1. Click on the Services tab in the menu.
  2. On the Services screen, click Configure on the Metering Service module.
  3. On the Metering Service screen, under the Plans section, click Create Plan.
  4. In the Create Plan modal that appears, populate the fields as follows:
    1. For the Name field, set the value to “Free”.
    2. For External ID, we will use the Stripe Product ID as the value. This can be obtained by:
      1. In Stripe, go to the Product catalog and select the “Free” product.
      2. On the product details screen for the product, copy the product ID and paste it back into the field in Zuplo.

Stripe product ID

  1. Under the Meters section, we will add our limits for our plan. We will add two values: 3. For the first meter, set the Label as “Requests” and the Max Value as “100”. 4. Click the Add Meter button under the first entry. 5. For the second meter, set the Label as “Todo Creates” and the Max Value as “3”.

Creating a plan

  1. With the details filled out for the Free plan, click Create Plan.

Next, we will create the meters for the Pro plan in Zuplo. For this, let’s do the following:

  1. Still, on the Metering Service screen, click Create Plan again.
  2. In the Create Plan modal that appears, populate the fields as follows:
    1. For the Name field, set the value to “Pro”.
    2. For External ID, we will use the Stripe Product ID as the value. This can be obtained by:
      1. In Stripe, go to the Product catalog and select the “Pro” product.
      2. On the product details screen for the product, copy the product ID and paste it back into the field in Zuplo.

Other stripe product ID

  1. Under the Meters section, we will add our limits for our plan. We will add two values: 6. For the first meter, set the Label as “Requests” and the Max Value as “1000000”. 7. Click the Add Meter button under the first entry. 8. For the second meter, set the Label as “Todo Creates” and the Max Value as “1000”.

Create another stripe plan

  1. With the details filled out for the Free plan, click Create Plan.

With both plans created, we should see them in the list of available plans on the Metering Service screen.

Zuplo metering service

At this point, we’re almost there. The last piece that we need to wire up the full end-to-end monetization experience is to configure the Zuplo Plugin and the corresponding webhook in Stripe.

Step 5: Configure The Zuplo-Stripe Plugin and Stripe Webhook#

In this next step, we will add the Zuplo StripeMonetizationPlugin to our Zuplo configuration. This will enable your Zuplo API to listen to Stripe Webhook subscription events. This plugin adds an endpoint that is used when configuring the Stripe Webhook.

Add the StripeMonetizationPlugin to Zuplo#

First, let's add the plugin to our Zuplo instance. To add the plugin, do the following:

  1. In Zuplo, go to the Code section of your project by clicking the corresponding header menu item.
  2. Under the modules folder, click the + button and select Runtime Extension.
  3. In the file that is created, zuplo.runtime.ts, add the following code for the StripeMonetizationPlugin:
import {
  RuntimeExtensions,
  StripeMonetizationPlugin,
  environment,
} from "@zuplo/runtime";
 
export function runtimeInit(runtime: RuntimeExtensions) {
  // Create the Stripe Plugin
  const stripe = new StripeMonetizationPlugin({
    webhooks: {
      signingSecret: environment.STRIPE_WEBHOOK_SIGNING_SECRET,
    },
    stripeSecretKey: environment.STRIPE_SECRET_KEY,
  });
  // Register the plugin
  runtime.addPlugin(stripe);
}
  1. With the file populated, click Save in the screen's bottom-left to save the updated config.

As you can see in the code, the plugin uses two environment variables: STRIPE_SECRET_KEY and STRIPE_WEBHOOK_SIGNING_SECRET. The STRIPE_SECRET_KEY is the same value added in Step 3 of this tutorial. The STRIPE_WEBHOOK_SIGNING_SECRET is a value we will grab from Stripe once we configure the webhook.

Configure the Stripe Webhook#

Next, we need to set up the webhook in Stripe. Heading back into the Stripe dashboard, we will do the following:

  1. Go back to the Developers screen, then select the Webhooks tab.
  2. Click Add an endpoint.
  3. In the modal that appears, fill in the following values and configuration:
    1. For the Endpoint URL, add the URL of your Zuplo instance, plus “/__plugins/stripe/webhooks”. This can be found back in Zuplo under Settings > General, then the value under URL.

Getting the Zuplo URL

  1. Click Select events to listen to and then select the event entries for:
    1. customer.subscription.created
    2. customer.subscription.updated
    3. customer.subscription.deleted
  2. Click Add events once selected.
  3. With the configuration plugged in, click Add endpoint to register the endpoint.

Stripe webhook setup

After you’ve created the webhook in Stripe, you’ll be brought to the details screen for the webhook. Here, we will grab the webhook secret we need for Zuplo. Under Signing secret, click Reveal. Then, copy the value.

Stripe webhook signing secret

Create the Stripe Webhook Signing Secret Variable in Zuplo#

With our webhook signing secret on the clipboard, we can now add the corresponding environment variable into Zuplo. To add this variable, do the following:

  1. In Zuplo, go to Settings and select Environment Variables from the left-side menu.
  2. On the Environment Variables screen, click Add Variable.
  3. On the modal that appears, enter the following details:
    1. In the Name field, set it as “STRIPE_WEBHOOK_SIGNING_SECRET
    2. In the Value field, paste in the webhook secret copied previously
    3. Check the Secret checkbox as we did with the previous Stripe environment variable we created.
  4. Click Save.

Environment variable for signing secret

At this point, we should have added both Stripe variables required for the monetization plugin to Zuplo.

Zuplo env vars

The last piece in this monetization flow is to add our monetization policy to the respective endpoints so that usage can be metered and blocked when it exceeds the allocated quota.

Step 6: Add the Monetization Policy to the Endpoints#

To round out our fully-fledged API monetization setup, we need a mechanism to meter the requests and block any that exceed the user's quota. We will use a monetization policy in Zuplo and attach it to the endpoints.

Create the monetize-requests Policy#

To create and add the policy, we will:

  1. Navigate to the routes.oas.json screen in Zuplo.
  2. Under the Route Designer tab, open up the Get all todos endpoint.
  3. Expand the endpoints Policies section.
  4. In the Policies section, under Request, click Add Policy.
  5. In the Choose Policy modal, select the Monetization tile.
  6. In the Create Policy modal, name the policy “monetize-requests”.
  7. Accepting the default configuration, which will increment the request meter by 1 for each request logged, click OK.

Before adding the policy, the Create Policy modal should look like this:

Adding monetization policy

After clicking OK, you should see the new policy added to the request pipeline. Once added, the policy should be the last to be executed in the request pipeline. Your endpoint configuration should look like this:

New zuplo route

Add the Policy to the Applicable Endpoints#

Now, we must add this same policy to our other endpoints. To do this, we will:

  1. Go to the policies.json file
  2. In the Policies List, find the monetize-requests policy, click the ellipsis (...), and select Apply Policy.
  3. In the Apply Policy modal, select the PATCH and DELETE endpoints.
  4. Click Apply.

Applying the policy

This will apply the policy to our other endpoints that require it.

Create the monetize-creates Policy#

Since our Create Todos [POST] endpoint will be recorded to a different meter, but still record calls to the Requests meter, we will need to create a slightly different monetization policy. For this, we will:

  1. Back in the routes.oas.json screen in Zuplo, open the Create todo endpoint under the Route Designer tab.
  2. Expand the endpoints Policies section.
  3. In the Policies section, under Request, click Add Policy.
  4. In the Choose Policy modal, select the Monetization tile.
  5. In the Create Policy modal, set the name to “monetize-creates”.
  6. Change the configuration so that it logs a request to both the todoCreates and requests meters.
{
  "export": "MonetizationInboundPolicy",
  "module": "$import(@zuplo/runtime)",
  "options": {
    "meters": {
      "requests": 1,
      "todoCreates": 1
    }
  }
}
  1. Once the configuration is updated, click OK.

Creating a new policy

  1. Ensure that the policy is at the bottom of the request policy pipeline.

Route config after adding second policy

  1. Click Save in the screen’s bottom-left corner.

Now, we have everything needed to implement end-to-end monetization with our Firebase API, Zuplo, and Stripe. Our final step will be to test everything to ensure it is set up correctly.

Step 6: Test and Verify The Monetization Setup#

In this final step, we must ensure that all aspects of our monetization setup work correctly. What we will do is:

  • Test that a subscription can be set up
  • Test that once a user is subscribed, they can access the API
  • Finally, test that Zuplo blocks users once they have exceeded their quota.

To test out our flow, head to your Zuplo Developer Portal and begin the end-to-end test.

Check the Subscription Flow#

  1. Log into the Developer Portal by clicking Sign In and signing in.
  2. If you have an old test key available in the portal for your user, delete it. To do this, you can:
    1. In your Zuplo project, navigate to Services and click Configure on the API Key Service entry.
    2. On the entry for your consumer, click on the ellipsis (...) and select Delete to delete the API key.
  3. Once logged into the portal, click on Pricing in the header menu.
  4. On the Pricing page, on the Free plan entry, click Subscribe.
  5. On the payment form that appears, fill out the fields as follows: 3. Under the Card information section: 1. For Card number, use the Stripe test card number by entering “4242 4242 4242 4242” 2. Under Expiry, enter “12/34”. 3. For the Security code, enter “123”. 4. For Cardholder name, enter your name. 5. Under Country/region, enter in your details.
  6. With the payment details filled in, click Submit.

You should then be redirected back to the developer portal, and Zuplo will await the confirmation that your subscription has been set up.

Note: If you are experiencing issues, saving the zuplo.runtime.ts file we created in Step 5, which establishes the webhook for your Zuplo instance, is vital.

Once the subscription is loaded, your Zuplo Developer Portal should be showing a screen similar to this:

Zuplo subscription screen

At this point, we can confirm that our subscription creation flow is working and that the subscription is successfully linked back to the developer portal.

Check the Metering Functionality#

Next, let’s ensure that our API key works for our endpoints and accurately meters the requests against the quotas for our plan. To do this, we will:

  1. In the developer portal, go to the Create todo endpoint on the left-hand menu.
  2. On the Create todo screen, click Test in the top-right corner.

Zuplo metering screenshot

  1. In the API Playground modal, send the example request by clicking Test.
  2. When the response returns, you should see it was successful, denoted by the 200 OK response returned.

Testing the API

  1. Go to the Get all todos endpoint in the developer portal and fire off a request by following the same steps in the API Playground. The response should contain your newly added todo.

Zuplo API playground

  1. By clicking on the Subscriptions menu item at the top of the developer portal, we should see that our requests have been metered against our quota on the Subscriptions screen.

Zuplo subscription update

Check on Quota Enforcement#

Lastly, let’s test to ensure that Zuplo blocks API requests above our quota. For this, go back to the Create todo endpoint in the portal and fire off 3 more requests to the endpoint through the API Playground. You should see that Zuplo is blocking the requests that exceed the quota.

Zuplo quota enforcement

In the Subscriptions screen, we should also see that the overage is being recorded here.

API quota exceeded

With that, we can confirm that all pieces of our monetization flow are working as intended and are ready to be shipped to our users.

Conclusion#

Following these steps, we have successfully added the ability to monetize our API. This capability allows API consumers to subscribe and use the API via the Zuplo Developer Portal. In the final part of this series, we will build on these APIs and add the following functionalities:

  • Day 5: Add AI features using Gemini

Keep following for our last detailed step-by-step tutorial to round out Firebase week!

Designed for Developers, Made for the Edge