Integrate Custom Signup Page with AWS Marketplace

  • Sun Apr 02 2023
  • Jazim Abbas

AWS Marketplace is a platform that allows customers to find, buy, and deploy software solutions that are built on or integrated with Amazon Web Services. If you're a software vendor, you can use AWS Marketplace to reach new customers and grow your business by listing and selling your products.

In this article, we'll walk you through the process of integrating your front-end application with AWS Marketplace, so that you can start selling your software to AWS customers. We'll cover the steps required to set up custom signup page and account provisioning.

Setting up AWS Marketplace for a SaaS Product

If you're planning to sell your SaaS (Software as a Service) application on AWS Marketplace, you need to go through a registration process. Here's a step-by-step guide on how to do it:

1. Sign in to your registered AWS Marketplace seller account.

2. Launch the Quick Start by clicking on this link.

  • This will take you to the AWS Cloudformation console, where you'll create a stack to deploy your SaaS Integration.
  • The Quick Start template source will be automatically populated with an Amazon S3 URL, which you don't need to change.
  • However, you can choose from different sample templates such as LAMP Stack, Ruby on Rails Stack, Wordpress blog and more.
  • In the Parameters section, you need to fill in the most important detail - the "Registration Page" field. By default, the Quick Start deployment will create a page hosted on Amazon CloudFront for AWS Marketplace customers to register for your product.
  • But if you want to use a custom registration page instead of the default one, you need to change the "Use custom registration page" option to "True".
  • You also need to fill in other details, which are straightforward.

Creating an API Endpoint for AWS Marketplace

We are using Next.js to build the API and frontend but you can choose any framework you prefer.

Use the following command to create a Nextjs app with TypeScript:

npx create-next-app@latest --typescript

Working

When a user registers for your SaaS App on AWS Marketplace, AWS will automatically send a token to the endpoint you provided. This token is sent in the body of an HTTP POST method and is passed using the key "x-amzn-marketplace-token", using form-urlencoded.

Since AWS passes the token in the HTTP POST method, you cannot use a Static Website URL (e.g., React, Angular) for the registration page. You need a server that can process the HTTP POST request and extract the token. Once you have the token, you can pass it to any static or dynamic website to complete the registration process.

Processing the HTTP POST Request

We need to create an API endpoint that can process the HTTP POST request and extract the token, and then pass it to any static or dynamic website.

Here's an example of what the code for this API might look like:

import type { NextApiRequest, NextApiResponse } from "next";

export default function handler(req: NextApiRequest, res: NextApiResponse) {
  if (req.method !== "POST") {
    return res.status(405).json({ message: "Method not allowed" });
  }

  try {
    const marketplaceToken = _validateReqBody(req.body);
    const redirectURL = "/marketplace-signup?token=" + marketplaceToken; // frontend signup page url

    res.redirect(302, redirectURL);
  } catch (err: any) {
    res.status(400).json({ message: err.message });
  }
}

function _validateReqBody(reqBody: any = {}) {
  const marketplaceToken = reqBody["x-amzn-marketplace-token"];

  if (!marketplaceToken) throw new Error("Token not found");
  return marketplaceToken;
}

In this code, we only allow HTTP POST requests because AWS uses this method to pass the token. We then validate the request body to ensure that the token is present and pass it to the frontend page.

Note that it's not mandatory to use a Next.js app for this; you can use any server-side framework that can process HTTP POST requests. You could even use API Gateway and then redirect the request to any static webpage with the token provided by AWS Marketplace.

Setting Up the Marketplace Subscription Endpoint

We don't need to create an endpoint to submit user details to API Gateway; we can directly call the API Gateway endpoint in the frontend app. However, this exposes the API Gateway endpoint, which we want to avoid. To prevent this, we can create an API endpoint.

Here's an example of what the code for this API might look like:

import type { NextApiRequest, NextApiResponse } from "next";

export default async function handler(req: NextApiRequest, res: NextApiResponse) {
  if (req.method !== "POST") return res.status(405).json({ message: "Method not allowed" });

  try {
    const data = await signupToAWSMarketplace(req.body ?? {});
    res.status(200).json({ message: "AWS Marketplace signup", data });
  } catch (err: any) {
    res.status(400).json({ message: err.message });
  }
}

async function signupToAWSMarketplace(fields: {}) {
  const response = await fetch(getGatewayEndpoint(), {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify(fields),
  });
  return response.json();
}

