How to easily make money with a API in 2023!

How to easily make money with a API in 2023!

Table of Contents

Introduction

In today’s digital world, APIs (Application Programming Interfaces) have become a vital component for businesses and organizations to communicate and share data with each other. APIs enable software applications to interact with each other, making it easier to automate processes, access data, and provide services.

However, APIs are not only useful for connecting software systems, but they also offer opportunities for entrepreneurs and developers to make money. In this blog entry, we will explore different ways in which you can leverage APIs to create a revenue stream and make money. Whether you are a developer, an entrepreneur, or simply interested in exploring the potential of APIs, this blog entry will provide you with valuable insights and practical tips to get started. So, let’s dive into the world of APIs and discover how you can monetize them to create a profitable business model.

Building the API

Building the Server

For building the server we use NodeJs. If you dont know how NodeJs works you can check out our tutorial here.

First we create a new NodeJS Project with the command:

npm init -y

This command will create a new package.json file in your directory, which contains information about your project, including its dependencies.

We also need express and the stripe package so we also have to install the libaries:

npm install express
npm install stripe

This command will download and install Express and its dependencies into your project’s node_modules directory.

Now create a new file called server.js in your project directory. This file will contain the code to start your web server. In the server.js file, add the following code:

const express = require('express');
const app = express();

app.get('/', (req, res) => {
  res.send('Hello World!');
});

app.listen(3000, () => {
  console.log('Server started on port 3000');
});

This code initializes a new Express application and defines a route for the root URL (/). When a client makes a GET request to the root URL, the server will respond with the message “Hello World!”. The app.listen method starts the server and listens for incoming requests on port 3000.

We now want to setup or routes for the API.

We now create a new route which sends back the sentence “Called the API”.

app.post('/api/getSentence', (req, res) => {
  res.send('Called the API');
});

Now if a user wants to use our API he can make a POST-Request to our API with the url:

<yourdomain>/api/getSentence

Earn Money with our API

Now we also want to make money with our API so we have to start monetizing it.

For this we will use the Payment processor Stripe

You have to create a new account and enable the test mode in the right top corner.

Now we want to add a new product and set it to recurring.

Your product settings could look something like this.

Now head over to the Stripe Dashboard and copy your API-Key for your NodeJs Server

You now want to use the Stripe Package like this:

const stripe = require("stripe")("YOUR-KEY")

Creating the Stripe Checkout Route

In order to create a new Stripe Customer we also have to provide a new Route for creating a new checkout session with stripe. We can do it like this:

app.post('/checkout', async (req, res) => {
  const session = await stripe.checkout.sessions.create({
    mode: 'subscription',
    payment_method_types: ['card'],
    line_items: [
      {
        price: 'price_YOUR-PRODUCT',
      },
    ],
    // {CHECKOUT_SESSION_ID} is a string literal; do not change it!
    // the actual Session ID is returned in the query parameter when your customer
    // is redirected to the success page.
    success_url:
      'http://YOUR-WEBSITE/dashboard?session_id={CHECKOUT_SESSION_ID}',
    cancel_url: 'http://YOUR-WEBSITE/error',
  });

  res.send(session);
});

If the user now makes a new POST-Request to our server we will send them the session information which is a lot of data generated by the stripe api.

Currently important is only the session.url part which contains the checkout url for our stripe payments.

Creating Stripe Webhooks

A Stripe webhook is a way for Stripe, a popular online payment processing platform, to send information about events that occur in your Stripe account to an endpoint in your web application. When certain events happen in your Stripe account, such as a payment being processed, a subscription being created, or a customer’s details being updated, Stripe will send an HTTP POST request to the specified webhook endpoint URL with the details of the event.

Webhooks allow your application to receive real-time updates from Stripe, which can be used to trigger actions in your application, such as updating a user’s account status or sending an email notification. This can help you to keep your application and your Stripe account in sync, without having to rely on manual updates or polling Stripe’s API for changes.

Webhooks require careful handling to ensure the security of your data, as well as the reliability and accuracy of the information being transmitted. Stripe provides detailed documentation on how to set up and test webhooks, as well as best practices for handling incoming webhook requests in your application. By using Stripe webhooks effectively, you can automate processes in your application and improve the user experience for your customers.

For creating a webhook we can copy the code of the offical stripe documentation here

app.post('/webhook', async (req, res) => {
  let data;
  let eventType;
  // Check if webhook signing is configured.
  const webhookSecret = 'whsec_YOUR-KEY';

  if (webhookSecret) {
    // Retrieve the event by verifying the signature using the raw body and secret.
    let event;
    let signature = req.headers['stripe-signature'];

    try {
      event = stripe.webhooks.constructEvent(
        req['rawBody'],
        signature,
        webhookSecret
      );
    } catch (err) {
      console.log(`  Webhook signature verification failed.`);
      return res.sendStatus(400);
    }
    // Extract the object from the event.
    data = event.data;
    eventType = event.type;
  } else {
    // Webhook signing is recommended, but if the secret is not configured in `config.js`,
    // retrieve the event data directly from the request body.
    data = req.body.data;
    eventType = req.body.type;
  }
 //Switch case here
  res.sendStatus(200);
});

