Understanding In-App Purchasing for JavaScript API

Introduction

With In-App Purchasing API, you can enable compelling feature sets and scenarios such as:

  • Creating a "freemium" model for your app where the app itself is free but you charge a premium for advanced services or functionality
  • Allowing customers to purchase in-app currency directly within your app experience
  • Allowing customers to subscribe to content available within your app
  • Making content available for purchase to be viewed within your app

In-App Purchasing API allows your app to present, process, and fulfill purchases of digital content and subscriptions within your app experience. To enable this feature set, simply implement In-App Purchasing API as detailed in this guide. It will handle the details about purchase flow, payment processing, providing a receipt to your app, and managing rights to the purchasable content.

Once you build a storefront, you can use In-App Purchasing API to vend purchasable digital items.

In-App Purchasing API allows for the three different types of purchasable items:

  • Consumable Content - content that does not require an entitlement or access rights to use, can be purchased multiple times by a customer, is available only on the device it is purchased from, and does not require any type of entitlement check to use
  • Entitled Content - content that requires an entitlement or access rights to use, can be purchased only once by a customer, and is available on all compatible devices registered to the customer's account
  • Subscription Content - content that requires an entitlement or access rights to use, is bound by a period of time, that auto-renews, and is available on all eligible devices registered to the customer's Amazon account

Separation of Responsibilities

The In-App Purchasing API is designed to encapsulate the complexity behind the purchase process while providing a fully featured API. While building your app, it is important to understand which parts of the purchase flow the app must implement, and which parts are handled by the Amazon Services library.

Your responsibility in the purchase flow is to present the item catalog, to direct customers into the Amazon-hosted purchase flow, and to sync previous transactions. You do not need to provide purchase dialogs, transaction timeout logic, or "Thank You" dialogs. The Amazon Services library provides all these features.

The Amazon Services library is responsible for presenting the purchase dialogs to the user, managing the complexity behind the purchase workflow starting when the customer decides to purchase an item and ending when the store provides the application a receipt for the purchase (or other status in the case of a failed purchase). In addition, the library will also handle error conditions that arise and handle receipt and entitlement management as well as all customer messaging.

Fig. 1: Separation of responsibilities


Core Concepts

API Structure

In-App Purchasing API for JavaScript is comprised of three elements:

  • Amazon Services JavaScript - The class/API that manages the interaction between the application and Amazon's native APIs.
  • Purchase Handlers - The object your application provides to respond to callbacks from the Amazon Services JavaScript. They are registered as an observer to the Amazon Services In-App Purchasing API.
  • Receipt Verification Service - An HTTP service you can use to validate the customer's purchase receipt.

Integration with In-App Purchasing API consists of registering the Purchase Handlers with the Amazon Services JavaScript, calling the API and responding to the callbacks. Depending on how it is running the callbacks could be triggered by your application's calls or they could be called asynchronously so your application should be able to process both modes of operation. Since the callbacks could happen at any time, you must structure your application to be stateless and not depend on any particular state of execution. For instance, a previous session of your application could have initiated a purchase request that was not delivered because the application shut down. When the application restarts and registers its Purchase Handler, it will have the queued purchase delivered.

Fig. 2: Amazon In-App Purchasing for JavaScript Overview

Content Sources

Your app can leverage In-App Purchasing API in a variety of ways. How you choose to implement it can impact how you build your app. No matter how you choose to implement it, there are two basic flows available to you: locally available content, and deliverable content.

Locally Available Content

Locally available content is unlocked or otherwise made available to the customer upon purchase. Under this model your app already has everything it needs for the customer to use the purchasable item except the right to use it. You can use all three types of purchasable items with this model.

Your app should contain the unique identifiers for each purchasable item (SKUs), the ability to present a catalog to the customer, and logic within the app to unlock the purchasable item upon successful transaction.

Fig. 3: Locally Available Content Structure

Deliverable Content

Deliverable content allows you to make new content available to the customer. Under this model, your app will download the new content from your servers and make it available to the customer.

