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:
- Log into your Stripe dashboard, and, in the left-side menu, go to More **and select **Product Catalog.
- On the Product catalog screen, click Add product.
- On the Add a product modal, fill in the following values:
- In the Name field, enter “Free”
- In the Description field, enter “Our awesome free Todo API. Includes 100 requests and up to 3 todo creates.”
- Ensure the product is set as Recurring.
- Set the Amount field to “$0.00”
- Ensure that Billing period is set to “Monthly”
- 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:
With the Free product created, let’s create the Pro product next. For that, back on the Product catalog screen, we will:
- Click Add product, again.
- On the Add a product modal, fill in the following values:
- In the Name field, enter “Pro”
- In the Description field, enter “Our awesome Todo API now with morrrrrrrrre. Includes 1000 Todo Creates and 1,000,000 requests.”
- Ensure the product is set as Recurring.
- Set the Amount field to “$100.00”
- Ensure that Billing period is set to “Monthly”
- 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:
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.
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:
- On the Pricing catalog screen, in the header menu, choose the Pricing tables tab.
- Click Create pricing table.
- On the Create your pricing table modal, select the products you created in the previous step and add them to the table.
- Optionally, you can also tweak the Button color field and others to customize the look and feel of the pricing table.
- Once the pricing table settings are dialed in, click Continue in the bottom-left of the modal.
- 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.
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:
- Go to the Stripe Developers page by clicking the link in the top-right of the dashboard.
- On the Developers page, select the API keys tab.
- Under the Standard keys section, go to Secret key and click Reveal test key.
- Copy the Secret key value.
Add the Stripe Secret Key to Zuplo
With the Stripe API key on our clipboard, head back into Zuplo and do the following:
- Click on Settings in the header menu.
- On the Settings screen, click Environment Variables on the left-hand menu.
- On the Environment Variables screen, click Add Variable.
- On the Environment Variable form, Fill in the following details:
- For the Name, add “STRIPE_SECRET_KEY”.
- For Value, paste the Stripe secret key from your clipboard.
- Check off the Secret checkbox to encrypt the key and make it not visible once set.
- Click Save in the bottom-left to persist the value to Zuplo.
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:
- Go to the Code tab in the header menu, and in the left-side menu under config, open the dev-portal.json.
- In the file, scroll to the Monetization Settings section and check the Enable Monetization checkbox.
- In the Pricing Table ID and Publishable Key fields, add in the values from Stripe (in the code snippet on the Pricing Table** **screen).
- For the Secret Key field, click the Select Environment Variable button at the end and select the STRIPE_SECRET_KEY entry we created earlier.
- 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.
On the Developer Portal, a Pricing menu item should appear at the top right of the screen.
Clicking on Pricing, we should also see our pricing table appear.
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:
- Click on the Services tab in the menu.
- On the Services screen, click Configure on the Metering Service module.
- On the Metering Service screen, under the Plans section, click Create Plan.
- In the Create Plan modal that appears, populate the fields as follows:
- For the Name field, set the value to “Free”.
- For External ID, we will use the Stripe Product ID as the value. This can be obtained by:
- In Stripe, go to the Product catalog and select the “Free” product.
- On the product details screen for the product, copy the product ID and paste it back into the field in Zuplo.
- Under the Meters section, we will add our limits for our plan. We will add two values:
- For the first meter, set the Label as “Requests” and the Max Value as “100”.
- Click the Add Meter button under the first entry.
- For the second meter, set the Label as “Todo Creates” and the Max Value as “3”.
- 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:
- Still, on the Metering Service screen, click Create Plan again.
- In the Create Plan modal that appears, populate the fields as follows:
- For the Name field, set the value to “Pro”.
- For External ID, we will use the Stripe Product ID as the value. This can be obtained by:
- In Stripe, go to the Product catalog and select the “Pro” product.
- On the product details screen for the product, copy the product ID and paste it back into the field in Zuplo.
- Under the Meters section, we will add our limits for our plan. We will add two values:
- For the first meter, set the Label as “Requests” and the Max Value as “1000000”.
- Click the Add Meter button under the first entry.
- For the second meter, set the Label as “Todo Creates” and the Max Value as “1000”.
- 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.
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:
- In Zuplo, go to the Code section of your project by clicking the corresponding header menu item.
- Under the modules folder, click the + button and select Runtime Extension.
- 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);
}
- 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:
- Go back to the Developers screen, then select the Webhooks tab.
- Click Add an endpoint.
- In the modal that appears, fill in the following values and configuration:
- 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.
- Click Select events to listen to and then select the event entries for:
- customer.subscription.created
- customer.subscription.updated
- customer.subscription.deleted
- Click Add events once selected.
- With the configuration plugged in, click Add endpoint to register the endpoint.
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.
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:
- In Zuplo, go to Settings and select Environment Variables from the left-side menu.
- On the Environment Variables screen, click Add Variable.
- On the modal that appears, enter the following details:
- In the Name field, set it as “STRIPE_WEBHOOK_SIGNING_SECRET”
- In the Value field, paste in the webhook secret copied previously
- Check the Secret checkbox as we did with the previous Stripe environment variable we created.
- Click Save.
At this point, we should have added both Stripe variables required for the monetization plugin to Zuplo.
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:
- Navigate to the routes.oas.json screen in Zuplo.
- Under the Route Designer tab, open up the Get all todos endpoint.
- Expand the endpoints Policies section.
- In the Policies section, under Request, click Add Policy.
- In the Choose Policy modal, select the Monetization tile.
- In the Create Policy modal, name the policy “monetize-requests”.
- 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:
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:
Add the Policy to the Applicable Endpoints
Now, we must add this same policy to our other endpoints. To do this, we will:
- Go to the policies.json file
- In the Policies List, find the monetize-requests policy, click the ellipsis (...), and select Apply Policy.
- In the Apply Policy modal, select the PATCH and DELETE endpoints.
- Click Apply.
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:
- Back in the routes.oas.json screen in Zuplo, open the Create todo endpoint under the Route Designer tab.
- Expand the endpoints Policies section.
- In the Policies section, under Request, click Add Policy.
- In the Choose Policy modal, select the Monetization tile.
- In the Create Policy modal, set the name to “monetize-creates”.
- 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
}
}
}
- Once the configuration is updated, click OK.
- Ensure that the policy is at the bottom of the request policy pipeline.
- 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
- Log into the Developer Portal by clicking Sign In and signing in.
- If you have an old test key available in the portal for your user, delete it. To do this, you can:
- In your Zuplo project, navigate to Services and click Configure on the API Key Service entry.
- On the entry for your consumer, click on the ellipsis (...) and select Delete to delete the API key.
- Once logged into the portal, click on Pricing in the header menu.
- On the Pricing page, on the Free plan entry, click Subscribe.
- 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.
- 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:
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:
- In the developer portal, go to the Create todo endpoint on the left-hand menu.
- On the Create todo screen, click Test in the top-right corner.
- In the API Playground modal, send the example request by clicking Test.
- When the response returns, you should see it was successful, denoted by the 200 OK response returned.
- 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.
- 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.
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.
In the Subscriptions screen, we should also see that the overage is being recorded here.
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!
Top comments (0)