function getGatewayEndpoint(): string {
  const gatewayEndpoint = process.env.API_GATEWAY_ENDPOINT;
  if (!gatewayEndpoint) throw new Error("API Gateway Endpoint not found");
  return gatewayEndpoint;
}

Building the Frontend Static Webpage

We need to set up a frontend page where customers can fill out the signup details, and then we can submit those details to AWS Marketplace using our custom endpoint.

I am creating a custom hook that encapsulates all the logic of form validation, form submission, and extracting the token, etc.

import { useEffect, useState } from "react";

type FormState = {
  name: string;
  company: string;
  email: string;
  phone: string;
};

const initialFormValue: FormState = {
  name: "",
  company: "",
  email: "",
  phone: "",
};

export default function useMarketplace() {
  const [token, setToken] = useState("");
  const [form, setForm] = useState<FormState>(initialFormValue);

  useEffect(() => {
    const searchParams = new URLSearchParams(window.location.search);
    const tokenParam = searchParams.get("token");

    if (!tokenParam) {
      alert("Marketplace Token not found");
      return;
    }

    setToken(tokenParam);
  }, []);

  const handleChangeInput = (e: React.ChangeEvent<HTMLInputElement>) => {
    const inputName = e.target.name;
    const inputValue = e.target.value;

    setForm((prev) => ({ ...prev, [inputName]: inputValue }));
  };

  const handleSubmit = async () => {
    if (!_isFormValid()) {
      alert("Please fill all the form fields");
      return;
    }

    await _signupToAWSMarketplace();
  };

  const _isFormValid = (): boolean => {
    const { name, company, email, phone } = form;
    if (!name || !company || !email || !phone) {
      return false;
    }

    return true;
  };

  const _signupToAWSMarketplace = async (): Promise<void> => {
    try {
      const response = await fetch("/api/marketplace", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(_getPayload()),
      });
      const data = await response.json();
      
      console.log("data: ", data);
      alert("AWS Marketplace signup Successfull: " + data.message);
    } catch (err: any) {
      alert(err.message);
    }
  };

  const _getPayload = () => {
    return {
      contactPerson: form.name,
      contactEmail: form.email,
      companyName: form.company,
      contactPhone: form.phone,
      regToken: _getParsedToken(),
    };
  };

  const _getParsedToken = (): string => {
    return token.replace(/\s+/g, "+");
  };

  return { form, handleChangeInput, handleSubmit };
}

The hook implementation is very straightforward, but two things you need to understand:

  • useEffect: In the useEffect, I am extracting the token. This token is provided by our API endpoint, as I mentioned above. If the token does not exist, you can add your custom logic. I am just doing an alert.
  • _getParsedToken: Let's say the token extracted something like this: eUX9NWisIhmi%dRRV%2FDDb7R. The % is replaced by whitespace. However, when we submit the user details along with the token to the API Gateway Endpoint, it will not accept it due to the token. The whitespace should be replaced with a plus sign (+). That’s the reason we need to replace it.

Now, we need a signup form where users can fill in the details, and we'll use the custom hook that we just created.

import React from "react";
import styles from "@/styles/marketplace.module.css";
import useMarketplace from "@/hooks/useMarketplace";

export default function AWSMarketplaceSignup() {
  const { form, handleChangeInput, handleSubmit } = useMarketplace();

  return (
    <div className={styles.container}>
      <h1>AWS Marketplace Signup</h1>
      <div className={styles.form}>
        <div className={styles.formItem}>
          <input
            type="text"
            placeholder="Contact Name"
            name="name"
            value={form?.name}
            onChange={handleChangeInput}
            className={styles.formInput}
          />
        </div>
        <div className={styles.formItem}>
          <input
            type="text"
            name="company"
            placeholder="Company Name"
            value={form?.company}
            onChange={handleChangeInput}
            className={styles.formInput}
          />
        </div>
        <div className={styles.formItem}>
          <input
            type="text"
            placeholder="Contact Email"
            name="email"
            value={form?.email}
            onChange={handleChangeInput}
            className={styles.formInput}
          />
        </div>
        <div className={styles.formItem}>
          <input
            type="text"
            placeholder="Contact Phone Number"
            name="phone"
            value={form?.phone}
            onChange={handleChangeInput}
            className={styles.formInput}
          />
        </div>

        <button className={styles.formBtn} onClick={handleSubmit}>
          Register
        </button>
      </div>
    </div>
  );
}

Resources