Your app should contain the unique identifiers for each purchasable item (SKUs), the ability to present a catalog to the customer, and logic within the app to download, persist, and make available the downloaded content upon successful transaction.

Fig. 4: Deliverable Content Structure

SKUs

A SKU (technically a stock-keeping unit) is a unique identifier for each distinct purchasable item. It is unique to you (specifically your developer account registered on the Distribution Portal), and is a (up to) 150-character length string of arbitrary structure that can contain the characters a-z, A-Z, 0-9, underscores, periods, and dashes, and is case sensitive. Purchasable items and SKUs have a 1:1 mapping. Your app will pass the SKU value via the PurchasingManager helper class to the client. The SKU is how the client knows what the customer is trying to purchase, and will manage the purchase flow accordingly.

You need to ensure that every purchasable item you define has a unique SKU. The SKUs are unique across your developer account. When you submit SKUs for multiple apps you need to ensure that there is no overlap.

Before a SKU can be used, it must be configured via the Distribution Portal. Refer to the Distribution Portal section of the In-App Purchasing Frequently Asked Questions List for information on how to configure SKUs.

Purchasable Items

A purchasable item is anything that a customer can purchase from within your app. Purchasable items require you to implement how your app uses these items; your code needs to manage this process.

Refer to the Distribution Agreement for information on what can and cannot be a purchasable item.

There are three kinds of purchasable items:

  • Consumable Content - content that does not require an entitlement or access rights to use, can be purchased multiple times by a customer, is available only on the device it is purchased from and does not require any type of entitlement check to use
  • Entitled Content - content that requires an entitlement or access rights to use, can be purchased only once by a customer, and is available on all compatible devices registered to the customer's account
  • Subscription Content - content that requires an entitlement or access rights to use, is bound by a period of time, that auto-renews, and is available on all eligible devices registered to the customer's Amazon account

The Amazon Services JavaScript

The Amazon Services JavaScript is an integral part of In-App Purchasing API. Once you initiate a purchase via In-App Purchasing API, the library will present an Amazon-branded user interface to complete the transaction. This flow is used by all apps that choose to employ In-App Purchasing API.

If an API call is made when the user is not authenticated with Amazon, the Amazon Services library will authenticate the user with Amazon. To ensure a good user experience and confirm the user is logged into Amazon's services, check for entitlements as soon as your application launches.

The library and Amazon's services present the user interface for all aspects of the purchase workflow. They provide the logic to display the purchasable item, perform the 1-Click purchase itself, and handle any preconditions or error scenarios that arise.

In the event a purchase is unsuccessful, the client will present messaging to the customer; your app should not message the customer. For example, if the customer does not have a valid credit card on file, the library redirects the customer to a page where they can update their payment information. You do not need to provide a confirmation or other interstitial dialog to the customer regarding the purchase flow.


In-App Purchasing API for JavaScript

The In-App Purchasing API comprises of two main components - AmazonServices, and Response Handlers that you implement and pass as an argument to the Amazon Services library upon initialization.

Amazon Service

AmazonService methods are as follows:

  • AmazonServices.IAP.registerObverver(purchasingObserver)
    • You must register your observer prior to using this class
    • This method needs to be called within your onLoad() lifecycle method
  • AmazonServices.IAP.purchaseItem(sku)
    • This method is used to initiate a purchase of a particular SKU
    • This method works with all types of Purchasable Items
    • The user interface surfaced uses the information configured for the SKU to determine the purchase flow presented to the customer
    • This method can be called from your app anytime
  • AmazonServices.IAP.getItemData(skus)
    • This method is used to retrieve Item data about a set of SKUs
    • This method works with all types of Purchasable Items
    • This method can be called from your app anytime
    • The parameter SKUs is an array of SKU strings
  • AmazonServices.IAP.getPurchaseUpdates(offset)
    • This method is used to sync previous purchases and revoked entitlements across devices
    • Only Entitled Content and Subscription Content are returned
    • This operation works with paginated data, with the beginning of the data set specified by the Offset
    • The PurchaseUpdatesResponse object will contain an offset marking the beginning of the next data set, if more is available
    • You should persist the Offset between invocations to mark where you are in the paginated dataset
    • You should correlate the Offset to the UserID, in the event multiple customers share the same physical device
    • It is best practice to persist the returned PurchaseUpdatesResponse data and last Offset to store the transaction history locally and only query the system for updates
    • This method should be called within the initialization of your application
  • AmazonServices.IAP.getUserId()
    • This method is used to retrieve the app-specific ID of the currently logged-in user
    • This method needs to be called within your onLoad() method
  • Amazon Services.IAP.PurchasingObserver()
    • The constructor to this class takes a hash table / object with functions for each of the response handlers that have been defined