This code is the basic code of a stripe webhook for NodeJs but we now also want to create a new API key if a user subscribes to our API and also want to store the key into our database.

For this we create a new eventType and wait until a checkout session is completed. We now want to create a new API-Key and store it into our database like this:

switch (eventType) {
    case 'checkout.session.completed':
      console.log(data);
      // Data included in the event object:
      const customerId = data.object.customer;
      const subscriptionId = data.object.subscription;

      console.log(
        ` Customer ${customerId} subscribed to plan ${subscriptionId}`
      );

      // Get the subscription. The first item is the plan the user subscribed to.
      const subscription = await stripe.subscriptions.retrieve(subscriptionId);
      const itemId = subscription.items.data[0].id;

      // Generate API key
      const { apiKey, hashedAPIKey } = generateAPIKey();
      console.log(`User's API Key: ${apiKey}`);
      console.log(`Hashed API Key: ${hashedAPIKey}`);

      // Store the API key in your database.
      customers[customerId] = {
        apikey: hashedAPIKey,
        itemId,
        active: true,
      };
      apiKeys[hashedAPIKey] = customerId;
      break;
  }

Storing API keys in plain text can be a significant security risk for your application. If an attacker gains access to your server or your source code, they can easily read and use your API keys to perform malicious actions, such as stealing user data, sending spam, or incurring unexpected charges. Additionally, if you need to share your code or collaborate with others, storing API keys in plain text can expose them to unintended parties. Instead, it is recommended to store API keys in a secure manner, such as using environment variables, encrypted configuration files, or a secure key management service, to minimize the risk of unauthorized access.

Thats why we create two new functions which are creating a new secured hashed APIKey

function generateAPIKey() {
  const { randomBytes } = require('crypto');
  const apiKey = randomBytes(16).toString('hex');
  const hashedAPIKey = hashAPIKey(apiKey);

  // Ensure API key is unique
  if (apiKeys[hashedAPIKey]) {
    generateAPIKey();
  } else {
    return { hashedAPIKey, apiKey };
  }
}

// Hash the API key
function hashAPIKey(apiKey) {
  const { createHash } = require('crypto');

  const hashedAPIKey = createHash('sha256').update(apiKey).digest('hex');

  return hashedAPIKey;
}

Use the Stripe Webhook CLI

The Stripe Webhook CLI is a tool that allows developers to test and debug webhooks on their local machine before deploying them to a production environment. With the CLI, developers can simulate events and generate test payloads, allowing them to observe and analyze the behavior of their webhook handlers. By using the Stripe Webhook CLI, developers can ensure that their webhook handlers are functioning correctly, which can help to prevent errors and downtime when processing payments and other Stripe events. Overall, the Stripe Webhook CLI is a valuable tool for developers who want to improve the reliability and performance of their Stripe integrations.

Because in testing mode the server is running on your local machine you need to download the stripe webhook cli and forward all requests to your local machine so the stripe api can access your machine

In production you can easily forward the stripe webhook to your production url

You can find a documentation about it here

https://stripe.com/docs/webhooks/test?locale=de-DE

Make money with every request

For every new request of our API we now want to bill the user with his own unqiue API-Key

For this we have to motify our code which we wrote earlier.

app.post('/api/getSentence', (req, res) => {
  const { apiKey } = req.query;
  if(!apiKey){
    res.sendStatus(400);
  }
  //Has the API-Key and compare it with DB
  const hashedAPIKey = hashAPIKey(apiKey);

  const customerId = apiKeys[hashedAPIKey];
  const customer = customers[customerId];

  if (!customer || !customer.active) {
    res.sendStatus(403); // not authorized
  } else {
    // Record usage with Stripe Billing
    const record = await stripe.subscriptionItems.createUsageRecord(
      customer.itemId,
      {
        quantity: 1,
        timestamp: 'now',
        action: 'increment',
      }
    );
  res.send('Called the API');
});

We now modified our API so that it checks if the User has a valid API-Key and if so he gets billed for this request.

You can now manage all your users and products in your Stripe Dashboard and you will get all your money every month.

Conclusion

In conclusion, building an API with Stripe payments can offer a multitude of benefits for your application. By integrating Stripe’s secure and reliable payment processing platform, you can provide a seamless and convenient payment experience for your users, while also ensuring the security of their sensitive payment information. Stripe also offers a wide range of features and tools to help you manage your payments, including support for multiple currencies, real-time transaction data, and automated reporting. Additionally, Stripe’s robust API documentation and developer tools make it easy to get started and customize your integration to suit your specific needs. Whether you are building a new application or enhancing an existing one, integrating Stripe payments can help you streamline your payment process, increase revenue, and provide a better user experience.

If you want to learn more about NodeJs, coding or making money with programming check out our offical blog:

https://forgetpasses.com/blog/