Item

An Item represents a purchasable item, and provides information for your storefront. It is a best practice to retrieve the price of the purchasable item and display it prior to having the customer initiate a purchase. The Item class can be used to access the localized price, title, and description strings. The price string will include the currency symbol and be formatted appropriately based on the locale.

Receipt

A receipt is provided for every purchase made. Every receipt will contain a PurchaseToken that can be used to validate a purchase via the Receipt Verification Service. The receipt is deemed secure, and you can safely rely solely on it to authorize access to content or functionality within your app. As a developer, you have access to the UserID, PurchaseToken, and SKU for a particular purchase. The PurchaseToken is dynamically generated each time Receipt data is returned and is not a unique order identifier. They are unique values for verifying the Receipt data returned in a response object. The PurchaseToken of a Receipt returned in a PurchaseResponse will be different than the PurchaseToken of a Receipt for the same user and SKU returned in a PurchaseUpdatesResponse.

Each PurchaseToken will successfully validate against the Receipt Verification Service at any given time.

Offset

The offset represents a position in a set of paginated results. Operations that make use of an offset as input will provide an offset as an output. You can use the offset to get the next set of results. To reset an offset, you can pass in Offset.BEGINNING. It is a best practice to persist the current offset of the call within your app and use that offset for subsequent calls. It is also best practice to associate an offset with a UserID in the event multiple customers share the same physical device. Offset values are base64 encoded values and not human readable.

Response Objects

Every call you initiate via the AmazonServices results in a response received by the corresponding response handler specified in registerObserver(). Each of these responses makes use of a response object. These responses are detailed below:

  • GetUserIdResponse - provides the app-specific UserID for the user currently logged into the Amazon Client
  • PurchaseUpdatesResponse - provides a paginated list of receipts and revoked SKUs since the offset passed into the initiating request. Receipts are returned in a set and are unordered.
  • ItemDataResponse - provides item data, keyed by SKU.
  • PurchaseResponse - provides a status on purchases initiated within your app. Any error for a purchase is opaque to the developer, you do not need to implement any error handling scenarios in your app; this is managed by In-App Purchasing API.

Purchasing Handlers

You must implement the following response handlers and register them in the registerObserver method with the AmazonServices:

  • onSdkAvailable(onAvailableResponse) - This gets called when the In-App Purchasing services are ready to be called by your code. Production applications should not grant entitlements when they are run in sandbox mode.
  • onGetUserIdResponse(userIdResponse) - Called in response to GetUserId.
  • onItemDataResponse(itemDataResponse) - Called in response to GetItemData. data.itemData is a hash table of itemData objects keyed by SKU.
  • onPurchaseResponse(purchaseResponse) - Called to report the status of a purchase operation. purchaseResponse.purchaseRequestStatus contains the status of the response. If a prior session of the application shut down before a purchase response could be delivered, this function will be called when a new session of the application registers a purchase hander.
  • onPurchaseUpdateResponse(data) - Called with the list of entitlements that the user has been granted. data.receipts contains a hash table, keyed on SKU, that contains the receipts for the IAPs that have been granted to the user. data.revokedSkus has a list of SKUs that the user can no longer use.

  • Next Step: Integrating Consumables Into Your App

    Return to Web App ResourcesProvide Documentation Feedback on Web Apps

Unavailable During Maintenance